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
raise BzrError("%r is not present in revision %s" % (file, revno))
513
revno = self.revision_id_to_revno(revision_id)
514
except errors.NoSuchRevision:
515
# TODO: This should not be BzrError,
516
# but NoSuchFile doesn't fit either
517
raise BzrError('%r is not present in revision %s'
518
% (file, revision_id))
520
raise BzrError('%r is not present in revision %s'
522
tree.print_file(file_id)
524
def get_transaction(self):
525
return self.control_files.get_transaction()
527
def revision_parents(self, revid):
528
return self.get_inventory_weave().parent_names(revid)
531
def set_make_working_trees(self, new_value):
532
"""Set the policy flag for making working trees when creating branches.
534
This only applies to branches that use this repository.
536
The default is 'True'.
537
:param new_value: True to restore the default, False to disable making
540
raise NotImplementedError(self.set_make_working_trees)
542
def make_working_trees(self):
543
"""Returns the policy for making working trees on new branches."""
544
raise NotImplementedError(self.make_working_trees)
547
def sign_revision(self, revision_id, gpg_strategy):
548
plaintext = Testament.from_revision(self, revision_id).as_short_text()
549
self.store_revision_signature(gpg_strategy, plaintext, revision_id)
552
def has_signature_for_revision_id(self, revision_id):
553
"""Query for a revision signature for revision_id in the repository."""
554
return self._revision_store.has_signature(revision_id,
555
self.get_transaction())
558
def get_signature_text(self, revision_id):
559
"""Return the text for a signature."""
560
return self._revision_store.get_signature_text(revision_id,
561
self.get_transaction())
564
class AllInOneRepository(Repository):
565
"""Legacy support - the repository behaviour for all-in-one branches."""
567
def __init__(self, _format, a_bzrdir, _revision_store, control_store, text_store):
568
# we reuse one control files instance.
569
dir_mode = a_bzrdir._control_files._dir_mode
570
file_mode = a_bzrdir._control_files._file_mode
572
def get_store(name, compressed=True, prefixed=False):
573
# FIXME: This approach of assuming stores are all entirely compressed
574
# or entirely uncompressed is tidy, but breaks upgrade from
575
# some existing branches where there's a mixture; we probably
576
# still want the option to look for both.
577
relpath = a_bzrdir._control_files._escape(name)
578
store = TextStore(a_bzrdir._control_files._transport.clone(relpath),
579
prefixed=prefixed, compressed=compressed,
582
#if self._transport.should_cache():
583
# cache_path = os.path.join(self.cache_root, name)
584
# os.mkdir(cache_path)
585
# store = bzrlib.store.CachedStore(store, cache_path)
588
# not broken out yet because the controlweaves|inventory_store
589
# and text_store | weave_store bits are still different.
590
if isinstance(_format, RepositoryFormat4):
591
# cannot remove these - there is still no consistent api
592
# which allows access to this old info.
593
self.inventory_store = get_store('inventory-store')
594
text_store = get_store('text-store')
595
super(AllInOneRepository, self).__init__(_format, a_bzrdir, a_bzrdir._control_files, _revision_store, control_store, text_store)
599
"""AllInOne repositories cannot be shared."""
603
def set_make_working_trees(self, new_value):
604
"""Set the policy flag for making working trees when creating branches.
606
This only applies to branches that use this repository.
608
The default is 'True'.
609
:param new_value: True to restore the default, False to disable making
612
raise NotImplementedError(self.set_make_working_trees)
614
def make_working_trees(self):
615
"""Returns the policy for making working trees on new branches."""
619
def install_revision(repository, rev, revision_tree):
620
"""Install all revision data into a repository."""
623
for p_id in rev.parent_ids:
624
if repository.has_revision(p_id):
625
present_parents.append(p_id)
626
parent_trees[p_id] = repository.revision_tree(p_id)
628
parent_trees[p_id] = EmptyTree()
630
inv = revision_tree.inventory
632
# Add the texts that are not already present
633
for path, ie in inv.iter_entries():
634
w = repository.weave_store.get_weave_or_empty(ie.file_id,
635
repository.get_transaction())
636
if ie.revision not in w:
638
for revision, tree in parent_trees.iteritems():
639
if ie.file_id not in tree:
641
parent_id = tree.inventory[ie.file_id].revision
642
if parent_id in text_parents:
644
text_parents.append(parent_id)
646
vfile = repository.weave_store.get_weave_or_empty(ie.file_id,
647
repository.get_transaction())
648
lines = revision_tree.get_file(ie.file_id).readlines()
649
vfile.add_lines(rev.revision_id, text_parents, lines)
651
# install the inventory
652
repository.add_inventory(rev.revision_id, inv, present_parents)
653
except errors.RevisionAlreadyPresent:
655
repository.add_revision(rev.revision_id, rev, inv)
658
class MetaDirRepository(Repository):
659
"""Repositories in the new meta-dir layout."""
661
def __init__(self, _format, a_bzrdir, control_files, _revision_store, control_store, text_store):
662
super(MetaDirRepository, self).__init__(_format,
669
dir_mode = self.control_files._dir_mode
670
file_mode = self.control_files._file_mode
674
"""Return True if this repository is flagged as a shared repository."""
675
return self.control_files._transport.has('shared-storage')
678
def set_make_working_trees(self, new_value):
679
"""Set the policy flag for making working trees when creating branches.
681
This only applies to branches that use this repository.
683
The default is 'True'.
684
:param new_value: True to restore the default, False to disable making
689
self.control_files._transport.delete('no-working-trees')
690
except errors.NoSuchFile:
693
self.control_files.put_utf8('no-working-trees', '')
695
def make_working_trees(self):
696
"""Returns the policy for making working trees on new branches."""
697
return not self.control_files._transport.has('no-working-trees')
700
class KnitRepository(MetaDirRepository):
701
"""Knit format repository."""
704
def all_revision_ids(self):
705
"""See Repository.all_revision_ids()."""
706
return self._revision_store.all_revision_ids(self.get_transaction())
708
def fileid_involved_between_revs(self, from_revid, to_revid):
709
"""Find file_id(s) which are involved in the changes between revisions.
711
This determines the set of revisions which are involved, and then
712
finds all file ids affected by those revisions.
714
vf = self._get_revision_vf()
715
from_set = set(vf.get_ancestry(from_revid))
716
to_set = set(vf.get_ancestry(to_revid))
717
changed = to_set.difference(from_set)
718
return self._fileid_involved_by_set(changed)
720
def fileid_involved(self, last_revid=None):
721
"""Find all file_ids modified in the ancestry of last_revid.
723
:param last_revid: If None, last_revision() will be used.
726
changed = set(self.all_revision_ids())
728
changed = set(self.get_ancestry(last_revid))
731
return self._fileid_involved_by_set(changed)
734
def get_ancestry(self, revision_id):
735
"""Return a list of revision-ids integrated by a revision.
737
This is topologically sorted.
739
if revision_id is None:
741
vf = self._get_revision_vf()
743
return [None] + vf.get_ancestry(revision_id)
744
except errors.RevisionNotPresent:
745
raise errors.NoSuchRevision(self, revision_id)
748
def get_revision(self, revision_id):
749
"""Return the Revision object for a named revision"""
750
return self.get_revision_reconcile(revision_id)
753
def get_revision_graph(self, revision_id=None):
754
"""Return a dictionary containing the revision graph.
756
:return: a dictionary of revision_id->revision_parents_list.
758
weave = self._get_revision_vf()
759
entire_graph = weave.get_graph()
760
if revision_id is None:
761
return weave.get_graph()
762
elif revision_id not in weave:
763
raise errors.NoSuchRevision(self, revision_id)
765
# add what can be reached from revision_id
767
pending = set([revision_id])
768
while len(pending) > 0:
770
result[node] = weave.get_parents(node)
771
for revision_id in result[node]:
772
if revision_id not in result:
773
pending.add(revision_id)
777
def get_revision_graph_with_ghosts(self, revision_ids=None):
778
"""Return a graph of the revisions with ghosts marked as applicable.
780
:param revision_ids: an iterable of revisions to graph or None for all.
781
:return: a Graph object with the graph reachable from revision_ids.
784
vf = self._get_revision_vf()
785
versions = set(vf.versions())
787
pending = set(self.all_revision_ids())
790
pending = set(revision_ids)
791
required = set(revision_ids)
794
revision_id = pending.pop()
795
if not revision_id in versions:
796
if revision_id in required:
797
raise errors.NoSuchRevision(self, revision_id)
799
result.add_ghost(revision_id)
800
# mark it as done so we dont try for it again.
801
done.add(revision_id)
803
parent_ids = vf.get_parents_with_ghosts(revision_id)
804
for parent_id in parent_ids:
805
# is this queued or done ?
806
if (parent_id not in pending and
807
parent_id not in done):
809
pending.add(parent_id)
810
result.add_node(revision_id, parent_ids)
811
done.add(revision_id)
814
def _get_revision_vf(self):
815
""":return: a versioned file containing the revisions."""
816
vf = self._revision_store.get_revision_file(self.get_transaction())
820
def reconcile(self, other=None, thorough=False):
821
"""Reconcile this repository."""
822
from bzrlib.reconcile import KnitReconciler
823
reconciler = KnitReconciler(self, thorough=thorough)
824
reconciler.reconcile()
827
def revision_parents(self, revid):
828
return self._get_revision_vf().get_parents(rev_id)
830
class RepositoryFormat(object):
831
"""A repository format.
833
Formats provide three things:
834
* An initialization routine to construct repository data on disk.
835
* a format string which is used when the BzrDir supports versioned
837
* an open routine which returns a Repository instance.
839
Formats are placed in an dict by their format string for reference
840
during opening. These should be subclasses of RepositoryFormat
843
Once a format is deprecated, just deprecate the initialize and open
844
methods on the format class. Do not deprecate the object, as the
845
object will be created every system load.
847
Common instance attributes:
848
_matchingbzrdir - the bzrdir format that the repository format was
849
originally written to work with. This can be used if manually
850
constructing a bzrdir and repository, or more commonly for test suite
854
_default_format = None
855
"""The default format used for new repositories."""
858
"""The known formats."""
861
def find_format(klass, a_bzrdir):
862
"""Return the format for the repository object in a_bzrdir."""
864
transport = a_bzrdir.get_repository_transport(None)
865
format_string = transport.get("format").read()
866
return klass._formats[format_string]
867
except errors.NoSuchFile:
868
raise errors.NoRepositoryPresent(a_bzrdir)
870
raise errors.UnknownFormatError(format=format_string)
872
def _get_control_store(self, repo_transport, control_files):
873
"""Return the control store for this repository."""
874
raise NotImplementedError(self._get_control_store)
877
def get_default_format(klass):
878
"""Return the current default format."""
879
return klass._default_format
881
def get_format_string(self):
882
"""Return the ASCII format string that identifies this format.
884
Note that in pre format ?? repositories the format string is
885
not permitted nor written to disk.
887
raise NotImplementedError(self.get_format_string)
889
def get_format_description(self):
890
"""Return the short desciption for this format."""
891
raise NotImplementedError(self.get_format_description)
893
def _get_revision_store(self, repo_transport, control_files):
894
"""Return the revision store object for this a_bzrdir."""
895
raise NotImplementedError(self._get_revision_store)
897
def _get_text_rev_store(self,
904
"""Common logic for getting a revision store for a repository.
906
see self._get_revision_store for the subclass-overridable method to
907
get the store for a repository.
909
from bzrlib.store.revision.text import TextRevisionStore
910
dir_mode = control_files._dir_mode
911
file_mode = control_files._file_mode
912
text_store =TextStore(transport.clone(name),
914
compressed=compressed,
917
_revision_store = TextRevisionStore(text_store, serializer)
918
return _revision_store
920
def _get_versioned_file_store(self,
925
versionedfile_class=WeaveFile,
927
weave_transport = control_files._transport.clone(name)
928
dir_mode = control_files._dir_mode
929
file_mode = control_files._file_mode
930
return VersionedFileStore(weave_transport, prefixed=prefixed,
933
versionedfile_class=versionedfile_class,
936
def initialize(self, a_bzrdir, shared=False):
937
"""Initialize a repository of this format in a_bzrdir.
939
:param a_bzrdir: The bzrdir to put the new repository in it.
940
:param shared: The repository should be initialized as a sharable one.
942
This may raise UninitializableFormat if shared repository are not
943
compatible the a_bzrdir.
946
def is_supported(self):
947
"""Is this format supported?
949
Supported formats must be initializable and openable.
950
Unsupported formats may not support initialization or committing or
951
some other features depending on the reason for not being supported.
955
def open(self, a_bzrdir, _found=False):
956
"""Return an instance of this format for the bzrdir a_bzrdir.
958
_found is a private parameter, do not use it.
960
raise NotImplementedError(self.open)
963
def register_format(klass, format):
964
klass._formats[format.get_format_string()] = format
967
def set_default_format(klass, format):
968
klass._default_format = format
971
def unregister_format(klass, format):
972
assert klass._formats[format.get_format_string()] is format
973
del klass._formats[format.get_format_string()]
976
class PreSplitOutRepositoryFormat(RepositoryFormat):
977
"""Base class for the pre split out repository formats."""
979
def initialize(self, a_bzrdir, shared=False, _internal=False):
980
"""Create a weave repository.
982
TODO: when creating split out bzr branch formats, move this to a common
983
base for Format5, Format6. or something like that.
985
from bzrlib.weavefile import write_weave_v5
986
from bzrlib.weave import Weave
989
raise errors.IncompatibleFormat(self, a_bzrdir._format)
992
# always initialized when the bzrdir is.
993
return self.open(a_bzrdir, _found=True)
995
# Create an empty weave
997
bzrlib.weavefile.write_weave_v5(Weave(), sio)
998
empty_weave = sio.getvalue()
1000
mutter('creating repository in %s.', a_bzrdir.transport.base)
1001
dirs = ['revision-store', 'weaves']
1002
files = [('inventory.weave', StringIO(empty_weave)),
1005
# FIXME: RBC 20060125 dont peek under the covers
1006
# NB: no need to escape relative paths that are url safe.
1007
control_files = LockableFiles(a_bzrdir.transport, 'branch-lock',
1009
control_files.create_lock()
1010
control_files.lock_write()
1011
control_files._transport.mkdir_multi(dirs,
1012
mode=control_files._dir_mode)
1014
for file, content in files:
1015
control_files.put(file, content)
1017
control_files.unlock()
1018
return self.open(a_bzrdir, _found=True)
1020
def _get_control_store(self, repo_transport, control_files):
1021
"""Return the control store for this repository."""
1022
return self._get_versioned_file_store('',
1027
def _get_text_store(self, transport, control_files):
1028
"""Get a store for file texts for this format."""
1029
raise NotImplementedError(self._get_text_store)
1031
def open(self, a_bzrdir, _found=False):
1032
"""See RepositoryFormat.open()."""
1034
# we are being called directly and must probe.
1035
raise NotImplementedError
1037
repo_transport = a_bzrdir.get_repository_transport(None)
1038
control_files = a_bzrdir._control_files
1039
text_store = self._get_text_store(repo_transport, control_files)
1040
control_store = self._get_control_store(repo_transport, control_files)
1041
_revision_store = self._get_revision_store(repo_transport, control_files)
1042
return AllInOneRepository(_format=self,
1044
_revision_store=_revision_store,
1045
control_store=control_store,
1046
text_store=text_store)
1049
class RepositoryFormat4(PreSplitOutRepositoryFormat):
1050
"""Bzr repository format 4.
1052
This repository format has:
1054
- TextStores for texts, inventories,revisions.
1056
This format is deprecated: it indexes texts using a text id which is
1057
removed in format 5; initializationa and write support for this format
1062
super(RepositoryFormat4, self).__init__()
1063
self._matchingbzrdir = bzrlib.bzrdir.BzrDirFormat4()
1065
def get_format_description(self):
1066
"""See RepositoryFormat.get_format_description()."""
1067
return "Repository format 4"
1069
def initialize(self, url, shared=False, _internal=False):
1070
"""Format 4 branches cannot be created."""
1071
raise errors.UninitializableFormat(self)
1073
def is_supported(self):
1074
"""Format 4 is not supported.
1076
It is not supported because the model changed from 4 to 5 and the
1077
conversion logic is expensive - so doing it on the fly was not
1082
def _get_control_store(self, repo_transport, control_files):
1083
"""Format 4 repositories have no formal control store at this point.
1085
This will cause any control-file-needing apis to fail - this is desired.
1089
def _get_revision_store(self, repo_transport, control_files):
1090
"""See RepositoryFormat._get_revision_store()."""
1091
from bzrlib.xml4 import serializer_v4
1092
return self._get_text_rev_store(repo_transport,
1095
serializer=serializer_v4)
1097
def _get_text_store(self, transport, control_files):
1098
"""See RepositoryFormat._get_text_store()."""
1101
class RepositoryFormat5(PreSplitOutRepositoryFormat):
1102
"""Bzr control format 5.
1104
This repository format has:
1105
- weaves for file texts and inventory
1107
- TextStores for revisions and signatures.
1111
super(RepositoryFormat5, self).__init__()
1112
self._matchingbzrdir = bzrlib.bzrdir.BzrDirFormat5()
1114
def get_format_description(self):
1115
"""See RepositoryFormat.get_format_description()."""
1116
return "Weave repository format 5"
1118
def _get_revision_store(self, repo_transport, control_files):
1119
"""See RepositoryFormat._get_revision_store()."""
1120
"""Return the revision store object for this a_bzrdir."""
1121
return self._get_text_rev_store(repo_transport,
1126
def _get_text_store(self, transport, control_files):
1127
"""See RepositoryFormat._get_text_store()."""
1128
return self._get_versioned_file_store('weaves', transport, control_files, prefixed=False)
1131
class RepositoryFormat6(PreSplitOutRepositoryFormat):
1132
"""Bzr control format 6.
1134
This repository format has:
1135
- weaves for file texts and inventory
1136
- hash subdirectory based stores.
1137
- TextStores for revisions and signatures.
1141
super(RepositoryFormat6, self).__init__()
1142
self._matchingbzrdir = bzrlib.bzrdir.BzrDirFormat6()
1144
def get_format_description(self):
1145
"""See RepositoryFormat.get_format_description()."""
1146
return "Weave repository format 6"
1148
def _get_revision_store(self, repo_transport, control_files):
1149
"""See RepositoryFormat._get_revision_store()."""
1150
return self._get_text_rev_store(repo_transport,
1156
def _get_text_store(self, transport, control_files):
1157
"""See RepositoryFormat._get_text_store()."""
1158
return self._get_versioned_file_store('weaves', transport, control_files)
1161
class MetaDirRepositoryFormat(RepositoryFormat):
1162
"""Common base class for the new repositories using the metadir layour."""
1165
super(MetaDirRepositoryFormat, self).__init__()
1166
self._matchingbzrdir = bzrlib.bzrdir.BzrDirMetaFormat1()
1168
def _create_control_files(self, a_bzrdir):
1169
"""Create the required files and the initial control_files object."""
1170
# FIXME: RBC 20060125 dont peek under the covers
1171
# NB: no need to escape relative paths that are url safe.
1172
repository_transport = a_bzrdir.get_repository_transport(self)
1173
control_files = LockableFiles(repository_transport, 'lock', LockDir)
1174
control_files.create_lock()
1175
return control_files
1177
def _upload_blank_content(self, a_bzrdir, dirs, files, utf8_files, shared):
1178
"""Upload the initial blank content."""
1179
control_files = self._create_control_files(a_bzrdir)
1180
control_files.lock_write()
1182
control_files._transport.mkdir_multi(dirs,
1183
mode=control_files._dir_mode)
1184
for file, content in files:
1185
control_files.put(file, content)
1186
for file, content in utf8_files:
1187
control_files.put_utf8(file, content)
1189
control_files.put_utf8('shared-storage', '')
1191
control_files.unlock()
1194
class RepositoryFormat7(MetaDirRepositoryFormat):
1195
"""Bzr repository 7.
1197
This repository format has:
1198
- weaves for file texts and inventory
1199
- hash subdirectory based stores.
1200
- TextStores for revisions and signatures.
1201
- a format marker of its own
1202
- an optional 'shared-storage' flag
1203
- an optional 'no-working-trees' flag
1206
def _get_control_store(self, repo_transport, control_files):
1207
"""Return the control store for this repository."""
1208
return self._get_versioned_file_store('',
1213
def get_format_string(self):
1214
"""See RepositoryFormat.get_format_string()."""
1215
return "Bazaar-NG Repository format 7"
1217
def get_format_description(self):
1218
"""See RepositoryFormat.get_format_description()."""
1219
return "Weave repository format 7"
1221
def _get_revision_store(self, repo_transport, control_files):
1222
"""See RepositoryFormat._get_revision_store()."""
1223
return self._get_text_rev_store(repo_transport,
1230
def _get_text_store(self, transport, control_files):
1231
"""See RepositoryFormat._get_text_store()."""
1232
return self._get_versioned_file_store('weaves',
1236
def initialize(self, a_bzrdir, shared=False):
1237
"""Create a weave repository.
1239
:param shared: If true the repository will be initialized as a shared
1242
from bzrlib.weavefile import write_weave_v5
1243
from bzrlib.weave import Weave
1245
# Create an empty weave
1247
bzrlib.weavefile.write_weave_v5(Weave(), sio)
1248
empty_weave = sio.getvalue()
1250
mutter('creating repository in %s.', a_bzrdir.transport.base)
1251
dirs = ['revision-store', 'weaves']
1252
files = [('inventory.weave', StringIO(empty_weave)),
1254
utf8_files = [('format', self.get_format_string())]
1256
self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
1257
return self.open(a_bzrdir=a_bzrdir, _found=True)
1259
def open(self, a_bzrdir, _found=False, _override_transport=None):
1260
"""See RepositoryFormat.open().
1262
:param _override_transport: INTERNAL USE ONLY. Allows opening the
1263
repository at a slightly different url
1264
than normal. I.e. during 'upgrade'.
1267
format = RepositoryFormat.find_format(a_bzrdir)
1268
assert format.__class__ == self.__class__
1269
if _override_transport is not None:
1270
repo_transport = _override_transport
1272
repo_transport = a_bzrdir.get_repository_transport(None)
1273
control_files = LockableFiles(repo_transport, 'lock', LockDir)
1274
text_store = self._get_text_store(repo_transport, control_files)
1275
control_store = self._get_control_store(repo_transport, control_files)
1276
_revision_store = self._get_revision_store(repo_transport, control_files)
1277
return MetaDirRepository(_format=self,
1279
control_files=control_files,
1280
_revision_store=_revision_store,
1281
control_store=control_store,
1282
text_store=text_store)
1285
class RepositoryFormatKnit1(MetaDirRepositoryFormat):
1286
"""Bzr repository knit format 1.
1288
This repository format has:
1289
- knits for file texts and inventory
1290
- hash subdirectory based stores.
1291
- knits for revisions and signatures
1292
- TextStores for revisions and signatures.
1293
- a format marker of its own
1294
- an optional 'shared-storage' flag
1295
- an optional 'no-working-trees' flag
1298
This format was introduced in bzr 0.8.
1301
def _get_control_store(self, repo_transport, control_files):
1302
"""Return the control store for this repository."""
1303
return VersionedFileStore(
1306
file_mode=control_files._file_mode,
1307
versionedfile_class=KnitVersionedFile,
1308
versionedfile_kwargs={'factory':KnitPlainFactory()},
1311
def get_format_string(self):
1312
"""See RepositoryFormat.get_format_string()."""
1313
return "Bazaar-NG Knit Repository Format 1"
1315
def get_format_description(self):
1316
"""See RepositoryFormat.get_format_description()."""
1317
return "Knit repository format 1"
1319
def _get_revision_store(self, repo_transport, control_files):
1320
"""See RepositoryFormat._get_revision_store()."""
1321
from bzrlib.store.revision.knit import KnitRevisionStore
1322
versioned_file_store = VersionedFileStore(
1324
file_mode=control_files._file_mode,
1327
versionedfile_class=KnitVersionedFile,
1328
versionedfile_kwargs={'delta':False, 'factory':KnitPlainFactory()},
1331
return KnitRevisionStore(versioned_file_store)
1333
def _get_text_store(self, transport, control_files):
1334
"""See RepositoryFormat._get_text_store()."""
1335
return self._get_versioned_file_store('knits',
1338
versionedfile_class=KnitVersionedFile,
1341
def initialize(self, a_bzrdir, shared=False):
1342
"""Create a knit format 1 repository.
1344
:param a_bzrdir: bzrdir to contain the new repository; must already
1346
:param shared: If true the repository will be initialized as a shared
1349
mutter('creating repository in %s.', a_bzrdir.transport.base)
1350
dirs = ['revision-store', 'knits']
1352
utf8_files = [('format', self.get_format_string())]
1354
self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
1355
repo_transport = a_bzrdir.get_repository_transport(None)
1356
control_files = LockableFiles(repo_transport, 'lock', LockDir)
1357
control_store = self._get_control_store(repo_transport, control_files)
1358
transaction = bzrlib.transactions.WriteTransaction()
1359
# trigger a write of the inventory store.
1360
control_store.get_weave_or_empty('inventory', transaction)
1361
_revision_store = self._get_revision_store(repo_transport, control_files)
1362
_revision_store.has_revision_id('A', transaction)
1363
_revision_store.get_signature_file(transaction)
1364
return self.open(a_bzrdir=a_bzrdir, _found=True)
1366
def open(self, a_bzrdir, _found=False, _override_transport=None):
1367
"""See RepositoryFormat.open().
1369
:param _override_transport: INTERNAL USE ONLY. Allows opening the
1370
repository at a slightly different url
1371
than normal. I.e. during 'upgrade'.
1374
format = RepositoryFormat.find_format(a_bzrdir)
1375
assert format.__class__ == self.__class__
1376
if _override_transport is not None:
1377
repo_transport = _override_transport
1379
repo_transport = a_bzrdir.get_repository_transport(None)
1380
control_files = LockableFiles(repo_transport, 'lock', LockDir)
1381
text_store = self._get_text_store(repo_transport, control_files)
1382
control_store = self._get_control_store(repo_transport, control_files)
1383
_revision_store = self._get_revision_store(repo_transport, control_files)
1384
return KnitRepository(_format=self,
1386
control_files=control_files,
1387
_revision_store=_revision_store,
1388
control_store=control_store,
1389
text_store=text_store)
1392
# formats which have no format string are not discoverable
1393
# and not independently creatable, so are not registered.
1394
RepositoryFormat.register_format(RepositoryFormat7())
1395
_default_format = RepositoryFormatKnit1()
1396
RepositoryFormat.register_format(_default_format)
1397
RepositoryFormat.set_default_format(_default_format)
1398
_legacy_formats = [RepositoryFormat4(),
1399
RepositoryFormat5(),
1400
RepositoryFormat6()]
1403
class InterRepository(InterObject):
1404
"""This class represents operations taking place between two repositories.
1406
Its instances have methods like copy_content and fetch, and contain
1407
references to the source and target repositories these operations can be
1410
Often we will provide convenience methods on 'repository' which carry out
1411
operations with another repository - they will always forward to
1412
InterRepository.get(other).method_name(parameters).
1416
"""The available optimised InterRepository types."""
1419
def copy_content(self, revision_id=None, basis=None):
1420
"""Make a complete copy of the content in self into destination.
1422
This is a destructive operation! Do not use it on existing
1425
:param revision_id: Only copy the content needed to construct
1426
revision_id and its parents.
1427
:param basis: Copy the needed data preferentially from basis.
1430
self.target.set_make_working_trees(self.source.make_working_trees())
1431
except NotImplementedError:
1433
# grab the basis available data
1434
if basis is not None:
1435
self.target.fetch(basis, revision_id=revision_id)
1436
# but dont bother fetching if we have the needed data now.
1437
if (revision_id not in (None, NULL_REVISION) and
1438
self.target.has_revision(revision_id)):
1440
self.target.fetch(self.source, revision_id=revision_id)
1442
def _double_lock(self, lock_source, lock_target):
1443
"""Take out too locks, rolling back the first if the second throws."""
1448
# we want to ensure that we don't leave source locked by mistake.
1449
# and any error on target should not confuse source.
1450
self.source.unlock()
1454
def fetch(self, revision_id=None, pb=None):
1455
"""Fetch the content required to construct revision_id.
1457
The content is copied from source to target.
1459
:param revision_id: if None all content is copied, if NULL_REVISION no
1461
:param pb: optional progress bar to use for progress reports. If not
1462
provided a default one will be created.
1464
Returns the copied revision count and the failed revisions in a tuple:
1467
from bzrlib.fetch import GenericRepoFetcher
1468
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1469
self.source, self.source._format, self.target, self.target._format)
1470
f = GenericRepoFetcher(to_repository=self.target,
1471
from_repository=self.source,
1472
last_revision=revision_id,
1474
return f.count_copied, f.failed_revisions
1476
def lock_read(self):
1477
"""Take out a logical read lock.
1479
This will lock the source branch and the target branch. The source gets
1480
a read lock and the target a read lock.
1482
self._double_lock(self.source.lock_read, self.target.lock_read)
1484
def lock_write(self):
1485
"""Take out a logical write lock.
1487
This will lock the source branch and the target branch. The source gets
1488
a read lock and the target a write lock.
1490
self._double_lock(self.source.lock_read, self.target.lock_write)
1493
def missing_revision_ids(self, revision_id=None):
1494
"""Return the revision ids that source has that target does not.
1496
These are returned in topological order.
1498
:param revision_id: only return revision ids included by this
1501
# generic, possibly worst case, slow code path.
1502
target_ids = set(self.target.all_revision_ids())
1503
if revision_id is not None:
1504
source_ids = self.source.get_ancestry(revision_id)
1505
assert source_ids[0] == None
1508
source_ids = self.source.all_revision_ids()
1509
result_set = set(source_ids).difference(target_ids)
1510
# this may look like a no-op: its not. It preserves the ordering
1511
# other_ids had while only returning the members from other_ids
1512
# that we've decided we need.
1513
return [rev_id for rev_id in source_ids if rev_id in result_set]
1516
"""Release the locks on source and target."""
1518
self.target.unlock()
1520
self.source.unlock()
1523
class InterWeaveRepo(InterRepository):
1524
"""Optimised code paths between Weave based repositories."""
1526
_matching_repo_format = RepositoryFormat7()
1527
"""Repository format for testing with."""
1530
def is_compatible(source, target):
1531
"""Be compatible with known Weave formats.
1533
We dont test for the stores being of specific types becase that
1534
could lead to confusing results, and there is no need to be
1538
return (isinstance(source._format, (RepositoryFormat5,
1540
RepositoryFormat7)) and
1541
isinstance(target._format, (RepositoryFormat5,
1543
RepositoryFormat7)))
1544
except AttributeError:
1548
def copy_content(self, revision_id=None, basis=None):
1549
"""See InterRepository.copy_content()."""
1550
# weave specific optimised path:
1551
if basis is not None:
1552
# copy the basis in, then fetch remaining data.
1553
basis.copy_content_into(self.target, revision_id)
1554
# the basis copy_content_into could misset this.
1556
self.target.set_make_working_trees(self.source.make_working_trees())
1557
except NotImplementedError:
1559
self.target.fetch(self.source, revision_id=revision_id)
1562
self.target.set_make_working_trees(self.source.make_working_trees())
1563
except NotImplementedError:
1565
# FIXME do not peek!
1566
if self.source.control_files._transport.listable():
1567
pb = bzrlib.ui.ui_factory.nested_progress_bar()
1569
self.target.weave_store.copy_all_ids(
1570
self.source.weave_store,
1572
from_transaction=self.source.get_transaction(),
1573
to_transaction=self.target.get_transaction())
1574
pb.update('copying inventory', 0, 1)
1575
self.target.control_weaves.copy_multi(
1576
self.source.control_weaves, ['inventory'],
1577
from_transaction=self.source.get_transaction(),
1578
to_transaction=self.target.get_transaction())
1579
self.target._revision_store.text_store.copy_all_ids(
1580
self.source._revision_store.text_store,
1585
self.target.fetch(self.source, revision_id=revision_id)
1588
def fetch(self, revision_id=None, pb=None):
1589
"""See InterRepository.fetch()."""
1590
from bzrlib.fetch import GenericRepoFetcher
1591
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1592
self.source, self.source._format, self.target, self.target._format)
1593
f = GenericRepoFetcher(to_repository=self.target,
1594
from_repository=self.source,
1595
last_revision=revision_id,
1597
return f.count_copied, f.failed_revisions
1600
def missing_revision_ids(self, revision_id=None):
1601
"""See InterRepository.missing_revision_ids()."""
1602
# we want all revisions to satisfy revision_id in source.
1603
# but we dont want to stat every file here and there.
1604
# we want then, all revisions other needs to satisfy revision_id
1605
# checked, but not those that we have locally.
1606
# so the first thing is to get a subset of the revisions to
1607
# satisfy revision_id in source, and then eliminate those that
1608
# we do already have.
1609
# this is slow on high latency connection to self, but as as this
1610
# disk format scales terribly for push anyway due to rewriting
1611
# inventory.weave, this is considered acceptable.
1613
if revision_id is not None:
1614
source_ids = self.source.get_ancestry(revision_id)
1615
assert source_ids[0] == None
1618
source_ids = self.source._all_possible_ids()
1619
source_ids_set = set(source_ids)
1620
# source_ids is the worst possible case we may need to pull.
1621
# now we want to filter source_ids against what we actually
1622
# have in target, but dont try to check for existence where we know
1623
# we do not have a revision as that would be pointless.
1624
target_ids = set(self.target._all_possible_ids())
1625
possibly_present_revisions = target_ids.intersection(source_ids_set)
1626
actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
1627
required_revisions = source_ids_set.difference(actually_present_revisions)
1628
required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
1629
if revision_id is not None:
1630
# we used get_ancestry to determine source_ids then we are assured all
1631
# revisions referenced are present as they are installed in topological order.
1632
# and the tip revision was validated by get_ancestry.
1633
return required_topo_revisions
1635
# if we just grabbed the possibly available ids, then
1636
# we only have an estimate of whats available and need to validate
1637
# that against the revision records.
1638
return self.source._eliminate_revisions_not_present(required_topo_revisions)
1641
class InterKnitRepo(InterRepository):
1642
"""Optimised code paths between Knit based repositories."""
1644
_matching_repo_format = RepositoryFormatKnit1()
1645
"""Repository format for testing with."""
1648
def is_compatible(source, target):
1649
"""Be compatible with known Knit formats.
1651
We dont test for the stores being of specific types becase that
1652
could lead to confusing results, and there is no need to be
1656
return (isinstance(source._format, (RepositoryFormatKnit1)) and
1657
isinstance(target._format, (RepositoryFormatKnit1)))
1658
except AttributeError:
1662
def fetch(self, revision_id=None, pb=None):
1663
"""See InterRepository.fetch()."""
1664
from bzrlib.fetch import KnitRepoFetcher
1665
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1666
self.source, self.source._format, self.target, self.target._format)
1667
f = KnitRepoFetcher(to_repository=self.target,
1668
from_repository=self.source,
1669
last_revision=revision_id,
1671
return f.count_copied, f.failed_revisions
1674
def missing_revision_ids(self, revision_id=None):
1675
"""See InterRepository.missing_revision_ids()."""
1676
if revision_id is not None:
1677
source_ids = self.source.get_ancestry(revision_id)
1678
assert source_ids[0] == None
1681
source_ids = self.source._all_possible_ids()
1682
source_ids_set = set(source_ids)
1683
# source_ids is the worst possible case we may need to pull.
1684
# now we want to filter source_ids against what we actually
1685
# have in target, but dont try to check for existence where we know
1686
# we do not have a revision as that would be pointless.
1687
target_ids = set(self.target._all_possible_ids())
1688
possibly_present_revisions = target_ids.intersection(source_ids_set)
1689
actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
1690
required_revisions = source_ids_set.difference(actually_present_revisions)
1691
required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
1692
if revision_id is not None:
1693
# we used get_ancestry to determine source_ids then we are assured all
1694
# revisions referenced are present as they are installed in topological order.
1695
# and the tip revision was validated by get_ancestry.
1696
return required_topo_revisions
1698
# if we just grabbed the possibly available ids, then
1699
# we only have an estimate of whats available and need to validate
1700
# that against the revision records.
1701
return self.source._eliminate_revisions_not_present(required_topo_revisions)
1703
InterRepository.register_optimiser(InterWeaveRepo)
1704
InterRepository.register_optimiser(InterKnitRepo)
1707
class RepositoryTestProviderAdapter(object):
1708
"""A tool to generate a suite testing multiple repository formats at once.
1710
This is done by copying the test once for each transport and injecting
1711
the transport_server, transport_readonly_server, and bzrdir_format and
1712
repository_format classes into each copy. Each copy is also given a new id()
1713
to make it easy to identify.
1716
def __init__(self, transport_server, transport_readonly_server, formats):
1717
self._transport_server = transport_server
1718
self._transport_readonly_server = transport_readonly_server
1719
self._formats = formats
1721
def adapt(self, test):
1722
result = TestSuite()
1723
for repository_format, bzrdir_format in self._formats:
1724
new_test = deepcopy(test)
1725
new_test.transport_server = self._transport_server
1726
new_test.transport_readonly_server = self._transport_readonly_server
1727
new_test.bzrdir_format = bzrdir_format
1728
new_test.repository_format = repository_format
1729
def make_new_test_id():
1730
new_id = "%s(%s)" % (new_test.id(), repository_format.__class__.__name__)
1731
return lambda: new_id
1732
new_test.id = make_new_test_id()
1733
result.addTest(new_test)
1737
class InterRepositoryTestProviderAdapter(object):
1738
"""A tool to generate a suite testing multiple inter repository formats.
1740
This is done by copying the test once for each interrepo provider and injecting
1741
the transport_server, transport_readonly_server, repository_format and
1742
repository_to_format classes into each copy.
1743
Each copy is also given a new id() to make it easy to identify.
1746
def __init__(self, transport_server, transport_readonly_server, formats):
1747
self._transport_server = transport_server
1748
self._transport_readonly_server = transport_readonly_server
1749
self._formats = formats
1751
def adapt(self, test):
1752
result = TestSuite()
1753
for interrepo_class, repository_format, repository_format_to in self._formats:
1754
new_test = deepcopy(test)
1755
new_test.transport_server = self._transport_server
1756
new_test.transport_readonly_server = self._transport_readonly_server
1757
new_test.interrepo_class = interrepo_class
1758
new_test.repository_format = repository_format
1759
new_test.repository_format_to = repository_format_to
1760
def make_new_test_id():
1761
new_id = "%s(%s)" % (new_test.id(), interrepo_class.__name__)
1762
return lambda: new_id
1763
new_test.id = make_new_test_id()
1764
result.addTest(new_test)
1768
def default_test_list():
1769
"""Generate the default list of interrepo permutations to test."""
1771
# test the default InterRepository between format 6 and the current
1773
# XXX: robertc 20060220 reinstate this when there are two supported
1774
# formats which do not have an optimal code path between them.
1775
result.append((InterRepository,
1776
RepositoryFormat6(),
1777
RepositoryFormatKnit1()))
1778
for optimiser in InterRepository._optimisers:
1779
result.append((optimiser,
1780
optimiser._matching_repo_format,
1781
optimiser._matching_repo_format
1783
# if there are specific combinations we want to use, we can add them
1788
class CopyConverter(object):
1789
"""A repository conversion tool which just performs a copy of the content.
1791
This is slow but quite reliable.
1794
def __init__(self, target_format):
1795
"""Create a CopyConverter.
1797
:param target_format: The format the resulting repository should be.
1799
self.target_format = target_format
1801
def convert(self, repo, pb):
1802
"""Perform the conversion of to_convert, giving feedback via pb.
1804
:param to_convert: The disk object to convert.
1805
:param pb: a progress bar to use for progress information.
1810
# this is only useful with metadir layouts - separated repo content.
1811
# trigger an assertion if not such
1812
repo._format.get_format_string()
1813
self.repo_dir = repo.bzrdir
1814
self.step('Moving repository to repository.backup')
1815
self.repo_dir.transport.move('repository', 'repository.backup')
1816
backup_transport = self.repo_dir.transport.clone('repository.backup')
1817
self.source_repo = repo._format.open(self.repo_dir,
1819
_override_transport=backup_transport)
1820
self.step('Creating new repository')
1821
converted = self.target_format.initialize(self.repo_dir,
1822
self.source_repo.is_shared())
1823
converted.lock_write()
1825
self.step('Copying content into repository.')
1826
self.source_repo.copy_content_into(converted)
1829
self.step('Deleting old repository content.')
1830
self.repo_dir.transport.delete_tree('repository.backup')
1831
self.pb.note('repository converted')
1833
def step(self, message):
1834
"""Update the pb by a step."""
1836
self.pb.update(message, self.count, self.total)
1839
# Copied from xml.sax.saxutils
1840
def _unescape_xml(data):
1841
"""Unescape &, <, and > in a string of data.
1843
data = data.replace("<", "<")
1844
data = data.replace(">", ">")
1845
# must do ampersand last
1846
return data.replace("&", "&")