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.lockable_files import LockableFiles
27
from bzrlib.osutils import safe_unicode
28
from bzrlib.revision import NULL_REVISION
29
from bzrlib.store import copy_all
30
from bzrlib.store.weave import WeaveStore
31
from bzrlib.store.text import TextStore
32
from bzrlib.symbol_versioning import *
33
from bzrlib.trace import mutter
34
from bzrlib.tree import RevisionTree
35
from bzrlib.testament import Testament
36
from bzrlib.tree import EmptyTree
41
class Repository(object):
42
"""Repository holding history for one or more branches.
44
The repository holds and retrieves historical information including
45
revisions and file history. It's normally accessed only by the Branch,
46
which views a particular line of development through that history.
48
The Repository builds on top of Stores and a Transport, which respectively
49
describe the disk data format and the way of accessing the (possibly
54
def _all_possible_ids(self):
55
"""Return all the possible revisions that we could find."""
56
return self.get_inventory_weave().names()
59
def all_revision_ids(self):
60
"""Returns a list of all the revision ids in the repository.
62
These are in as much topological order as the underlying store can
63
present: for weaves ghosts may lead to a lack of correctness until
64
the reweave updates the parents list.
66
result = self._all_possible_ids()
67
return self._eliminate_revisions_not_present(result)
70
def _eliminate_revisions_not_present(self, revision_ids):
71
"""Check every revision id in revision_ids to see if we have it.
73
Returns a set of the present revisions.
76
for id in revision_ids:
77
if self.has_revision(id):
83
"""Construct the current default format repository in a_bzrdir."""
84
return RepositoryFormat.get_default_format().initialize(a_bzrdir)
86
def __init__(self, _format, a_bzrdir, control_files, revision_store):
87
"""instantiate a Repository.
89
:param _format: The format of the repository on disk.
90
:param a_bzrdir: The BzrDir of the repository.
92
In the future we will have a single api for all stores for
93
getting file texts, inventories and revisions, then
94
this construct will accept instances of those things.
97
self._format = _format
98
# the following are part of the public API for Repository:
99
self.bzrdir = a_bzrdir
100
self.control_files = control_files
101
self.revision_store = revision_store
103
def lock_write(self):
104
self.control_files.lock_write()
107
self.control_files.lock_read()
110
def missing_revision_ids(self, other, revision_id=None):
111
"""Return the revision ids that other has that this does not.
113
These are returned in topological order.
115
revision_id: only return revision ids included by revision_id.
117
return InterRepository.get(other, self).missing_revision_ids(revision_id)
121
"""Open the repository rooted at base.
123
For instance, if the repository is at URL/.bzr/repository,
124
Repository.open(URL) -> a Repository instance.
126
control = bzrlib.bzrdir.BzrDir.open(base)
127
return control.open_repository()
129
def copy_content_into(self, destination, revision_id=None, basis=None):
130
"""Make a complete copy of the content in self into destination.
132
This is a destructive operation! Do not use it on existing
135
return InterRepository.get(self, destination).copy_content(revision_id, basis)
137
def fetch(self, source, revision_id=None, pb=None):
138
"""Fetch the content required to construct revision_id from source.
140
If revision_id is None all content is copied.
142
return InterRepository.get(source, self).fetch(revision_id=revision_id,
146
self.control_files.unlock()
149
def clone(self, a_bzrdir, revision_id=None, basis=None):
150
"""Clone this repository into a_bzrdir using the current format.
152
Currently no check is made that the format of this repository and
153
the bzrdir format are compatible. FIXME RBC 20060201.
155
if not isinstance(a_bzrdir._format, self.bzrdir._format.__class__):
156
# use target default format.
157
result = a_bzrdir.create_repository()
158
# FIXME RBC 20060209 split out the repository type to avoid this check ?
159
elif isinstance(a_bzrdir._format,
160
(bzrlib.bzrdir.BzrDirFormat4,
161
bzrlib.bzrdir.BzrDirFormat5,
162
bzrlib.bzrdir.BzrDirFormat6)):
163
result = a_bzrdir.open_repository()
165
result = self._format.initialize(a_bzrdir, shared=self.is_shared())
166
self.copy_content_into(result, revision_id, basis)
169
def has_revision(self, revision_id):
170
"""True if this branch has a copy of the revision.
172
This does not necessarily imply the revision is merge
173
or on the mainline."""
174
return (revision_id is None
175
or self.revision_store.has_id(revision_id))
178
def get_revision_xml_file(self, revision_id):
179
"""Return XML file object for revision object."""
180
if not revision_id or not isinstance(revision_id, basestring):
181
raise InvalidRevisionId(revision_id=revision_id, branch=self)
183
return self.revision_store.get(revision_id)
184
except (IndexError, KeyError):
185
raise bzrlib.errors.NoSuchRevision(self, revision_id)
188
def get_revision_xml(self, revision_id):
189
return self.get_revision_xml_file(revision_id).read()
192
def get_revision(self, revision_id):
193
"""Return the Revision object for a named revision"""
194
xml_file = self.get_revision_xml_file(revision_id)
197
r = bzrlib.xml5.serializer_v5.read_revision(xml_file)
198
except SyntaxError, e:
199
raise bzrlib.errors.BzrError('failed to unpack revision_xml',
203
assert r.revision_id == revision_id
207
def get_revision_sha1(self, revision_id):
208
"""Hash the stored value of a revision, and return it."""
209
# In the future, revision entries will be signed. At that
210
# point, it is probably best *not* to include the signature
211
# in the revision hash. Because that lets you re-sign
212
# the revision, (add signatures/remove signatures) and still
213
# have all hash pointers stay consistent.
214
# But for now, just hash the contents.
215
return bzrlib.osutils.sha_file(self.get_revision_xml_file(revision_id))
218
def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
219
self.revision_store.add(StringIO(gpg_strategy.sign(plaintext)),
222
def fileid_involved_between_revs(self, from_revid, to_revid):
223
"""Find file_id(s) which are involved in the changes between revisions.
225
This determines the set of revisions which are involved, and then
226
finds all file ids affected by those revisions.
228
# TODO: jam 20060119 This code assumes that w.inclusions will
229
# always be correct. But because of the presence of ghosts
230
# it is possible to be wrong.
231
# One specific example from Robert Collins:
232
# Two branches, with revisions ABC, and AD
233
# C is a ghost merge of D.
234
# Inclusions doesn't recognize D as an ancestor.
235
# If D is ever merged in the future, the weave
236
# won't be fixed, because AD never saw revision C
237
# to cause a conflict which would force a reweave.
238
w = self.get_inventory_weave()
239
from_set = set(w.inclusions([w.lookup(from_revid)]))
240
to_set = set(w.inclusions([w.lookup(to_revid)]))
241
included = to_set.difference(from_set)
242
changed = map(w.idx_to_name, included)
243
return self._fileid_involved_by_set(changed)
245
def fileid_involved(self, last_revid=None):
246
"""Find all file_ids modified in the ancestry of last_revid.
248
:param last_revid: If None, last_revision() will be used.
250
w = self.get_inventory_weave()
252
changed = set(w._names)
254
included = w.inclusions([w.lookup(last_revid)])
255
changed = map(w.idx_to_name, included)
256
return self._fileid_involved_by_set(changed)
258
def fileid_involved_by_set(self, changes):
259
"""Find all file_ids modified by the set of revisions passed in.
261
:param changes: A set() of revision ids
263
# TODO: jam 20060119 This line does *nothing*, remove it.
264
# or better yet, change _fileid_involved_by_set so
265
# that it takes the inventory weave, rather than
266
# pulling it out by itself.
267
return self._fileid_involved_by_set(changes)
269
def _fileid_involved_by_set(self, changes):
270
"""Find the set of file-ids affected by the set of revisions.
272
:param changes: A set() of revision ids.
273
:return: A set() of file ids.
275
This peaks at the Weave, interpreting each line, looking to
276
see if it mentions one of the revisions. And if so, includes
277
the file id mentioned.
278
This expects both the Weave format, and the serialization
279
to have a single line per file/directory, and to have
280
fileid="" and revision="" on that line.
282
assert isinstance(self._format, (RepositoryFormat5,
285
RepositoryFormatKnit1)), \
286
"fileid_involved only supported for branches which store inventory as unnested xml"
288
w = self.get_inventory_weave()
290
for line in w._weave:
292
# it is ugly, but it is due to the weave structure
293
if not isinstance(line, basestring): continue
295
start = line.find('file_id="')+9
296
if start < 9: continue
297
end = line.find('"', start)
299
file_id = xml.sax.saxutils.unescape(line[start:end])
301
# check if file_id is already present
302
if file_id in file_ids: continue
304
start = line.find('revision="')+10
305
if start < 10: continue
306
end = line.find('"', start)
308
revision_id = xml.sax.saxutils.unescape(line[start:end])
310
if revision_id in changes:
311
file_ids.add(file_id)
315
def get_inventory_weave(self):
316
return self.control_weaves.get_weave('inventory',
317
self.get_transaction())
320
def get_inventory(self, revision_id):
321
"""Get Inventory object by hash."""
322
xml = self.get_inventory_xml(revision_id)
323
return bzrlib.xml5.serializer_v5.read_inventory_from_string(xml)
326
def get_inventory_xml(self, revision_id):
327
"""Get inventory XML as a file object."""
329
assert isinstance(revision_id, basestring), type(revision_id)
330
iw = self.get_inventory_weave()
331
return iw.get_text(iw.lookup(revision_id))
333
raise bzrlib.errors.HistoryMissing(self, 'inventory', revision_id)
336
def get_inventory_sha1(self, revision_id):
337
"""Return the sha1 hash of the inventory entry
339
return self.get_revision(revision_id).inventory_sha1
342
def get_revision_inventory(self, revision_id):
343
"""Return inventory of a past revision."""
344
# TODO: Unify this with get_inventory()
345
# bzr 0.0.6 and later imposes the constraint that the inventory_id
346
# must be the same as its revision, so this is trivial.
347
if revision_id is None:
348
# This does not make sense: if there is no revision,
349
# then it is the current tree inventory surely ?!
350
# and thus get_root_id() is something that looks at the last
351
# commit on the branch, and the get_root_id is an inventory check.
352
raise NotImplementedError
353
# return Inventory(self.get_root_id())
355
return self.get_inventory(revision_id)
359
"""Return True if this repository is flagged as a shared repository."""
360
# FIXME format 4-6 cannot be shared, this is technically faulty.
361
return self.control_files._transport.has('shared-storage')
364
def revision_tree(self, revision_id):
365
"""Return Tree for a revision on this branch.
367
`revision_id` may be None for the null revision, in which case
368
an `EmptyTree` is returned."""
369
# TODO: refactor this to use an existing revision object
370
# so we don't need to read it in twice.
371
if revision_id is None or revision_id == NULL_REVISION:
374
inv = self.get_revision_inventory(revision_id)
375
return RevisionTree(self, inv, revision_id)
378
def get_ancestry(self, revision_id):
379
"""Return a list of revision-ids integrated by a revision.
381
This is topologically sorted.
383
if revision_id is None:
385
if not self.has_revision(revision_id):
386
raise errors.NoSuchRevision(self, revision_id)
387
w = self.get_inventory_weave()
388
return [None] + map(w.idx_to_name,
389
w.inclusions([w.lookup(revision_id)]))
392
def print_file(self, file, revision_id):
393
"""Print `file` to stdout.
395
FIXME RBC 20060125 as John Meinel points out this is a bad api
396
- it writes to stdout, it assumes that that is valid etc. Fix
397
by creating a new more flexible convenience function.
399
tree = self.revision_tree(revision_id)
400
# use inventory as it was in that revision
401
file_id = tree.inventory.path2id(file)
403
raise BzrError("%r is not present in revision %s" % (file, revno))
405
revno = self.revision_id_to_revno(revision_id)
406
except errors.NoSuchRevision:
407
# TODO: This should not be BzrError,
408
# but NoSuchFile doesn't fit either
409
raise BzrError('%r is not present in revision %s'
410
% (file, revision_id))
412
raise BzrError('%r is not present in revision %s'
414
tree.print_file(file_id)
416
def get_transaction(self):
417
return self.control_files.get_transaction()
420
def set_make_working_trees(self, new_value):
421
"""Set the policy flag for making working trees when creating branches.
423
This only applies to branches that use this repository.
425
The default is 'True'.
426
:param new_value: True to restore the default, False to disable making
429
# FIXME: split out into a new class/strategy ?
430
if isinstance(self._format, (RepositoryFormat4,
433
raise NotImplementedError(self.set_make_working_trees)
436
self.control_files._transport.delete('no-working-trees')
437
except errors.NoSuchFile:
440
self.control_files.put_utf8('no-working-trees', '')
442
def make_working_trees(self):
443
"""Returns the policy for making working trees on new branches."""
444
# FIXME: split out into a new class/strategy ?
445
if isinstance(self._format, (RepositoryFormat4,
449
return not self.control_files._transport.has('no-working-trees')
452
def sign_revision(self, revision_id, gpg_strategy):
453
plaintext = Testament.from_revision(self, revision_id).as_short_text()
454
self.store_revision_signature(gpg_strategy, plaintext, revision_id)
457
class AllInOneRepository(Repository):
458
"""Legacy support - the repository behaviour for all-in-one branches."""
460
def __init__(self, _format, a_bzrdir, revision_store):
461
# we reuse one control files instance.
462
dir_mode = a_bzrdir._control_files._dir_mode
463
file_mode = a_bzrdir._control_files._file_mode
465
def get_weave(name, prefixed=False):
467
name = safe_unicode(name)
470
relpath = a_bzrdir._control_files._escape(name)
471
weave_transport = a_bzrdir._control_files._transport.clone(relpath)
472
ws = WeaveStore(weave_transport, prefixed=prefixed,
475
if a_bzrdir._control_files._transport.should_cache():
476
ws.enable_cache = True
479
def get_store(name, compressed=True, prefixed=False):
480
# FIXME: This approach of assuming stores are all entirely compressed
481
# or entirely uncompressed is tidy, but breaks upgrade from
482
# some existing branches where there's a mixture; we probably
483
# still want the option to look for both.
484
relpath = a_bzrdir._control_files._escape(name)
485
store = TextStore(a_bzrdir._control_files._transport.clone(relpath),
486
prefixed=prefixed, compressed=compressed,
489
#if self._transport.should_cache():
490
# cache_path = os.path.join(self.cache_root, name)
491
# os.mkdir(cache_path)
492
# store = bzrlib.store.CachedStore(store, cache_path)
495
# not broken out yet because the controlweaves|inventory_store
496
# and text_store | weave_store bits are still different.
497
if isinstance(_format, RepositoryFormat4):
498
self.inventory_store = get_store('inventory-store')
499
self.text_store = get_store('text-store')
500
elif isinstance(_format, RepositoryFormat5):
501
self.control_weaves = get_weave('')
502
self.weave_store = get_weave('weaves')
503
elif isinstance(_format, RepositoryFormat6):
504
self.control_weaves = get_weave('')
505
self.weave_store = get_weave('weaves', prefixed=True)
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)
513
class MetaDirRepository(Repository):
514
"""Repositories in the new meta-dir layout."""
516
def __init__(self, _format, a_bzrdir, control_files, revision_store):
517
super(MetaDirRepository, self).__init__(_format,
522
dir_mode = self.control_files._dir_mode
523
file_mode = self.control_files._file_mode
525
def get_weave(name, prefixed=False):
527
name = safe_unicode(name)
530
relpath = self.control_files._escape(name)
531
weave_transport = self.control_files._transport.clone(relpath)
532
ws = WeaveStore(weave_transport, prefixed=prefixed,
535
if self.control_files._transport.should_cache():
536
ws.enable_cache = True
539
if isinstance(self._format, RepositoryFormat7):
540
self.control_weaves = get_weave('')
541
self.weave_store = get_weave('weaves', prefixed=True)
542
elif isinstance(self._format, RepositoryFormatKnit1):
543
self.control_weaves = get_weave('')
544
self.weave_store = get_weave('knits', prefixed=True)
546
raise errors.BzrError('unreachable code: unexpected repository'
550
class RepositoryFormat(object):
551
"""A repository format.
553
Formats provide three things:
554
* An initialization routine to construct repository data on disk.
555
* a format string which is used when the BzrDir supports versioned
557
* an open routine which returns a Repository instance.
559
Formats are placed in an dict by their format string for reference
560
during opening. These should be subclasses of RepositoryFormat
563
Once a format is deprecated, just deprecate the initialize and open
564
methods on the format class. Do not deprecate the object, as the
565
object will be created every system load.
567
Common instance attributes:
568
_matchingbzrdir - the bzrdir format that the repository format was
569
originally written to work with. This can be used if manually
570
constructing a bzrdir and repository, or more commonly for test suite
574
_default_format = None
575
"""The default format used for new repositories."""
578
"""The known formats."""
581
def find_format(klass, a_bzrdir):
582
"""Return the format for the repository object in a_bzrdir."""
584
transport = a_bzrdir.get_repository_transport(None)
585
format_string = transport.get("format").read()
586
return klass._formats[format_string]
587
except errors.NoSuchFile:
588
raise errors.NoRepositoryPresent(a_bzrdir)
590
raise errors.UnknownFormatError(format_string)
593
def get_default_format(klass):
594
"""Return the current default format."""
595
return klass._default_format
597
def get_format_string(self):
598
"""Return the ASCII format string that identifies this format.
600
Note that in pre format ?? repositories the format string is
601
not permitted nor written to disk.
603
raise NotImplementedError(self.get_format_string)
605
def _get_revision_store(self, repo_transport, control_files):
606
"""Return the revision store object for this a_bzrdir."""
607
raise NotImplementedError(self._get_rev_store)
609
def _get_rev_store(self,
615
"""Common logic for getting a revision store for a repository.
617
see self._get_revision_store for the method to
618
get the store for a repository.
621
name = safe_unicode(name)
624
dir_mode = control_files._dir_mode
625
file_mode = control_files._file_mode
626
revision_store =TextStore(transport.clone(name),
628
compressed=compressed,
631
revision_store.register_suffix('sig')
632
return revision_store
634
def initialize(self, a_bzrdir, shared=False):
635
"""Initialize a repository of this format in a_bzrdir.
637
:param a_bzrdir: The bzrdir to put the new repository in it.
638
:param shared: The repository should be initialized as a sharable one.
640
This may raise UninitializableFormat if shared repository are not
641
compatible the a_bzrdir.
644
def is_supported(self):
645
"""Is this format supported?
647
Supported formats must be initializable and openable.
648
Unsupported formats may not support initialization or committing or
649
some other features depending on the reason for not being supported.
653
def open(self, a_bzrdir, _found=False):
654
"""Return an instance of this format for the bzrdir a_bzrdir.
656
_found is a private parameter, do not use it.
658
raise NotImplementedError(self.open)
661
def register_format(klass, format):
662
klass._formats[format.get_format_string()] = format
665
def set_default_format(klass, format):
666
klass._default_format = format
669
def unregister_format(klass, format):
670
assert klass._formats[format.get_format_string()] is format
671
del klass._formats[format.get_format_string()]
674
class PreSplitOutRepositoryFormat(RepositoryFormat):
675
"""Base class for the pre split out repository formats."""
677
def initialize(self, a_bzrdir, shared=False, _internal=False):
678
"""Create a weave repository.
680
TODO: when creating split out bzr branch formats, move this to a common
681
base for Format5, Format6. or something like that.
683
from bzrlib.weavefile import write_weave_v5
684
from bzrlib.weave import Weave
687
raise errors.IncompatibleFormat(self, a_bzrdir._format)
690
# always initialized when the bzrdir is.
691
return self.open(a_bzrdir, _found=True)
693
# Create an empty weave
695
bzrlib.weavefile.write_weave_v5(Weave(), sio)
696
empty_weave = sio.getvalue()
698
mutter('creating repository in %s.', a_bzrdir.transport.base)
699
dirs = ['revision-store', 'weaves']
700
lock_file = 'branch-lock'
701
files = [('inventory.weave', StringIO(empty_weave)),
704
# FIXME: RBC 20060125 dont peek under the covers
705
# NB: no need to escape relative paths that are url safe.
706
control_files = LockableFiles(a_bzrdir.transport, 'branch-lock')
707
control_files.lock_write()
708
control_files._transport.mkdir_multi(dirs,
709
mode=control_files._dir_mode)
711
for file, content in files:
712
control_files.put(file, content)
714
control_files.unlock()
715
return self.open(a_bzrdir, _found=True)
717
def open(self, a_bzrdir, _found=False):
718
"""See RepositoryFormat.open()."""
720
# we are being called directly and must probe.
721
raise NotImplementedError
723
repo_transport = a_bzrdir.get_repository_transport(None)
724
control_files = a_bzrdir._control_files
725
revision_store = self._get_revision_store(repo_transport, control_files)
726
return AllInOneRepository(_format=self,
728
revision_store=revision_store)
731
class RepositoryFormat4(PreSplitOutRepositoryFormat):
732
"""Bzr repository format 4.
734
This repository format has:
736
- TextStores for texts, inventories,revisions.
738
This format is deprecated: it indexes texts using a text id which is
739
removed in format 5; initializationa and write support for this format
744
super(RepositoryFormat4, self).__init__()
745
self._matchingbzrdir = bzrlib.bzrdir.BzrDirFormat4()
747
def initialize(self, url, shared=False, _internal=False):
748
"""Format 4 branches cannot be created."""
749
raise errors.UninitializableFormat(self)
751
def is_supported(self):
752
"""Format 4 is not supported.
754
It is not supported because the model changed from 4 to 5 and the
755
conversion logic is expensive - so doing it on the fly was not
760
def _get_revision_store(self, repo_transport, control_files):
761
"""See RepositoryFormat._get_revision_store()."""
762
return self._get_rev_store(repo_transport,
767
class RepositoryFormat5(PreSplitOutRepositoryFormat):
768
"""Bzr control format 5.
770
This repository format has:
771
- weaves for file texts and inventory
773
- TextStores for revisions and signatures.
777
super(RepositoryFormat5, self).__init__()
778
self._matchingbzrdir = bzrlib.bzrdir.BzrDirFormat5()
780
def _get_revision_store(self, repo_transport, control_files):
781
"""See RepositoryFormat._get_revision_store()."""
782
"""Return the revision store object for this a_bzrdir."""
783
return self._get_rev_store(repo_transport,
789
class RepositoryFormat6(PreSplitOutRepositoryFormat):
790
"""Bzr control format 6.
792
This repository format has:
793
- weaves for file texts and inventory
794
- hash subdirectory based stores.
795
- TextStores for revisions and signatures.
799
super(RepositoryFormat6, self).__init__()
800
self._matchingbzrdir = bzrlib.bzrdir.BzrDirFormat6()
802
def _get_revision_store(self, repo_transport, control_files):
803
"""See RepositoryFormat._get_revision_store()."""
804
return self._get_rev_store(repo_transport,
811
class MetaDirRepositoryFormat(RepositoryFormat):
812
"""Common base class for the new repositories using the metadir layour."""
815
super(MetaDirRepositoryFormat, self).__init__()
816
self._matchingbzrdir = bzrlib.bzrdir.BzrDirMetaFormat1()
818
def _create_control_files(self, a_bzrdir):
819
"""Create the required files and the initial control_files object."""
820
# FIXME: RBC 20060125 dont peek under the covers
821
# NB: no need to escape relative paths that are url safe.
823
repository_transport = a_bzrdir.get_repository_transport(self)
824
repository_transport.put(lock_file, StringIO()) # TODO get the file mode from the bzrdir lock files., mode=file_mode)
825
control_files = LockableFiles(repository_transport, 'lock')
828
def _get_revision_store(self, repo_transport, control_files):
829
"""See RepositoryFormat._get_revision_store()."""
830
return self._get_rev_store(repo_transport,
837
def open(self, a_bzrdir, _found=False, _override_transport=None):
838
"""See RepositoryFormat.open().
840
:param _override_transport: INTERNAL USE ONLY. Allows opening the
841
repository at a slightly different url
842
than normal. I.e. during 'upgrade'.
845
format = RepositoryFormat.find_format(a_bzrdir)
846
assert format.__class__ == self.__class__
847
if _override_transport is not None:
848
repo_transport = _override_transport
850
repo_transport = a_bzrdir.get_repository_transport(None)
851
control_files = LockableFiles(repo_transport, 'lock')
852
revision_store = self._get_revision_store(repo_transport, control_files)
853
return MetaDirRepository(_format=self,
855
control_files=control_files,
856
revision_store=revision_store)
858
def _upload_blank_content(self, a_bzrdir, dirs, files, utf8_files, shared):
859
"""Upload the initial blank content."""
860
control_files = self._create_control_files(a_bzrdir)
861
control_files.lock_write()
862
control_files._transport.mkdir_multi(dirs,
863
mode=control_files._dir_mode)
865
for file, content in files:
866
control_files.put(file, content)
867
for file, content in utf8_files:
868
control_files.put_utf8(file, content)
870
control_files.put_utf8('shared-storage', '')
872
control_files.unlock()
875
class RepositoryFormat7(MetaDirRepositoryFormat):
878
This repository format has:
879
- weaves for file texts and inventory
880
- hash subdirectory based stores.
881
- TextStores for revisions and signatures.
882
- a format marker of its own
883
- an optional 'shared-storage' flag
884
- an optional 'no-working-trees' flag
887
def get_format_string(self):
888
"""See RepositoryFormat.get_format_string()."""
889
return "Bazaar-NG Repository format 7"
891
def initialize(self, a_bzrdir, shared=False):
892
"""Create a weave repository.
894
:param shared: If true the repository will be initialized as a shared
897
from bzrlib.weavefile import write_weave_v5
898
from bzrlib.weave import Weave
900
# Create an empty weave
902
bzrlib.weavefile.write_weave_v5(Weave(), sio)
903
empty_weave = sio.getvalue()
905
mutter('creating repository in %s.', a_bzrdir.transport.base)
906
dirs = ['revision-store', 'weaves']
907
files = [('inventory.weave', StringIO(empty_weave)),
909
utf8_files = [('format', self.get_format_string())]
911
self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
912
return self.open(a_bzrdir=a_bzrdir, _found=True)
915
class RepositoryFormatKnit1(MetaDirRepositoryFormat):
916
"""Bzr repository knit format 1.
918
This repository format has:
919
- knits for file texts and inventory
920
- hash subdirectory based stores.
921
- knits for revisions and signatures
922
- TextStores for revisions and signatures.
923
- a format marker of its own
924
- an optional 'shared-storage' flag
925
- an optional 'no-working-trees' flag
928
def get_format_string(self):
929
"""See RepositoryFormat.get_format_string()."""
930
return "Bazaar-NG Knit Repository Format 1"
932
def initialize(self, a_bzrdir, shared=False):
933
"""Create a knit format 1 repository.
935
:param shared: If true the repository will be initialized as a shared
938
from bzrlib.weavefile import write_weave_v5
939
from bzrlib.weave import Weave
941
# Create an empty weave
943
bzrlib.weavefile.write_weave_v5(Weave(), sio)
944
empty_weave = sio.getvalue()
946
mutter('creating repository in %s.', a_bzrdir.transport.base)
947
dirs = ['revision-store', 'knits']
948
files = [('inventory.weave', StringIO(empty_weave)),
950
utf8_files = [('format', self.get_format_string())]
952
self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
953
return self.open(a_bzrdir=a_bzrdir, _found=True)
956
# formats which have no format string are not discoverable
957
# and not independently creatable, so are not registered.
958
_default_format = RepositoryFormat7()
959
RepositoryFormat.register_format(_default_format)
960
RepositoryFormat.register_format(RepositoryFormatKnit1())
961
RepositoryFormat.set_default_format(_default_format)
962
_legacy_formats = [RepositoryFormat4(),
967
class InterRepository(object):
968
"""This class represents operations taking place between two repositories.
970
Its instances have methods like copy_content and fetch, and contain
971
references to the source and target repositories these operations can be
974
Often we will provide convenience methods on 'repository' which carry out
975
operations with another repository - they will always forward to
976
InterRepository.get(other).method_name(parameters).
978
# XXX: FIXME: FUTURE: robertc
979
# testing of these probably requires a factory in optimiser type, and
980
# then a test adapter to test each type thoroughly.
984
"""The available optimised InterRepository types."""
986
def __init__(self, source, target):
987
"""Construct a default InterRepository instance. Please use 'get'.
989
Only subclasses of InterRepository should call
990
InterRepository.__init__ - clients should call InterRepository.get
991
instead which will create an optimised InterRepository if possible.
997
def copy_content(self, revision_id=None, basis=None):
998
"""Make a complete copy of the content in self into destination.
1000
This is a destructive operation! Do not use it on existing
1003
:param revision_id: Only copy the content needed to construct
1004
revision_id and its parents.
1005
:param basis: Copy the needed data preferentially from basis.
1008
self.target.set_make_working_trees(self.source.make_working_trees())
1009
except NotImplementedError:
1011
# grab the basis available data
1012
if basis is not None:
1013
self.target.fetch(basis, revision_id=revision_id)
1014
# but dont both fetching if we have the needed data now.
1015
if (revision_id not in (None, NULL_REVISION) and
1016
self.target.has_revision(revision_id)):
1018
self.target.fetch(self.source, revision_id=revision_id)
1020
def _double_lock(self, lock_source, lock_target):
1021
"""Take out too locks, rolling back the first if the second throws."""
1026
# we want to ensure that we don't leave source locked by mistake.
1027
# and any error on target should not confuse source.
1028
self.source.unlock()
1032
def fetch(self, revision_id=None, pb=None):
1033
"""Fetch the content required to construct revision_id.
1035
The content is copied from source to target.
1037
:param revision_id: if None all content is copied, if NULL_REVISION no
1039
:param pb: optional progress bar to use for progress reports. If not
1040
provided a default one will be created.
1042
Returns the copied revision count and the failed revisions in a tuple:
1045
from bzrlib.fetch import RepoFetcher
1046
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1047
self.source, self.source._format, self.target, self.target._format)
1048
f = RepoFetcher(to_repository=self.target,
1049
from_repository=self.source,
1050
last_revision=revision_id,
1052
return f.count_copied, f.failed_revisions
1055
def get(klass, repository_source, repository_target):
1056
"""Retrieve a InterRepository worker object for these repositories.
1058
:param repository_source: the repository to be the 'source' member of
1059
the InterRepository instance.
1060
:param repository_target: the repository to be the 'target' member of
1061
the InterRepository instance.
1062
If an optimised InterRepository worker exists it will be used otherwise
1063
a default InterRepository instance will be created.
1065
for provider in klass._optimisers:
1066
if provider.is_compatible(repository_source, repository_target):
1067
return provider(repository_source, repository_target)
1068
return InterRepository(repository_source, repository_target)
1070
def lock_read(self):
1071
"""Take out a logical read lock.
1073
This will lock the source branch and the target branch. The source gets
1074
a read lock and the target a read lock.
1076
self._double_lock(self.source.lock_read, self.target.lock_read)
1078
def lock_write(self):
1079
"""Take out a logical write lock.
1081
This will lock the source branch and the target branch. The source gets
1082
a read lock and the target a write lock.
1084
self._double_lock(self.source.lock_read, self.target.lock_write)
1087
def missing_revision_ids(self, revision_id=None):
1088
"""Return the revision ids that source has that target does not.
1090
These are returned in topological order.
1092
:param revision_id: only return revision ids included by this
1095
# generic, possibly worst case, slow code path.
1096
target_ids = set(self.target.all_revision_ids())
1097
if revision_id is not None:
1098
source_ids = self.source.get_ancestry(revision_id)
1099
assert source_ids.pop(0) == None
1101
source_ids = self.source.all_revision_ids()
1102
result_set = set(source_ids).difference(target_ids)
1103
# this may look like a no-op: its not. It preserves the ordering
1104
# other_ids had while only returning the members from other_ids
1105
# that we've decided we need.
1106
return [rev_id for rev_id in source_ids if rev_id in result_set]
1109
def register_optimiser(klass, optimiser):
1110
"""Register an InterRepository optimiser."""
1111
klass._optimisers.add(optimiser)
1114
"""Release the locks on source and target."""
1116
self.target.unlock()
1118
self.source.unlock()
1121
def unregister_optimiser(klass, optimiser):
1122
"""Unregister an InterRepository optimiser."""
1123
klass._optimisers.remove(optimiser)
1126
class InterWeaveRepo(InterRepository):
1127
"""Optimised code paths between Weave based repositories."""
1129
_matching_repo_format = _default_format
1130
"""Repository format for testing with."""
1133
def is_compatible(source, target):
1134
"""Be compatible with known Weave formats.
1136
We dont test for the stores being of specific types becase that
1137
could lead to confusing results, and there is no need to be
1141
return (isinstance(source._format, (RepositoryFormat5,
1143
RepositoryFormat7)) and
1144
isinstance(target._format, (RepositoryFormat5,
1146
RepositoryFormat7)))
1147
except AttributeError:
1151
def copy_content(self, revision_id=None, basis=None):
1152
"""See InterRepository.copy_content()."""
1153
# weave specific optimised path:
1154
if basis is not None:
1155
# copy the basis in, then fetch remaining data.
1156
basis.copy_content_into(self.target, revision_id)
1157
# the basis copy_content_into could misset this.
1159
self.target.set_make_working_trees(self.source.make_working_trees())
1160
except NotImplementedError:
1162
self.target.fetch(self.source, revision_id=revision_id)
1165
self.target.set_make_working_trees(self.source.make_working_trees())
1166
except NotImplementedError:
1168
# FIXME do not peek!
1169
if self.source.control_files._transport.listable():
1170
pb = bzrlib.ui.ui_factory.progress_bar()
1171
copy_all(self.source.weave_store,
1172
self.target.weave_store, pb=pb)
1173
pb.update('copying inventory', 0, 1)
1174
self.target.control_weaves.copy_multi(
1175
self.source.control_weaves, ['inventory'])
1176
copy_all(self.source.revision_store,
1177
self.target.revision_store, pb=pb)
1179
self.target.fetch(self.source, revision_id=revision_id)
1182
def fetch(self, revision_id=None, pb=None):
1183
"""See InterRepository.fetch()."""
1184
from bzrlib.fetch import RepoFetcher
1185
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1186
self.source, self.source._format, self.target, self.target._format)
1187
f = RepoFetcher(to_repository=self.target,
1188
from_repository=self.source,
1189
last_revision=revision_id,
1191
return f.count_copied, f.failed_revisions
1194
def missing_revision_ids(self, revision_id=None):
1195
"""See InterRepository.missing_revision_ids()."""
1196
# we want all revisions to satisfy revision_id in source.
1197
# but we dont want to stat every file here and there.
1198
# we want then, all revisions other needs to satisfy revision_id
1199
# checked, but not those that we have locally.
1200
# so the first thing is to get a subset of the revisions to
1201
# satisfy revision_id in source, and then eliminate those that
1202
# we do already have.
1203
# this is slow on high latency connection to self, but as as this
1204
# disk format scales terribly for push anyway due to rewriting
1205
# inventory.weave, this is considered acceptable.
1207
if revision_id is not None:
1208
source_ids = self.source.get_ancestry(revision_id)
1209
assert source_ids.pop(0) == None
1211
source_ids = self.source._all_possible_ids()
1212
source_ids_set = set(source_ids)
1213
# source_ids is the worst possible case we may need to pull.
1214
# now we want to filter source_ids against what we actually
1215
# have in target, but dont try to check for existence where we know
1216
# we do not have a revision as that would be pointless.
1217
target_ids = set(self.target._all_possible_ids())
1218
possibly_present_revisions = target_ids.intersection(source_ids_set)
1219
actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
1220
required_revisions = source_ids_set.difference(actually_present_revisions)
1221
required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
1222
if revision_id is not None:
1223
# we used get_ancestry to determine source_ids then we are assured all
1224
# revisions referenced are present as they are installed in topological order.
1225
# and the tip revision was validated by get_ancestry.
1226
return required_topo_revisions
1228
# if we just grabbed the possibly available ids, then
1229
# we only have an estimate of whats available and need to validate
1230
# that against the revision records.
1231
return self.source._eliminate_revisions_not_present(required_topo_revisions)
1234
InterRepository.register_optimiser(InterWeaveRepo)
1237
class RepositoryTestProviderAdapter(object):
1238
"""A tool to generate a suite testing multiple repository formats at once.
1240
This is done by copying the test once for each transport and injecting
1241
the transport_server, transport_readonly_server, and bzrdir_format and
1242
repository_format classes into each copy. Each copy is also given a new id()
1243
to make it easy to identify.
1246
def __init__(self, transport_server, transport_readonly_server, formats):
1247
self._transport_server = transport_server
1248
self._transport_readonly_server = transport_readonly_server
1249
self._formats = formats
1251
def adapt(self, test):
1252
result = TestSuite()
1253
for repository_format, bzrdir_format in self._formats:
1254
new_test = deepcopy(test)
1255
new_test.transport_server = self._transport_server
1256
new_test.transport_readonly_server = self._transport_readonly_server
1257
new_test.bzrdir_format = bzrdir_format
1258
new_test.repository_format = repository_format
1259
def make_new_test_id():
1260
new_id = "%s(%s)" % (new_test.id(), repository_format.__class__.__name__)
1261
return lambda: new_id
1262
new_test.id = make_new_test_id()
1263
result.addTest(new_test)
1267
class InterRepositoryTestProviderAdapter(object):
1268
"""A tool to generate a suite testing multiple inter repository formats.
1270
This is done by copying the test once for each interrepo provider and injecting
1271
the transport_server, transport_readonly_server, repository_format and
1272
repository_to_format classes into each copy.
1273
Each copy is also given a new id() to make it easy to identify.
1276
def __init__(self, transport_server, transport_readonly_server, formats):
1277
self._transport_server = transport_server
1278
self._transport_readonly_server = transport_readonly_server
1279
self._formats = formats
1281
def adapt(self, test):
1282
result = TestSuite()
1283
for interrepo_class, repository_format, repository_format_to in self._formats:
1284
new_test = deepcopy(test)
1285
new_test.transport_server = self._transport_server
1286
new_test.transport_readonly_server = self._transport_readonly_server
1287
new_test.interrepo_class = interrepo_class
1288
new_test.repository_format = repository_format
1289
new_test.repository_format_to = repository_format_to
1290
def make_new_test_id():
1291
new_id = "%s(%s)" % (new_test.id(), interrepo_class.__name__)
1292
return lambda: new_id
1293
new_test.id = make_new_test_id()
1294
result.addTest(new_test)
1298
def default_test_list():
1299
"""Generate the default list of interrepo permutations to test."""
1301
# test the default InterRepository between format 6 and the current
1303
# XXX: robertc 20060220 reinstate this when there are two supported
1304
# formats which do not have an optimal code path between them.
1305
result.append((InterRepository,
1306
RepositoryFormat6(),
1307
RepositoryFormatKnit1()))
1308
for optimiser in InterRepository._optimisers:
1309
result.append((optimiser,
1310
optimiser._matching_repo_format,
1311
optimiser._matching_repo_format
1313
# if there are specific combinations we want to use, we can add them
1318
class CopyConverter(object):
1319
"""A repository conversion tool which just performs a copy of the content.
1321
This is slow but quite reliable.
1324
def __init__(self, target_format):
1325
"""Create a CopyConverter.
1327
:param target_format: The format the resulting repository should be.
1329
self.target_format = target_format
1331
def convert(self, repo, pb):
1332
"""Perform the conversion of to_convert, giving feedback via pb.
1334
:param to_convert: The disk object to convert.
1335
:param pb: a progress bar to use for progress information.
1340
# this is only useful with metadir layouts - separated repo content.
1341
# trigger an assertion if not such
1342
repo._format.get_format_string()
1343
self.repo_dir = repo.bzrdir
1344
self.step('Moving repository to repository.backup')
1345
self.repo_dir.transport.move('repository', 'repository.backup')
1346
backup_transport = self.repo_dir.transport.clone('repository.backup')
1347
self.source_repo = repo._format.open(self.repo_dir,
1349
_override_transport=backup_transport)
1350
self.step('Creating new repository')
1351
converted = self.target_format.initialize(self.repo_dir,
1352
self.source_repo.is_shared())
1353
converted.lock_write()
1355
self.step('Copying content into repository.')
1356
self.source_repo.copy_content_into(converted)
1359
self.step('Deleting old repository content.')
1360
self.repo_dir.transport.delete_tree('repository.backup')
1361
self.pb.note('repository converted')
1363
def step(self, message):
1364
"""Update the pb by a step."""
1366
self.pb.update(message, self.count, self.total)