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.
170
def lock_write(self):
171
self.control_files.lock_write()
174
self.control_files.lock_read()
177
return self.control_files.is_locked()
180
def missing_revision_ids(self, other, revision_id=None):
181
"""Return the revision ids that other has that this does not.
183
These are returned in topological order.
185
revision_id: only return revision ids included by revision_id.
187
return InterRepository.get(other, self).missing_revision_ids(revision_id)
191
"""Open the repository rooted at base.
193
For instance, if the repository is at URL/.bzr/repository,
194
Repository.open(URL) -> a Repository instance.
196
control = bzrlib.bzrdir.BzrDir.open(base)
197
return control.open_repository()
199
def copy_content_into(self, destination, revision_id=None, basis=None):
200
"""Make a complete copy of the content in self into destination.
202
This is a destructive operation! Do not use it on existing
205
return InterRepository.get(self, destination).copy_content(revision_id, basis)
207
def fetch(self, source, revision_id=None, pb=None):
208
"""Fetch the content required to construct revision_id from source.
210
If revision_id is None all content is copied.
212
return InterRepository.get(source, self).fetch(revision_id=revision_id,
216
self.control_files.unlock()
219
def clone(self, a_bzrdir, revision_id=None, basis=None):
220
"""Clone this repository into a_bzrdir using the current format.
222
Currently no check is made that the format of this repository and
223
the bzrdir format are compatible. FIXME RBC 20060201.
225
if not isinstance(a_bzrdir._format, self.bzrdir._format.__class__):
226
# use target default format.
227
result = a_bzrdir.create_repository()
228
# FIXME RBC 20060209 split out the repository type to avoid this check ?
229
elif isinstance(a_bzrdir._format,
230
(bzrlib.bzrdir.BzrDirFormat4,
231
bzrlib.bzrdir.BzrDirFormat5,
232
bzrlib.bzrdir.BzrDirFormat6)):
233
result = a_bzrdir.open_repository()
235
result = self._format.initialize(a_bzrdir, shared=self.is_shared())
236
self.copy_content_into(result, revision_id, basis)
240
def has_revision(self, revision_id):
241
"""True if this repository has a copy of the revision."""
242
return self._revision_store.has_revision_id(revision_id,
243
self.get_transaction())
246
def get_revision_reconcile(self, revision_id):
247
"""'reconcile' helper routine that allows access to a revision always.
249
This variant of get_revision does not cross check the weave graph
250
against the revision one as get_revision does: but it should only
251
be used by reconcile, or reconcile-alike commands that are correcting
252
or testing the revision graph.
254
if not revision_id or not isinstance(revision_id, basestring):
255
raise InvalidRevisionId(revision_id=revision_id, branch=self)
256
return self._revision_store.get_revision(revision_id,
257
self.get_transaction())
260
def get_revision_xml(self, revision_id):
261
rev = self.get_revision(revision_id)
263
# the current serializer..
264
self._revision_store._serializer.write_revision(rev, rev_tmp)
266
return rev_tmp.getvalue()
269
def get_revision(self, revision_id):
270
"""Return the Revision object for a named revision"""
271
r = self.get_revision_reconcile(revision_id)
272
# weave corruption can lead to absent revision markers that should be
274
# the following test is reasonably cheap (it needs a single weave read)
275
# and the weave is cached in read transactions. In write transactions
276
# it is not cached but typically we only read a small number of
277
# revisions. For knits when they are introduced we will probably want
278
# to ensure that caching write transactions are in use.
279
inv = self.get_inventory_weave()
280
self._check_revision_parents(r, inv)
283
def _check_revision_parents(self, revision, inventory):
284
"""Private to Repository and Fetch.
286
This checks the parentage of revision in an inventory weave for
287
consistency and is only applicable to inventory-weave-for-ancestry
288
using repository formats & fetchers.
290
weave_parents = inventory.get_parents(revision.revision_id)
291
weave_names = inventory.versions()
292
for parent_id in revision.parent_ids:
293
if parent_id in weave_names:
294
# this parent must not be a ghost.
295
if not parent_id in weave_parents:
297
raise errors.CorruptRepository(self)
300
def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
301
signature = gpg_strategy.sign(plaintext)
302
self._revision_store.add_revision_signature_text(revision_id,
304
self.get_transaction())
306
def fileid_involved_between_revs(self, from_revid, to_revid):
307
"""Find file_id(s) which are involved in the changes between revisions.
309
This determines the set of revisions which are involved, and then
310
finds all file ids affected by those revisions.
312
w = self.get_inventory_weave()
313
from_set = set(w.get_ancestry(from_revid))
314
to_set = set(w.get_ancestry(to_revid))
315
changed = to_set.difference(from_set)
316
return self._fileid_involved_by_set(changed)
318
def fileid_involved(self, last_revid=None):
319
"""Find all file_ids modified in the ancestry of last_revid.
321
:param last_revid: If None, last_revision() will be used.
323
w = self.get_inventory_weave()
325
changed = set(w.versions())
327
changed = set(w.get_ancestry(last_revid))
328
return self._fileid_involved_by_set(changed)
330
def fileid_involved_by_set(self, changes):
331
"""Find all file_ids modified by the set of revisions passed in.
333
:param changes: A set() of revision ids
335
# TODO: jam 20060119 This line does *nothing*, remove it.
336
# or better yet, change _fileid_involved_by_set so
337
# that it takes the inventory weave, rather than
338
# pulling it out by itself.
339
return self._fileid_involved_by_set(changes)
341
def _fileid_involved_by_set(self, changes):
342
"""Find the set of file-ids affected by the set of revisions.
344
:param changes: A set() of revision ids.
345
:return: A set() of file ids.
347
This peaks at the Weave, interpreting each line, looking to
348
see if it mentions one of the revisions. And if so, includes
349
the file id mentioned.
350
This expects both the Weave format, and the serialization
351
to have a single line per file/directory, and to have
352
fileid="" and revision="" on that line.
354
assert isinstance(self._format, (RepositoryFormat5,
357
RepositoryFormatKnit1)), \
358
"fileid_involved only supported for branches which store inventory as unnested xml"
360
w = self.get_inventory_weave()
363
# this code needs to read every line in every inventory for the
364
# inventories [changes]. Seeing a line twice is ok. Seeing a line
365
# not pesent in one of those inventories is unnecessary and not
366
# harmful because we are filtering by the revision id marker in the
367
# inventory lines to only select file ids altered in one of those
368
# revisions. We dont need to see all lines in the inventory because
369
# only those added in an inventory in rev X can contain a revision=X
371
for line in w.iter_lines_added_or_present_in_versions(changes):
372
start = line.find('file_id="')+9
373
if start < 9: continue
374
end = line.find('"', start)
376
file_id = _unescape_xml(line[start:end])
378
# check if file_id is already present
379
if file_id in file_ids: continue
381
start = line.find('revision="')+10
382
if start < 10: continue
383
end = line.find('"', start)
385
revision_id = _unescape_xml(line[start:end])
386
if revision_id in changes:
387
file_ids.add(file_id)
391
def get_inventory_weave(self):
392
return self.control_weaves.get_weave('inventory',
393
self.get_transaction())
396
def get_inventory(self, revision_id):
397
"""Get Inventory object by hash."""
398
xml = self.get_inventory_xml(revision_id)
399
return bzrlib.xml5.serializer_v5.read_inventory_from_string(xml)
402
def get_inventory_xml(self, revision_id):
403
"""Get inventory XML as a file object."""
405
assert isinstance(revision_id, basestring), type(revision_id)
406
iw = self.get_inventory_weave()
407
return iw.get_text(revision_id)
409
raise bzrlib.errors.HistoryMissing(self, 'inventory', revision_id)
412
def get_inventory_sha1(self, revision_id):
413
"""Return the sha1 hash of the inventory entry
415
return self.get_revision(revision_id).inventory_sha1
418
def get_revision_graph(self, revision_id=None):
419
"""Return a dictionary containing the revision graph.
421
:return: a dictionary of revision_id->revision_parents_list.
423
weave = self.get_inventory_weave()
424
all_revisions = self._eliminate_revisions_not_present(weave.versions())
425
entire_graph = dict([(node, weave.get_parents(node)) for
426
node in all_revisions])
427
if revision_id is None:
429
elif revision_id not in entire_graph:
430
raise errors.NoSuchRevision(self, revision_id)
432
# add what can be reached from revision_id
434
pending = set([revision_id])
435
while len(pending) > 0:
437
result[node] = entire_graph[node]
438
for revision_id in result[node]:
439
if revision_id not in result:
440
pending.add(revision_id)
444
def get_revision_graph_with_ghosts(self, revision_ids=None):
445
"""Return a graph of the revisions with ghosts marked as applicable.
447
:param revision_ids: an iterable of revisions to graph or None for all.
448
:return: a Graph object with the graph reachable from revision_ids.
452
pending = set(self.all_revision_ids())
455
pending = set(revision_ids)
456
required = set(revision_ids)
459
revision_id = pending.pop()
461
rev = self.get_revision(revision_id)
462
except errors.NoSuchRevision:
463
if revision_id in required:
466
result.add_ghost(revision_id)
468
for parent_id in rev.parent_ids:
469
# is this queued or done ?
470
if (parent_id not in pending and
471
parent_id not in done):
473
pending.add(parent_id)
474
result.add_node(revision_id, rev.parent_ids)
475
done.add(revision_id)
479
def get_revision_inventory(self, revision_id):
480
"""Return inventory of a past revision."""
481
# TODO: Unify this with get_inventory()
482
# bzr 0.0.6 and later imposes the constraint that the inventory_id
483
# must be the same as its revision, so this is trivial.
484
if revision_id is None:
485
# This does not make sense: if there is no revision,
486
# then it is the current tree inventory surely ?!
487
# and thus get_root_id() is something that looks at the last
488
# commit on the branch, and the get_root_id is an inventory check.
489
raise NotImplementedError
490
# return Inventory(self.get_root_id())
492
return self.get_inventory(revision_id)
496
"""Return True if this repository is flagged as a shared repository."""
497
raise NotImplementedError(self.is_shared)
501
"""Reconcile this repository."""
502
from bzrlib.reconcile import RepoReconciler
503
reconciler = RepoReconciler(self)
504
reconciler.reconcile()
508
def revision_tree(self, revision_id):
509
"""Return Tree for a revision on this branch.
511
`revision_id` may be None for the null revision, in which case
512
an `EmptyTree` is returned."""
513
# TODO: refactor this to use an existing revision object
514
# so we don't need to read it in twice.
515
if revision_id is None or revision_id == NULL_REVISION:
518
inv = self.get_revision_inventory(revision_id)
519
return RevisionTree(self, inv, revision_id)
522
def get_ancestry(self, revision_id):
523
"""Return a list of revision-ids integrated by a revision.
525
This is topologically sorted.
527
if revision_id is None:
529
if not self.has_revision(revision_id):
530
raise errors.NoSuchRevision(self, revision_id)
531
w = self.get_inventory_weave()
532
candidates = w.get_ancestry(revision_id)
533
return [None] + candidates # self._eliminate_revisions_not_present(candidates)
536
def print_file(self, file, revision_id):
537
"""Print `file` to stdout.
539
FIXME RBC 20060125 as John Meinel points out this is a bad api
540
- it writes to stdout, it assumes that that is valid etc. Fix
541
by creating a new more flexible convenience function.
543
tree = self.revision_tree(revision_id)
544
# use inventory as it was in that revision
545
file_id = tree.inventory.path2id(file)
547
raise BzrError("%r is not present in revision %s" % (file, revno))
549
revno = self.revision_id_to_revno(revision_id)
550
except errors.NoSuchRevision:
551
# TODO: This should not be BzrError,
552
# but NoSuchFile doesn't fit either
553
raise BzrError('%r is not present in revision %s'
554
% (file, revision_id))
556
raise BzrError('%r is not present in revision %s'
558
tree.print_file(file_id)
560
def get_transaction(self):
561
return self.control_files.get_transaction()
563
def revision_parents(self, revid):
564
return self.get_inventory_weave().parent_names(revid)
567
def set_make_working_trees(self, new_value):
568
"""Set the policy flag for making working trees when creating branches.
570
This only applies to branches that use this repository.
572
The default is 'True'.
573
:param new_value: True to restore the default, False to disable making
576
raise NotImplementedError(self.set_make_working_trees)
578
def make_working_trees(self):
579
"""Returns the policy for making working trees on new branches."""
580
raise NotImplementedError(self.make_working_trees)
583
def sign_revision(self, revision_id, gpg_strategy):
584
plaintext = Testament.from_revision(self, revision_id).as_short_text()
585
self.store_revision_signature(gpg_strategy, plaintext, revision_id)
588
def has_signature_for_revision_id(self, revision_id):
589
"""Query for a revision signature for revision_id in the repository."""
590
return self._revision_store.has_signature(revision_id,
591
self.get_transaction())
594
def get_signature_text(self, revision_id):
595
"""Return the text for a signature."""
596
return self._revision_store.get_signature_text(revision_id,
597
self.get_transaction())
600
class AllInOneRepository(Repository):
601
"""Legacy support - the repository behaviour for all-in-one branches."""
603
def __init__(self, _format, a_bzrdir, _revision_store, control_store, text_store):
604
# we reuse one control files instance.
605
dir_mode = a_bzrdir._control_files._dir_mode
606
file_mode = a_bzrdir._control_files._file_mode
608
def get_store(name, compressed=True, prefixed=False):
609
# FIXME: This approach of assuming stores are all entirely compressed
610
# or entirely uncompressed is tidy, but breaks upgrade from
611
# some existing branches where there's a mixture; we probably
612
# still want the option to look for both.
613
relpath = a_bzrdir._control_files._escape(name)
614
store = TextStore(a_bzrdir._control_files._transport.clone(relpath),
615
prefixed=prefixed, compressed=compressed,
618
#if self._transport.should_cache():
619
# cache_path = os.path.join(self.cache_root, name)
620
# os.mkdir(cache_path)
621
# store = bzrlib.store.CachedStore(store, cache_path)
624
# not broken out yet because the controlweaves|inventory_store
625
# and text_store | weave_store bits are still different.
626
if isinstance(_format, RepositoryFormat4):
627
# cannot remove these - there is still no consistent api
628
# which allows access to this old info.
629
self.inventory_store = get_store('inventory-store')
630
text_store = get_store('text-store')
631
super(AllInOneRepository, self).__init__(_format, a_bzrdir, a_bzrdir._control_files, _revision_store, control_store, text_store)
635
"""AllInOne repositories cannot be shared."""
639
def set_make_working_trees(self, new_value):
640
"""Set the policy flag for making working trees when creating branches.
642
This only applies to branches that use this repository.
644
The default is 'True'.
645
:param new_value: True to restore the default, False to disable making
648
raise NotImplementedError(self.set_make_working_trees)
650
def make_working_trees(self):
651
"""Returns the policy for making working trees on new branches."""
655
class MetaDirRepository(Repository):
656
"""Repositories in the new meta-dir layout."""
658
def __init__(self, _format, a_bzrdir, control_files, _revision_store, control_store, text_store):
659
super(MetaDirRepository, self).__init__(_format,
666
dir_mode = self.control_files._dir_mode
667
file_mode = self.control_files._file_mode
671
"""Return True if this repository is flagged as a shared repository."""
672
return self.control_files._transport.has('shared-storage')
675
def set_make_working_trees(self, new_value):
676
"""Set the policy flag for making working trees when creating branches.
678
This only applies to branches that use this repository.
680
The default is 'True'.
681
:param new_value: True to restore the default, False to disable making
686
self.control_files._transport.delete('no-working-trees')
687
except errors.NoSuchFile:
690
self.control_files.put_utf8('no-working-trees', '')
692
def make_working_trees(self):
693
"""Returns the policy for making working trees on new branches."""
694
return not self.control_files._transport.has('no-working-trees')
697
class KnitRepository(MetaDirRepository):
698
"""Knit format repository."""
701
def all_revision_ids(self):
702
"""See Repository.all_revision_ids()."""
703
return self._revision_store.all_revision_ids(self.get_transaction())
705
def fileid_involved_between_revs(self, from_revid, to_revid):
706
"""Find file_id(s) which are involved in the changes between revisions.
708
This determines the set of revisions which are involved, and then
709
finds all file ids affected by those revisions.
711
vf = self._get_revision_vf()
712
from_set = set(vf.get_ancestry(from_revid))
713
to_set = set(vf.get_ancestry(to_revid))
714
changed = to_set.difference(from_set)
715
return self._fileid_involved_by_set(changed)
717
def fileid_involved(self, last_revid=None):
718
"""Find all file_ids modified in the ancestry of last_revid.
720
:param last_revid: If None, last_revision() will be used.
723
changed = set(self.all_revision_ids())
725
changed = set(self.get_ancestry(last_revid))
728
return self._fileid_involved_by_set(changed)
731
def get_ancestry(self, revision_id):
732
"""Return a list of revision-ids integrated by a revision.
734
This is topologically sorted.
736
if revision_id is None:
738
vf = self._get_revision_vf()
740
return [None] + vf.get_ancestry(revision_id)
741
except errors.RevisionNotPresent:
742
raise errors.NoSuchRevision(self, revision_id)
745
def get_revision(self, revision_id):
746
"""Return the Revision object for a named revision"""
747
return self.get_revision_reconcile(revision_id)
750
def get_revision_graph(self, revision_id=None):
751
"""Return a dictionary containing the revision graph.
753
:return: a dictionary of revision_id->revision_parents_list.
755
weave = self._get_revision_vf()
756
entire_graph = weave.get_graph()
757
if revision_id is None:
758
return weave.get_graph()
759
elif revision_id not in weave:
760
raise errors.NoSuchRevision(self, revision_id)
762
# add what can be reached from revision_id
764
pending = set([revision_id])
765
while len(pending) > 0:
767
result[node] = weave.get_parents(node)
768
for revision_id in result[node]:
769
if revision_id not in result:
770
pending.add(revision_id)
774
def get_revision_graph_with_ghosts(self, revision_ids=None):
775
"""Return a graph of the revisions with ghosts marked as applicable.
777
:param revision_ids: an iterable of revisions to graph or None for all.
778
:return: a Graph object with the graph reachable from revision_ids.
781
vf = self._get_revision_vf()
782
versions = set(vf.versions())
784
pending = set(self.all_revision_ids())
787
pending = set(revision_ids)
788
required = set(revision_ids)
791
revision_id = pending.pop()
792
if not revision_id in versions:
793
if revision_id in required:
794
raise errors.NoSuchRevision(self, revision_id)
796
result.add_ghost(revision_id)
797
# mark it as done so we dont try for it again.
798
done.add(revision_id)
800
parent_ids = vf.get_parents_with_ghosts(revision_id)
801
for parent_id in parent_ids:
802
# is this queued or done ?
803
if (parent_id not in pending and
804
parent_id not in done):
806
pending.add(parent_id)
807
result.add_node(revision_id, parent_ids)
808
done.add(revision_id)
811
def _get_revision_vf(self):
812
""":return: a versioned file containing the revisions."""
813
vf = self._revision_store.get_revision_file(self.get_transaction())
818
"""Reconcile this repository."""
819
from bzrlib.reconcile import KnitReconciler
820
reconciler = KnitReconciler(self)
821
reconciler.reconcile()
824
def revision_parents(self, revid):
825
return self._get_revision_vf().get_parents(rev_id)
827
class RepositoryFormat(object):
828
"""A repository format.
830
Formats provide three things:
831
* An initialization routine to construct repository data on disk.
832
* a format string which is used when the BzrDir supports versioned
834
* an open routine which returns a Repository instance.
836
Formats are placed in an dict by their format string for reference
837
during opening. These should be subclasses of RepositoryFormat
840
Once a format is deprecated, just deprecate the initialize and open
841
methods on the format class. Do not deprecate the object, as the
842
object will be created every system load.
844
Common instance attributes:
845
_matchingbzrdir - the bzrdir format that the repository format was
846
originally written to work with. This can be used if manually
847
constructing a bzrdir and repository, or more commonly for test suite
851
_default_format = None
852
"""The default format used for new repositories."""
855
"""The known formats."""
858
def find_format(klass, a_bzrdir):
859
"""Return the format for the repository object in a_bzrdir."""
861
transport = a_bzrdir.get_repository_transport(None)
862
format_string = transport.get("format").read()
863
return klass._formats[format_string]
864
except errors.NoSuchFile:
865
raise errors.NoRepositoryPresent(a_bzrdir)
867
raise errors.UnknownFormatError(format_string)
869
def _get_control_store(self, repo_transport, control_files):
870
"""Return the control store for this repository."""
871
raise NotImplementedError(self._get_control_store)
874
def get_default_format(klass):
875
"""Return the current default format."""
876
return klass._default_format
878
def get_format_string(self):
879
"""Return the ASCII format string that identifies this format.
881
Note that in pre format ?? repositories the format string is
882
not permitted nor written to disk.
884
raise NotImplementedError(self.get_format_string)
886
def get_format_description(self):
887
"""Return the short desciption for this format."""
888
raise NotImplementedError(self.get_format_description)
890
def _get_revision_store(self, repo_transport, control_files):
891
"""Return the revision store object for this a_bzrdir."""
892
raise NotImplementedError(self._get_revision_store)
894
def _get_text_rev_store(self,
901
"""Common logic for getting a revision store for a repository.
903
see self._get_revision_store for the subclass-overridable method to
904
get the store for a repository.
906
from bzrlib.store.revision.text import TextRevisionStore
907
dir_mode = control_files._dir_mode
908
file_mode = control_files._file_mode
909
text_store =TextStore(transport.clone(name),
911
compressed=compressed,
914
_revision_store = TextRevisionStore(text_store, serializer)
915
return _revision_store
917
def _get_versioned_file_store(self,
922
versionedfile_class=WeaveFile,
924
weave_transport = control_files._transport.clone(name)
925
dir_mode = control_files._dir_mode
926
file_mode = control_files._file_mode
927
return VersionedFileStore(weave_transport, prefixed=prefixed,
930
versionedfile_class=versionedfile_class,
933
def initialize(self, a_bzrdir, shared=False):
934
"""Initialize a repository of this format in a_bzrdir.
936
:param a_bzrdir: The bzrdir to put the new repository in it.
937
:param shared: The repository should be initialized as a sharable one.
939
This may raise UninitializableFormat if shared repository are not
940
compatible the a_bzrdir.
943
def is_supported(self):
944
"""Is this format supported?
946
Supported formats must be initializable and openable.
947
Unsupported formats may not support initialization or committing or
948
some other features depending on the reason for not being supported.
952
def open(self, a_bzrdir, _found=False):
953
"""Return an instance of this format for the bzrdir a_bzrdir.
955
_found is a private parameter, do not use it.
957
raise NotImplementedError(self.open)
960
def register_format(klass, format):
961
klass._formats[format.get_format_string()] = format
964
def set_default_format(klass, format):
965
klass._default_format = format
968
def unregister_format(klass, format):
969
assert klass._formats[format.get_format_string()] is format
970
del klass._formats[format.get_format_string()]
973
class PreSplitOutRepositoryFormat(RepositoryFormat):
974
"""Base class for the pre split out repository formats."""
976
def initialize(self, a_bzrdir, shared=False, _internal=False):
977
"""Create a weave repository.
979
TODO: when creating split out bzr branch formats, move this to a common
980
base for Format5, Format6. or something like that.
982
from bzrlib.weavefile import write_weave_v5
983
from bzrlib.weave import Weave
986
raise errors.IncompatibleFormat(self, a_bzrdir._format)
989
# always initialized when the bzrdir is.
990
return self.open(a_bzrdir, _found=True)
992
# Create an empty weave
994
bzrlib.weavefile.write_weave_v5(Weave(), sio)
995
empty_weave = sio.getvalue()
997
mutter('creating repository in %s.', a_bzrdir.transport.base)
998
dirs = ['revision-store', 'weaves']
999
files = [('inventory.weave', StringIO(empty_weave)),
1002
# FIXME: RBC 20060125 dont peek under the covers
1003
# NB: no need to escape relative paths that are url safe.
1004
control_files = LockableFiles(a_bzrdir.transport, 'branch-lock',
1006
control_files.create_lock()
1007
control_files.lock_write()
1008
control_files._transport.mkdir_multi(dirs,
1009
mode=control_files._dir_mode)
1011
for file, content in files:
1012
control_files.put(file, content)
1014
control_files.unlock()
1015
return self.open(a_bzrdir, _found=True)
1017
def _get_control_store(self, repo_transport, control_files):
1018
"""Return the control store for this repository."""
1019
return self._get_versioned_file_store('',
1024
def _get_text_store(self, transport, control_files):
1025
"""Get a store for file texts for this format."""
1026
raise NotImplementedError(self._get_text_store)
1028
def open(self, a_bzrdir, _found=False):
1029
"""See RepositoryFormat.open()."""
1031
# we are being called directly and must probe.
1032
raise NotImplementedError
1034
repo_transport = a_bzrdir.get_repository_transport(None)
1035
control_files = a_bzrdir._control_files
1036
text_store = self._get_text_store(repo_transport, control_files)
1037
control_store = self._get_control_store(repo_transport, control_files)
1038
_revision_store = self._get_revision_store(repo_transport, control_files)
1039
return AllInOneRepository(_format=self,
1041
_revision_store=_revision_store,
1042
control_store=control_store,
1043
text_store=text_store)
1046
class RepositoryFormat4(PreSplitOutRepositoryFormat):
1047
"""Bzr repository format 4.
1049
This repository format has:
1051
- TextStores for texts, inventories,revisions.
1053
This format is deprecated: it indexes texts using a text id which is
1054
removed in format 5; initializationa and write support for this format
1059
super(RepositoryFormat4, self).__init__()
1060
self._matchingbzrdir = bzrlib.bzrdir.BzrDirFormat4()
1062
def get_format_description(self):
1063
"""See RepositoryFormat.get_format_description()."""
1064
return "Repository format 4"
1066
def initialize(self, url, shared=False, _internal=False):
1067
"""Format 4 branches cannot be created."""
1068
raise errors.UninitializableFormat(self)
1070
def is_supported(self):
1071
"""Format 4 is not supported.
1073
It is not supported because the model changed from 4 to 5 and the
1074
conversion logic is expensive - so doing it on the fly was not
1079
def _get_control_store(self, repo_transport, control_files):
1080
"""Format 4 repositories have no formal control store at this point.
1082
This will cause any control-file-needing apis to fail - this is desired.
1086
def _get_revision_store(self, repo_transport, control_files):
1087
"""See RepositoryFormat._get_revision_store()."""
1088
from bzrlib.xml4 import serializer_v4
1089
return self._get_text_rev_store(repo_transport,
1092
serializer=serializer_v4)
1094
def _get_text_store(self, transport, control_files):
1095
"""See RepositoryFormat._get_text_store()."""
1098
class RepositoryFormat5(PreSplitOutRepositoryFormat):
1099
"""Bzr control format 5.
1101
This repository format has:
1102
- weaves for file texts and inventory
1104
- TextStores for revisions and signatures.
1108
super(RepositoryFormat5, self).__init__()
1109
self._matchingbzrdir = bzrlib.bzrdir.BzrDirFormat5()
1111
def get_format_description(self):
1112
"""See RepositoryFormat.get_format_description()."""
1113
return "Weave repository format 5"
1115
def _get_revision_store(self, repo_transport, control_files):
1116
"""See RepositoryFormat._get_revision_store()."""
1117
"""Return the revision store object for this a_bzrdir."""
1118
return self._get_text_rev_store(repo_transport,
1123
def _get_text_store(self, transport, control_files):
1124
"""See RepositoryFormat._get_text_store()."""
1125
return self._get_versioned_file_store('weaves', transport, control_files, prefixed=False)
1128
class RepositoryFormat6(PreSplitOutRepositoryFormat):
1129
"""Bzr control format 6.
1131
This repository format has:
1132
- weaves for file texts and inventory
1133
- hash subdirectory based stores.
1134
- TextStores for revisions and signatures.
1138
super(RepositoryFormat6, self).__init__()
1139
self._matchingbzrdir = bzrlib.bzrdir.BzrDirFormat6()
1141
def get_format_description(self):
1142
"""See RepositoryFormat.get_format_description()."""
1143
return "Weave repository format 6"
1145
def _get_revision_store(self, repo_transport, control_files):
1146
"""See RepositoryFormat._get_revision_store()."""
1147
return self._get_text_rev_store(repo_transport,
1153
def _get_text_store(self, transport, control_files):
1154
"""See RepositoryFormat._get_text_store()."""
1155
return self._get_versioned_file_store('weaves', transport, control_files)
1158
class MetaDirRepositoryFormat(RepositoryFormat):
1159
"""Common base class for the new repositories using the metadir layour."""
1162
super(MetaDirRepositoryFormat, self).__init__()
1163
self._matchingbzrdir = bzrlib.bzrdir.BzrDirMetaFormat1()
1165
def _create_control_files(self, a_bzrdir):
1166
"""Create the required files and the initial control_files object."""
1167
# FIXME: RBC 20060125 dont peek under the covers
1168
# NB: no need to escape relative paths that are url safe.
1169
repository_transport = a_bzrdir.get_repository_transport(self)
1170
control_files = LockableFiles(repository_transport, 'lock', LockDir)
1171
control_files.create_lock()
1172
return control_files
1174
def _upload_blank_content(self, a_bzrdir, dirs, files, utf8_files, shared):
1175
"""Upload the initial blank content."""
1176
control_files = self._create_control_files(a_bzrdir)
1177
control_files.lock_write()
1179
control_files._transport.mkdir_multi(dirs,
1180
mode=control_files._dir_mode)
1181
for file, content in files:
1182
control_files.put(file, content)
1183
for file, content in utf8_files:
1184
control_files.put_utf8(file, content)
1186
control_files.put_utf8('shared-storage', '')
1188
control_files.unlock()
1191
class RepositoryFormat7(MetaDirRepositoryFormat):
1192
"""Bzr repository 7.
1194
This repository format has:
1195
- weaves for file texts and inventory
1196
- hash subdirectory based stores.
1197
- TextStores for revisions and signatures.
1198
- a format marker of its own
1199
- an optional 'shared-storage' flag
1200
- an optional 'no-working-trees' flag
1203
def _get_control_store(self, repo_transport, control_files):
1204
"""Return the control store for this repository."""
1205
return self._get_versioned_file_store('',
1210
def get_format_string(self):
1211
"""See RepositoryFormat.get_format_string()."""
1212
return "Bazaar-NG Repository format 7"
1214
def get_format_description(self):
1215
"""See RepositoryFormat.get_format_description()."""
1216
return "Weave repository format 7"
1218
def _get_revision_store(self, repo_transport, control_files):
1219
"""See RepositoryFormat._get_revision_store()."""
1220
return self._get_text_rev_store(repo_transport,
1227
def _get_text_store(self, transport, control_files):
1228
"""See RepositoryFormat._get_text_store()."""
1229
return self._get_versioned_file_store('weaves',
1233
def initialize(self, a_bzrdir, shared=False):
1234
"""Create a weave repository.
1236
:param shared: If true the repository will be initialized as a shared
1239
from bzrlib.weavefile import write_weave_v5
1240
from bzrlib.weave import Weave
1242
# Create an empty weave
1244
bzrlib.weavefile.write_weave_v5(Weave(), sio)
1245
empty_weave = sio.getvalue()
1247
mutter('creating repository in %s.', a_bzrdir.transport.base)
1248
dirs = ['revision-store', 'weaves']
1249
files = [('inventory.weave', StringIO(empty_weave)),
1251
utf8_files = [('format', self.get_format_string())]
1253
self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
1254
return self.open(a_bzrdir=a_bzrdir, _found=True)
1256
def open(self, a_bzrdir, _found=False, _override_transport=None):
1257
"""See RepositoryFormat.open().
1259
:param _override_transport: INTERNAL USE ONLY. Allows opening the
1260
repository at a slightly different url
1261
than normal. I.e. during 'upgrade'.
1264
format = RepositoryFormat.find_format(a_bzrdir)
1265
assert format.__class__ == self.__class__
1266
if _override_transport is not None:
1267
repo_transport = _override_transport
1269
repo_transport = a_bzrdir.get_repository_transport(None)
1270
control_files = LockableFiles(repo_transport, 'lock', LockDir)
1271
text_store = self._get_text_store(repo_transport, control_files)
1272
control_store = self._get_control_store(repo_transport, control_files)
1273
_revision_store = self._get_revision_store(repo_transport, control_files)
1274
return MetaDirRepository(_format=self,
1276
control_files=control_files,
1277
_revision_store=_revision_store,
1278
control_store=control_store,
1279
text_store=text_store)
1282
class RepositoryFormatKnit1(MetaDirRepositoryFormat):
1283
"""Bzr repository knit format 1.
1285
This repository format has:
1286
- knits for file texts and inventory
1287
- hash subdirectory based stores.
1288
- knits for revisions and signatures
1289
- TextStores for revisions and signatures.
1290
- a format marker of its own
1291
- an optional 'shared-storage' flag
1292
- an optional 'no-working-trees' flag
1295
This format was introduced in bzr 0.8.
1298
def _get_control_store(self, repo_transport, control_files):
1299
"""Return the control store for this repository."""
1300
return VersionedFileStore(
1303
file_mode=control_files._file_mode,
1304
versionedfile_class=KnitVersionedFile,
1305
versionedfile_kwargs={'factory':KnitPlainFactory()},
1308
def get_format_string(self):
1309
"""See RepositoryFormat.get_format_string()."""
1310
return "Bazaar-NG Knit Repository Format 1"
1312
def get_format_description(self):
1313
"""See RepositoryFormat.get_format_description()."""
1314
return "Knit repository format 1"
1316
def _get_revision_store(self, repo_transport, control_files):
1317
"""See RepositoryFormat._get_revision_store()."""
1318
from bzrlib.store.revision.knit import KnitRevisionStore
1319
versioned_file_store = VersionedFileStore(
1321
file_mode=control_files._file_mode,
1324
versionedfile_class=KnitVersionedFile,
1325
versionedfile_kwargs={'delta':False, 'factory':KnitPlainFactory()},
1328
return KnitRevisionStore(versioned_file_store)
1330
def _get_text_store(self, transport, control_files):
1331
"""See RepositoryFormat._get_text_store()."""
1332
return self._get_versioned_file_store('knits',
1335
versionedfile_class=KnitVersionedFile,
1338
def initialize(self, a_bzrdir, shared=False):
1339
"""Create a knit format 1 repository.
1341
:param a_bzrdir: bzrdir to contain the new repository; must already
1343
:param shared: If true the repository will be initialized as a shared
1346
mutter('creating repository in %s.', a_bzrdir.transport.base)
1347
dirs = ['revision-store', 'knits']
1349
utf8_files = [('format', self.get_format_string())]
1351
self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
1352
repo_transport = a_bzrdir.get_repository_transport(None)
1353
control_files = LockableFiles(repo_transport, 'lock', LockDir)
1354
control_store = self._get_control_store(repo_transport, control_files)
1355
transaction = bzrlib.transactions.WriteTransaction()
1356
# trigger a write of the inventory store.
1357
control_store.get_weave_or_empty('inventory', transaction)
1358
_revision_store = self._get_revision_store(repo_transport, control_files)
1359
_revision_store.has_revision_id('A', transaction)
1360
_revision_store.get_signature_file(transaction)
1361
return self.open(a_bzrdir=a_bzrdir, _found=True)
1363
def open(self, a_bzrdir, _found=False, _override_transport=None):
1364
"""See RepositoryFormat.open().
1366
:param _override_transport: INTERNAL USE ONLY. Allows opening the
1367
repository at a slightly different url
1368
than normal. I.e. during 'upgrade'.
1371
format = RepositoryFormat.find_format(a_bzrdir)
1372
assert format.__class__ == self.__class__
1373
if _override_transport is not None:
1374
repo_transport = _override_transport
1376
repo_transport = a_bzrdir.get_repository_transport(None)
1377
control_files = LockableFiles(repo_transport, 'lock', LockDir)
1378
text_store = self._get_text_store(repo_transport, control_files)
1379
control_store = self._get_control_store(repo_transport, control_files)
1380
_revision_store = self._get_revision_store(repo_transport, control_files)
1381
return KnitRepository(_format=self,
1383
control_files=control_files,
1384
_revision_store=_revision_store,
1385
control_store=control_store,
1386
text_store=text_store)
1389
# formats which have no format string are not discoverable
1390
# and not independently creatable, so are not registered.
1391
RepositoryFormat.register_format(RepositoryFormat7())
1392
_default_format = RepositoryFormatKnit1()
1393
RepositoryFormat.register_format(_default_format)
1394
RepositoryFormat.set_default_format(_default_format)
1395
_legacy_formats = [RepositoryFormat4(),
1396
RepositoryFormat5(),
1397
RepositoryFormat6()]
1400
class InterRepository(InterObject):
1401
"""This class represents operations taking place between two repositories.
1403
Its instances have methods like copy_content and fetch, and contain
1404
references to the source and target repositories these operations can be
1407
Often we will provide convenience methods on 'repository' which carry out
1408
operations with another repository - they will always forward to
1409
InterRepository.get(other).method_name(parameters).
1413
"""The available optimised InterRepository types."""
1416
def copy_content(self, revision_id=None, basis=None):
1417
"""Make a complete copy of the content in self into destination.
1419
This is a destructive operation! Do not use it on existing
1422
:param revision_id: Only copy the content needed to construct
1423
revision_id and its parents.
1424
:param basis: Copy the needed data preferentially from basis.
1427
self.target.set_make_working_trees(self.source.make_working_trees())
1428
except NotImplementedError:
1430
# grab the basis available data
1431
if basis is not None:
1432
self.target.fetch(basis, revision_id=revision_id)
1433
# but dont bother fetching if we have the needed data now.
1434
if (revision_id not in (None, NULL_REVISION) and
1435
self.target.has_revision(revision_id)):
1437
self.target.fetch(self.source, revision_id=revision_id)
1439
def _double_lock(self, lock_source, lock_target):
1440
"""Take out too locks, rolling back the first if the second throws."""
1445
# we want to ensure that we don't leave source locked by mistake.
1446
# and any error on target should not confuse source.
1447
self.source.unlock()
1451
def fetch(self, revision_id=None, pb=None):
1452
"""Fetch the content required to construct revision_id.
1454
The content is copied from source to target.
1456
:param revision_id: if None all content is copied, if NULL_REVISION no
1458
:param pb: optional progress bar to use for progress reports. If not
1459
provided a default one will be created.
1461
Returns the copied revision count and the failed revisions in a tuple:
1464
from bzrlib.fetch import GenericRepoFetcher
1465
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1466
self.source, self.source._format, self.target, self.target._format)
1467
f = GenericRepoFetcher(to_repository=self.target,
1468
from_repository=self.source,
1469
last_revision=revision_id,
1471
return f.count_copied, f.failed_revisions
1473
def lock_read(self):
1474
"""Take out a logical read lock.
1476
This will lock the source branch and the target branch. The source gets
1477
a read lock and the target a read lock.
1479
self._double_lock(self.source.lock_read, self.target.lock_read)
1481
def lock_write(self):
1482
"""Take out a logical write lock.
1484
This will lock the source branch and the target branch. The source gets
1485
a read lock and the target a write lock.
1487
self._double_lock(self.source.lock_read, self.target.lock_write)
1490
def missing_revision_ids(self, revision_id=None):
1491
"""Return the revision ids that source has that target does not.
1493
These are returned in topological order.
1495
:param revision_id: only return revision ids included by this
1498
# generic, possibly worst case, slow code path.
1499
target_ids = set(self.target.all_revision_ids())
1500
if revision_id is not None:
1501
source_ids = self.source.get_ancestry(revision_id)
1502
assert source_ids.pop(0) == None
1504
source_ids = self.source.all_revision_ids()
1505
result_set = set(source_ids).difference(target_ids)
1506
# this may look like a no-op: its not. It preserves the ordering
1507
# other_ids had while only returning the members from other_ids
1508
# that we've decided we need.
1509
return [rev_id for rev_id in source_ids if rev_id in result_set]
1512
"""Release the locks on source and target."""
1514
self.target.unlock()
1516
self.source.unlock()
1519
class InterWeaveRepo(InterRepository):
1520
"""Optimised code paths between Weave based repositories."""
1522
_matching_repo_format = RepositoryFormat7()
1523
"""Repository format for testing with."""
1526
def is_compatible(source, target):
1527
"""Be compatible with known Weave formats.
1529
We dont test for the stores being of specific types becase that
1530
could lead to confusing results, and there is no need to be
1534
return (isinstance(source._format, (RepositoryFormat5,
1536
RepositoryFormat7)) and
1537
isinstance(target._format, (RepositoryFormat5,
1539
RepositoryFormat7)))
1540
except AttributeError:
1544
def copy_content(self, revision_id=None, basis=None):
1545
"""See InterRepository.copy_content()."""
1546
# weave specific optimised path:
1547
if basis is not None:
1548
# copy the basis in, then fetch remaining data.
1549
basis.copy_content_into(self.target, revision_id)
1550
# the basis copy_content_into could misset this.
1552
self.target.set_make_working_trees(self.source.make_working_trees())
1553
except NotImplementedError:
1555
self.target.fetch(self.source, revision_id=revision_id)
1558
self.target.set_make_working_trees(self.source.make_working_trees())
1559
except NotImplementedError:
1561
# FIXME do not peek!
1562
if self.source.control_files._transport.listable():
1563
pb = bzrlib.ui.ui_factory.nested_progress_bar()
1565
self.target.weave_store.copy_all_ids(
1566
self.source.weave_store,
1568
from_transaction=self.source.get_transaction(),
1569
to_transaction=self.target.get_transaction())
1570
pb.update('copying inventory', 0, 1)
1571
self.target.control_weaves.copy_multi(
1572
self.source.control_weaves, ['inventory'],
1573
from_transaction=self.source.get_transaction(),
1574
to_transaction=self.target.get_transaction())
1575
self.target._revision_store.text_store.copy_all_ids(
1576
self.source._revision_store.text_store,
1581
self.target.fetch(self.source, revision_id=revision_id)
1584
def fetch(self, revision_id=None, pb=None):
1585
"""See InterRepository.fetch()."""
1586
from bzrlib.fetch import GenericRepoFetcher
1587
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1588
self.source, self.source._format, self.target, self.target._format)
1589
f = GenericRepoFetcher(to_repository=self.target,
1590
from_repository=self.source,
1591
last_revision=revision_id,
1593
return f.count_copied, f.failed_revisions
1596
def missing_revision_ids(self, revision_id=None):
1597
"""See InterRepository.missing_revision_ids()."""
1598
# we want all revisions to satisfy revision_id in source.
1599
# but we dont want to stat every file here and there.
1600
# we want then, all revisions other needs to satisfy revision_id
1601
# checked, but not those that we have locally.
1602
# so the first thing is to get a subset of the revisions to
1603
# satisfy revision_id in source, and then eliminate those that
1604
# we do already have.
1605
# this is slow on high latency connection to self, but as as this
1606
# disk format scales terribly for push anyway due to rewriting
1607
# inventory.weave, this is considered acceptable.
1609
if revision_id is not None:
1610
source_ids = self.source.get_ancestry(revision_id)
1611
assert source_ids.pop(0) == None
1613
source_ids = self.source._all_possible_ids()
1614
source_ids_set = set(source_ids)
1615
# source_ids is the worst possible case we may need to pull.
1616
# now we want to filter source_ids against what we actually
1617
# have in target, but dont try to check for existence where we know
1618
# we do not have a revision as that would be pointless.
1619
target_ids = set(self.target._all_possible_ids())
1620
possibly_present_revisions = target_ids.intersection(source_ids_set)
1621
actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
1622
required_revisions = source_ids_set.difference(actually_present_revisions)
1623
required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
1624
if revision_id is not None:
1625
# we used get_ancestry to determine source_ids then we are assured all
1626
# revisions referenced are present as they are installed in topological order.
1627
# and the tip revision was validated by get_ancestry.
1628
return required_topo_revisions
1630
# if we just grabbed the possibly available ids, then
1631
# we only have an estimate of whats available and need to validate
1632
# that against the revision records.
1633
return self.source._eliminate_revisions_not_present(required_topo_revisions)
1636
class InterKnitRepo(InterRepository):
1637
"""Optimised code paths between Knit based repositories."""
1639
_matching_repo_format = RepositoryFormatKnit1()
1640
"""Repository format for testing with."""
1643
def is_compatible(source, target):
1644
"""Be compatible with known Knit formats.
1646
We dont test for the stores being of specific types becase that
1647
could lead to confusing results, and there is no need to be
1651
return (isinstance(source._format, (RepositoryFormatKnit1)) and
1652
isinstance(target._format, (RepositoryFormatKnit1)))
1653
except AttributeError:
1657
def fetch(self, revision_id=None, pb=None):
1658
"""See InterRepository.fetch()."""
1659
from bzrlib.fetch import KnitRepoFetcher
1660
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1661
self.source, self.source._format, self.target, self.target._format)
1662
f = KnitRepoFetcher(to_repository=self.target,
1663
from_repository=self.source,
1664
last_revision=revision_id,
1666
return f.count_copied, f.failed_revisions
1669
def missing_revision_ids(self, revision_id=None):
1670
"""See InterRepository.missing_revision_ids()."""
1671
if revision_id is not None:
1672
source_ids = self.source.get_ancestry(revision_id)
1673
assert source_ids.pop(0) == None
1675
source_ids = self.source._all_possible_ids()
1676
source_ids_set = set(source_ids)
1677
# source_ids is the worst possible case we may need to pull.
1678
# now we want to filter source_ids against what we actually
1679
# have in target, but dont try to check for existence where we know
1680
# we do not have a revision as that would be pointless.
1681
target_ids = set(self.target._all_possible_ids())
1682
possibly_present_revisions = target_ids.intersection(source_ids_set)
1683
actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
1684
required_revisions = source_ids_set.difference(actually_present_revisions)
1685
required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
1686
if revision_id is not None:
1687
# we used get_ancestry to determine source_ids then we are assured all
1688
# revisions referenced are present as they are installed in topological order.
1689
# and the tip revision was validated by get_ancestry.
1690
return required_topo_revisions
1692
# if we just grabbed the possibly available ids, then
1693
# we only have an estimate of whats available and need to validate
1694
# that against the revision records.
1695
return self.source._eliminate_revisions_not_present(required_topo_revisions)
1697
InterRepository.register_optimiser(InterWeaveRepo)
1698
InterRepository.register_optimiser(InterKnitRepo)
1701
class RepositoryTestProviderAdapter(object):
1702
"""A tool to generate a suite testing multiple repository formats at once.
1704
This is done by copying the test once for each transport and injecting
1705
the transport_server, transport_readonly_server, and bzrdir_format and
1706
repository_format classes into each copy. Each copy is also given a new id()
1707
to make it easy to identify.
1710
def __init__(self, transport_server, transport_readonly_server, formats):
1711
self._transport_server = transport_server
1712
self._transport_readonly_server = transport_readonly_server
1713
self._formats = formats
1715
def adapt(self, test):
1716
result = TestSuite()
1717
for repository_format, bzrdir_format in self._formats:
1718
new_test = deepcopy(test)
1719
new_test.transport_server = self._transport_server
1720
new_test.transport_readonly_server = self._transport_readonly_server
1721
new_test.bzrdir_format = bzrdir_format
1722
new_test.repository_format = repository_format
1723
def make_new_test_id():
1724
new_id = "%s(%s)" % (new_test.id(), repository_format.__class__.__name__)
1725
return lambda: new_id
1726
new_test.id = make_new_test_id()
1727
result.addTest(new_test)
1731
class InterRepositoryTestProviderAdapter(object):
1732
"""A tool to generate a suite testing multiple inter repository formats.
1734
This is done by copying the test once for each interrepo provider and injecting
1735
the transport_server, transport_readonly_server, repository_format and
1736
repository_to_format classes into each copy.
1737
Each copy is also given a new id() to make it easy to identify.
1740
def __init__(self, transport_server, transport_readonly_server, formats):
1741
self._transport_server = transport_server
1742
self._transport_readonly_server = transport_readonly_server
1743
self._formats = formats
1745
def adapt(self, test):
1746
result = TestSuite()
1747
for interrepo_class, repository_format, repository_format_to in self._formats:
1748
new_test = deepcopy(test)
1749
new_test.transport_server = self._transport_server
1750
new_test.transport_readonly_server = self._transport_readonly_server
1751
new_test.interrepo_class = interrepo_class
1752
new_test.repository_format = repository_format
1753
new_test.repository_format_to = repository_format_to
1754
def make_new_test_id():
1755
new_id = "%s(%s)" % (new_test.id(), interrepo_class.__name__)
1756
return lambda: new_id
1757
new_test.id = make_new_test_id()
1758
result.addTest(new_test)
1762
def default_test_list():
1763
"""Generate the default list of interrepo permutations to test."""
1765
# test the default InterRepository between format 6 and the current
1767
# XXX: robertc 20060220 reinstate this when there are two supported
1768
# formats which do not have an optimal code path between them.
1769
result.append((InterRepository,
1770
RepositoryFormat6(),
1771
RepositoryFormatKnit1()))
1772
for optimiser in InterRepository._optimisers:
1773
result.append((optimiser,
1774
optimiser._matching_repo_format,
1775
optimiser._matching_repo_format
1777
# if there are specific combinations we want to use, we can add them
1782
class CopyConverter(object):
1783
"""A repository conversion tool which just performs a copy of the content.
1785
This is slow but quite reliable.
1788
def __init__(self, target_format):
1789
"""Create a CopyConverter.
1791
:param target_format: The format the resulting repository should be.
1793
self.target_format = target_format
1795
def convert(self, repo, pb):
1796
"""Perform the conversion of to_convert, giving feedback via pb.
1798
:param to_convert: The disk object to convert.
1799
:param pb: a progress bar to use for progress information.
1804
# this is only useful with metadir layouts - separated repo content.
1805
# trigger an assertion if not such
1806
repo._format.get_format_string()
1807
self.repo_dir = repo.bzrdir
1808
self.step('Moving repository to repository.backup')
1809
self.repo_dir.transport.move('repository', 'repository.backup')
1810
backup_transport = self.repo_dir.transport.clone('repository.backup')
1811
self.source_repo = repo._format.open(self.repo_dir,
1813
_override_transport=backup_transport)
1814
self.step('Creating new repository')
1815
converted = self.target_format.initialize(self.repo_dir,
1816
self.source_repo.is_shared())
1817
converted.lock_write()
1819
self.step('Copying content into repository.')
1820
self.source_repo.copy_content_into(converted)
1823
self.step('Deleting old repository content.')
1824
self.repo_dir.transport.delete_tree('repository.backup')
1825
self.pb.note('repository converted')
1827
def step(self, message):
1828
"""Update the pb by a step."""
1830
self.pb.update(message, self.count, self.total)
1833
# Copied from xml.sax.saxutils
1834
def _unescape_xml(data):
1835
"""Unescape &, <, and > in a string of data.
1837
data = data.replace("<", "<")
1838
data = data.replace(">", ">")
1839
# must do ampersand last
1840
return data.replace("&", "&")