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
from bzrlib.inter import InterObject
27
from bzrlib.knit import KnitVersionedFile
28
from bzrlib.lockable_files import LockableFiles
29
from bzrlib.osutils import safe_unicode
30
from bzrlib.revision import NULL_REVISION
31
from bzrlib.store.versioned import VersionedFileStore, 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
39
from bzrlib.weave import WeaveFile
43
class Repository(object):
44
"""Repository holding history for one or more branches.
46
The repository holds and retrieves historical information including
47
revisions and file history. It's normally accessed only by the Branch,
48
which views a particular line of development through that history.
50
The Repository builds on top of Stores and a Transport, which respectively
51
describe the disk data format and the way of accessing the (possibly
56
def _all_possible_ids(self):
57
"""Return all the possible revisions that we could find."""
58
return self.get_inventory_weave().versions()
61
def all_revision_ids(self):
62
"""Returns a list of all the revision ids in the repository.
64
These are in as much topological order as the underlying store can
65
present: for weaves ghosts may lead to a lack of correctness until
66
the reweave updates the parents list.
68
result = self._all_possible_ids()
69
return self._eliminate_revisions_not_present(result)
72
def _eliminate_revisions_not_present(self, revision_ids):
73
"""Check every revision id in revision_ids to see if we have it.
75
Returns a set of the present revisions.
78
for id in revision_ids:
79
if self.has_revision(id):
85
"""Construct the current default format repository in a_bzrdir."""
86
return RepositoryFormat.get_default_format().initialize(a_bzrdir)
88
def __init__(self, _format, a_bzrdir, control_files, revision_store, text_store):
89
"""instantiate a Repository.
91
:param _format: The format of the repository on disk.
92
:param a_bzrdir: The BzrDir of the repository.
94
In the future we will have a single api for all stores for
95
getting file texts, inventories and revisions, then
96
this construct will accept instances of those things.
99
self._format = _format
100
# the following are part of the public API for Repository:
101
self.bzrdir = a_bzrdir
102
self.control_files = control_files
103
self.revision_store = revision_store
104
self.text_store = text_store
105
# backwards compatability
106
self.weave_store = text_store
108
def lock_write(self):
109
self.control_files.lock_write()
112
self.control_files.lock_read()
115
def missing_revision_ids(self, other, revision_id=None):
116
"""Return the revision ids that other has that this does not.
118
These are returned in topological order.
120
revision_id: only return revision ids included by revision_id.
122
return InterRepository.get(other, self).missing_revision_ids(revision_id)
126
"""Open the repository rooted at base.
128
For instance, if the repository is at URL/.bzr/repository,
129
Repository.open(URL) -> a Repository instance.
131
control = bzrlib.bzrdir.BzrDir.open(base)
132
return control.open_repository()
134
def copy_content_into(self, destination, revision_id=None, basis=None):
135
"""Make a complete copy of the content in self into destination.
137
This is a destructive operation! Do not use it on existing
140
return InterRepository.get(self, destination).copy_content(revision_id, basis)
142
def fetch(self, source, revision_id=None, pb=None):
143
"""Fetch the content required to construct revision_id from source.
145
If revision_id is None all content is copied.
147
return InterRepository.get(source, self).fetch(revision_id=revision_id,
151
self.control_files.unlock()
154
def clone(self, a_bzrdir, revision_id=None, basis=None):
155
"""Clone this repository into a_bzrdir using the current format.
157
Currently no check is made that the format of this repository and
158
the bzrdir format are compatible. FIXME RBC 20060201.
160
if not isinstance(a_bzrdir._format, self.bzrdir._format.__class__):
161
# use target default format.
162
result = a_bzrdir.create_repository()
163
# FIXME RBC 20060209 split out the repository type to avoid this check ?
164
elif isinstance(a_bzrdir._format,
165
(bzrlib.bzrdir.BzrDirFormat4,
166
bzrlib.bzrdir.BzrDirFormat5,
167
bzrlib.bzrdir.BzrDirFormat6)):
168
result = a_bzrdir.open_repository()
170
result = self._format.initialize(a_bzrdir, shared=self.is_shared())
171
self.copy_content_into(result, revision_id, basis)
174
def has_revision(self, revision_id):
175
"""True if this branch has a copy of the revision.
177
This does not necessarily imply the revision is merge
178
or on the mainline."""
179
return (revision_id is None
180
or self.revision_store.has_id(revision_id))
183
def get_revision_xml_file(self, revision_id):
184
"""Return XML file object for revision object."""
185
if not revision_id or not isinstance(revision_id, basestring):
186
raise InvalidRevisionId(revision_id=revision_id, branch=self)
188
return self.revision_store.get(revision_id)
189
except (IndexError, KeyError):
190
raise bzrlib.errors.NoSuchRevision(self, revision_id)
193
def get_revision_xml(self, revision_id):
194
return self.get_revision_xml_file(revision_id).read()
197
def get_revision(self, revision_id):
198
"""Return the Revision object for a named revision"""
199
xml_file = self.get_revision_xml_file(revision_id)
202
r = bzrlib.xml5.serializer_v5.read_revision(xml_file)
203
except SyntaxError, e:
204
raise bzrlib.errors.BzrError('failed to unpack revision_xml',
208
assert r.revision_id == revision_id
212
def get_revision_sha1(self, revision_id):
213
"""Hash the stored value of a revision, and return it."""
214
# In the future, revision entries will be signed. At that
215
# point, it is probably best *not* to include the signature
216
# in the revision hash. Because that lets you re-sign
217
# the revision, (add signatures/remove signatures) and still
218
# have all hash pointers stay consistent.
219
# But for now, just hash the contents.
220
return bzrlib.osutils.sha_file(self.get_revision_xml_file(revision_id))
223
def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
224
self.revision_store.add(StringIO(gpg_strategy.sign(plaintext)),
227
def fileid_involved_between_revs(self, from_revid, to_revid):
228
"""Find file_id(s) which are involved in the changes between revisions.
230
This determines the set of revisions which are involved, and then
231
finds all file ids affected by those revisions.
233
# TODO: jam 20060119 This code assumes that w.inclusions will
234
# always be correct. But because of the presence of ghosts
235
# it is possible to be wrong.
236
# One specific example from Robert Collins:
237
# Two branches, with revisions ABC, and AD
238
# C is a ghost merge of D.
239
# Inclusions doesn't recognize D as an ancestor.
240
# If D is ever merged in the future, the weave
241
# won't be fixed, because AD never saw revision C
242
# to cause a conflict which would force a reweave.
243
w = self.get_inventory_weave()
244
from_set = set(w.get_ancestry(from_revid))
245
to_set = set(w.get_ancestry(to_revid))
246
changed = to_set.difference(from_set)
247
return self._fileid_involved_by_set(changed)
249
def fileid_involved(self, last_revid=None):
250
"""Find all file_ids modified in the ancestry of last_revid.
252
:param last_revid: If None, last_revision() will be used.
254
w = self.get_inventory_weave()
256
changed = set(w.versions())
258
changed = set(w.get_ancestry(last_revid))
259
return self._fileid_involved_by_set(changed)
261
def fileid_involved_by_set(self, changes):
262
"""Find all file_ids modified by the set of revisions passed in.
264
:param changes: A set() of revision ids
266
# TODO: jam 20060119 This line does *nothing*, remove it.
267
# or better yet, change _fileid_involved_by_set so
268
# that it takes the inventory weave, rather than
269
# pulling it out by itself.
270
return self._fileid_involved_by_set(changes)
272
def _fileid_involved_by_set(self, changes):
273
"""Find the set of file-ids affected by the set of revisions.
275
:param changes: A set() of revision ids.
276
:return: A set() of file ids.
278
This peaks at the Weave, interpreting each line, looking to
279
see if it mentions one of the revisions. And if so, includes
280
the file id mentioned.
281
This expects both the Weave format, and the serialization
282
to have a single line per file/directory, and to have
283
fileid="" and revision="" on that line.
285
assert isinstance(self._format, (RepositoryFormat5,
288
RepositoryFormatKnit1)), \
289
"fileid_involved only supported for branches which store inventory as unnested xml"
291
w = self.get_inventory_weave()
293
for line in w._weave:
295
# it is ugly, but it is due to the weave structure
296
if not isinstance(line, basestring): continue
298
start = line.find('file_id="')+9
299
if start < 9: continue
300
end = line.find('"', start)
302
file_id = xml.sax.saxutils.unescape(line[start:end])
304
# check if file_id is already present
305
if file_id in file_ids: continue
307
start = line.find('revision="')+10
308
if start < 10: continue
309
end = line.find('"', start)
311
revision_id = xml.sax.saxutils.unescape(line[start:end])
313
if revision_id in changes:
314
file_ids.add(file_id)
318
def get_inventory_weave(self):
319
return self.control_weaves.get_weave('inventory',
320
self.get_transaction())
323
def get_inventory(self, revision_id):
324
"""Get Inventory object by hash."""
325
xml = self.get_inventory_xml(revision_id)
326
return bzrlib.xml5.serializer_v5.read_inventory_from_string(xml)
329
def get_inventory_xml(self, revision_id):
330
"""Get inventory XML as a file object."""
332
assert isinstance(revision_id, basestring), type(revision_id)
333
iw = self.get_inventory_weave()
334
return iw.get_text(revision_id)
336
raise bzrlib.errors.HistoryMissing(self, 'inventory', revision_id)
339
def get_inventory_sha1(self, revision_id):
340
"""Return the sha1 hash of the inventory entry
342
return self.get_revision(revision_id).inventory_sha1
345
def get_revision_inventory(self, revision_id):
346
"""Return inventory of a past revision."""
347
# TODO: Unify this with get_inventory()
348
# bzr 0.0.6 and later imposes the constraint that the inventory_id
349
# must be the same as its revision, so this is trivial.
350
if revision_id is None:
351
# This does not make sense: if there is no revision,
352
# then it is the current tree inventory surely ?!
353
# and thus get_root_id() is something that looks at the last
354
# commit on the branch, and the get_root_id is an inventory check.
355
raise NotImplementedError
356
# return Inventory(self.get_root_id())
358
return self.get_inventory(revision_id)
362
"""Return True if this repository is flagged as a shared repository."""
363
# FIXME format 4-6 cannot be shared, this is technically faulty.
364
return self.control_files._transport.has('shared-storage')
367
def revision_tree(self, revision_id):
368
"""Return Tree for a revision on this branch.
370
`revision_id` may be None for the null revision, in which case
371
an `EmptyTree` is returned."""
372
# TODO: refactor this to use an existing revision object
373
# so we don't need to read it in twice.
374
if revision_id is None or revision_id == NULL_REVISION:
377
inv = self.get_revision_inventory(revision_id)
378
return RevisionTree(self, inv, revision_id)
381
def get_ancestry(self, revision_id):
382
"""Return a list of revision-ids integrated by a revision.
384
This is topologically sorted.
386
if revision_id is None:
388
if not self.has_revision(revision_id):
389
raise errors.NoSuchRevision(self, revision_id)
390
w = self.get_inventory_weave()
391
return [None] + w.get_ancestry(revision_id)
394
def print_file(self, file, revision_id):
395
"""Print `file` to stdout.
397
FIXME RBC 20060125 as John Meinel points out this is a bad api
398
- it writes to stdout, it assumes that that is valid etc. Fix
399
by creating a new more flexible convenience function.
401
tree = self.revision_tree(revision_id)
402
# use inventory as it was in that revision
403
file_id = tree.inventory.path2id(file)
405
raise BzrError("%r is not present in revision %s" % (file, revno))
407
revno = self.revision_id_to_revno(revision_id)
408
except errors.NoSuchRevision:
409
# TODO: This should not be BzrError,
410
# but NoSuchFile doesn't fit either
411
raise BzrError('%r is not present in revision %s'
412
% (file, revision_id))
414
raise BzrError('%r is not present in revision %s'
416
tree.print_file(file_id)
418
def get_transaction(self):
419
return self.control_files.get_transaction()
422
def set_make_working_trees(self, new_value):
423
"""Set the policy flag for making working trees when creating branches.
425
This only applies to branches that use this repository.
427
The default is 'True'.
428
:param new_value: True to restore the default, False to disable making
431
# FIXME: split out into a new class/strategy ?
432
if isinstance(self._format, (RepositoryFormat4,
435
raise NotImplementedError(self.set_make_working_trees)
438
self.control_files._transport.delete('no-working-trees')
439
except errors.NoSuchFile:
442
self.control_files.put_utf8('no-working-trees', '')
444
def make_working_trees(self):
445
"""Returns the policy for making working trees on new branches."""
446
# FIXME: split out into a new class/strategy ?
447
if isinstance(self._format, (RepositoryFormat4,
451
return not self.control_files._transport.has('no-working-trees')
454
def sign_revision(self, revision_id, gpg_strategy):
455
plaintext = Testament.from_revision(self, revision_id).as_short_text()
456
self.store_revision_signature(gpg_strategy, plaintext, revision_id)
459
class AllInOneRepository(Repository):
460
"""Legacy support - the repository behaviour for all-in-one branches."""
462
def __init__(self, _format, a_bzrdir, revision_store, text_store):
463
# we reuse one control files instance.
464
dir_mode = a_bzrdir._control_files._dir_mode
465
file_mode = a_bzrdir._control_files._file_mode
467
def get_weave(name, prefixed=False):
469
name = safe_unicode(name)
472
relpath = a_bzrdir._control_files._escape(name)
473
weave_transport = a_bzrdir._control_files._transport.clone(relpath)
474
ws = WeaveStore(weave_transport, prefixed=prefixed,
477
if a_bzrdir._control_files._transport.should_cache():
478
ws.enable_cache = True
481
def get_store(name, compressed=True, prefixed=False):
482
# FIXME: This approach of assuming stores are all entirely compressed
483
# or entirely uncompressed is tidy, but breaks upgrade from
484
# some existing branches where there's a mixture; we probably
485
# still want the option to look for both.
486
relpath = a_bzrdir._control_files._escape(name)
487
store = TextStore(a_bzrdir._control_files._transport.clone(relpath),
488
prefixed=prefixed, compressed=compressed,
491
#if self._transport.should_cache():
492
# cache_path = os.path.join(self.cache_root, name)
493
# os.mkdir(cache_path)
494
# store = bzrlib.store.CachedStore(store, cache_path)
497
# not broken out yet because the controlweaves|inventory_store
498
# and text_store | weave_store bits are still different.
499
if isinstance(_format, RepositoryFormat4):
500
self.inventory_store = get_store('inventory-store')
501
text_store = get_store('text-store')
502
elif isinstance(_format, RepositoryFormat5):
503
self.control_weaves = get_weave('')
504
elif isinstance(_format, RepositoryFormat6):
505
self.control_weaves = get_weave('')
507
raise errors.BzrError('unreachable code: unexpected repository'
509
revision_store.register_suffix('sig')
510
super(AllInOneRepository, self).__init__(_format, a_bzrdir, a_bzrdir._control_files, revision_store, text_store)
513
class MetaDirRepository(Repository):
514
"""Repositories in the new meta-dir layout."""
516
def __init__(self, _format, a_bzrdir, control_files, revision_store, text_store):
517
super(MetaDirRepository, self).__init__(_format,
523
dir_mode = self.control_files._dir_mode
524
file_mode = self.control_files._file_mode
526
def get_weave(name, prefixed=False):
528
name = safe_unicode(name)
531
relpath = self.control_files._escape(name)
532
weave_transport = self.control_files._transport.clone(relpath)
533
ws = WeaveStore(weave_transport, prefixed=prefixed,
536
if self.control_files._transport.should_cache():
537
ws.enable_cache = True
540
if isinstance(self._format, RepositoryFormat7):
541
self.control_weaves = get_weave('')
542
elif isinstance(self._format, RepositoryFormatKnit1):
543
self.control_weaves = get_weave('control')
545
raise errors.BzrError('unreachable code: unexpected repository'
549
class RepositoryFormat(object):
550
"""A repository format.
552
Formats provide three things:
553
* An initialization routine to construct repository data on disk.
554
* a format string which is used when the BzrDir supports versioned
556
* an open routine which returns a Repository instance.
558
Formats are placed in an dict by their format string for reference
559
during opening. These should be subclasses of RepositoryFormat
562
Once a format is deprecated, just deprecate the initialize and open
563
methods on the format class. Do not deprecate the object, as the
564
object will be created every system load.
566
Common instance attributes:
567
_matchingbzrdir - the bzrdir format that the repository format was
568
originally written to work with. This can be used if manually
569
constructing a bzrdir and repository, or more commonly for test suite
573
_default_format = None
574
"""The default format used for new repositories."""
577
"""The known formats."""
580
def find_format(klass, a_bzrdir):
581
"""Return the format for the repository object in a_bzrdir."""
583
transport = a_bzrdir.get_repository_transport(None)
584
format_string = transport.get("format").read()
585
return klass._formats[format_string]
586
except errors.NoSuchFile:
587
raise errors.NoRepositoryPresent(a_bzrdir)
589
raise errors.UnknownFormatError(format_string)
592
def get_default_format(klass):
593
"""Return the current default format."""
594
return klass._default_format
596
def get_format_string(self):
597
"""Return the ASCII format string that identifies this format.
599
Note that in pre format ?? repositories the format string is
600
not permitted nor written to disk.
602
raise NotImplementedError(self.get_format_string)
604
def _get_revision_store(self, repo_transport, control_files):
605
"""Return the revision store object for this a_bzrdir."""
606
raise NotImplementedError(self._get_revision_store)
608
def _get_rev_store(self,
614
"""Common logic for getting a revision store for a repository.
616
see self._get_revision_store for the subclass-overridable method to
617
get the store for a repository.
619
dir_mode = control_files._dir_mode
620
file_mode = control_files._file_mode
621
revision_store =TextStore(transport.clone(name),
623
compressed=compressed,
626
revision_store.register_suffix('sig')
627
return revision_store
629
def _get_versioned_file_store(self,
634
versionedfile_class=WeaveFile):
635
weave_transport = control_files._transport.clone(name)
636
dir_mode = control_files._dir_mode
637
file_mode = control_files._file_mode
638
return VersionedFileStore(weave_transport, prefixed=prefixed,
641
versionedfile_class=versionedfile_class)
643
def initialize(self, a_bzrdir, shared=False):
644
"""Initialize a repository of this format in a_bzrdir.
646
:param a_bzrdir: The bzrdir to put the new repository in it.
647
:param shared: The repository should be initialized as a sharable one.
649
This may raise UninitializableFormat if shared repository are not
650
compatible the a_bzrdir.
653
def is_supported(self):
654
"""Is this format supported?
656
Supported formats must be initializable and openable.
657
Unsupported formats may not support initialization or committing or
658
some other features depending on the reason for not being supported.
662
def open(self, a_bzrdir, _found=False):
663
"""Return an instance of this format for the bzrdir a_bzrdir.
665
_found is a private parameter, do not use it.
667
raise NotImplementedError(self.open)
670
def register_format(klass, format):
671
klass._formats[format.get_format_string()] = format
674
def set_default_format(klass, format):
675
klass._default_format = format
678
def unregister_format(klass, format):
679
assert klass._formats[format.get_format_string()] is format
680
del klass._formats[format.get_format_string()]
683
class PreSplitOutRepositoryFormat(RepositoryFormat):
684
"""Base class for the pre split out repository formats."""
686
def initialize(self, a_bzrdir, shared=False, _internal=False):
687
"""Create a weave repository.
689
TODO: when creating split out bzr branch formats, move this to a common
690
base for Format5, Format6. or something like that.
692
from bzrlib.weavefile import write_weave_v5
693
from bzrlib.weave import Weave
696
raise errors.IncompatibleFormat(self, a_bzrdir._format)
699
# always initialized when the bzrdir is.
700
return self.open(a_bzrdir, _found=True)
702
# Create an empty weave
704
bzrlib.weavefile.write_weave_v5(Weave(), sio)
705
empty_weave = sio.getvalue()
707
mutter('creating repository in %s.', a_bzrdir.transport.base)
708
dirs = ['revision-store', 'weaves']
709
lock_file = 'branch-lock'
710
files = [('inventory.weave', StringIO(empty_weave)),
713
# FIXME: RBC 20060125 dont peek under the covers
714
# NB: no need to escape relative paths that are url safe.
715
control_files = LockableFiles(a_bzrdir.transport, 'branch-lock')
716
control_files.lock_write()
717
control_files._transport.mkdir_multi(dirs,
718
mode=control_files._dir_mode)
720
for file, content in files:
721
control_files.put(file, content)
723
control_files.unlock()
724
return self.open(a_bzrdir, _found=True)
726
def _get_text_store(self, transport, control_files):
727
"""Get a store for file texts for this format."""
728
raise NotImplementedError(self._get_text_store)
730
def open(self, a_bzrdir, _found=False):
731
"""See RepositoryFormat.open()."""
733
# we are being called directly and must probe.
734
raise NotImplementedError
736
repo_transport = a_bzrdir.get_repository_transport(None)
737
control_files = a_bzrdir._control_files
738
revision_store = self._get_revision_store(repo_transport, control_files)
739
text_store = self._get_text_store(repo_transport, control_files)
740
return AllInOneRepository(_format=self,
742
revision_store=revision_store,
743
text_store=text_store)
746
class RepositoryFormat4(PreSplitOutRepositoryFormat):
747
"""Bzr repository format 4.
749
This repository format has:
751
- TextStores for texts, inventories,revisions.
753
This format is deprecated: it indexes texts using a text id which is
754
removed in format 5; initializationa and write support for this format
759
super(RepositoryFormat4, self).__init__()
760
self._matchingbzrdir = bzrlib.bzrdir.BzrDirFormat4()
762
def initialize(self, url, shared=False, _internal=False):
763
"""Format 4 branches cannot be created."""
764
raise errors.UninitializableFormat(self)
766
def is_supported(self):
767
"""Format 4 is not supported.
769
It is not supported because the model changed from 4 to 5 and the
770
conversion logic is expensive - so doing it on the fly was not
775
def _get_revision_store(self, repo_transport, control_files):
776
"""See RepositoryFormat._get_revision_store()."""
777
return self._get_rev_store(repo_transport,
781
def _get_text_store(self, transport, control_files):
782
"""See RepositoryFormat._get_text_store()."""
785
class RepositoryFormat5(PreSplitOutRepositoryFormat):
786
"""Bzr control format 5.
788
This repository format has:
789
- weaves for file texts and inventory
791
- TextStores for revisions and signatures.
795
super(RepositoryFormat5, self).__init__()
796
self._matchingbzrdir = bzrlib.bzrdir.BzrDirFormat5()
798
def _get_revision_store(self, repo_transport, control_files):
799
"""See RepositoryFormat._get_revision_store()."""
800
"""Return the revision store object for this a_bzrdir."""
801
return self._get_rev_store(repo_transport,
806
def _get_text_store(self, transport, control_files):
807
"""See RepositoryFormat._get_text_store()."""
808
return self._get_versioned_file_store('weaves', transport, control_files, prefixed=False)
811
class RepositoryFormat6(PreSplitOutRepositoryFormat):
812
"""Bzr control format 6.
814
This repository format has:
815
- weaves for file texts and inventory
816
- hash subdirectory based stores.
817
- TextStores for revisions and signatures.
821
super(RepositoryFormat6, self).__init__()
822
self._matchingbzrdir = bzrlib.bzrdir.BzrDirFormat6()
824
def _get_revision_store(self, repo_transport, control_files):
825
"""See RepositoryFormat._get_revision_store()."""
826
return self._get_rev_store(repo_transport,
832
def _get_text_store(self, transport, control_files):
833
"""See RepositoryFormat._get_text_store()."""
834
return self._get_versioned_file_store('weaves', transport, control_files)
837
class MetaDirRepositoryFormat(RepositoryFormat):
838
"""Common base class for the new repositories using the metadir layour."""
841
super(MetaDirRepositoryFormat, self).__init__()
842
self._matchingbzrdir = bzrlib.bzrdir.BzrDirMetaFormat1()
844
def _create_control_files(self, a_bzrdir):
845
"""Create the required files and the initial control_files object."""
846
# FIXME: RBC 20060125 dont peek under the covers
847
# NB: no need to escape relative paths that are url safe.
849
repository_transport = a_bzrdir.get_repository_transport(self)
850
repository_transport.put(lock_file, StringIO()) # TODO get the file mode from the bzrdir lock files., mode=file_mode)
851
control_files = LockableFiles(repository_transport, 'lock')
854
def _get_revision_store(self, repo_transport, control_files):
855
"""See RepositoryFormat._get_revision_store()."""
856
return self._get_rev_store(repo_transport,
863
def open(self, a_bzrdir, _found=False, _override_transport=None):
864
"""See RepositoryFormat.open().
866
:param _override_transport: INTERNAL USE ONLY. Allows opening the
867
repository at a slightly different url
868
than normal. I.e. during 'upgrade'.
871
format = RepositoryFormat.find_format(a_bzrdir)
872
assert format.__class__ == self.__class__
873
if _override_transport is not None:
874
repo_transport = _override_transport
876
repo_transport = a_bzrdir.get_repository_transport(None)
877
control_files = LockableFiles(repo_transport, 'lock')
878
revision_store = self._get_revision_store(repo_transport, control_files)
879
text_store = self._get_text_store(repo_transport, control_files)
880
return MetaDirRepository(_format=self,
882
control_files=control_files,
883
revision_store=revision_store,
884
text_store=text_store)
886
def _upload_blank_content(self, a_bzrdir, dirs, files, utf8_files, shared):
887
"""Upload the initial blank content."""
888
control_files = self._create_control_files(a_bzrdir)
889
control_files.lock_write()
890
control_files._transport.mkdir_multi(dirs,
891
mode=control_files._dir_mode)
893
for file, content in files:
894
control_files.put(file, content)
895
for file, content in utf8_files:
896
control_files.put_utf8(file, content)
898
control_files.put_utf8('shared-storage', '')
900
control_files.unlock()
903
class RepositoryFormat7(MetaDirRepositoryFormat):
906
This repository format has:
907
- weaves for file texts and inventory
908
- hash subdirectory based stores.
909
- TextStores for revisions and signatures.
910
- a format marker of its own
911
- an optional 'shared-storage' flag
912
- an optional 'no-working-trees' flag
915
def get_format_string(self):
916
"""See RepositoryFormat.get_format_string()."""
917
return "Bazaar-NG Repository format 7"
919
def _get_text_store(self, transport, control_files):
920
"""See RepositoryFormat._get_text_store()."""
921
return self._get_versioned_file_store('weaves',
925
def initialize(self, a_bzrdir, shared=False):
926
"""Create a weave repository.
928
:param shared: If true the repository will be initialized as a shared
931
from bzrlib.weavefile import write_weave_v5
932
from bzrlib.weave import Weave
934
# Create an empty weave
936
bzrlib.weavefile.write_weave_v5(Weave(), sio)
937
empty_weave = sio.getvalue()
939
mutter('creating repository in %s.', a_bzrdir.transport.base)
940
dirs = ['revision-store', 'weaves']
941
files = [('inventory.weave', StringIO(empty_weave)),
943
utf8_files = [('format', self.get_format_string())]
945
self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
946
return self.open(a_bzrdir=a_bzrdir, _found=True)
949
class RepositoryFormatKnit1(MetaDirRepositoryFormat):
950
"""Bzr repository knit format 1.
952
This repository format has:
953
- knits for file texts and inventory
954
- hash subdirectory based stores.
955
- knits for revisions and signatures
956
- TextStores for revisions and signatures.
957
- a format marker of its own
958
- an optional 'shared-storage' flag
959
- an optional 'no-working-trees' flag
962
def get_format_string(self):
963
"""See RepositoryFormat.get_format_string()."""
964
return "Bazaar-NG Knit Repository Format 1"
966
def _get_text_store(self, transport, control_files):
967
"""See RepositoryFormat._get_text_store()."""
968
return self._get_versioned_file_store('knits',
971
versionedfile_class=KnitVersionedFile)
973
def initialize(self, a_bzrdir, shared=False):
974
"""Create a knit format 1 repository.
976
:param shared: If true the repository will be initialized as a shared
978
XXX NOTE that this current uses a Weave for testing and will become
979
A Knit in due course.
981
from bzrlib.weavefile import write_weave_v5
982
from bzrlib.weave import Weave
984
# Create an empty weave
986
bzrlib.weavefile.write_weave_v5(Weave(), sio)
987
empty_weave = sio.getvalue()
989
mutter('creating repository in %s.', a_bzrdir.transport.base)
990
dirs = ['revision-store', 'knits', 'control']
991
files = [('control/inventory.weave', StringIO(empty_weave)),
993
utf8_files = [('format', self.get_format_string())]
995
self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
996
return self.open(a_bzrdir=a_bzrdir, _found=True)
999
# formats which have no format string are not discoverable
1000
# and not independently creatable, so are not registered.
1001
_default_format = RepositoryFormat7()
1002
RepositoryFormat.register_format(_default_format)
1003
RepositoryFormat.register_format(RepositoryFormatKnit1())
1004
RepositoryFormat.set_default_format(_default_format)
1005
_legacy_formats = [RepositoryFormat4(),
1006
RepositoryFormat5(),
1007
RepositoryFormat6()]
1010
class InterRepository(InterObject):
1011
"""This class represents operations taking place between two repositories.
1013
Its instances have methods like copy_content and fetch, and contain
1014
references to the source and target repositories these operations can be
1017
Often we will provide convenience methods on 'repository' which carry out
1018
operations with another repository - they will always forward to
1019
InterRepository.get(other).method_name(parameters).
1023
"""The available optimised InterRepository types."""
1026
def copy_content(self, revision_id=None, basis=None):
1027
"""Make a complete copy of the content in self into destination.
1029
This is a destructive operation! Do not use it on existing
1032
:param revision_id: Only copy the content needed to construct
1033
revision_id and its parents.
1034
:param basis: Copy the needed data preferentially from basis.
1037
self.target.set_make_working_trees(self.source.make_working_trees())
1038
except NotImplementedError:
1040
# grab the basis available data
1041
if basis is not None:
1042
self.target.fetch(basis, revision_id=revision_id)
1043
# but dont both fetching if we have the needed data now.
1044
if (revision_id not in (None, NULL_REVISION) and
1045
self.target.has_revision(revision_id)):
1047
self.target.fetch(self.source, revision_id=revision_id)
1049
def _double_lock(self, lock_source, lock_target):
1050
"""Take out too locks, rolling back the first if the second throws."""
1055
# we want to ensure that we don't leave source locked by mistake.
1056
# and any error on target should not confuse source.
1057
self.source.unlock()
1061
def fetch(self, revision_id=None, pb=None):
1062
"""Fetch the content required to construct revision_id.
1064
The content is copied from source to target.
1066
:param revision_id: if None all content is copied, if NULL_REVISION no
1068
:param pb: optional progress bar to use for progress reports. If not
1069
provided a default one will be created.
1071
Returns the copied revision count and the failed revisions in a tuple:
1074
from bzrlib.fetch import RepoFetcher
1075
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1076
self.source, self.source._format, self.target, self.target._format)
1077
f = RepoFetcher(to_repository=self.target,
1078
from_repository=self.source,
1079
last_revision=revision_id,
1081
return f.count_copied, f.failed_revisions
1083
def lock_read(self):
1084
"""Take out a logical read lock.
1086
This will lock the source branch and the target branch. The source gets
1087
a read lock and the target a read lock.
1089
self._double_lock(self.source.lock_read, self.target.lock_read)
1091
def lock_write(self):
1092
"""Take out a logical write lock.
1094
This will lock the source branch and the target branch. The source gets
1095
a read lock and the target a write lock.
1097
self._double_lock(self.source.lock_read, self.target.lock_write)
1100
def missing_revision_ids(self, revision_id=None):
1101
"""Return the revision ids that source has that target does not.
1103
These are returned in topological order.
1105
:param revision_id: only return revision ids included by this
1108
# generic, possibly worst case, slow code path.
1109
target_ids = set(self.target.all_revision_ids())
1110
if revision_id is not None:
1111
source_ids = self.source.get_ancestry(revision_id)
1112
assert source_ids.pop(0) == None
1114
source_ids = self.source.all_revision_ids()
1115
result_set = set(source_ids).difference(target_ids)
1116
# this may look like a no-op: its not. It preserves the ordering
1117
# other_ids had while only returning the members from other_ids
1118
# that we've decided we need.
1119
return [rev_id for rev_id in source_ids if rev_id in result_set]
1122
"""Release the locks on source and target."""
1124
self.target.unlock()
1126
self.source.unlock()
1129
class InterWeaveRepo(InterRepository):
1130
"""Optimised code paths between Weave based repositories."""
1132
_matching_repo_format = _default_format
1133
"""Repository format for testing with."""
1136
def is_compatible(source, target):
1137
"""Be compatible with known Weave formats.
1139
We dont test for the stores being of specific types becase that
1140
could lead to confusing results, and there is no need to be
1144
return (isinstance(source._format, (RepositoryFormat5,
1146
RepositoryFormat7)) and
1147
isinstance(target._format, (RepositoryFormat5,
1149
RepositoryFormat7)))
1150
except AttributeError:
1154
def copy_content(self, revision_id=None, basis=None):
1155
"""See InterRepository.copy_content()."""
1156
# weave specific optimised path:
1157
if basis is not None:
1158
# copy the basis in, then fetch remaining data.
1159
basis.copy_content_into(self.target, revision_id)
1160
# the basis copy_content_into could misset this.
1162
self.target.set_make_working_trees(self.source.make_working_trees())
1163
except NotImplementedError:
1165
self.target.fetch(self.source, revision_id=revision_id)
1168
self.target.set_make_working_trees(self.source.make_working_trees())
1169
except NotImplementedError:
1171
# FIXME do not peek!
1172
if self.source.control_files._transport.listable():
1173
pb = bzrlib.ui.ui_factory.progress_bar()
1174
self.target.weave_store.copy_all_ids(
1175
self.source.weave_store,
1177
from_transaction=self.source.get_transaction())
1178
pb.update('copying inventory', 0, 1)
1179
self.target.control_weaves.copy_multi(
1180
self.source.control_weaves, ['inventory'],
1181
from_transaction=self.source.get_transaction())
1182
self.target.revision_store.copy_all_ids(
1183
self.source.revision_store,
1186
self.target.fetch(self.source, revision_id=revision_id)
1189
def fetch(self, revision_id=None, pb=None):
1190
"""See InterRepository.fetch()."""
1191
from bzrlib.fetch import RepoFetcher
1192
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1193
self.source, self.source._format, self.target, self.target._format)
1194
f = RepoFetcher(to_repository=self.target,
1195
from_repository=self.source,
1196
last_revision=revision_id,
1198
return f.count_copied, f.failed_revisions
1201
def missing_revision_ids(self, revision_id=None):
1202
"""See InterRepository.missing_revision_ids()."""
1203
# we want all revisions to satisfy revision_id in source.
1204
# but we dont want to stat every file here and there.
1205
# we want then, all revisions other needs to satisfy revision_id
1206
# checked, but not those that we have locally.
1207
# so the first thing is to get a subset of the revisions to
1208
# satisfy revision_id in source, and then eliminate those that
1209
# we do already have.
1210
# this is slow on high latency connection to self, but as as this
1211
# disk format scales terribly for push anyway due to rewriting
1212
# inventory.weave, this is considered acceptable.
1214
if revision_id is not None:
1215
source_ids = self.source.get_ancestry(revision_id)
1216
assert source_ids.pop(0) == None
1218
source_ids = self.source._all_possible_ids()
1219
source_ids_set = set(source_ids)
1220
# source_ids is the worst possible case we may need to pull.
1221
# now we want to filter source_ids against what we actually
1222
# have in target, but dont try to check for existence where we know
1223
# we do not have a revision as that would be pointless.
1224
target_ids = set(self.target._all_possible_ids())
1225
possibly_present_revisions = target_ids.intersection(source_ids_set)
1226
actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
1227
required_revisions = source_ids_set.difference(actually_present_revisions)
1228
required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
1229
if revision_id is not None:
1230
# we used get_ancestry to determine source_ids then we are assured all
1231
# revisions referenced are present as they are installed in topological order.
1232
# and the tip revision was validated by get_ancestry.
1233
return required_topo_revisions
1235
# if we just grabbed the possibly available ids, then
1236
# we only have an estimate of whats available and need to validate
1237
# that against the revision records.
1238
return self.source._eliminate_revisions_not_present(required_topo_revisions)
1241
InterRepository.register_optimiser(InterWeaveRepo)
1244
class RepositoryTestProviderAdapter(object):
1245
"""A tool to generate a suite testing multiple repository formats at once.
1247
This is done by copying the test once for each transport and injecting
1248
the transport_server, transport_readonly_server, and bzrdir_format and
1249
repository_format classes into each copy. Each copy is also given a new id()
1250
to make it easy to identify.
1253
def __init__(self, transport_server, transport_readonly_server, formats):
1254
self._transport_server = transport_server
1255
self._transport_readonly_server = transport_readonly_server
1256
self._formats = formats
1258
def adapt(self, test):
1259
result = TestSuite()
1260
for repository_format, bzrdir_format in self._formats:
1261
new_test = deepcopy(test)
1262
new_test.transport_server = self._transport_server
1263
new_test.transport_readonly_server = self._transport_readonly_server
1264
new_test.bzrdir_format = bzrdir_format
1265
new_test.repository_format = repository_format
1266
def make_new_test_id():
1267
new_id = "%s(%s)" % (new_test.id(), repository_format.__class__.__name__)
1268
return lambda: new_id
1269
new_test.id = make_new_test_id()
1270
result.addTest(new_test)
1274
class InterRepositoryTestProviderAdapter(object):
1275
"""A tool to generate a suite testing multiple inter repository formats.
1277
This is done by copying the test once for each interrepo provider and injecting
1278
the transport_server, transport_readonly_server, repository_format and
1279
repository_to_format classes into each copy.
1280
Each copy is also given a new id() to make it easy to identify.
1283
def __init__(self, transport_server, transport_readonly_server, formats):
1284
self._transport_server = transport_server
1285
self._transport_readonly_server = transport_readonly_server
1286
self._formats = formats
1288
def adapt(self, test):
1289
result = TestSuite()
1290
for interrepo_class, repository_format, repository_format_to in self._formats:
1291
new_test = deepcopy(test)
1292
new_test.transport_server = self._transport_server
1293
new_test.transport_readonly_server = self._transport_readonly_server
1294
new_test.interrepo_class = interrepo_class
1295
new_test.repository_format = repository_format
1296
new_test.repository_format_to = repository_format_to
1297
def make_new_test_id():
1298
new_id = "%s(%s)" % (new_test.id(), interrepo_class.__name__)
1299
return lambda: new_id
1300
new_test.id = make_new_test_id()
1301
result.addTest(new_test)
1305
def default_test_list():
1306
"""Generate the default list of interrepo permutations to test."""
1308
# test the default InterRepository between format 6 and the current
1310
# XXX: robertc 20060220 reinstate this when there are two supported
1311
# formats which do not have an optimal code path between them.
1312
result.append((InterRepository,
1313
RepositoryFormat6(),
1314
RepositoryFormatKnit1()))
1315
for optimiser in InterRepository._optimisers:
1316
result.append((optimiser,
1317
optimiser._matching_repo_format,
1318
optimiser._matching_repo_format
1320
# if there are specific combinations we want to use, we can add them
1325
class CopyConverter(object):
1326
"""A repository conversion tool which just performs a copy of the content.
1328
This is slow but quite reliable.
1331
def __init__(self, target_format):
1332
"""Create a CopyConverter.
1334
:param target_format: The format the resulting repository should be.
1336
self.target_format = target_format
1338
def convert(self, repo, pb):
1339
"""Perform the conversion of to_convert, giving feedback via pb.
1341
:param to_convert: The disk object to convert.
1342
:param pb: a progress bar to use for progress information.
1347
# this is only useful with metadir layouts - separated repo content.
1348
# trigger an assertion if not such
1349
repo._format.get_format_string()
1350
self.repo_dir = repo.bzrdir
1351
self.step('Moving repository to repository.backup')
1352
self.repo_dir.transport.move('repository', 'repository.backup')
1353
backup_transport = self.repo_dir.transport.clone('repository.backup')
1354
self.source_repo = repo._format.open(self.repo_dir,
1356
_override_transport=backup_transport)
1357
self.step('Creating new repository')
1358
converted = self.target_format.initialize(self.repo_dir,
1359
self.source_repo.is_shared())
1360
converted.lock_write()
1362
self.step('Copying content into repository.')
1363
self.source_repo.copy_content_into(converted)
1366
self.step('Deleting old repository content.')
1367
self.repo_dir.transport.delete_tree('repository.backup')
1368
self.pb.note('repository converted')
1370
def step(self, message):
1371
"""Update the pb by a step."""
1373
self.pb.update(message, self.count, self.total)