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.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.versioned.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 _all_possible_ids(self):
56
"""Return all the possible revisions that we could find."""
57
return self.get_inventory_weave().versions()
60
def all_revision_ids(self):
61
"""Returns a list of all the revision ids in the repository.
63
These are in as much topological order as the underlying store can
64
present: for weaves ghosts may lead to a lack of correctness until
65
the reweave updates the parents list.
67
result = self._all_possible_ids()
68
return self._eliminate_revisions_not_present(result)
71
def _eliminate_revisions_not_present(self, revision_ids):
72
"""Check every revision id in revision_ids to see if we have it.
74
Returns a set of the present revisions.
77
for id in revision_ids:
78
if self.has_revision(id):
84
"""Construct the current default format repository in a_bzrdir."""
85
return RepositoryFormat.get_default_format().initialize(a_bzrdir)
87
def __init__(self, _format, a_bzrdir, control_files, revision_store):
88
"""instantiate a Repository.
90
:param _format: The format of the repository on disk.
91
:param a_bzrdir: The BzrDir of the repository.
93
In the future we will have a single api for all stores for
94
getting file texts, inventories and revisions, then
95
this construct will accept instances of those things.
98
self._format = _format
99
# the following are part of the public API for Repository:
100
self.bzrdir = a_bzrdir
101
self.control_files = control_files
102
self.revision_store = revision_store
104
def lock_write(self):
105
self.control_files.lock_write()
108
self.control_files.lock_read()
111
def missing_revision_ids(self, other, revision_id=None):
112
"""Return the revision ids that other has that this does not.
114
These are returned in topological order.
116
revision_id: only return revision ids included by revision_id.
118
return InterRepository.get(other, self).missing_revision_ids(revision_id)
122
"""Open the repository rooted at base.
124
For instance, if the repository is at URL/.bzr/repository,
125
Repository.open(URL) -> a Repository instance.
127
control = bzrlib.bzrdir.BzrDir.open(base)
128
return control.open_repository()
130
def copy_content_into(self, destination, revision_id=None, basis=None):
131
"""Make a complete copy of the content in self into destination.
133
This is a destructive operation! Do not use it on existing
136
return InterRepository.get(self, destination).copy_content(revision_id, basis)
138
def fetch(self, source, revision_id=None, pb=None):
139
"""Fetch the content required to construct revision_id from source.
141
If revision_id is None all content is copied.
143
return InterRepository.get(source, self).fetch(revision_id=revision_id,
147
self.control_files.unlock()
150
def clone(self, a_bzrdir, revision_id=None, basis=None):
151
"""Clone this repository into a_bzrdir using the current format.
153
Currently no check is made that the format of this repository and
154
the bzrdir format are compatible. FIXME RBC 20060201.
156
if not isinstance(a_bzrdir._format, self.bzrdir._format.__class__):
157
# use target default format.
158
result = a_bzrdir.create_repository()
159
# FIXME RBC 20060209 split out the repository type to avoid this check ?
160
elif isinstance(a_bzrdir._format,
161
(bzrlib.bzrdir.BzrDirFormat4,
162
bzrlib.bzrdir.BzrDirFormat5,
163
bzrlib.bzrdir.BzrDirFormat6)):
164
result = a_bzrdir.open_repository()
166
result = self._format.initialize(a_bzrdir, shared=self.is_shared())
167
self.copy_content_into(result, revision_id, basis)
170
def has_revision(self, revision_id):
171
"""True if this branch has a copy of the revision.
173
This does not necessarily imply the revision is merge
174
or on the mainline."""
175
return (revision_id is None
176
or self.revision_store.has_id(revision_id))
179
def get_revision_xml_file(self, revision_id):
180
"""Return XML file object for revision object."""
181
if not revision_id or not isinstance(revision_id, basestring):
182
raise InvalidRevisionId(revision_id=revision_id, branch=self)
184
return self.revision_store.get(revision_id)
185
except (IndexError, KeyError):
186
raise bzrlib.errors.NoSuchRevision(self, revision_id)
189
def get_revision_xml(self, revision_id):
190
return self.get_revision_xml_file(revision_id).read()
193
def get_revision(self, revision_id):
194
"""Return the Revision object for a named revision"""
195
xml_file = self.get_revision_xml_file(revision_id)
198
r = bzrlib.xml5.serializer_v5.read_revision(xml_file)
199
except SyntaxError, e:
200
raise bzrlib.errors.BzrError('failed to unpack revision_xml',
204
assert r.revision_id == revision_id
208
def get_revision_sha1(self, revision_id):
209
"""Hash the stored value of a revision, and return it."""
210
# In the future, revision entries will be signed. At that
211
# point, it is probably best *not* to include the signature
212
# in the revision hash. Because that lets you re-sign
213
# the revision, (add signatures/remove signatures) and still
214
# have all hash pointers stay consistent.
215
# But for now, just hash the contents.
216
return bzrlib.osutils.sha_file(self.get_revision_xml_file(revision_id))
219
def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
220
self.revision_store.add(StringIO(gpg_strategy.sign(plaintext)),
223
def fileid_involved_between_revs(self, from_revid, to_revid):
224
"""Find file_id(s) which are involved in the changes between revisions.
226
This determines the set of revisions which are involved, and then
227
finds all file ids affected by those revisions.
229
# TODO: jam 20060119 This code assumes that w.inclusions will
230
# always be correct. But because of the presence of ghosts
231
# it is possible to be wrong.
232
# One specific example from Robert Collins:
233
# Two branches, with revisions ABC, and AD
234
# C is a ghost merge of D.
235
# Inclusions doesn't recognize D as an ancestor.
236
# If D is ever merged in the future, the weave
237
# won't be fixed, because AD never saw revision C
238
# to cause a conflict which would force a reweave.
239
w = self.get_inventory_weave()
240
from_set = set(w.inclusions([w.lookup(from_revid)]))
241
to_set = set(w.inclusions([w.lookup(to_revid)]))
242
included = to_set.difference(from_set)
243
changed = map(w.idx_to_name, included)
244
return self._fileid_involved_by_set(changed)
246
def fileid_involved(self, last_revid=None):
247
"""Find all file_ids modified in the ancestry of last_revid.
249
:param last_revid: If None, last_revision() will be used.
251
w = self.get_inventory_weave()
253
changed = set(w._names)
255
included = w.inclusions([w.lookup(last_revid)])
256
changed = map(w.idx_to_name, included)
257
return self._fileid_involved_by_set(changed)
259
def fileid_involved_by_set(self, changes):
260
"""Find all file_ids modified by the set of revisions passed in.
262
:param changes: A set() of revision ids
264
# TODO: jam 20060119 This line does *nothing*, remove it.
265
# or better yet, change _fileid_involved_by_set so
266
# that it takes the inventory weave, rather than
267
# pulling it out by itself.
268
return self._fileid_involved_by_set(changes)
270
def _fileid_involved_by_set(self, changes):
271
"""Find the set of file-ids affected by the set of revisions.
273
:param changes: A set() of revision ids.
274
:return: A set() of file ids.
276
This peaks at the Weave, interpreting each line, looking to
277
see if it mentions one of the revisions. And if so, includes
278
the file id mentioned.
279
This expects both the Weave format, and the serialization
280
to have a single line per file/directory, and to have
281
fileid="" and revision="" on that line.
283
assert isinstance(self._format, (RepositoryFormat5,
286
RepositoryFormatKnit1)), \
287
"fileid_involved only supported for branches which store inventory as unnested xml"
289
w = self.get_inventory_weave()
291
for line in w._weave:
293
# it is ugly, but it is due to the weave structure
294
if not isinstance(line, basestring): continue
296
start = line.find('file_id="')+9
297
if start < 9: continue
298
end = line.find('"', start)
300
file_id = xml.sax.saxutils.unescape(line[start:end])
302
# check if file_id is already present
303
if file_id in file_ids: continue
305
start = line.find('revision="')+10
306
if start < 10: continue
307
end = line.find('"', start)
309
revision_id = xml.sax.saxutils.unescape(line[start:end])
311
if revision_id in changes:
312
file_ids.add(file_id)
316
def get_inventory_weave(self):
317
return self.control_weaves.get_weave('inventory',
318
self.get_transaction())
321
def get_inventory(self, revision_id):
322
"""Get Inventory object by hash."""
323
xml = self.get_inventory_xml(revision_id)
324
return bzrlib.xml5.serializer_v5.read_inventory_from_string(xml)
327
def get_inventory_xml(self, revision_id):
328
"""Get inventory XML as a file object."""
330
assert isinstance(revision_id, basestring), type(revision_id)
331
iw = self.get_inventory_weave()
332
return iw.get_text(iw.lookup(revision_id))
334
raise bzrlib.errors.HistoryMissing(self, 'inventory', revision_id)
337
def get_inventory_sha1(self, revision_id):
338
"""Return the sha1 hash of the inventory entry
340
return self.get_revision(revision_id).inventory_sha1
343
def get_revision_inventory(self, revision_id):
344
"""Return inventory of a past revision."""
345
# TODO: Unify this with get_inventory()
346
# bzr 0.0.6 and later imposes the constraint that the inventory_id
347
# must be the same as its revision, so this is trivial.
348
if revision_id is None:
349
# This does not make sense: if there is no revision,
350
# then it is the current tree inventory surely ?!
351
# and thus get_root_id() is something that looks at the last
352
# commit on the branch, and the get_root_id is an inventory check.
353
raise NotImplementedError
354
# return Inventory(self.get_root_id())
356
return self.get_inventory(revision_id)
360
"""Return True if this repository is flagged as a shared repository."""
361
# FIXME format 4-6 cannot be shared, this is technically faulty.
362
return self.control_files._transport.has('shared-storage')
365
def revision_tree(self, revision_id):
366
"""Return Tree for a revision on this branch.
368
`revision_id` may be None for the null revision, in which case
369
an `EmptyTree` is returned."""
370
# TODO: refactor this to use an existing revision object
371
# so we don't need to read it in twice.
372
if revision_id is None or revision_id == NULL_REVISION:
375
inv = self.get_revision_inventory(revision_id)
376
return RevisionTree(self, inv, revision_id)
379
def get_ancestry(self, revision_id):
380
"""Return a list of revision-ids integrated by a revision.
382
This is topologically sorted.
384
if revision_id is None:
386
if not self.has_revision(revision_id):
387
raise errors.NoSuchRevision(self, revision_id)
388
w = self.get_inventory_weave()
389
return [None] + map(w.idx_to_name,
390
w.inclusions([w.lookup(revision_id)]))
393
def print_file(self, file, revision_id):
394
"""Print `file` to stdout.
396
FIXME RBC 20060125 as John Meinel points out this is a bad api
397
- it writes to stdout, it assumes that that is valid etc. Fix
398
by creating a new more flexible convenience function.
400
tree = self.revision_tree(revision_id)
401
# use inventory as it was in that revision
402
file_id = tree.inventory.path2id(file)
404
raise BzrError("%r is not present in revision %s" % (file, revno))
406
revno = self.revision_id_to_revno(revision_id)
407
except errors.NoSuchRevision:
408
# TODO: This should not be BzrError,
409
# but NoSuchFile doesn't fit either
410
raise BzrError('%r is not present in revision %s'
411
% (file, revision_id))
413
raise BzrError('%r is not present in revision %s'
415
tree.print_file(file_id)
417
def get_transaction(self):
418
return self.control_files.get_transaction()
421
def set_make_working_trees(self, new_value):
422
"""Set the policy flag for making working trees when creating branches.
424
This only applies to branches that use this repository.
426
The default is 'True'.
427
:param new_value: True to restore the default, False to disable making
430
# FIXME: split out into a new class/strategy ?
431
if isinstance(self._format, (RepositoryFormat4,
434
raise NotImplementedError(self.set_make_working_trees)
437
self.control_files._transport.delete('no-working-trees')
438
except errors.NoSuchFile:
441
self.control_files.put_utf8('no-working-trees', '')
443
def make_working_trees(self):
444
"""Returns the policy for making working trees on new branches."""
445
# FIXME: split out into a new class/strategy ?
446
if isinstance(self._format, (RepositoryFormat4,
450
return not self.control_files._transport.has('no-working-trees')
453
def sign_revision(self, revision_id, gpg_strategy):
454
plaintext = Testament.from_revision(self, revision_id).as_short_text()
455
self.store_revision_signature(gpg_strategy, plaintext, revision_id)
458
class AllInOneRepository(Repository):
459
"""Legacy support - the repository behaviour for all-in-one branches."""
461
def __init__(self, _format, a_bzrdir, revision_store):
462
# we reuse one control files instance.
463
dir_mode = a_bzrdir._control_files._dir_mode
464
file_mode = a_bzrdir._control_files._file_mode
466
def get_weave(name, prefixed=False):
468
name = safe_unicode(name)
471
relpath = a_bzrdir._control_files._escape(name)
472
weave_transport = a_bzrdir._control_files._transport.clone(relpath)
473
ws = WeaveStore(weave_transport, prefixed=prefixed,
476
if a_bzrdir._control_files._transport.should_cache():
477
ws.enable_cache = True
480
def get_store(name, compressed=True, prefixed=False):
481
# FIXME: This approach of assuming stores are all entirely compressed
482
# or entirely uncompressed is tidy, but breaks upgrade from
483
# some existing branches where there's a mixture; we probably
484
# still want the option to look for both.
485
relpath = a_bzrdir._control_files._escape(name)
486
store = TextStore(a_bzrdir._control_files._transport.clone(relpath),
487
prefixed=prefixed, compressed=compressed,
490
#if self._transport.should_cache():
491
# cache_path = os.path.join(self.cache_root, name)
492
# os.mkdir(cache_path)
493
# store = bzrlib.store.CachedStore(store, cache_path)
496
# not broken out yet because the controlweaves|inventory_store
497
# and text_store | weave_store bits are still different.
498
if isinstance(_format, RepositoryFormat4):
499
self.inventory_store = get_store('inventory-store')
500
self.text_store = get_store('text-store')
501
elif isinstance(_format, RepositoryFormat5):
502
self.control_weaves = get_weave('')
503
self.weave_store = get_weave('weaves')
504
elif isinstance(_format, RepositoryFormat6):
505
self.control_weaves = get_weave('')
506
self.weave_store = get_weave('weaves', prefixed=True)
508
raise errors.BzrError('unreachable code: unexpected repository'
510
revision_store.register_suffix('sig')
511
super(AllInOneRepository, self).__init__(_format, a_bzrdir, a_bzrdir._control_files, revision_store)
514
class MetaDirRepository(Repository):
515
"""Repositories in the new meta-dir layout."""
517
def __init__(self, _format, a_bzrdir, control_files, revision_store):
518
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
self.weave_store = get_weave('weaves', prefixed=True)
543
elif isinstance(self._format, RepositoryFormatKnit1):
544
self.control_weaves = get_weave('')
545
self.weave_store = get_weave('knits', prefixed=True)
547
raise errors.BzrError('unreachable code: unexpected repository'
551
class RepositoryFormat(object):
552
"""A repository format.
554
Formats provide three things:
555
* An initialization routine to construct repository data on disk.
556
* a format string which is used when the BzrDir supports versioned
558
* an open routine which returns a Repository instance.
560
Formats are placed in an dict by their format string for reference
561
during opening. These should be subclasses of RepositoryFormat
564
Once a format is deprecated, just deprecate the initialize and open
565
methods on the format class. Do not deprecate the object, as the
566
object will be created every system load.
568
Common instance attributes:
569
_matchingbzrdir - the bzrdir format that the repository format was
570
originally written to work with. This can be used if manually
571
constructing a bzrdir and repository, or more commonly for test suite
575
_default_format = None
576
"""The default format used for new repositories."""
579
"""The known formats."""
582
def find_format(klass, a_bzrdir):
583
"""Return the format for the repository object in a_bzrdir."""
585
transport = a_bzrdir.get_repository_transport(None)
586
format_string = transport.get("format").read()
587
return klass._formats[format_string]
588
except errors.NoSuchFile:
589
raise errors.NoRepositoryPresent(a_bzrdir)
591
raise errors.UnknownFormatError(format_string)
594
def get_default_format(klass):
595
"""Return the current default format."""
596
return klass._default_format
598
def get_format_string(self):
599
"""Return the ASCII format string that identifies this format.
601
Note that in pre format ?? repositories the format string is
602
not permitted nor written to disk.
604
raise NotImplementedError(self.get_format_string)
606
def _get_revision_store(self, repo_transport, control_files):
607
"""Return the revision store object for this a_bzrdir."""
608
raise NotImplementedError(self._get_revision_store)
610
def _get_rev_store(self,
616
"""Common logic for getting a revision store for a repository.
618
see self._get_revision_store for the method to
619
get the store for a repository.
622
name = safe_unicode(name)
625
dir_mode = control_files._dir_mode
626
file_mode = control_files._file_mode
627
revision_store =TextStore(transport.clone(name),
629
compressed=compressed,
632
revision_store.register_suffix('sig')
633
return revision_store
635
def initialize(self, a_bzrdir, shared=False):
636
"""Initialize a repository of this format in a_bzrdir.
638
:param a_bzrdir: The bzrdir to put the new repository in it.
639
:param shared: The repository should be initialized as a sharable one.
641
This may raise UninitializableFormat if shared repository are not
642
compatible the a_bzrdir.
645
def is_supported(self):
646
"""Is this format supported?
648
Supported formats must be initializable and openable.
649
Unsupported formats may not support initialization or committing or
650
some other features depending on the reason for not being supported.
654
def open(self, a_bzrdir, _found=False):
655
"""Return an instance of this format for the bzrdir a_bzrdir.
657
_found is a private parameter, do not use it.
659
raise NotImplementedError(self.open)
662
def register_format(klass, format):
663
klass._formats[format.get_format_string()] = format
666
def set_default_format(klass, format):
667
klass._default_format = format
670
def unregister_format(klass, format):
671
assert klass._formats[format.get_format_string()] is format
672
del klass._formats[format.get_format_string()]
675
class PreSplitOutRepositoryFormat(RepositoryFormat):
676
"""Base class for the pre split out repository formats."""
678
def initialize(self, a_bzrdir, shared=False, _internal=False):
679
"""Create a weave repository.
681
TODO: when creating split out bzr branch formats, move this to a common
682
base for Format5, Format6. or something like that.
684
from bzrlib.weavefile import write_weave_v5
685
from bzrlib.weave import Weave
688
raise errors.IncompatibleFormat(self, a_bzrdir._format)
691
# always initialized when the bzrdir is.
692
return self.open(a_bzrdir, _found=True)
694
# Create an empty weave
696
bzrlib.weavefile.write_weave_v5(Weave(), sio)
697
empty_weave = sio.getvalue()
699
mutter('creating repository in %s.', a_bzrdir.transport.base)
700
dirs = ['revision-store', 'weaves']
701
lock_file = 'branch-lock'
702
files = [('inventory.weave', StringIO(empty_weave)),
705
# FIXME: RBC 20060125 dont peek under the covers
706
# NB: no need to escape relative paths that are url safe.
707
control_files = LockableFiles(a_bzrdir.transport, 'branch-lock')
708
control_files.lock_write()
709
control_files._transport.mkdir_multi(dirs,
710
mode=control_files._dir_mode)
712
for file, content in files:
713
control_files.put(file, content)
715
control_files.unlock()
716
return self.open(a_bzrdir, _found=True)
718
def open(self, a_bzrdir, _found=False):
719
"""See RepositoryFormat.open()."""
721
# we are being called directly and must probe.
722
raise NotImplementedError
724
repo_transport = a_bzrdir.get_repository_transport(None)
725
control_files = a_bzrdir._control_files
726
revision_store = self._get_revision_store(repo_transport, control_files)
727
return AllInOneRepository(_format=self,
729
revision_store=revision_store)
732
class RepositoryFormat4(PreSplitOutRepositoryFormat):
733
"""Bzr repository format 4.
735
This repository format has:
737
- TextStores for texts, inventories,revisions.
739
This format is deprecated: it indexes texts using a text id which is
740
removed in format 5; initializationa and write support for this format
745
super(RepositoryFormat4, self).__init__()
746
self._matchingbzrdir = bzrlib.bzrdir.BzrDirFormat4()
748
def initialize(self, url, shared=False, _internal=False):
749
"""Format 4 branches cannot be created."""
750
raise errors.UninitializableFormat(self)
752
def is_supported(self):
753
"""Format 4 is not supported.
755
It is not supported because the model changed from 4 to 5 and the
756
conversion logic is expensive - so doing it on the fly was not
761
def _get_revision_store(self, repo_transport, control_files):
762
"""See RepositoryFormat._get_revision_store()."""
763
return self._get_rev_store(repo_transport,
768
class RepositoryFormat5(PreSplitOutRepositoryFormat):
769
"""Bzr control format 5.
771
This repository format has:
772
- weaves for file texts and inventory
774
- TextStores for revisions and signatures.
778
super(RepositoryFormat5, self).__init__()
779
self._matchingbzrdir = bzrlib.bzrdir.BzrDirFormat5()
781
def _get_revision_store(self, repo_transport, control_files):
782
"""See RepositoryFormat._get_revision_store()."""
783
"""Return the revision store object for this a_bzrdir."""
784
return self._get_rev_store(repo_transport,
790
class RepositoryFormat6(PreSplitOutRepositoryFormat):
791
"""Bzr control format 6.
793
This repository format has:
794
- weaves for file texts and inventory
795
- hash subdirectory based stores.
796
- TextStores for revisions and signatures.
800
super(RepositoryFormat6, self).__init__()
801
self._matchingbzrdir = bzrlib.bzrdir.BzrDirFormat6()
803
def _get_revision_store(self, repo_transport, control_files):
804
"""See RepositoryFormat._get_revision_store()."""
805
return self._get_rev_store(repo_transport,
812
class MetaDirRepositoryFormat(RepositoryFormat):
813
"""Common base class for the new repositories using the metadir layour."""
816
super(MetaDirRepositoryFormat, self).__init__()
817
self._matchingbzrdir = bzrlib.bzrdir.BzrDirMetaFormat1()
819
def _create_control_files(self, a_bzrdir):
820
"""Create the required files and the initial control_files object."""
821
# FIXME: RBC 20060125 dont peek under the covers
822
# NB: no need to escape relative paths that are url safe.
824
repository_transport = a_bzrdir.get_repository_transport(self)
825
repository_transport.put(lock_file, StringIO()) # TODO get the file mode from the bzrdir lock files., mode=file_mode)
826
control_files = LockableFiles(repository_transport, 'lock')
829
def _get_revision_store(self, repo_transport, control_files):
830
"""See RepositoryFormat._get_revision_store()."""
831
return self._get_rev_store(repo_transport,
838
def open(self, a_bzrdir, _found=False, _override_transport=None):
839
"""See RepositoryFormat.open().
841
:param _override_transport: INTERNAL USE ONLY. Allows opening the
842
repository at a slightly different url
843
than normal. I.e. during 'upgrade'.
846
format = RepositoryFormat.find_format(a_bzrdir)
847
assert format.__class__ == self.__class__
848
if _override_transport is not None:
849
repo_transport = _override_transport
851
repo_transport = a_bzrdir.get_repository_transport(None)
852
control_files = LockableFiles(repo_transport, 'lock')
853
revision_store = self._get_revision_store(repo_transport, control_files)
854
return MetaDirRepository(_format=self,
856
control_files=control_files,
857
revision_store=revision_store)
859
def _upload_blank_content(self, a_bzrdir, dirs, files, utf8_files, shared):
860
"""Upload the initial blank content."""
861
control_files = self._create_control_files(a_bzrdir)
862
control_files.lock_write()
863
control_files._transport.mkdir_multi(dirs,
864
mode=control_files._dir_mode)
866
for file, content in files:
867
control_files.put(file, content)
868
for file, content in utf8_files:
869
control_files.put_utf8(file, content)
871
control_files.put_utf8('shared-storage', '')
873
control_files.unlock()
876
class RepositoryFormat7(MetaDirRepositoryFormat):
879
This repository format has:
880
- weaves for file texts and inventory
881
- hash subdirectory based stores.
882
- TextStores for revisions and signatures.
883
- a format marker of its own
884
- an optional 'shared-storage' flag
885
- an optional 'no-working-trees' flag
888
def get_format_string(self):
889
"""See RepositoryFormat.get_format_string()."""
890
return "Bazaar-NG Repository format 7"
892
def initialize(self, a_bzrdir, shared=False):
893
"""Create a weave repository.
895
:param shared: If true the repository will be initialized as a shared
898
from bzrlib.weavefile import write_weave_v5
899
from bzrlib.weave import Weave
901
# Create an empty weave
903
bzrlib.weavefile.write_weave_v5(Weave(), sio)
904
empty_weave = sio.getvalue()
906
mutter('creating repository in %s.', a_bzrdir.transport.base)
907
dirs = ['revision-store', 'weaves']
908
files = [('inventory.weave', StringIO(empty_weave)),
910
utf8_files = [('format', self.get_format_string())]
912
self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
913
return self.open(a_bzrdir=a_bzrdir, _found=True)
916
class RepositoryFormatKnit1(MetaDirRepositoryFormat):
917
"""Bzr repository knit format 1.
919
This repository format has:
920
- knits for file texts and inventory
921
- hash subdirectory based stores.
922
- knits for revisions and signatures
923
- TextStores for revisions and signatures.
924
- a format marker of its own
925
- an optional 'shared-storage' flag
926
- an optional 'no-working-trees' flag
929
def get_format_string(self):
930
"""See RepositoryFormat.get_format_string()."""
931
return "Bazaar-NG Knit Repository Format 1"
933
def initialize(self, a_bzrdir, shared=False):
934
"""Create a knit format 1 repository.
936
:param shared: If true the repository will be initialized as a shared
938
XXX NOTE that this current uses a Weave for testing and will become
939
A Knit in due course.
941
from bzrlib.weavefile import write_weave_v5
942
from bzrlib.weave import Weave
944
# Create an empty weave
946
bzrlib.weavefile.write_weave_v5(Weave(), sio)
947
empty_weave = sio.getvalue()
949
mutter('creating repository in %s.', a_bzrdir.transport.base)
950
dirs = ['revision-store', 'knits']
951
files = [('inventory.weave', StringIO(empty_weave)),
953
utf8_files = [('format', self.get_format_string())]
955
self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
956
return self.open(a_bzrdir=a_bzrdir, _found=True)
959
# formats which have no format string are not discoverable
960
# and not independently creatable, so are not registered.
961
_default_format = RepositoryFormat7()
962
RepositoryFormat.register_format(_default_format)
963
RepositoryFormat.register_format(RepositoryFormatKnit1())
964
RepositoryFormat.set_default_format(_default_format)
965
_legacy_formats = [RepositoryFormat4(),
970
class InterRepository(InterObject):
971
"""This class represents operations taking place between two repositories.
973
Its instances have methods like copy_content and fetch, and contain
974
references to the source and target repositories these operations can be
977
Often we will provide convenience methods on 'repository' which carry out
978
operations with another repository - they will always forward to
979
InterRepository.get(other).method_name(parameters).
983
"""The available optimised InterRepository types."""
986
def copy_content(self, revision_id=None, basis=None):
987
"""Make a complete copy of the content in self into destination.
989
This is a destructive operation! Do not use it on existing
992
:param revision_id: Only copy the content needed to construct
993
revision_id and its parents.
994
:param basis: Copy the needed data preferentially from basis.
997
self.target.set_make_working_trees(self.source.make_working_trees())
998
except NotImplementedError:
1000
# grab the basis available data
1001
if basis is not None:
1002
self.target.fetch(basis, revision_id=revision_id)
1003
# but dont both fetching if we have the needed data now.
1004
if (revision_id not in (None, NULL_REVISION) and
1005
self.target.has_revision(revision_id)):
1007
self.target.fetch(self.source, revision_id=revision_id)
1009
def _double_lock(self, lock_source, lock_target):
1010
"""Take out too locks, rolling back the first if the second throws."""
1015
# we want to ensure that we don't leave source locked by mistake.
1016
# and any error on target should not confuse source.
1017
self.source.unlock()
1021
def fetch(self, revision_id=None, pb=None):
1022
"""Fetch the content required to construct revision_id.
1024
The content is copied from source to target.
1026
:param revision_id: if None all content is copied, if NULL_REVISION no
1028
:param pb: optional progress bar to use for progress reports. If not
1029
provided a default one will be created.
1031
Returns the copied revision count and the failed revisions in a tuple:
1034
from bzrlib.fetch import RepoFetcher
1035
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1036
self.source, self.source._format, self.target, self.target._format)
1037
f = RepoFetcher(to_repository=self.target,
1038
from_repository=self.source,
1039
last_revision=revision_id,
1041
return f.count_copied, f.failed_revisions
1043
def lock_read(self):
1044
"""Take out a logical read lock.
1046
This will lock the source branch and the target branch. The source gets
1047
a read lock and the target a read lock.
1049
self._double_lock(self.source.lock_read, self.target.lock_read)
1051
def lock_write(self):
1052
"""Take out a logical write lock.
1054
This will lock the source branch and the target branch. The source gets
1055
a read lock and the target a write lock.
1057
self._double_lock(self.source.lock_read, self.target.lock_write)
1060
def missing_revision_ids(self, revision_id=None):
1061
"""Return the revision ids that source has that target does not.
1063
These are returned in topological order.
1065
:param revision_id: only return revision ids included by this
1068
# generic, possibly worst case, slow code path.
1069
target_ids = set(self.target.all_revision_ids())
1070
if revision_id is not None:
1071
source_ids = self.source.get_ancestry(revision_id)
1072
assert source_ids.pop(0) == None
1074
source_ids = self.source.all_revision_ids()
1075
result_set = set(source_ids).difference(target_ids)
1076
# this may look like a no-op: its not. It preserves the ordering
1077
# other_ids had while only returning the members from other_ids
1078
# that we've decided we need.
1079
return [rev_id for rev_id in source_ids if rev_id in result_set]
1082
"""Release the locks on source and target."""
1084
self.target.unlock()
1086
self.source.unlock()
1089
class InterWeaveRepo(InterRepository):
1090
"""Optimised code paths between Weave based repositories."""
1092
_matching_repo_format = _default_format
1093
"""Repository format for testing with."""
1096
def is_compatible(source, target):
1097
"""Be compatible with known Weave formats.
1099
We dont test for the stores being of specific types becase that
1100
could lead to confusing results, and there is no need to be
1104
return (isinstance(source._format, (RepositoryFormat5,
1106
RepositoryFormat7)) and
1107
isinstance(target._format, (RepositoryFormat5,
1109
RepositoryFormat7)))
1110
except AttributeError:
1114
def copy_content(self, revision_id=None, basis=None):
1115
"""See InterRepository.copy_content()."""
1116
# weave specific optimised path:
1117
if basis is not None:
1118
# copy the basis in, then fetch remaining data.
1119
basis.copy_content_into(self.target, revision_id)
1120
# the basis copy_content_into could misset this.
1122
self.target.set_make_working_trees(self.source.make_working_trees())
1123
except NotImplementedError:
1125
self.target.fetch(self.source, revision_id=revision_id)
1128
self.target.set_make_working_trees(self.source.make_working_trees())
1129
except NotImplementedError:
1131
# FIXME do not peek!
1132
if self.source.control_files._transport.listable():
1133
pb = bzrlib.ui.ui_factory.progress_bar()
1134
copy_all(self.source.weave_store,
1135
self.target.weave_store, pb=pb)
1136
pb.update('copying inventory', 0, 1)
1137
self.target.control_weaves.copy_multi(
1138
self.source.control_weaves, ['inventory'])
1139
copy_all(self.source.revision_store,
1140
self.target.revision_store, pb=pb)
1142
self.target.fetch(self.source, revision_id=revision_id)
1145
def fetch(self, revision_id=None, pb=None):
1146
"""See InterRepository.fetch()."""
1147
from bzrlib.fetch import RepoFetcher
1148
mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1149
self.source, self.source._format, self.target, self.target._format)
1150
f = RepoFetcher(to_repository=self.target,
1151
from_repository=self.source,
1152
last_revision=revision_id,
1154
return f.count_copied, f.failed_revisions
1157
def missing_revision_ids(self, revision_id=None):
1158
"""See InterRepository.missing_revision_ids()."""
1159
# we want all revisions to satisfy revision_id in source.
1160
# but we dont want to stat every file here and there.
1161
# we want then, all revisions other needs to satisfy revision_id
1162
# checked, but not those that we have locally.
1163
# so the first thing is to get a subset of the revisions to
1164
# satisfy revision_id in source, and then eliminate those that
1165
# we do already have.
1166
# this is slow on high latency connection to self, but as as this
1167
# disk format scales terribly for push anyway due to rewriting
1168
# inventory.weave, this is considered acceptable.
1170
if revision_id is not None:
1171
source_ids = self.source.get_ancestry(revision_id)
1172
assert source_ids.pop(0) == None
1174
source_ids = self.source._all_possible_ids()
1175
source_ids_set = set(source_ids)
1176
# source_ids is the worst possible case we may need to pull.
1177
# now we want to filter source_ids against what we actually
1178
# have in target, but dont try to check for existence where we know
1179
# we do not have a revision as that would be pointless.
1180
target_ids = set(self.target._all_possible_ids())
1181
possibly_present_revisions = target_ids.intersection(source_ids_set)
1182
actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
1183
required_revisions = source_ids_set.difference(actually_present_revisions)
1184
required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
1185
if revision_id is not None:
1186
# we used get_ancestry to determine source_ids then we are assured all
1187
# revisions referenced are present as they are installed in topological order.
1188
# and the tip revision was validated by get_ancestry.
1189
return required_topo_revisions
1191
# if we just grabbed the possibly available ids, then
1192
# we only have an estimate of whats available and need to validate
1193
# that against the revision records.
1194
return self.source._eliminate_revisions_not_present(required_topo_revisions)
1197
InterRepository.register_optimiser(InterWeaveRepo)
1200
class RepositoryTestProviderAdapter(object):
1201
"""A tool to generate a suite testing multiple repository formats at once.
1203
This is done by copying the test once for each transport and injecting
1204
the transport_server, transport_readonly_server, and bzrdir_format and
1205
repository_format classes into each copy. Each copy is also given a new id()
1206
to make it easy to identify.
1209
def __init__(self, transport_server, transport_readonly_server, formats):
1210
self._transport_server = transport_server
1211
self._transport_readonly_server = transport_readonly_server
1212
self._formats = formats
1214
def adapt(self, test):
1215
result = TestSuite()
1216
for repository_format, bzrdir_format in self._formats:
1217
new_test = deepcopy(test)
1218
new_test.transport_server = self._transport_server
1219
new_test.transport_readonly_server = self._transport_readonly_server
1220
new_test.bzrdir_format = bzrdir_format
1221
new_test.repository_format = repository_format
1222
def make_new_test_id():
1223
new_id = "%s(%s)" % (new_test.id(), repository_format.__class__.__name__)
1224
return lambda: new_id
1225
new_test.id = make_new_test_id()
1226
result.addTest(new_test)
1230
class InterRepositoryTestProviderAdapter(object):
1231
"""A tool to generate a suite testing multiple inter repository formats.
1233
This is done by copying the test once for each interrepo provider and injecting
1234
the transport_server, transport_readonly_server, repository_format and
1235
repository_to_format classes into each copy.
1236
Each copy is also given a new id() to make it easy to identify.
1239
def __init__(self, transport_server, transport_readonly_server, formats):
1240
self._transport_server = transport_server
1241
self._transport_readonly_server = transport_readonly_server
1242
self._formats = formats
1244
def adapt(self, test):
1245
result = TestSuite()
1246
for interrepo_class, repository_format, repository_format_to in self._formats:
1247
new_test = deepcopy(test)
1248
new_test.transport_server = self._transport_server
1249
new_test.transport_readonly_server = self._transport_readonly_server
1250
new_test.interrepo_class = interrepo_class
1251
new_test.repository_format = repository_format
1252
new_test.repository_format_to = repository_format_to
1253
def make_new_test_id():
1254
new_id = "%s(%s)" % (new_test.id(), interrepo_class.__name__)
1255
return lambda: new_id
1256
new_test.id = make_new_test_id()
1257
result.addTest(new_test)
1261
def default_test_list():
1262
"""Generate the default list of interrepo permutations to test."""
1264
# test the default InterRepository between format 6 and the current
1266
# XXX: robertc 20060220 reinstate this when there are two supported
1267
# formats which do not have an optimal code path between them.
1268
result.append((InterRepository,
1269
RepositoryFormat6(),
1270
RepositoryFormatKnit1()))
1271
for optimiser in InterRepository._optimisers:
1272
result.append((optimiser,
1273
optimiser._matching_repo_format,
1274
optimiser._matching_repo_format
1276
# if there are specific combinations we want to use, we can add them
1281
class CopyConverter(object):
1282
"""A repository conversion tool which just performs a copy of the content.
1284
This is slow but quite reliable.
1287
def __init__(self, target_format):
1288
"""Create a CopyConverter.
1290
:param target_format: The format the resulting repository should be.
1292
self.target_format = target_format
1294
def convert(self, repo, pb):
1295
"""Perform the conversion of to_convert, giving feedback via pb.
1297
:param to_convert: The disk object to convert.
1298
:param pb: a progress bar to use for progress information.
1303
# this is only useful with metadir layouts - separated repo content.
1304
# trigger an assertion if not such
1305
repo._format.get_format_string()
1306
self.repo_dir = repo.bzrdir
1307
self.step('Moving repository to repository.backup')
1308
self.repo_dir.transport.move('repository', 'repository.backup')
1309
backup_transport = self.repo_dir.transport.clone('repository.backup')
1310
self.source_repo = repo._format.open(self.repo_dir,
1312
_override_transport=backup_transport)
1313
self.step('Creating new repository')
1314
converted = self.target_format.initialize(self.repo_dir,
1315
self.source_repo.is_shared())
1316
converted.lock_write()
1318
self.step('Copying content into repository.')
1319
self.source_repo.copy_content_into(converted)
1322
self.step('Deleting old repository content.')
1323
self.repo_dir.transport.delete_tree('repository.backup')
1324
self.pb.note('repository converted')
1326
def step(self, message):
1327
"""Update the pb by a step."""
1329
self.pb.update(message, self.count, self.total)