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.lockable_files import LockableFiles
28
from bzrlib.osutils import safe_unicode
29
from bzrlib.revision import NULL_REVISION
30
from bzrlib.store import copy_all
31
from bzrlib.store.weave import WeaveStore
32
from bzrlib.store.text import TextStore
33
from bzrlib.symbol_versioning import *
34
from bzrlib.trace import mutter
35
from bzrlib.tree import RevisionTree
36
from bzrlib.testament import Testament
37
from bzrlib.tree import EmptyTree
42
class Repository(object):
43
"""Repository holding history for one or more branches.
45
The repository holds and retrieves historical information including
46
revisions and file history. It's normally accessed only by the Branch,
47
which views a particular line of development through that history.
49
The Repository builds on top of Stores and a Transport, which respectively
50
describe the disk data format and the way of accessing the (possibly
55
def add_inventory(self, revid, inv, parents):
56
"""Add the inventory inv to the repository as revid.
58
:param parents: The revision ids of the parents that revid
59
is known to have and are in the repository already.
61
returns the sha1 of the serialized inventory.
63
inv_text = bzrlib.xml5.serializer_v5.write_inventory_to_string(inv)
64
inv_sha1 = bzrlib.osutils.sha_string(inv_text)
65
self.control_weaves.add_text('inventory', revid,
66
bzrlib.osutils.split_lines(inv_text), parents,
67
self.get_transaction())
71
def add_revision(self, rev_id, rev, inv=None, config=None):
72
"""Add rev to the revision store as rev_id.
74
:param rev_id: the revision id to use.
75
:param rev: The revision object.
76
:param inv: The inventory for the revision. if None, it will be looked
77
up in the inventory storer
78
:param config: If None no digital signature will be created.
79
If supplied its signature_needed method will be used
80
to determine if a signature should be made.
82
if config is not None and config.signature_needed():
84
inv = self.get_inventory(rev_id)
85
plaintext = Testament(rev, inv).as_short_text()
86
self.store_revision_signature(
87
gpg.GPGStrategy(config), plaintext, rev_id)
88
if not rev_id in self.get_inventory_weave():
90
raise errors.WeaveRevisionNotPresent(rev_id,
91
self.get_inventory_weave())
93
# yes, this is not suitable for adding with ghosts.
94
self.add_inventory(rev_id, inv, rev.parent_ids)
97
bzrlib.xml5.serializer_v5.write_revision(rev, rev_tmp)
99
self.revision_store.add(rev_tmp, rev_id)
100
mutter('added revision_id {%s}', rev_id)
103
def _all_possible_ids(self):
104
"""Return all the possible revisions that we could find."""
105
return self.get_inventory_weave().names()
108
def all_revision_ids(self):
109
"""Returns a list of all the revision ids in the repository.
111
These are in as much topological order as the underlying store can
112
present: for weaves ghosts may lead to a lack of correctness until
113
the reweave updates the parents list.
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):
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
self.revision_store = revision_store
152
def lock_write(self):
153
self.control_files.lock_write()
156
self.control_files.lock_read()
159
def missing_revision_ids(self, other, revision_id=None):
160
"""Return the revision ids that other has that this does not.
162
These are returned in topological order.
164
revision_id: only return revision ids included by revision_id.
166
return InterRepository.get(other, self).missing_revision_ids(revision_id)
170
"""Open the repository rooted at base.
172
For instance, if the repository is at URL/.bzr/repository,
173
Repository.open(URL) -> a Repository instance.
175
control = bzrlib.bzrdir.BzrDir.open(base)
176
return control.open_repository()
178
def copy_content_into(self, destination, revision_id=None, basis=None):
179
"""Make a complete copy of the content in self into destination.
181
This is a destructive operation! Do not use it on existing
184
return InterRepository.get(self, destination).copy_content(revision_id, basis)
186
def fetch(self, source, revision_id=None, pb=None):
187
"""Fetch the content required to construct revision_id from source.
189
If revision_id is None all content is copied.
191
return InterRepository.get(source, self).fetch(revision_id=revision_id,
195
self.control_files.unlock()
198
def clone(self, a_bzrdir, revision_id=None, basis=None):
199
"""Clone this repository into a_bzrdir using the current format.
201
Currently no check is made that the format of this repository and
202
the bzrdir format are compatible. FIXME RBC 20060201.
204
if not isinstance(a_bzrdir._format, self.bzrdir._format.__class__):
205
# use target default format.
206
result = a_bzrdir.create_repository()
207
# FIXME RBC 20060209 split out the repository type to avoid this check ?
208
elif isinstance(a_bzrdir._format,
209
(bzrlib.bzrdir.BzrDirFormat4,
210
bzrlib.bzrdir.BzrDirFormat5,
211
bzrlib.bzrdir.BzrDirFormat6)):
212
result = a_bzrdir.open_repository()
214
result = self._format.initialize(a_bzrdir, shared=self.is_shared())
215
self.copy_content_into(result, revision_id, basis)
218
def has_revision(self, revision_id):
219
"""True if this branch has a copy of the revision.
221
This does not necessarily imply the revision is merge
222
or on the mainline."""
223
return (revision_id is None
224
or self.revision_store.has_id(revision_id))
227
def get_revision_xml_file(self, revision_id):
228
"""Return XML file object for revision object."""
229
if not revision_id or not isinstance(revision_id, basestring):
230
raise InvalidRevisionId(revision_id=revision_id, branch=self)
232
return self.revision_store.get(revision_id)
233
except (IndexError, KeyError):
234
raise bzrlib.errors.NoSuchRevision(self, revision_id)
237
def get_revision_xml(self, revision_id):
238
return self.get_revision_xml_file(revision_id).read()
241
def get_revision_reconcile(self, revision_id):
242
"""'reconcile' helper routine that allows access to a revision always.
244
This variant of get_revision does not cross check the weave graph
245
against the revision one as get_revision does: but it should only
246
be used by reconcile, or reconcile-alike commands that are correcting
247
or testing the revision graph.
249
xml_file = self.get_revision_xml_file(revision_id)
252
r = bzrlib.xml5.serializer_v5.read_revision(xml_file)
253
except SyntaxError, e:
254
raise bzrlib.errors.BzrError('failed to unpack revision_xml',
258
assert r.revision_id == revision_id
262
def get_revision(self, revision_id):
263
"""Return the Revision object for a named revision"""
264
r = self.get_revision_reconcile(revision_id)
265
# weave corruption can lead to absent revision markers that should be
267
# the following test is reasonably cheap (it needs a single weave read)
268
# and the weave is cached in read transactions. In write transactions
269
# it is not cached but typically we only read a small number of
270
# revisions. For knits when they are introduced we will probably want
271
# to ensure that caching write transactions are in use.
272
inv = self.get_inventory_weave()
273
self._check_revision_parents(r, inv)
276
def _check_revision_parents(self, revision, inventory):
277
"""Private to Repository and Fetch.
279
This checks the parentage of revision in an inventory weave for
280
consistency and is only applicable to inventory-weave-for-ancestry
281
using repository formats & fetchers.
283
weave_parents = inventory.parent_names(revision.revision_id)
284
weave_names = inventory.names()
285
for parent_id in revision.parent_ids:
286
if parent_id in weave_names:
287
# this parent must not be a ghost.
288
if not parent_id in weave_parents:
290
raise errors.CorruptRepository(self)
293
def get_revision_sha1(self, revision_id):
294
"""Hash the stored value of a revision, and return it."""
295
# In the future, revision entries will be signed. At that
296
# point, it is probably best *not* to include the signature
297
# in the revision hash. Because that lets you re-sign
298
# the revision, (add signatures/remove signatures) and still
299
# have all hash pointers stay consistent.
300
# But for now, just hash the contents.
301
return bzrlib.osutils.sha_file(self.get_revision_xml_file(revision_id))
304
def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
305
self.revision_store.add(StringIO(gpg_strategy.sign(plaintext)),
308
def fileid_involved_between_revs(self, from_revid, to_revid):
309
"""Find file_id(s) which are involved in the changes between revisions.
311
This determines the set of revisions which are involved, and then
312
finds all file ids affected by those revisions.
314
# TODO: jam 20060119 This code assumes that w.inclusions will
315
# always be correct. But because of the presence of ghosts
316
# it is possible to be wrong.
317
# One specific example from Robert Collins:
318
# Two branches, with revisions ABC, and AD
319
# C is a ghost merge of D.
320
# Inclusions doesn't recognize D as an ancestor.
321
# If D is ever merged in the future, the weave
322
# won't be fixed, because AD never saw revision C
323
# to cause a conflict which would force a reweave.
324
w = self.get_inventory_weave()
325
from_set = set(w.inclusions([w.lookup(from_revid)]))
326
to_set = set(w.inclusions([w.lookup(to_revid)]))
327
included = to_set.difference(from_set)
328
changed = map(w.idx_to_name, included)
329
return self._fileid_involved_by_set(changed)
331
def fileid_involved(self, last_revid=None):
332
"""Find all file_ids modified in the ancestry of last_revid.
334
:param last_revid: If None, last_revision() will be used.
336
w = self.get_inventory_weave()
338
changed = set(w._names)
340
included = w.inclusions([w.lookup(last_revid)])
341
changed = map(w.idx_to_name, included)
342
return self._fileid_involved_by_set(changed)
344
def fileid_involved_by_set(self, changes):
345
"""Find all file_ids modified by the set of revisions passed in.
347
:param changes: A set() of revision ids
349
# TODO: jam 20060119 This line does *nothing*, remove it.
350
# or better yet, change _fileid_involved_by_set so
351
# that it takes the inventory weave, rather than
352
# pulling it out by itself.
353
return self._fileid_involved_by_set(changes)
355
def _fileid_involved_by_set(self, changes):
356
"""Find the set of file-ids affected by the set of revisions.
358
:param changes: A set() of revision ids.
359
:return: A set() of file ids.
361
This peaks at the Weave, interpreting each line, looking to
362
see if it mentions one of the revisions. And if so, includes
363
the file id mentioned.
364
This expects both the Weave format, and the serialization
365
to have a single line per file/directory, and to have
366
fileid="" and revision="" on that line.
368
assert isinstance(self._format, (RepositoryFormat5,
371
RepositoryFormatKnit1)), \
372
"fileid_involved only supported for branches which store inventory as unnested xml"
374
w = self.get_inventory_weave()
376
for line in w._weave:
378
# it is ugly, but it is due to the weave structure
379
if not isinstance(line, basestring): continue
381
start = line.find('file_id="')+9
382
if start < 9: continue
383
end = line.find('"', start)
385
file_id = xml.sax.saxutils.unescape(line[start:end])
387
# check if file_id is already present
388
if file_id in file_ids: continue
390
start = line.find('revision="')+10
391
if start < 10: continue
392
end = line.find('"', start)
394
revision_id = xml.sax.saxutils.unescape(line[start:end])
396
if revision_id in changes:
397
file_ids.add(file_id)
401
def get_inventory_weave(self):
402
return self.control_weaves.get_weave('inventory',
403
self.get_transaction())
406
def get_inventory(self, revision_id):
407
"""Get Inventory object by hash."""
408
xml = self.get_inventory_xml(revision_id)
409
return bzrlib.xml5.serializer_v5.read_inventory_from_string(xml)
412
def get_inventory_xml(self, revision_id):
413
"""Get inventory XML as a file object."""
415
assert isinstance(revision_id, basestring), type(revision_id)
416
iw = self.get_inventory_weave()
417
return iw.get_text(iw.lookup(revision_id))
419
raise bzrlib.errors.HistoryMissing(self, 'inventory', revision_id)
422
def get_inventory_sha1(self, revision_id):
423
"""Return the sha1 hash of the inventory entry
425
return self.get_revision(revision_id).inventory_sha1
428
def get_revision_inventory(self, revision_id):
429
"""Return inventory of a past revision."""
430
# TODO: Unify this with get_inventory()
431
# bzr 0.0.6 and later imposes the constraint that the inventory_id
432
# must be the same as its revision, so this is trivial.
433
if revision_id is None:
434
# This does not make sense: if there is no revision,
435
# then it is the current tree inventory surely ?!
436
# and thus get_root_id() is something that looks at the last
437
# commit on the branch, and the get_root_id is an inventory check.
438
raise NotImplementedError
439
# return Inventory(self.get_root_id())
441
return self.get_inventory(revision_id)
445
"""Return True if this repository is flagged as a shared repository."""
446
# FIXME format 4-6 cannot be shared, this is technically faulty.
447
return self.control_files._transport.has('shared-storage')
450
def revision_tree(self, revision_id):
451
"""Return Tree for a revision on this branch.
453
`revision_id` may be None for the null revision, in which case
454
an `EmptyTree` is returned."""
455
# TODO: refactor this to use an existing revision object
456
# so we don't need to read it in twice.
457
if revision_id is None or revision_id == NULL_REVISION:
460
inv = self.get_revision_inventory(revision_id)
461
return RevisionTree(self, inv, revision_id)
464
def get_ancestry(self, revision_id):
465
"""Return a list of revision-ids integrated by a revision.
467
This is topologically sorted.
469
if revision_id is None:
471
if not self.has_revision(revision_id):
472
raise errors.NoSuchRevision(self, revision_id)
473
w = self.get_inventory_weave()
474
return [None] + map(w.idx_to_name,
475
w.inclusions([w.lookup(revision_id)]))
478
def print_file(self, file, revision_id):
479
"""Print `file` to stdout.
481
FIXME RBC 20060125 as John Meinel points out this is a bad api
482
- it writes to stdout, it assumes that that is valid etc. Fix
483
by creating a new more flexible convenience function.
485
tree = self.revision_tree(revision_id)
486
# use inventory as it was in that revision
487
file_id = tree.inventory.path2id(file)
489
raise BzrError("%r is not present in revision %s" % (file, revno))
491
revno = self.revision_id_to_revno(revision_id)
492
except errors.NoSuchRevision:
493
# TODO: This should not be BzrError,
494
# but NoSuchFile doesn't fit either
495
raise BzrError('%r is not present in revision %s'
496
% (file, revision_id))
498
raise BzrError('%r is not present in revision %s'
500
tree.print_file(file_id)
502
def get_transaction(self):
503
return self.control_files.get_transaction()
506
def set_make_working_trees(self, new_value):
507
"""Set the policy flag for making working trees when creating branches.
509
This only applies to branches that use this repository.
511
The default is 'True'.
512
:param new_value: True to restore the default, False to disable making
515
# FIXME: split out into a new class/strategy ?
516
if isinstance(self._format, (RepositoryFormat4,
519
raise NotImplementedError(self.set_make_working_trees)
522
self.control_files._transport.delete('no-working-trees')
523
except errors.NoSuchFile:
526
self.control_files.put_utf8('no-working-trees', '')
528
def make_working_trees(self):
529
"""Returns the policy for making working trees on new branches."""
530
# FIXME: split out into a new class/strategy ?
531
if isinstance(self._format, (RepositoryFormat4,
535
return not self.control_files._transport.has('no-working-trees')
538
def sign_revision(self, revision_id, gpg_strategy):
539
plaintext = Testament.from_revision(self, revision_id).as_short_text()
540
self.store_revision_signature(gpg_strategy, plaintext, revision_id)
543
class AllInOneRepository(Repository):
544
"""Legacy support - the repository behaviour for all-in-one branches."""
546
def __init__(self, _format, a_bzrdir, revision_store):
547
# we reuse one control files instance.
548
dir_mode = a_bzrdir._control_files._dir_mode
549
file_mode = a_bzrdir._control_files._file_mode
551
def get_weave(name, prefixed=False):
553
name = safe_unicode(name)
556
relpath = a_bzrdir._control_files._escape(name)
557
weave_transport = a_bzrdir._control_files._transport.clone(relpath)
558
ws = WeaveStore(weave_transport, prefixed=prefixed,
561
if a_bzrdir._control_files._transport.should_cache():
562
ws.enable_cache = True
565
def get_store(name, compressed=True, prefixed=False):
566
# FIXME: This approach of assuming stores are all entirely compressed
567
# or entirely uncompressed is tidy, but breaks upgrade from
568
# some existing branches where there's a mixture; we probably
569
# still want the option to look for both.
570
relpath = a_bzrdir._control_files._escape(name)
571
store = TextStore(a_bzrdir._control_files._transport.clone(relpath),
572
prefixed=prefixed, compressed=compressed,
575
#if self._transport.should_cache():
576
# cache_path = os.path.join(self.cache_root, name)
577
# os.mkdir(cache_path)
578
# store = bzrlib.store.CachedStore(store, cache_path)
581
# not broken out yet because the controlweaves|inventory_store
582
# and text_store | weave_store bits are still different.
583
if isinstance(_format, RepositoryFormat4):
584
self.inventory_store = get_store('inventory-store')
585
self.text_store = get_store('text-store')
586
elif isinstance(_format, RepositoryFormat5):
587
self.control_weaves = get_weave('')
588
self.weave_store = get_weave('weaves')
589
elif isinstance(_format, RepositoryFormat6):
590
self.control_weaves = get_weave('')
591
self.weave_store = get_weave('weaves', prefixed=True)
593
raise errors.BzrError('unreachable code: unexpected repository'
595
revision_store.register_suffix('sig')
596
super(AllInOneRepository, self).__init__(_format, a_bzrdir, a_bzrdir._control_files, revision_store)
599
class MetaDirRepository(Repository):
600
"""Repositories in the new meta-dir layout."""
602
def __init__(self, _format, a_bzrdir, control_files, revision_store):
603
super(MetaDirRepository, self).__init__(_format,
608
dir_mode = self.control_files._dir_mode
609
file_mode = self.control_files._file_mode
611
def get_weave(name, prefixed=False):
613
name = safe_unicode(name)
616
relpath = self.control_files._escape(name)
617
weave_transport = self.control_files._transport.clone(relpath)
618
ws = WeaveStore(weave_transport, prefixed=prefixed,
621
if self.control_files._transport.should_cache():
622
ws.enable_cache = True
625
if isinstance(self._format, RepositoryFormat7):
626
self.control_weaves = get_weave('')
627
self.weave_store = get_weave('weaves', prefixed=True)
628
elif isinstance(self._format, RepositoryFormatKnit1):
629
self.control_weaves = get_weave('')
630
self.weave_store = get_weave('knits', prefixed=True)
632
raise errors.BzrError('unreachable code: unexpected repository'
636
class RepositoryFormat(object):
637
"""A repository format.
639
Formats provide three things:
640
* An initialization routine to construct repository data on disk.
641
* a format string which is used when the BzrDir supports versioned
643
* an open routine which returns a Repository instance.
645
Formats are placed in an dict by their format string for reference
646
during opening. These should be subclasses of RepositoryFormat
649
Once a format is deprecated, just deprecate the initialize and open
650
methods on the format class. Do not deprecate the object, as the
651
object will be created every system load.
653
Common instance attributes:
654
_matchingbzrdir - the bzrdir format that the repository format was
655
originally written to work with. This can be used if manually
656
constructing a bzrdir and repository, or more commonly for test suite
660
_default_format = None
661
"""The default format used for new repositories."""
664
"""The known formats."""
667
def find_format(klass, a_bzrdir):
668
"""Return the format for the repository object in a_bzrdir."""
670
transport = a_bzrdir.get_repository_transport(None)
671
format_string = transport.get("format").read()
672
return klass._formats[format_string]
673
except errors.NoSuchFile:
674
raise errors.NoRepositoryPresent(a_bzrdir)
676
raise errors.UnknownFormatError(format_string)
679
def get_default_format(klass):
680
"""Return the current default format."""
681
return klass._default_format
683
def get_format_string(self):
684
"""Return the ASCII format string that identifies this format.
686
Note that in pre format ?? repositories the format string is
687
not permitted nor written to disk.
689
raise NotImplementedError(self.get_format_string)
691
def _get_revision_store(self, repo_transport, control_files):
692
"""Return the revision store object for this a_bzrdir."""
693
raise NotImplementedError(self._get_revision_store)
695
def _get_rev_store(self,
701
"""Common logic for getting a revision store for a repository.
703
see self._get_revision_store for the method to
704
get the store for a repository.
707
name = safe_unicode(name)
710
dir_mode = control_files._dir_mode
711
file_mode = control_files._file_mode
712
revision_store =TextStore(transport.clone(name),
714
compressed=compressed,
717
revision_store.register_suffix('sig')
718
return revision_store
720
def initialize(self, a_bzrdir, shared=False):
721
"""Initialize a repository of this format in a_bzrdir.
723
:param a_bzrdir: The bzrdir to put the new repository in it.
724
:param shared: The repository should be initialized as a sharable one.
726
This may raise UninitializableFormat if shared repository are not
727
compatible the a_bzrdir.
730
def is_supported(self):
731
"""Is this format supported?
733
Supported formats must be initializable and openable.
734
Unsupported formats may not support initialization or committing or
735
some other features depending on the reason for not being supported.
739
def open(self, a_bzrdir, _found=False):
740
"""Return an instance of this format for the bzrdir a_bzrdir.
742
_found is a private parameter, do not use it.
744
raise NotImplementedError(self.open)
747
def register_format(klass, format):
748
klass._formats[format.get_format_string()] = format
751
def set_default_format(klass, format):
752
klass._default_format = format
755
def unregister_format(klass, format):
756
assert klass._formats[format.get_format_string()] is format
757
del klass._formats[format.get_format_string()]
760
class PreSplitOutRepositoryFormat(RepositoryFormat):
761
"""Base class for the pre split out repository formats."""
763
def initialize(self, a_bzrdir, shared=False, _internal=False):
764
"""Create a weave repository.
766
TODO: when creating split out bzr branch formats, move this to a common
767
base for Format5, Format6. or something like that.
769
from bzrlib.weavefile import write_weave_v5
770
from bzrlib.weave import Weave
773
raise errors.IncompatibleFormat(self, a_bzrdir._format)
776
# always initialized when the bzrdir is.
777
return self.open(a_bzrdir, _found=True)
779
# Create an empty weave
781
bzrlib.weavefile.write_weave_v5(Weave(), sio)
782
empty_weave = sio.getvalue()
784
mutter('creating repository in %s.', a_bzrdir.transport.base)
785
dirs = ['revision-store', 'weaves']
786
lock_file = 'branch-lock'
787
files = [('inventory.weave', StringIO(empty_weave)),
790
# FIXME: RBC 20060125 dont peek under the covers
791
# NB: no need to escape relative paths that are url safe.
792
control_files = LockableFiles(a_bzrdir.transport, 'branch-lock')
793
control_files.lock_write()
794
control_files._transport.mkdir_multi(dirs,
795
mode=control_files._dir_mode)
797
for file, content in files:
798
control_files.put(file, content)
800
control_files.unlock()
801
return self.open(a_bzrdir, _found=True)
803
def open(self, a_bzrdir, _found=False):
804
"""See RepositoryFormat.open()."""
806
# we are being called directly and must probe.
807
raise NotImplementedError
809
repo_transport = a_bzrdir.get_repository_transport(None)
810
control_files = a_bzrdir._control_files
811
revision_store = self._get_revision_store(repo_transport, control_files)
812
return AllInOneRepository(_format=self,
814
revision_store=revision_store)
817
class RepositoryFormat4(PreSplitOutRepositoryFormat):
818
"""Bzr repository format 4.
820
This repository format has:
822
- TextStores for texts, inventories,revisions.
824
This format is deprecated: it indexes texts using a text id which is
825
removed in format 5; initializationa and write support for this format
830
super(RepositoryFormat4, self).__init__()
831
self._matchingbzrdir = bzrlib.bzrdir.BzrDirFormat4()
833
def initialize(self, url, shared=False, _internal=False):
834
"""Format 4 branches cannot be created."""
835
raise errors.UninitializableFormat(self)
837
def is_supported(self):
838
"""Format 4 is not supported.
840
It is not supported because the model changed from 4 to 5 and the
841
conversion logic is expensive - so doing it on the fly was not
846
def _get_revision_store(self, repo_transport, control_files):
847
"""See RepositoryFormat._get_revision_store()."""
848
return self._get_rev_store(repo_transport,
853
class RepositoryFormat5(PreSplitOutRepositoryFormat):
854
"""Bzr control format 5.
856
This repository format has:
857
- weaves for file texts and inventory
859
- TextStores for revisions and signatures.
863
super(RepositoryFormat5, self).__init__()
864
self._matchingbzrdir = bzrlib.bzrdir.BzrDirFormat5()
866
def _get_revision_store(self, repo_transport, control_files):
867
"""See RepositoryFormat._get_revision_store()."""
868
"""Return the revision store object for this a_bzrdir."""
869
return self._get_rev_store(repo_transport,
875
class RepositoryFormat6(PreSplitOutRepositoryFormat):
876
"""Bzr control format 6.
878
This repository format has:
879
- weaves for file texts and inventory
880
- hash subdirectory based stores.
881
- TextStores for revisions and signatures.
885
super(RepositoryFormat6, self).__init__()
886
self._matchingbzrdir = bzrlib.bzrdir.BzrDirFormat6()
888
def _get_revision_store(self, repo_transport, control_files):
889
"""See RepositoryFormat._get_revision_store()."""
890
return self._get_rev_store(repo_transport,
897
class MetaDirRepositoryFormat(RepositoryFormat):
898
"""Common base class for the new repositories using the metadir layour."""
901
super(MetaDirRepositoryFormat, self).__init__()
902
self._matchingbzrdir = bzrlib.bzrdir.BzrDirMetaFormat1()
904
def _create_control_files(self, a_bzrdir):
905
"""Create the required files and the initial control_files object."""
906
# FIXME: RBC 20060125 dont peek under the covers
907
# NB: no need to escape relative paths that are url safe.
909
repository_transport = a_bzrdir.get_repository_transport(self)
910
repository_transport.put(lock_file, StringIO()) # TODO get the file mode from the bzrdir lock files., mode=file_mode)
911
control_files = LockableFiles(repository_transport, 'lock')
914
def _get_revision_store(self, repo_transport, control_files):
915
"""See RepositoryFormat._get_revision_store()."""
916
return self._get_rev_store(repo_transport,
923
def open(self, a_bzrdir, _found=False, _override_transport=None):
924
"""See RepositoryFormat.open().
926
:param _override_transport: INTERNAL USE ONLY. Allows opening the
927
repository at a slightly different url
928
than normal. I.e. during 'upgrade'.
931
format = RepositoryFormat.find_format(a_bzrdir)
932
assert format.__class__ == self.__class__
933
if _override_transport is not None:
934
repo_transport = _override_transport
936
repo_transport = a_bzrdir.get_repository_transport(None)
937
control_files = LockableFiles(repo_transport, 'lock')
938
revision_store = self._get_revision_store(repo_transport, control_files)
939
return MetaDirRepository(_format=self,
941
control_files=control_files,
942
revision_store=revision_store)
944
def _upload_blank_content(self, a_bzrdir, dirs, files, utf8_files, shared):
945
"""Upload the initial blank content."""
946
control_files = self._create_control_files(a_bzrdir)
947
control_files.lock_write()
948
control_files._transport.mkdir_multi(dirs,
949
mode=control_files._dir_mode)
951
for file, content in files:
952
control_files.put(file, content)
953
for file, content in utf8_files:
954
control_files.put_utf8(file, content)
956
control_files.put_utf8('shared-storage', '')
958
control_files.unlock()
961
class RepositoryFormat7(MetaDirRepositoryFormat):
964
This repository format has:
965
- weaves for file texts and inventory
966
- hash subdirectory based stores.
967
- TextStores for revisions and signatures.
968
- a format marker of its own
969
- an optional 'shared-storage' flag
970
- an optional 'no-working-trees' flag
973
def get_format_string(self):
974
"""See RepositoryFormat.get_format_string()."""
975
return "Bazaar-NG Repository format 7"
977
def initialize(self, a_bzrdir, shared=False):
978
"""Create a weave repository.
980
:param shared: If true the repository will be initialized as a shared
983
from bzrlib.weavefile import write_weave_v5
984
from bzrlib.weave import Weave
986
# Create an empty weave
988
bzrlib.weavefile.write_weave_v5(Weave(), sio)
989
empty_weave = sio.getvalue()
991
mutter('creating repository in %s.', a_bzrdir.transport.base)
992
dirs = ['revision-store', 'weaves']
993
files = [('inventory.weave', StringIO(empty_weave)),
995
utf8_files = [('format', self.get_format_string())]
997
self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
998
return self.open(a_bzrdir=a_bzrdir, _found=True)
1001
class RepositoryFormatKnit1(MetaDirRepositoryFormat):
1002
"""Bzr repository knit format 1.
1004
This repository format has:
1005
- knits for file texts and inventory
1006
- hash subdirectory based stores.
1007
- knits for revisions and signatures
1008
- TextStores for revisions and signatures.
1009
- a format marker of its own
1010
- an optional 'shared-storage' flag
1011
- an optional 'no-working-trees' flag
1014
def get_format_string(self):
1015
"""See RepositoryFormat.get_format_string()."""
1016
return "Bazaar-NG Knit Repository Format 1"
1018
def initialize(self, a_bzrdir, shared=False):
1019
"""Create a knit format 1 repository.
1021
:param shared: If true the repository will be initialized as a shared
1023
XXX NOTE that this current uses a Weave for testing and will become
1024
A Knit in due course.
1026
from bzrlib.weavefile import write_weave_v5
1027
from bzrlib.weave import Weave
1029
# Create an empty weave
1031
bzrlib.weavefile.write_weave_v5(Weave(), sio)
1032
empty_weave = sio.getvalue()
1034
mutter('creating repository in %s.', a_bzrdir.transport.base)
1035
dirs = ['revision-store', 'knits']
1036
files = [('inventory.weave', StringIO(empty_weave)),
1038
utf8_files = [('format', self.get_format_string())]
1040
self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
1041
return self.open(a_bzrdir=a_bzrdir, _found=True)
1044
# formats which have no format string are not discoverable
1045
# and not independently creatable, so are not registered.
1046
_default_format = RepositoryFormat7()
1047
RepositoryFormat.register_format(_default_format)
1048
RepositoryFormat.register_format(RepositoryFormatKnit1())
1049
RepositoryFormat.set_default_format(_default_format)
1050
_legacy_formats = [RepositoryFormat4(),
1051
RepositoryFormat5(),
1052
RepositoryFormat6()]
1055
class InterRepository(object):
1056
"""This class represents operations taking place between two repositories.
1058
Its instances have methods like copy_content and fetch, and contain
1059
references to the source and target repositories these operations can be
1062
Often we will provide convenience methods on 'repository' which carry out
1063
operations with another repository - they will always forward to
1064
InterRepository.get(other).method_name(parameters).
1066
# XXX: FIXME: FUTURE: robertc
1067
# testing of these probably requires a factory in optimiser type, and
1068
# then a test adapter to test each type thoroughly.
1072
"""The available optimised InterRepository types."""
1074
def __init__(self, source, target):
1075
"""Construct a default InterRepository instance. Please use 'get'.
1077
Only subclasses of InterRepository should call
1078
InterRepository.__init__ - clients should call InterRepository.get
1079
instead which will create an optimised InterRepository if possible.
1081
self.source = source
1082
self.target = target
1085
def copy_content(self, revision_id=None, basis=None):
1086
"""Make a complete copy of the content in self into destination.
1088
This is a destructive operation! Do not use it on existing
1091
:param revision_id: Only copy the content needed to construct
1092
revision_id and its parents.
1093
:param basis: Copy the needed data preferentially from basis.
1096
self.target.set_make_working_trees(self.source.make_working_trees())
1097
except NotImplementedError:
1099
# grab the basis available data
1100
if basis is not None:
1101
self.target.fetch(basis, revision_id=revision_id)
1102
# but dont both fetching if we have the needed data now.
1103
if (revision_id not in (None, NULL_REVISION) and
1104
self.target.has_revision(revision_id)):
1106
self.target.fetch(self.source, revision_id=revision_id)
1108
def _double_lock(self, lock_source, lock_target):
1109
"""Take out too locks, rolling back the first if the second throws."""
1114
# we want to ensure that we don't leave source locked by mistake.
1115
# and any error on target should not confuse source.
1116
self.source.unlock()
1120
def fetch(self, revision_id=None, pb=None):
1121
"""Fetch the content required to construct revision_id.
1123
The content is copied from source to target.
1125
:param revision_id: if None all content is copied, if NULL_REVISION no
1127
:param pb: optional progress bar to use for progress reports. If not
1128
provided a default one will be created.
1130
Returns the copied revision count and the failed revisions in a tuple:
1133
from bzrlib.fetch import RepoFetcher
1134
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1135
self.source, self.source._format, self.target, self.target._format)
1136
f = RepoFetcher(to_repository=self.target,
1137
from_repository=self.source,
1138
last_revision=revision_id,
1140
return f.count_copied, f.failed_revisions
1143
def get(klass, repository_source, repository_target):
1144
"""Retrieve a InterRepository worker object for these repositories.
1146
:param repository_source: the repository to be the 'source' member of
1147
the InterRepository instance.
1148
:param repository_target: the repository to be the 'target' member of
1149
the InterRepository instance.
1150
If an optimised InterRepository worker exists it will be used otherwise
1151
a default InterRepository instance will be created.
1153
for provider in klass._optimisers:
1154
if provider.is_compatible(repository_source, repository_target):
1155
return provider(repository_source, repository_target)
1156
return InterRepository(repository_source, repository_target)
1158
def lock_read(self):
1159
"""Take out a logical read lock.
1161
This will lock the source branch and the target branch. The source gets
1162
a read lock and the target a read lock.
1164
self._double_lock(self.source.lock_read, self.target.lock_read)
1166
def lock_write(self):
1167
"""Take out a logical write lock.
1169
This will lock the source branch and the target branch. The source gets
1170
a read lock and the target a write lock.
1172
self._double_lock(self.source.lock_read, self.target.lock_write)
1175
def missing_revision_ids(self, revision_id=None):
1176
"""Return the revision ids that source has that target does not.
1178
These are returned in topological order.
1180
:param revision_id: only return revision ids included by this
1183
# generic, possibly worst case, slow code path.
1184
target_ids = set(self.target.all_revision_ids())
1185
if revision_id is not None:
1186
source_ids = self.source.get_ancestry(revision_id)
1187
assert source_ids.pop(0) == None
1189
source_ids = self.source.all_revision_ids()
1190
result_set = set(source_ids).difference(target_ids)
1191
# this may look like a no-op: its not. It preserves the ordering
1192
# other_ids had while only returning the members from other_ids
1193
# that we've decided we need.
1194
return [rev_id for rev_id in source_ids if rev_id in result_set]
1197
def register_optimiser(klass, optimiser):
1198
"""Register an InterRepository optimiser."""
1199
klass._optimisers.add(optimiser)
1202
"""Release the locks on source and target."""
1204
self.target.unlock()
1206
self.source.unlock()
1209
def unregister_optimiser(klass, optimiser):
1210
"""Unregister an InterRepository optimiser."""
1211
klass._optimisers.remove(optimiser)
1214
class InterWeaveRepo(InterRepository):
1215
"""Optimised code paths between Weave based repositories."""
1217
_matching_repo_format = _default_format
1218
"""Repository format for testing with."""
1221
def is_compatible(source, target):
1222
"""Be compatible with known Weave formats.
1224
We dont test for the stores being of specific types becase that
1225
could lead to confusing results, and there is no need to be
1229
return (isinstance(source._format, (RepositoryFormat5,
1231
RepositoryFormat7)) and
1232
isinstance(target._format, (RepositoryFormat5,
1234
RepositoryFormat7)))
1235
except AttributeError:
1239
def copy_content(self, revision_id=None, basis=None):
1240
"""See InterRepository.copy_content()."""
1241
# weave specific optimised path:
1242
if basis is not None:
1243
# copy the basis in, then fetch remaining data.
1244
basis.copy_content_into(self.target, revision_id)
1245
# the basis copy_content_into could misset this.
1247
self.target.set_make_working_trees(self.source.make_working_trees())
1248
except NotImplementedError:
1250
self.target.fetch(self.source, revision_id=revision_id)
1253
self.target.set_make_working_trees(self.source.make_working_trees())
1254
except NotImplementedError:
1256
# FIXME do not peek!
1257
if self.source.control_files._transport.listable():
1258
pb = bzrlib.ui.ui_factory.progress_bar()
1259
copy_all(self.source.weave_store,
1260
self.target.weave_store, pb=pb)
1261
pb.update('copying inventory', 0, 1)
1262
self.target.control_weaves.copy_multi(
1263
self.source.control_weaves, ['inventory'])
1264
copy_all(self.source.revision_store,
1265
self.target.revision_store, pb=pb)
1267
self.target.fetch(self.source, revision_id=revision_id)
1270
def fetch(self, revision_id=None, pb=None):
1271
"""See InterRepository.fetch()."""
1272
from bzrlib.fetch import RepoFetcher
1273
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1274
self.source, self.source._format, self.target, self.target._format)
1275
f = RepoFetcher(to_repository=self.target,
1276
from_repository=self.source,
1277
last_revision=revision_id,
1279
return f.count_copied, f.failed_revisions
1282
def missing_revision_ids(self, revision_id=None):
1283
"""See InterRepository.missing_revision_ids()."""
1284
# we want all revisions to satisfy revision_id in source.
1285
# but we dont want to stat every file here and there.
1286
# we want then, all revisions other needs to satisfy revision_id
1287
# checked, but not those that we have locally.
1288
# so the first thing is to get a subset of the revisions to
1289
# satisfy revision_id in source, and then eliminate those that
1290
# we do already have.
1291
# this is slow on high latency connection to self, but as as this
1292
# disk format scales terribly for push anyway due to rewriting
1293
# inventory.weave, this is considered acceptable.
1295
if revision_id is not None:
1296
source_ids = self.source.get_ancestry(revision_id)
1297
assert source_ids.pop(0) == None
1299
source_ids = self.source._all_possible_ids()
1300
source_ids_set = set(source_ids)
1301
# source_ids is the worst possible case we may need to pull.
1302
# now we want to filter source_ids against what we actually
1303
# have in target, but dont try to check for existence where we know
1304
# we do not have a revision as that would be pointless.
1305
target_ids = set(self.target._all_possible_ids())
1306
possibly_present_revisions = target_ids.intersection(source_ids_set)
1307
actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
1308
required_revisions = source_ids_set.difference(actually_present_revisions)
1309
required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
1310
if revision_id is not None:
1311
# we used get_ancestry to determine source_ids then we are assured all
1312
# revisions referenced are present as they are installed in topological order.
1313
# and the tip revision was validated by get_ancestry.
1314
return required_topo_revisions
1316
# if we just grabbed the possibly available ids, then
1317
# we only have an estimate of whats available and need to validate
1318
# that against the revision records.
1319
return self.source._eliminate_revisions_not_present(required_topo_revisions)
1322
InterRepository.register_optimiser(InterWeaveRepo)
1325
class RepositoryTestProviderAdapter(object):
1326
"""A tool to generate a suite testing multiple repository formats at once.
1328
This is done by copying the test once for each transport and injecting
1329
the transport_server, transport_readonly_server, and bzrdir_format and
1330
repository_format classes into each copy. Each copy is also given a new id()
1331
to make it easy to identify.
1334
def __init__(self, transport_server, transport_readonly_server, formats):
1335
self._transport_server = transport_server
1336
self._transport_readonly_server = transport_readonly_server
1337
self._formats = formats
1339
def adapt(self, test):
1340
result = TestSuite()
1341
for repository_format, bzrdir_format in self._formats:
1342
new_test = deepcopy(test)
1343
new_test.transport_server = self._transport_server
1344
new_test.transport_readonly_server = self._transport_readonly_server
1345
new_test.bzrdir_format = bzrdir_format
1346
new_test.repository_format = repository_format
1347
def make_new_test_id():
1348
new_id = "%s(%s)" % (new_test.id(), repository_format.__class__.__name__)
1349
return lambda: new_id
1350
new_test.id = make_new_test_id()
1351
result.addTest(new_test)
1355
class InterRepositoryTestProviderAdapter(object):
1356
"""A tool to generate a suite testing multiple inter repository formats.
1358
This is done by copying the test once for each interrepo provider and injecting
1359
the transport_server, transport_readonly_server, repository_format and
1360
repository_to_format classes into each copy.
1361
Each copy is also given a new id() to make it easy to identify.
1364
def __init__(self, transport_server, transport_readonly_server, formats):
1365
self._transport_server = transport_server
1366
self._transport_readonly_server = transport_readonly_server
1367
self._formats = formats
1369
def adapt(self, test):
1370
result = TestSuite()
1371
for interrepo_class, repository_format, repository_format_to in self._formats:
1372
new_test = deepcopy(test)
1373
new_test.transport_server = self._transport_server
1374
new_test.transport_readonly_server = self._transport_readonly_server
1375
new_test.interrepo_class = interrepo_class
1376
new_test.repository_format = repository_format
1377
new_test.repository_format_to = repository_format_to
1378
def make_new_test_id():
1379
new_id = "%s(%s)" % (new_test.id(), interrepo_class.__name__)
1380
return lambda: new_id
1381
new_test.id = make_new_test_id()
1382
result.addTest(new_test)
1386
def default_test_list():
1387
"""Generate the default list of interrepo permutations to test."""
1389
# test the default InterRepository between format 6 and the current
1391
# XXX: robertc 20060220 reinstate this when there are two supported
1392
# formats which do not have an optimal code path between them.
1393
result.append((InterRepository,
1394
RepositoryFormat6(),
1395
RepositoryFormatKnit1()))
1396
for optimiser in InterRepository._optimisers:
1397
result.append((optimiser,
1398
optimiser._matching_repo_format,
1399
optimiser._matching_repo_format
1401
# if there are specific combinations we want to use, we can add them
1406
class CopyConverter(object):
1407
"""A repository conversion tool which just performs a copy of the content.
1409
This is slow but quite reliable.
1412
def __init__(self, target_format):
1413
"""Create a CopyConverter.
1415
:param target_format: The format the resulting repository should be.
1417
self.target_format = target_format
1419
def convert(self, repo, pb):
1420
"""Perform the conversion of to_convert, giving feedback via pb.
1422
:param to_convert: The disk object to convert.
1423
:param pb: a progress bar to use for progress information.
1428
# this is only useful with metadir layouts - separated repo content.
1429
# trigger an assertion if not such
1430
repo._format.get_format_string()
1431
self.repo_dir = repo.bzrdir
1432
self.step('Moving repository to repository.backup')
1433
self.repo_dir.transport.move('repository', 'repository.backup')
1434
backup_transport = self.repo_dir.transport.clone('repository.backup')
1435
self.source_repo = repo._format.open(self.repo_dir,
1437
_override_transport=backup_transport)
1438
self.step('Creating new repository')
1439
converted = self.target_format.initialize(self.repo_dir,
1440
self.source_repo.is_shared())
1441
converted.lock_write()
1443
self.step('Copying content into repository.')
1444
self.source_repo.copy_content_into(converted)
1447
self.step('Deleting old repository content.')
1448
self.repo_dir.transport.delete_tree('repository.backup')
1449
self.pb.note('repository converted')
1451
def step(self, message):
1452
"""Update the pb by a step."""
1454
self.pb.update(message, self.count, self.total)