1
# Copyright (C) 2005 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
20
import xml.sax.saxutils
23
from bzrlib.decorators import needs_read_lock, needs_write_lock
24
import bzrlib.errors as errors
25
from bzrlib.errors import InvalidRevisionId
26
import bzrlib.gpg as gpg
27
from bzrlib.inter import InterObject
28
from bzrlib.knit import KnitVersionedFile
29
from bzrlib.lockable_files import LockableFiles
30
from bzrlib.osutils import safe_unicode
31
from bzrlib.revision import NULL_REVISION
32
from bzrlib.store.versioned import VersionedFileStore, WeaveStore
33
from bzrlib.store.text import TextStore
34
from bzrlib.symbol_versioning import *
35
from bzrlib.trace import mutter
36
from bzrlib.tree import RevisionTree
37
from bzrlib.tsort import topo_sort
38
from bzrlib.testament import Testament
39
from bzrlib.tree import EmptyTree
41
from bzrlib.weave import WeaveFile
45
class Repository(object):
46
"""Repository holding history for one or more branches.
48
The repository holds and retrieves historical information including
49
revisions and file history. It's normally accessed only by the Branch,
50
which views a particular line of development through that history.
52
The Repository builds on top of Stores and a Transport, which respectively
53
describe the disk data format and the way of accessing the (possibly
58
def add_inventory(self, revid, inv, parents):
59
"""Add the inventory inv to the repository as revid.
61
:param parents: The revision ids of the parents that revid
62
is known to have and are in the repository already.
64
returns the sha1 of the serialized inventory.
66
inv_text = bzrlib.xml5.serializer_v5.write_inventory_to_string(inv)
67
inv_sha1 = bzrlib.osutils.sha_string(inv_text)
68
inv_vf = self.control_weaves.get_weave('inventory',
69
self.get_transaction())
70
inv_vf.add_lines(revid, parents, bzrlib.osutils.split_lines(inv_text))
74
def add_revision(self, rev_id, rev, inv=None, config=None):
75
"""Add rev to the revision store as rev_id.
77
:param rev_id: the revision id to use.
78
:param rev: The revision object.
79
:param inv: The inventory for the revision. if None, it will be looked
80
up in the inventory storer
81
:param config: If None no digital signature will be created.
82
If supplied its signature_needed method will be used
83
to determine if a signature should be made.
85
if config is not None and config.signature_needed():
87
inv = self.get_inventory(rev_id)
88
plaintext = Testament(rev, inv).as_short_text()
89
self.store_revision_signature(
90
gpg.GPGStrategy(config), plaintext, rev_id)
91
if not rev_id in self.get_inventory_weave():
93
raise errors.WeaveRevisionNotPresent(rev_id,
94
self.get_inventory_weave())
96
# yes, this is not suitable for adding with ghosts.
97
self.add_inventory(rev_id, inv, rev.parent_ids)
98
self._revision_store.add_revision(rev, self.get_transaction())
101
def _all_possible_ids(self):
102
"""Return all the possible revisions that we could find."""
103
return self.get_inventory_weave().versions()
106
def all_revision_ids(self):
107
"""Returns a list of all the revision ids in the repository.
109
These are in as much topological order as the underlying store can
110
present: for weaves ghosts may lead to a lack of correctness until
111
the reweave updates the parents list.
113
if self._revision_store.text_store.listable():
114
return self._revision_store.all_revision_ids(self.get_transaction())
115
result = self._all_possible_ids()
116
return self._eliminate_revisions_not_present(result)
119
def _eliminate_revisions_not_present(self, revision_ids):
120
"""Check every revision id in revision_ids to see if we have it.
122
Returns a set of the present revisions.
125
for id in revision_ids:
126
if self.has_revision(id):
131
def create(a_bzrdir):
132
"""Construct the current default format repository in a_bzrdir."""
133
return RepositoryFormat.get_default_format().initialize(a_bzrdir)
135
def __init__(self, _format, a_bzrdir, control_files, _revision_store, control_store, text_store):
136
"""instantiate a Repository.
138
:param _format: The format of the repository on disk.
139
:param a_bzrdir: The BzrDir of the repository.
141
In the future we will have a single api for all stores for
142
getting file texts, inventories and revisions, then
143
this construct will accept instances of those things.
145
object.__init__(self)
146
self._format = _format
147
# the following are part of the public API for Repository:
148
self.bzrdir = a_bzrdir
149
self.control_files = control_files
150
# backwards compatible until we fully transition
151
self.revision_store = _revision_store.text_store
152
self._revision_store = _revision_store
153
self.text_store = text_store
154
# backwards compatability
155
self.weave_store = text_store
156
# not right yet - should be more semantically clear ?
158
self.control_store = control_store
159
self.control_weaves = control_store
161
def lock_write(self):
162
self.control_files.lock_write()
165
self.control_files.lock_read()
168
def missing_revision_ids(self, other, revision_id=None):
169
"""Return the revision ids that other has that this does not.
171
These are returned in topological order.
173
revision_id: only return revision ids included by revision_id.
175
return InterRepository.get(other, self).missing_revision_ids(revision_id)
179
"""Open the repository rooted at base.
181
For instance, if the repository is at URL/.bzr/repository,
182
Repository.open(URL) -> a Repository instance.
184
control = bzrlib.bzrdir.BzrDir.open(base)
185
return control.open_repository()
187
def copy_content_into(self, destination, revision_id=None, basis=None):
188
"""Make a complete copy of the content in self into destination.
190
This is a destructive operation! Do not use it on existing
193
return InterRepository.get(self, destination).copy_content(revision_id, basis)
195
def fetch(self, source, revision_id=None, pb=None):
196
"""Fetch the content required to construct revision_id from source.
198
If revision_id is None all content is copied.
200
return InterRepository.get(source, self).fetch(revision_id=revision_id,
204
self.control_files.unlock()
207
def clone(self, a_bzrdir, revision_id=None, basis=None):
208
"""Clone this repository into a_bzrdir using the current format.
210
Currently no check is made that the format of this repository and
211
the bzrdir format are compatible. FIXME RBC 20060201.
213
if not isinstance(a_bzrdir._format, self.bzrdir._format.__class__):
214
# use target default format.
215
result = a_bzrdir.create_repository()
216
# FIXME RBC 20060209 split out the repository type to avoid this check ?
217
elif isinstance(a_bzrdir._format,
218
(bzrlib.bzrdir.BzrDirFormat4,
219
bzrlib.bzrdir.BzrDirFormat5,
220
bzrlib.bzrdir.BzrDirFormat6)):
221
result = a_bzrdir.open_repository()
223
result = self._format.initialize(a_bzrdir, shared=self.is_shared())
224
self.copy_content_into(result, revision_id, basis)
228
def has_revision(self, revision_id):
229
"""True if this repository has a copy of the revision."""
230
return self._revision_store.has_revision_id(revision_id,
231
self.get_transaction())
234
def get_revision_reconcile(self, revision_id):
235
"""'reconcile' helper routine that allows access to a revision always.
237
This variant of get_revision does not cross check the weave graph
238
against the revision one as get_revision does: but it should only
239
be used by reconcile, or reconcile-alike commands that are correcting
240
or testing the revision graph.
242
if not revision_id or not isinstance(revision_id, basestring):
243
raise InvalidRevisionId(revision_id=revision_id, branch=self)
244
return self._revision_store.get_revision(revision_id,
245
self.get_transaction())
248
def get_revision_xml(self, revision_id):
249
rev = self.get_revision(revision_id)
251
# the current serializer..
252
self._revision_store._serializer.write_revision(rev, rev_tmp)
254
return rev_tmp.getvalue()
257
def get_revision(self, revision_id):
258
"""Return the Revision object for a named revision"""
259
r = self.get_revision_reconcile(revision_id)
260
# weave corruption can lead to absent revision markers that should be
262
# the following test is reasonably cheap (it needs a single weave read)
263
# and the weave is cached in read transactions. In write transactions
264
# it is not cached but typically we only read a small number of
265
# revisions. For knits when they are introduced we will probably want
266
# to ensure that caching write transactions are in use.
267
inv = self.get_inventory_weave()
268
self._check_revision_parents(r, inv)
271
def _check_revision_parents(self, revision, inventory):
272
"""Private to Repository and Fetch.
274
This checks the parentage of revision in an inventory weave for
275
consistency and is only applicable to inventory-weave-for-ancestry
276
using repository formats & fetchers.
278
weave_parents = inventory.get_parents(revision.revision_id)
279
weave_names = inventory.versions()
280
for parent_id in revision.parent_ids:
281
if parent_id in weave_names:
282
# this parent must not be a ghost.
283
if not parent_id in weave_parents:
285
raise errors.CorruptRepository(self)
288
def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
289
signature = gpg_strategy.sign(plaintext)
290
self._revision_store.add_revision_signature_text(revision_id,
292
self.get_transaction())
294
def fileid_involved_between_revs(self, from_revid, to_revid):
295
"""Find file_id(s) which are involved in the changes between revisions.
297
This determines the set of revisions which are involved, and then
298
finds all file ids affected by those revisions.
300
# TODO: jam 20060119 This code assumes that w.inclusions will
301
# always be correct. But because of the presence of ghosts
302
# it is possible to be wrong.
303
# One specific example from Robert Collins:
304
# Two branches, with revisions ABC, and AD
305
# C is a ghost merge of D.
306
# Inclusions doesn't recognize D as an ancestor.
307
# If D is ever merged in the future, the weave
308
# won't be fixed, because AD never saw revision C
309
# to cause a conflict which would force a reweave.
310
w = self.get_inventory_weave()
311
from_set = set(w.get_ancestry(from_revid))
312
to_set = set(w.get_ancestry(to_revid))
313
changed = to_set.difference(from_set)
314
return self._fileid_involved_by_set(changed)
316
def fileid_involved(self, last_revid=None):
317
"""Find all file_ids modified in the ancestry of last_revid.
319
:param last_revid: If None, last_revision() will be used.
321
w = self.get_inventory_weave()
323
changed = set(w.versions())
325
changed = set(w.get_ancestry(last_revid))
326
return self._fileid_involved_by_set(changed)
328
def fileid_involved_by_set(self, changes):
329
"""Find all file_ids modified by the set of revisions passed in.
331
:param changes: A set() of revision ids
333
# TODO: jam 20060119 This line does *nothing*, remove it.
334
# or better yet, change _fileid_involved_by_set so
335
# that it takes the inventory weave, rather than
336
# pulling it out by itself.
337
return self._fileid_involved_by_set(changes)
339
def _fileid_involved_by_set(self, changes):
340
"""Find the set of file-ids affected by the set of revisions.
342
:param changes: A set() of revision ids.
343
:return: A set() of file ids.
345
This peaks at the Weave, interpreting each line, looking to
346
see if it mentions one of the revisions. And if so, includes
347
the file id mentioned.
348
This expects both the Weave format, and the serialization
349
to have a single line per file/directory, and to have
350
fileid="" and revision="" on that line.
352
assert isinstance(self._format, (RepositoryFormat5,
355
RepositoryFormatKnit1)), \
356
"fileid_involved only supported for branches which store inventory as unnested xml"
358
w = self.get_inventory_weave()
360
for line in w._weave:
362
# it is ugly, but it is due to the weave structure
363
if not isinstance(line, basestring): continue
365
start = line.find('file_id="')+9
366
if start < 9: continue
367
end = line.find('"', start)
369
file_id = xml.sax.saxutils.unescape(line[start:end])
371
# check if file_id is already present
372
if file_id in file_ids: continue
374
start = line.find('revision="')+10
375
if start < 10: continue
376
end = line.find('"', start)
378
revision_id = xml.sax.saxutils.unescape(line[start:end])
380
if revision_id in changes:
381
file_ids.add(file_id)
385
def get_inventory_weave(self):
386
return self.control_weaves.get_weave('inventory',
387
self.get_transaction())
390
def get_inventory(self, revision_id):
391
"""Get Inventory object by hash."""
392
xml = self.get_inventory_xml(revision_id)
393
return bzrlib.xml5.serializer_v5.read_inventory_from_string(xml)
396
def get_inventory_xml(self, revision_id):
397
"""Get inventory XML as a file object."""
399
assert isinstance(revision_id, basestring), type(revision_id)
400
iw = self.get_inventory_weave()
401
return iw.get_text(revision_id)
403
raise bzrlib.errors.HistoryMissing(self, 'inventory', revision_id)
406
def get_inventory_sha1(self, revision_id):
407
"""Return the sha1 hash of the inventory entry
409
return self.get_revision(revision_id).inventory_sha1
412
def get_revision_graph(self, revision_id=None):
413
"""Return a dictionary containing the revision graph.
415
:return: a dictionary of revision_id->revision_parents_list.
417
weave = self.get_inventory_weave()
418
all_revisions = self._eliminate_revisions_not_present(weave.names())
419
entire_graph = dict([(node, weave.parent_names(node)) for
420
node in all_revisions])
421
if revision_id is None:
423
elif revision_id not in entire_graph:
424
raise errors.NoSuchRevision(self, revision_id)
426
# add what can be reached from revision_id
428
pending = set([revision_id])
429
while len(pending) > 0:
431
result[node] = entire_graph[node]
432
for revision_id in result[node]:
433
if revision_id not in result:
434
pending.add(revision_id)
438
def get_revision_inventory(self, revision_id):
439
"""Return inventory of a past revision."""
440
# TODO: Unify this with get_inventory()
441
# bzr 0.0.6 and later imposes the constraint that the inventory_id
442
# must be the same as its revision, so this is trivial.
443
if revision_id is None:
444
# This does not make sense: if there is no revision,
445
# then it is the current tree inventory surely ?!
446
# and thus get_root_id() is something that looks at the last
447
# commit on the branch, and the get_root_id is an inventory check.
448
raise NotImplementedError
449
# return Inventory(self.get_root_id())
451
return self.get_inventory(revision_id)
455
"""Return True if this repository is flagged as a shared repository."""
456
# FIXME format 4-6 cannot be shared, this is technically faulty.
457
return self.control_files._transport.has('shared-storage')
460
def revision_tree(self, revision_id):
461
"""Return Tree for a revision on this branch.
463
`revision_id` may be None for the null revision, in which case
464
an `EmptyTree` is returned."""
465
# TODO: refactor this to use an existing revision object
466
# so we don't need to read it in twice.
467
if revision_id is None or revision_id == NULL_REVISION:
470
inv = self.get_revision_inventory(revision_id)
471
return RevisionTree(self, inv, revision_id)
474
def get_ancestry(self, revision_id):
475
"""Return a list of revision-ids integrated by a revision.
477
This is topologically sorted.
479
if revision_id is None:
481
if not self.has_revision(revision_id):
482
raise errors.NoSuchRevision(self, revision_id)
483
w = self.get_inventory_weave()
484
return [None] + w.get_ancestry(revision_id)
487
def print_file(self, file, revision_id):
488
"""Print `file` to stdout.
490
FIXME RBC 20060125 as John Meinel points out this is a bad api
491
- it writes to stdout, it assumes that that is valid etc. Fix
492
by creating a new more flexible convenience function.
494
tree = self.revision_tree(revision_id)
495
# use inventory as it was in that revision
496
file_id = tree.inventory.path2id(file)
498
raise BzrError("%r is not present in revision %s" % (file, revno))
500
revno = self.revision_id_to_revno(revision_id)
501
except errors.NoSuchRevision:
502
# TODO: This should not be BzrError,
503
# but NoSuchFile doesn't fit either
504
raise BzrError('%r is not present in revision %s'
505
% (file, revision_id))
507
raise BzrError('%r is not present in revision %s'
509
tree.print_file(file_id)
511
def get_transaction(self):
512
return self.control_files.get_transaction()
514
def revision_parents(self, revid):
515
return self.get_inventory_weave().parent_names(revid)
518
def set_make_working_trees(self, new_value):
519
"""Set the policy flag for making working trees when creating branches.
521
This only applies to branches that use this repository.
523
The default is 'True'.
524
:param new_value: True to restore the default, False to disable making
527
# FIXME: split out into a new class/strategy ?
528
if isinstance(self._format, (RepositoryFormat4,
531
raise NotImplementedError(self.set_make_working_trees)
534
self.control_files._transport.delete('no-working-trees')
535
except errors.NoSuchFile:
538
self.control_files.put_utf8('no-working-trees', '')
540
def make_working_trees(self):
541
"""Returns the policy for making working trees on new branches."""
542
# FIXME: split out into a new class/strategy ?
543
if isinstance(self._format, (RepositoryFormat4,
547
return not self.control_files._transport.has('no-working-trees')
550
def sign_revision(self, revision_id, gpg_strategy):
551
plaintext = Testament.from_revision(self, revision_id).as_short_text()
552
self.store_revision_signature(gpg_strategy, plaintext, revision_id)
555
def has_signature_for_revision_id(self, revision_id):
556
"""Query for a revision signature for revision_id in the repository."""
557
return self._revision_store.has_signature(revision_id,
558
self.get_transaction())
561
class AllInOneRepository(Repository):
562
"""Legacy support - the repository behaviour for all-in-one branches."""
564
def __init__(self, _format, a_bzrdir, _revision_store, control_store, text_store):
565
# we reuse one control files instance.
566
dir_mode = a_bzrdir._control_files._dir_mode
567
file_mode = a_bzrdir._control_files._file_mode
569
def get_weave(name, prefixed=False):
571
name = safe_unicode(name)
574
relpath = a_bzrdir._control_files._escape(name)
575
weave_transport = a_bzrdir._control_files._transport.clone(relpath)
576
ws = WeaveStore(weave_transport, prefixed=prefixed,
579
if a_bzrdir._control_files._transport.should_cache():
580
ws.enable_cache = True
583
def get_store(name, compressed=True, prefixed=False):
584
# FIXME: This approach of assuming stores are all entirely compressed
585
# or entirely uncompressed is tidy, but breaks upgrade from
586
# some existing branches where there's a mixture; we probably
587
# still want the option to look for both.
588
relpath = a_bzrdir._control_files._escape(name)
589
store = TextStore(a_bzrdir._control_files._transport.clone(relpath),
590
prefixed=prefixed, compressed=compressed,
593
#if self._transport.should_cache():
594
# cache_path = os.path.join(self.cache_root, name)
595
# os.mkdir(cache_path)
596
# store = bzrlib.store.CachedStore(store, cache_path)
599
# not broken out yet because the controlweaves|inventory_store
600
# and text_store | weave_store bits are still different.
601
if isinstance(_format, RepositoryFormat4):
602
# cannot remove these - there is still no consistent api
603
# which allows access to this old info.
604
self.inventory_store = get_store('inventory-store')
605
text_store = get_store('text-store')
606
super(AllInOneRepository, self).__init__(_format, a_bzrdir, a_bzrdir._control_files, _revision_store, control_store, text_store)
609
class MetaDirRepository(Repository):
610
"""Repositories in the new meta-dir layout."""
612
def __init__(self, _format, a_bzrdir, control_files, _revision_store, control_store, text_store):
613
super(MetaDirRepository, self).__init__(_format,
620
dir_mode = self.control_files._dir_mode
621
file_mode = self.control_files._file_mode
623
def get_weave(name, prefixed=False):
625
name = safe_unicode(name)
628
relpath = self.control_files._escape(name)
629
weave_transport = self.control_files._transport.clone(relpath)
630
ws = WeaveStore(weave_transport, prefixed=prefixed,
633
if self.control_files._transport.should_cache():
634
ws.enable_cache = True
638
class KnitRepository(MetaDirRepository):
639
"""Knit format repository."""
642
def all_revision_ids(self):
643
"""See Repository.all_revision_ids()."""
644
return self._revision_store.all_revision_ids(self.get_transaction())
647
class RepositoryFormat(object):
648
"""A repository format.
650
Formats provide three things:
651
* An initialization routine to construct repository data on disk.
652
* a format string which is used when the BzrDir supports versioned
654
* an open routine which returns a Repository instance.
656
Formats are placed in an dict by their format string for reference
657
during opening. These should be subclasses of RepositoryFormat
660
Once a format is deprecated, just deprecate the initialize and open
661
methods on the format class. Do not deprecate the object, as the
662
object will be created every system load.
664
Common instance attributes:
665
_matchingbzrdir - the bzrdir format that the repository format was
666
originally written to work with. This can be used if manually
667
constructing a bzrdir and repository, or more commonly for test suite
671
_default_format = None
672
"""The default format used for new repositories."""
675
"""The known formats."""
678
def find_format(klass, a_bzrdir):
679
"""Return the format for the repository object in a_bzrdir."""
681
transport = a_bzrdir.get_repository_transport(None)
682
format_string = transport.get("format").read()
683
return klass._formats[format_string]
684
except errors.NoSuchFile:
685
raise errors.NoRepositoryPresent(a_bzrdir)
687
raise errors.UnknownFormatError(format_string)
689
def _get_control_store(self, repo_transport, control_files):
690
"""Return the control store for this repository."""
691
raise NotImplementedError(self._get_control_store)
694
def get_default_format(klass):
695
"""Return the current default format."""
696
return klass._default_format
698
def get_format_string(self):
699
"""Return the ASCII format string that identifies this format.
701
Note that in pre format ?? repositories the format string is
702
not permitted nor written to disk.
704
raise NotImplementedError(self.get_format_string)
706
def _get_revision_store(self, repo_transport, control_files):
707
"""Return the revision store object for this a_bzrdir."""
708
raise NotImplementedError(self._get_revision_store)
710
def _get_text_rev_store(self,
717
"""Common logic for getting a revision store for a repository.
719
see self._get_revision_store for the subclass-overridable method to
720
get the store for a repository.
722
from bzrlib.store.revision.text import TextRevisionStore
723
dir_mode = control_files._dir_mode
724
file_mode = control_files._file_mode
725
text_store =TextStore(transport.clone(name),
727
compressed=compressed,
730
_revision_store = TextRevisionStore(text_store, serializer)
731
return _revision_store
733
def _get_versioned_file_store(self,
738
versionedfile_class=WeaveFile):
739
weave_transport = control_files._transport.clone(name)
740
dir_mode = control_files._dir_mode
741
file_mode = control_files._file_mode
742
return VersionedFileStore(weave_transport, prefixed=prefixed,
745
versionedfile_class=versionedfile_class)
747
def initialize(self, a_bzrdir, shared=False):
748
"""Initialize a repository of this format in a_bzrdir.
750
:param a_bzrdir: The bzrdir to put the new repository in it.
751
:param shared: The repository should be initialized as a sharable one.
753
This may raise UninitializableFormat if shared repository are not
754
compatible the a_bzrdir.
757
def is_supported(self):
758
"""Is this format supported?
760
Supported formats must be initializable and openable.
761
Unsupported formats may not support initialization or committing or
762
some other features depending on the reason for not being supported.
766
def open(self, a_bzrdir, _found=False):
767
"""Return an instance of this format for the bzrdir a_bzrdir.
769
_found is a private parameter, do not use it.
771
raise NotImplementedError(self.open)
774
def register_format(klass, format):
775
klass._formats[format.get_format_string()] = format
778
def set_default_format(klass, format):
779
klass._default_format = format
782
def unregister_format(klass, format):
783
assert klass._formats[format.get_format_string()] is format
784
del klass._formats[format.get_format_string()]
787
class PreSplitOutRepositoryFormat(RepositoryFormat):
788
"""Base class for the pre split out repository formats."""
790
def initialize(self, a_bzrdir, shared=False, _internal=False):
791
"""Create a weave repository.
793
TODO: when creating split out bzr branch formats, move this to a common
794
base for Format5, Format6. or something like that.
796
from bzrlib.weavefile import write_weave_v5
797
from bzrlib.weave import Weave
800
raise errors.IncompatibleFormat(self, a_bzrdir._format)
803
# always initialized when the bzrdir is.
804
return self.open(a_bzrdir, _found=True)
806
# Create an empty weave
808
bzrlib.weavefile.write_weave_v5(Weave(), sio)
809
empty_weave = sio.getvalue()
811
mutter('creating repository in %s.', a_bzrdir.transport.base)
812
dirs = ['revision-store', 'weaves']
813
lock_file = 'branch-lock'
814
files = [('inventory.weave', StringIO(empty_weave)),
817
# FIXME: RBC 20060125 dont peek under the covers
818
# NB: no need to escape relative paths that are url safe.
819
control_files = LockableFiles(a_bzrdir.transport, 'branch-lock')
820
control_files.lock_write()
821
control_files._transport.mkdir_multi(dirs,
822
mode=control_files._dir_mode)
824
for file, content in files:
825
control_files.put(file, content)
827
control_files.unlock()
828
return self.open(a_bzrdir, _found=True)
830
def _get_control_store(self, repo_transport, control_files):
831
"""Return the control store for this repository."""
832
return self._get_versioned_file_store('',
837
def _get_text_store(self, transport, control_files):
838
"""Get a store for file texts for this format."""
839
raise NotImplementedError(self._get_text_store)
841
def open(self, a_bzrdir, _found=False):
842
"""See RepositoryFormat.open()."""
844
# we are being called directly and must probe.
845
raise NotImplementedError
847
repo_transport = a_bzrdir.get_repository_transport(None)
848
control_files = a_bzrdir._control_files
849
text_store = self._get_text_store(repo_transport, control_files)
850
control_store = self._get_control_store(repo_transport, control_files)
851
_revision_store = self._get_revision_store(repo_transport, control_files)
852
return AllInOneRepository(_format=self,
854
_revision_store=_revision_store,
855
control_store=control_store,
856
text_store=text_store)
859
class RepositoryFormat4(PreSplitOutRepositoryFormat):
860
"""Bzr repository format 4.
862
This repository format has:
864
- TextStores for texts, inventories,revisions.
866
This format is deprecated: it indexes texts using a text id which is
867
removed in format 5; initializationa and write support for this format
872
super(RepositoryFormat4, self).__init__()
873
self._matchingbzrdir = bzrlib.bzrdir.BzrDirFormat4()
875
def initialize(self, url, shared=False, _internal=False):
876
"""Format 4 branches cannot be created."""
877
raise errors.UninitializableFormat(self)
879
def is_supported(self):
880
"""Format 4 is not supported.
882
It is not supported because the model changed from 4 to 5 and the
883
conversion logic is expensive - so doing it on the fly was not
888
def _get_control_store(self, repo_transport, control_files):
889
"""Format 4 repositories have no formal control store at this point.
891
This will cause any control-file-needing apis to fail - this is desired.
895
def _get_revision_store(self, repo_transport, control_files):
896
"""See RepositoryFormat._get_revision_store()."""
897
from bzrlib.xml4 import serializer_v4
898
return self._get_text_rev_store(repo_transport,
901
serializer=serializer_v4)
903
def _get_text_store(self, transport, control_files):
904
"""See RepositoryFormat._get_text_store()."""
907
class RepositoryFormat5(PreSplitOutRepositoryFormat):
908
"""Bzr control format 5.
910
This repository format has:
911
- weaves for file texts and inventory
913
- TextStores for revisions and signatures.
917
super(RepositoryFormat5, self).__init__()
918
self._matchingbzrdir = bzrlib.bzrdir.BzrDirFormat5()
920
def _get_revision_store(self, repo_transport, control_files):
921
"""See RepositoryFormat._get_revision_store()."""
922
"""Return the revision store object for this a_bzrdir."""
923
return self._get_text_rev_store(repo_transport,
928
def _get_text_store(self, transport, control_files):
929
"""See RepositoryFormat._get_text_store()."""
930
return self._get_versioned_file_store('weaves', transport, control_files, prefixed=False)
933
class RepositoryFormat6(PreSplitOutRepositoryFormat):
934
"""Bzr control format 6.
936
This repository format has:
937
- weaves for file texts and inventory
938
- hash subdirectory based stores.
939
- TextStores for revisions and signatures.
943
super(RepositoryFormat6, self).__init__()
944
self._matchingbzrdir = bzrlib.bzrdir.BzrDirFormat6()
946
def _get_revision_store(self, repo_transport, control_files):
947
"""See RepositoryFormat._get_revision_store()."""
948
return self._get_text_rev_store(repo_transport,
954
def _get_text_store(self, transport, control_files):
955
"""See RepositoryFormat._get_text_store()."""
956
return self._get_versioned_file_store('weaves', transport, control_files)
959
class MetaDirRepositoryFormat(RepositoryFormat):
960
"""Common base class for the new repositories using the metadir layour."""
963
super(MetaDirRepositoryFormat, self).__init__()
964
self._matchingbzrdir = bzrlib.bzrdir.BzrDirMetaFormat1()
966
def _create_control_files(self, a_bzrdir):
967
"""Create the required files and the initial control_files object."""
968
# FIXME: RBC 20060125 dont peek under the covers
969
# NB: no need to escape relative paths that are url safe.
971
repository_transport = a_bzrdir.get_repository_transport(self)
972
repository_transport.put(lock_file, StringIO()) # TODO get the file mode from the bzrdir lock files., mode=file_mode)
973
control_files = LockableFiles(repository_transport, 'lock')
976
def _get_control_store(self, repo_transport, control_files):
977
"""Return the control store for this repository."""
978
return self._get_versioned_file_store('',
983
def _get_revision_store(self, repo_transport, control_files):
984
"""See RepositoryFormat._get_revision_store()."""
985
return self._get_text_rev_store(repo_transport,
992
def open(self, a_bzrdir, _found=False, _override_transport=None):
993
"""See RepositoryFormat.open().
995
:param _override_transport: INTERNAL USE ONLY. Allows opening the
996
repository at a slightly different url
997
than normal. I.e. during 'upgrade'.
1000
format = RepositoryFormat.find_format(a_bzrdir)
1001
assert format.__class__ == self.__class__
1002
if _override_transport is not None:
1003
repo_transport = _override_transport
1005
repo_transport = a_bzrdir.get_repository_transport(None)
1006
control_files = LockableFiles(repo_transport, 'lock')
1007
text_store = self._get_text_store(repo_transport, control_files)
1008
control_store = self._get_control_store(repo_transport, control_files)
1009
_revision_store = self._get_revision_store(repo_transport, control_files)
1010
return MetaDirRepository(_format=self,
1012
control_files=control_files,
1013
_revision_store=_revision_store,
1014
control_store=control_store,
1015
text_store=text_store)
1017
def _upload_blank_content(self, a_bzrdir, dirs, files, utf8_files, shared):
1018
"""Upload the initial blank content."""
1019
control_files = self._create_control_files(a_bzrdir)
1020
control_files.lock_write()
1021
control_files._transport.mkdir_multi(dirs,
1022
mode=control_files._dir_mode)
1024
for file, content in files:
1025
control_files.put(file, content)
1026
for file, content in utf8_files:
1027
control_files.put_utf8(file, content)
1029
control_files.put_utf8('shared-storage', '')
1031
control_files.unlock()
1034
class RepositoryFormat7(MetaDirRepositoryFormat):
1035
"""Bzr repository 7.
1037
This repository format has:
1038
- weaves for file texts and inventory
1039
- hash subdirectory based stores.
1040
- TextStores for revisions and signatures.
1041
- a format marker of its own
1042
- an optional 'shared-storage' flag
1043
- an optional 'no-working-trees' flag
1046
def get_format_string(self):
1047
"""See RepositoryFormat.get_format_string()."""
1048
return "Bazaar-NG Repository format 7"
1050
def _get_text_store(self, transport, control_files):
1051
"""See RepositoryFormat._get_text_store()."""
1052
return self._get_versioned_file_store('weaves',
1056
def initialize(self, a_bzrdir, shared=False):
1057
"""Create a weave repository.
1059
:param shared: If true the repository will be initialized as a shared
1062
from bzrlib.weavefile import write_weave_v5
1063
from bzrlib.weave import Weave
1065
# Create an empty weave
1067
bzrlib.weavefile.write_weave_v5(Weave(), sio)
1068
empty_weave = sio.getvalue()
1070
mutter('creating repository in %s.', a_bzrdir.transport.base)
1071
dirs = ['revision-store', 'weaves']
1072
files = [('inventory.weave', StringIO(empty_weave)),
1074
utf8_files = [('format', self.get_format_string())]
1076
self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
1077
return self.open(a_bzrdir=a_bzrdir, _found=True)
1079
def open(self, a_bzrdir, _found=False, _override_transport=None):
1080
"""See RepositoryFormat.open().
1082
:param _override_transport: INTERNAL USE ONLY. Allows opening the
1083
repository at a slightly different url
1084
than normal. I.e. during 'upgrade'.
1087
format = RepositoryFormat.find_format(a_bzrdir)
1088
assert format.__class__ == self.__class__
1089
if _override_transport is not None:
1090
repo_transport = _override_transport
1092
repo_transport = a_bzrdir.get_repository_transport(None)
1093
control_files = LockableFiles(repo_transport, 'lock')
1094
text_store = self._get_text_store(repo_transport, control_files)
1095
control_store = self._get_control_store(repo_transport, control_files)
1096
_revision_store = self._get_revision_store(repo_transport, control_files)
1097
return KnitRepository(_format=self,
1099
control_files=control_files,
1100
_revision_store=_revision_store,
1101
control_store=control_store,
1102
text_store=text_store)
1105
class RepositoryFormatKnit1(MetaDirRepositoryFormat):
1106
"""Bzr repository knit format 1.
1108
This repository format has:
1109
- knits for file texts and inventory
1110
- hash subdirectory based stores.
1111
- knits for revisions and signatures
1112
- TextStores for revisions and signatures.
1113
- a format marker of its own
1114
- an optional 'shared-storage' flag
1115
- an optional 'no-working-trees' flag
1118
def get_format_string(self):
1119
"""See RepositoryFormat.get_format_string()."""
1120
return "Bazaar-NG Knit Repository Format 1"
1122
def _get_text_store(self, transport, control_files):
1123
"""See RepositoryFormat._get_text_store()."""
1124
return self._get_versioned_file_store('knits',
1127
versionedfile_class=KnitVersionedFile)
1129
def initialize(self, a_bzrdir, shared=False):
1130
"""Create a knit format 1 repository.
1132
:param shared: If true the repository will be initialized as a shared
1134
XXX NOTE that this current uses a Weave for testing and will become
1135
A Knit in due course.
1137
from bzrlib.weavefile import write_weave_v5
1138
from bzrlib.weave import Weave
1140
# Create an empty weave
1142
bzrlib.weavefile.write_weave_v5(Weave(), sio)
1143
empty_weave = sio.getvalue()
1145
mutter('creating repository in %s.', a_bzrdir.transport.base)
1146
dirs = ['revision-store', 'knits', 'control']
1147
files = [('control/inventory.weave', StringIO(empty_weave)),
1149
utf8_files = [('format', self.get_format_string())]
1151
self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
1152
repo_transport = a_bzrdir.get_repository_transport(None)
1153
control_files = LockableFiles(repo_transport, 'lock')
1154
control_store = self._get_control_store(repo_transport, control_files)
1155
control_store.get_weave_or_empty('inventory',
1156
bzrlib.transactions.PassThroughTransaction())
1157
return self.open(a_bzrdir=a_bzrdir, _found=True)
1160
# formats which have no format string are not discoverable
1161
# and not independently creatable, so are not registered.
1162
_default_format = RepositoryFormat7()
1163
RepositoryFormat.register_format(_default_format)
1164
RepositoryFormat.register_format(RepositoryFormatKnit1())
1165
RepositoryFormat.set_default_format(_default_format)
1166
_legacy_formats = [RepositoryFormat4(),
1167
RepositoryFormat5(),
1168
RepositoryFormat6()]
1171
class InterRepository(InterObject):
1172
"""This class represents operations taking place between two repositories.
1174
Its instances have methods like copy_content and fetch, and contain
1175
references to the source and target repositories these operations can be
1178
Often we will provide convenience methods on 'repository' which carry out
1179
operations with another repository - they will always forward to
1180
InterRepository.get(other).method_name(parameters).
1184
"""The available optimised InterRepository types."""
1187
def copy_content(self, revision_id=None, basis=None):
1188
"""Make a complete copy of the content in self into destination.
1190
This is a destructive operation! Do not use it on existing
1193
:param revision_id: Only copy the content needed to construct
1194
revision_id and its parents.
1195
:param basis: Copy the needed data preferentially from basis.
1198
self.target.set_make_working_trees(self.source.make_working_trees())
1199
except NotImplementedError:
1201
# grab the basis available data
1202
if basis is not None:
1203
self.target.fetch(basis, revision_id=revision_id)
1204
# but dont both fetching if we have the needed data now.
1205
if (revision_id not in (None, NULL_REVISION) and
1206
self.target.has_revision(revision_id)):
1208
self.target.fetch(self.source, revision_id=revision_id)
1210
def _double_lock(self, lock_source, lock_target):
1211
"""Take out too locks, rolling back the first if the second throws."""
1216
# we want to ensure that we don't leave source locked by mistake.
1217
# and any error on target should not confuse source.
1218
self.source.unlock()
1222
def fetch(self, revision_id=None, pb=None):
1223
"""Fetch the content required to construct revision_id.
1225
The content is copied from source to target.
1227
:param revision_id: if None all content is copied, if NULL_REVISION no
1229
:param pb: optional progress bar to use for progress reports. If not
1230
provided a default one will be created.
1232
Returns the copied revision count and the failed revisions in a tuple:
1235
from bzrlib.fetch import RepoFetcher
1236
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1237
self.source, self.source._format, self.target, self.target._format)
1238
f = RepoFetcher(to_repository=self.target,
1239
from_repository=self.source,
1240
last_revision=revision_id,
1242
return f.count_copied, f.failed_revisions
1244
def lock_read(self):
1245
"""Take out a logical read lock.
1247
This will lock the source branch and the target branch. The source gets
1248
a read lock and the target a read lock.
1250
self._double_lock(self.source.lock_read, self.target.lock_read)
1252
def lock_write(self):
1253
"""Take out a logical write lock.
1255
This will lock the source branch and the target branch. The source gets
1256
a read lock and the target a write lock.
1258
self._double_lock(self.source.lock_read, self.target.lock_write)
1261
def missing_revision_ids(self, revision_id=None):
1262
"""Return the revision ids that source has that target does not.
1264
These are returned in topological order.
1266
:param revision_id: only return revision ids included by this
1269
# generic, possibly worst case, slow code path.
1270
target_ids = set(self.target.all_revision_ids())
1271
if revision_id is not None:
1272
source_ids = self.source.get_ancestry(revision_id)
1273
assert source_ids.pop(0) == None
1275
source_ids = self.source.all_revision_ids()
1276
result_set = set(source_ids).difference(target_ids)
1277
# this may look like a no-op: its not. It preserves the ordering
1278
# other_ids had while only returning the members from other_ids
1279
# that we've decided we need.
1280
return [rev_id for rev_id in source_ids if rev_id in result_set]
1283
"""Release the locks on source and target."""
1285
self.target.unlock()
1287
self.source.unlock()
1290
class InterWeaveRepo(InterRepository):
1291
"""Optimised code paths between Weave based repositories."""
1293
_matching_repo_format = _default_format
1294
"""Repository format for testing with."""
1297
def is_compatible(source, target):
1298
"""Be compatible with known Weave formats.
1300
We dont test for the stores being of specific types becase that
1301
could lead to confusing results, and there is no need to be
1305
return (isinstance(source._format, (RepositoryFormat5,
1307
RepositoryFormat7)) and
1308
isinstance(target._format, (RepositoryFormat5,
1310
RepositoryFormat7)))
1311
except AttributeError:
1315
def copy_content(self, revision_id=None, basis=None):
1316
"""See InterRepository.copy_content()."""
1317
# weave specific optimised path:
1318
if basis is not None:
1319
# copy the basis in, then fetch remaining data.
1320
basis.copy_content_into(self.target, revision_id)
1321
# the basis copy_content_into could misset this.
1323
self.target.set_make_working_trees(self.source.make_working_trees())
1324
except NotImplementedError:
1326
self.target.fetch(self.source, revision_id=revision_id)
1329
self.target.set_make_working_trees(self.source.make_working_trees())
1330
except NotImplementedError:
1332
# FIXME do not peek!
1333
if self.source.control_files._transport.listable():
1334
pb = bzrlib.ui.ui_factory.progress_bar()
1335
self.target.weave_store.copy_all_ids(
1336
self.source.weave_store,
1338
from_transaction=self.source.get_transaction())
1339
pb.update('copying inventory', 0, 1)
1340
self.target.control_weaves.copy_multi(
1341
self.source.control_weaves, ['inventory'],
1342
from_transaction=self.source.get_transaction())
1343
self.target.revision_store.copy_all_ids(
1344
self.source.revision_store,
1347
self.target.fetch(self.source, revision_id=revision_id)
1350
def fetch(self, revision_id=None, pb=None):
1351
"""See InterRepository.fetch()."""
1352
from bzrlib.fetch import RepoFetcher
1353
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1354
self.source, self.source._format, self.target, self.target._format)
1355
f = RepoFetcher(to_repository=self.target,
1356
from_repository=self.source,
1357
last_revision=revision_id,
1359
return f.count_copied, f.failed_revisions
1362
def missing_revision_ids(self, revision_id=None):
1363
"""See InterRepository.missing_revision_ids()."""
1364
# we want all revisions to satisfy revision_id in source.
1365
# but we dont want to stat every file here and there.
1366
# we want then, all revisions other needs to satisfy revision_id
1367
# checked, but not those that we have locally.
1368
# so the first thing is to get a subset of the revisions to
1369
# satisfy revision_id in source, and then eliminate those that
1370
# we do already have.
1371
# this is slow on high latency connection to self, but as as this
1372
# disk format scales terribly for push anyway due to rewriting
1373
# inventory.weave, this is considered acceptable.
1375
if revision_id is not None:
1376
source_ids = self.source.get_ancestry(revision_id)
1377
assert source_ids.pop(0) == None
1379
source_ids = self.source._all_possible_ids()
1380
source_ids_set = set(source_ids)
1381
# source_ids is the worst possible case we may need to pull.
1382
# now we want to filter source_ids against what we actually
1383
# have in target, but dont try to check for existence where we know
1384
# we do not have a revision as that would be pointless.
1385
target_ids = set(self.target._all_possible_ids())
1386
possibly_present_revisions = target_ids.intersection(source_ids_set)
1387
actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
1388
required_revisions = source_ids_set.difference(actually_present_revisions)
1389
required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
1390
if revision_id is not None:
1391
# we used get_ancestry to determine source_ids then we are assured all
1392
# revisions referenced are present as they are installed in topological order.
1393
# and the tip revision was validated by get_ancestry.
1394
return required_topo_revisions
1396
# if we just grabbed the possibly available ids, then
1397
# we only have an estimate of whats available and need to validate
1398
# that against the revision records.
1399
return self.source._eliminate_revisions_not_present(required_topo_revisions)
1402
InterRepository.register_optimiser(InterWeaveRepo)
1405
class RepositoryTestProviderAdapter(object):
1406
"""A tool to generate a suite testing multiple repository formats at once.
1408
This is done by copying the test once for each transport and injecting
1409
the transport_server, transport_readonly_server, and bzrdir_format and
1410
repository_format classes into each copy. Each copy is also given a new id()
1411
to make it easy to identify.
1414
def __init__(self, transport_server, transport_readonly_server, formats):
1415
self._transport_server = transport_server
1416
self._transport_readonly_server = transport_readonly_server
1417
self._formats = formats
1419
def adapt(self, test):
1420
result = TestSuite()
1421
for repository_format, bzrdir_format in self._formats:
1422
new_test = deepcopy(test)
1423
new_test.transport_server = self._transport_server
1424
new_test.transport_readonly_server = self._transport_readonly_server
1425
new_test.bzrdir_format = bzrdir_format
1426
new_test.repository_format = repository_format
1427
def make_new_test_id():
1428
new_id = "%s(%s)" % (new_test.id(), repository_format.__class__.__name__)
1429
return lambda: new_id
1430
new_test.id = make_new_test_id()
1431
result.addTest(new_test)
1435
class InterRepositoryTestProviderAdapter(object):
1436
"""A tool to generate a suite testing multiple inter repository formats.
1438
This is done by copying the test once for each interrepo provider and injecting
1439
the transport_server, transport_readonly_server, repository_format and
1440
repository_to_format classes into each copy.
1441
Each copy is also given a new id() to make it easy to identify.
1444
def __init__(self, transport_server, transport_readonly_server, formats):
1445
self._transport_server = transport_server
1446
self._transport_readonly_server = transport_readonly_server
1447
self._formats = formats
1449
def adapt(self, test):
1450
result = TestSuite()
1451
for interrepo_class, repository_format, repository_format_to in self._formats:
1452
new_test = deepcopy(test)
1453
new_test.transport_server = self._transport_server
1454
new_test.transport_readonly_server = self._transport_readonly_server
1455
new_test.interrepo_class = interrepo_class
1456
new_test.repository_format = repository_format
1457
new_test.repository_format_to = repository_format_to
1458
def make_new_test_id():
1459
new_id = "%s(%s)" % (new_test.id(), interrepo_class.__name__)
1460
return lambda: new_id
1461
new_test.id = make_new_test_id()
1462
result.addTest(new_test)
1466
def default_test_list():
1467
"""Generate the default list of interrepo permutations to test."""
1469
# test the default InterRepository between format 6 and the current
1471
# XXX: robertc 20060220 reinstate this when there are two supported
1472
# formats which do not have an optimal code path between them.
1473
result.append((InterRepository,
1474
RepositoryFormat6(),
1475
RepositoryFormatKnit1()))
1476
for optimiser in InterRepository._optimisers:
1477
result.append((optimiser,
1478
optimiser._matching_repo_format,
1479
optimiser._matching_repo_format
1481
# if there are specific combinations we want to use, we can add them
1486
class CopyConverter(object):
1487
"""A repository conversion tool which just performs a copy of the content.
1489
This is slow but quite reliable.
1492
def __init__(self, target_format):
1493
"""Create a CopyConverter.
1495
:param target_format: The format the resulting repository should be.
1497
self.target_format = target_format
1499
def convert(self, repo, pb):
1500
"""Perform the conversion of to_convert, giving feedback via pb.
1502
:param to_convert: The disk object to convert.
1503
:param pb: a progress bar to use for progress information.
1508
# this is only useful with metadir layouts - separated repo content.
1509
# trigger an assertion if not such
1510
repo._format.get_format_string()
1511
self.repo_dir = repo.bzrdir
1512
self.step('Moving repository to repository.backup')
1513
self.repo_dir.transport.move('repository', 'repository.backup')
1514
backup_transport = self.repo_dir.transport.clone('repository.backup')
1515
self.source_repo = repo._format.open(self.repo_dir,
1517
_override_transport=backup_transport)
1518
self.step('Creating new repository')
1519
converted = self.target_format.initialize(self.repo_dir,
1520
self.source_repo.is_shared())
1521
converted.lock_write()
1523
self.step('Copying content into repository.')
1524
self.source_repo.copy_content_into(converted)
1527
self.step('Deleting old repository content.')
1528
self.repo_dir.transport.delete_tree('repository.backup')
1529
self.pb.note('repository converted')
1531
def step(self, message):
1532
"""Update the pb by a step."""
1534
self.pb.update(message, self.count, self.total)