/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
1
# Copyright (C) 2005 Canonical Ltd
2
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.
7
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.
12
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
1185.65.10 by Robert Collins
Rename Controlfiles to LockableFiles.
16
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
17
from copy import deepcopy
1185.65.10 by Robert Collins
Rename Controlfiles to LockableFiles.
18
from cStringIO import StringIO
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
19
from unittest import TestSuite
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
20
import xml.sax.saxutils
21
1185.65.10 by Robert Collins
Rename Controlfiles to LockableFiles.
22
1534.4.28 by Robert Collins
first cut at merge from integration.
23
from bzrlib.decorators import needs_read_lock, needs_write_lock
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
24
import bzrlib.errors as errors
1534.4.28 by Robert Collins
first cut at merge from integration.
25
from bzrlib.errors import InvalidRevisionId
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
26
import bzrlib.gpg as gpg
1185.66.3 by Aaron Bentley
Renamed ControlFiles to LockableFiles
27
from bzrlib.lockable_files import LockableFiles
1534.4.28 by Robert Collins
first cut at merge from integration.
28
from bzrlib.osutils import safe_unicode
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
29
from bzrlib.revision import NULL_REVISION
1185.65.14 by Robert Collins
Merge from aaron. Whee, we are synced. Yay. Begone the foul demons of merge conflicts.
30
from bzrlib.store import copy_all
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
31
from bzrlib.store.weave import WeaveStore
32
from bzrlib.store.text import TextStore
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
33
from bzrlib.symbol_versioning import *
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
34
from bzrlib.trace import mutter
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
35
from bzrlib.tree import RevisionTree
36
from bzrlib.testament import Testament
1534.4.28 by Robert Collins
first cut at merge from integration.
37
from bzrlib.tree import EmptyTree
1185.79.2 by John Arbash Meinel
Adding progress bars to copy_all and copy_multi, fixing ordering of repository.clone() to pull inventories after weaves.
38
import bzrlib.ui
1534.4.28 by Robert Collins
first cut at merge from integration.
39
import bzrlib.xml5
1185.70.3 by Martin Pool
Various updates to make storage branch mergeable:
40
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
41
1185.66.5 by Aaron Bentley
Renamed RevisionStorage to Repository
42
class Repository(object):
1185.70.3 by Martin Pool
Various updates to make storage branch mergeable:
43
    """Repository holding history for one or more branches.
44
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.
48
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 
51
    remote) disk.
52
    """
1185.65.17 by Robert Collins
Merge from integration, mode-changes are broken.
53
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
54
    @needs_write_lock
55
    def add_inventory(self, revid, inv, parents):
56
        """Add the inventory inv to the repository as revid.
57
        
58
        :param parents: The revision ids of the parents that revid
59
                        is known to have and are in the repository already.
60
61
        returns the sha1 of the serialized inventory.
62
        """
63
        inv_text = bzrlib.xml5.serializer_v5.write_inventory_to_string(inv)
64
        inv_sha1 = bzrlib.osutils.sha_string(inv_text)
65
        self.control_weaves.add_text('inventory', revid,
66
                   bzrlib.osutils.split_lines(inv_text), parents,
67
                   self.get_transaction())
68
        return inv_sha1
69
70
    @needs_write_lock
71
    def add_revision(self, rev_id, rev, inv=None, config=None):
72
        """Add rev to the revision store as rev_id.
73
74
        :param rev_id: the revision id to use.
75
        :param rev: The revision object.
76
        :param inv: The inventory for the revision. if None, it will be looked
77
                    up in the inventory storer
78
        :param config: If None no digital signature will be created.
79
                       If supplied its signature_needed method will be used
80
                       to determine if a signature should be made.
81
        """
82
        if config is not None and config.signature_needed():
83
            if inv is None:
84
                inv = self.get_inventory(rev_id)
85
            plaintext = Testament(rev, inv).as_short_text()
86
            self.store_revision_signature(
87
                gpg.GPGStrategy(config), plaintext, rev_id)
88
        if not rev_id in self.get_inventory_weave():
89
            if inv is None:
90
                raise errors.WeaveRevisionNotPresent(rev_id,
91
                                                     self.get_inventory_weave())
92
            else:
93
                # yes, this is not suitable for adding with ghosts.
94
                self.add_inventory(rev_id, inv, rev.parent_ids)
95
            
96
        rev_tmp = StringIO()
97
        bzrlib.xml5.serializer_v5.write_revision(rev, rev_tmp)
98
        rev_tmp.seek(0)
99
        self.revision_store.add(rev_tmp, rev_id)
100
        mutter('added revision_id {%s}', rev_id)
101
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
102
    @needs_read_lock
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
103
    def _all_possible_ids(self):
104
        """Return all the possible revisions that we could find."""
105
        return self.get_inventory_weave().names()
106
107
    @needs_read_lock
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
108
    def all_revision_ids(self):
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
109
        """Returns a list of all the revision ids in the repository. 
110
111
        These are in as much topological order as the underlying store can 
112
        present: for weaves ghosts may lead to a lack of correctness until
113
        the reweave updates the parents list.
114
        """
115
        result = self._all_possible_ids()
116
        return self._eliminate_revisions_not_present(result)
117
118
    @needs_read_lock
119
    def _eliminate_revisions_not_present(self, revision_ids):
120
        """Check every revision id in revision_ids to see if we have it.
121
122
        Returns a set of the present revisions.
123
        """
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
124
        result = []
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
125
        for id in revision_ids:
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
126
            if self.has_revision(id):
127
               result.append(id)
128
        return result
129
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
130
    @staticmethod
131
    def create(a_bzrdir):
132
        """Construct the current default format repository in a_bzrdir."""
133
        return RepositoryFormat.get_default_format().initialize(a_bzrdir)
134
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
135
    def __init__(self, _format, a_bzrdir, control_files, revision_store):
136
        """instantiate a Repository.
137
138
        :param _format: The format of the repository on disk.
139
        :param a_bzrdir: The BzrDir of the repository.
140
141
        In the future we will have a single api for all stores for
142
        getting file texts, inventories and revisions, then
143
        this construct will accept instances of those things.
144
        """
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
145
        object.__init__(self)
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
146
        self._format = _format
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
147
        # the following are part of the public API for Repository:
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
148
        self.bzrdir = a_bzrdir
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
149
        self.control_files = control_files
150
        self.revision_store = revision_store
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
151
152
    def lock_write(self):
153
        self.control_files.lock_write()
154
155
    def lock_read(self):
156
        self.control_files.lock_read()
157
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
158
    @needs_read_lock
159
    def missing_revision_ids(self, other, revision_id=None):
160
        """Return the revision ids that other has that this does not.
161
        
162
        These are returned in topological order.
163
164
        revision_id: only return revision ids included by revision_id.
165
        """
1534.1.34 by Robert Collins
Move missing_revision_ids from Repository to InterRepository, and eliminate the now unused Repository._compatible_formats method.
166
        return InterRepository.get(other, self).missing_revision_ids(revision_id)
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
167
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
168
    @staticmethod
169
    def open(base):
170
        """Open the repository rooted at base.
171
172
        For instance, if the repository is at URL/.bzr/repository,
173
        Repository.open(URL) -> a Repository instance.
174
        """
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
175
        control = bzrlib.bzrdir.BzrDir.open(base)
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
176
        return control.open_repository()
177
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
178
    def copy_content_into(self, destination, revision_id=None, basis=None):
1534.6.6 by Robert Collins
Move find_repository to bzrdir, its not quite ideal there but its simpler and until someone chooses to vary the search by branch type its completely sufficient.
179
        """Make a complete copy of the content in self into destination.
180
        
181
        This is a destructive operation! Do not use it on existing 
182
        repositories.
183
        """
1534.1.33 by Robert Collins
Move copy_content_into into InterRepository and InterWeaveRepo, and disable the default codepath test as we have optimised paths for all current combinations.
184
        return InterRepository.get(self, destination).copy_content(revision_id, basis)
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
185
1534.1.31 by Robert Collins
Deprecated fetch.fetch and fetch.greedy_fetch for branch.fetch, and move the Repository.fetch internals to InterRepo and InterWeaveRepo.
186
    def fetch(self, source, revision_id=None, pb=None):
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
187
        """Fetch the content required to construct revision_id from source.
188
189
        If revision_id is None all content is copied.
190
        """
1534.1.31 by Robert Collins
Deprecated fetch.fetch and fetch.greedy_fetch for branch.fetch, and move the Repository.fetch internals to InterRepo and InterWeaveRepo.
191
        return InterRepository.get(source, self).fetch(revision_id=revision_id,
192
                                                       pb=pb)
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
193
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
194
    def unlock(self):
195
        self.control_files.unlock()
196
1185.65.27 by Robert Collins
Tweak storage towards mergability.
197
    @needs_read_lock
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
198
    def clone(self, a_bzrdir, revision_id=None, basis=None):
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
199
        """Clone this repository into a_bzrdir using the current format.
200
201
        Currently no check is made that the format of this repository and
202
        the bzrdir format are compatible. FIXME RBC 20060201.
203
        """
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
204
        if not isinstance(a_bzrdir._format, self.bzrdir._format.__class__):
205
            # use target default format.
206
            result = a_bzrdir.create_repository()
207
        # FIXME RBC 20060209 split out the repository type to avoid this check ?
208
        elif isinstance(a_bzrdir._format,
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
209
                      (bzrlib.bzrdir.BzrDirFormat4,
210
                       bzrlib.bzrdir.BzrDirFormat5,
211
                       bzrlib.bzrdir.BzrDirFormat6)):
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
212
            result = a_bzrdir.open_repository()
213
        else:
1534.6.5 by Robert Collins
Cloning of repos preserves shared and make-working-tree attributes.
214
            result = self._format.initialize(a_bzrdir, shared=self.is_shared())
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
215
        self.copy_content_into(result, revision_id, basis)
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
216
        return result
217
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
218
    def has_revision(self, revision_id):
219
        """True if this branch has a copy of the revision.
220
221
        This does not necessarily imply the revision is merge
222
        or on the mainline."""
223
        return (revision_id is None
224
                or self.revision_store.has_id(revision_id))
225
226
    @needs_read_lock
227
    def get_revision_xml_file(self, revision_id):
228
        """Return XML file object for revision object."""
229
        if not revision_id or not isinstance(revision_id, basestring):
230
            raise InvalidRevisionId(revision_id=revision_id, branch=self)
231
        try:
232
            return self.revision_store.get(revision_id)
233
        except (IndexError, KeyError):
234
            raise bzrlib.errors.NoSuchRevision(self, revision_id)
235
1185.65.27 by Robert Collins
Tweak storage towards mergability.
236
    @needs_read_lock
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
237
    def get_revision_xml(self, revision_id):
238
        return self.get_revision_xml_file(revision_id).read()
239
1185.65.27 by Robert Collins
Tweak storage towards mergability.
240
    @needs_read_lock
1570.1.13 by Robert Collins
Check for incorrect revision parentage in the weave during revision access.
241
    def get_revision_reconcile(self, revision_id):
242
        """'reconcile' helper routine that allows access to a revision always.
243
        
244
        This variant of get_revision does not cross check the weave graph
245
        against the revision one as get_revision does: but it should only
246
        be used by reconcile, or reconcile-alike commands that are correcting
247
        or testing the revision graph.
248
        """
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
249
        xml_file = self.get_revision_xml_file(revision_id)
250
251
        try:
252
            r = bzrlib.xml5.serializer_v5.read_revision(xml_file)
253
        except SyntaxError, e:
254
            raise bzrlib.errors.BzrError('failed to unpack revision_xml',
255
                                         [revision_id,
256
                                          str(e)])
257
            
258
        assert r.revision_id == revision_id
259
        return r
260
1185.65.27 by Robert Collins
Tweak storage towards mergability.
261
    @needs_read_lock
1570.1.13 by Robert Collins
Check for incorrect revision parentage in the weave during revision access.
262
    def get_revision(self, revision_id):
263
        """Return the Revision object for a named revision"""
264
        r = self.get_revision_reconcile(revision_id)
265
        # weave corruption can lead to absent revision markers that should be
266
        # present.
267
        # the following test is reasonably cheap (it needs a single weave read)
268
        # and the weave is cached in read transactions. In write transactions
269
        # it is not cached but typically we only read a small number of
270
        # revisions. For knits when they are introduced we will probably want
271
        # to ensure that caching write transactions are in use.
272
        inv = self.get_inventory_weave()
273
        weave_parents = inv.parent_names(revision_id)
274
        weave_names = inv.names()
275
        for parent_id in r.parent_ids:
276
            if parent_id in weave_names:
277
                # this parent must not be a ghost.
278
                if not parent_id in weave_parents:
279
                    # but it is a ghost
280
                    raise errors.CorruptRepository(self)
281
        return r
282
283
    @needs_read_lock
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
284
    def get_revision_sha1(self, revision_id):
285
        """Hash the stored value of a revision, and return it."""
286
        # In the future, revision entries will be signed. At that
287
        # point, it is probably best *not* to include the signature
288
        # in the revision hash. Because that lets you re-sign
289
        # the revision, (add signatures/remove signatures) and still
290
        # have all hash pointers stay consistent.
291
        # But for now, just hash the contents.
292
        return bzrlib.osutils.sha_file(self.get_revision_xml_file(revision_id))
293
294
    @needs_write_lock
295
    def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
296
        self.revision_store.add(StringIO(gpg_strategy.sign(plaintext)), 
297
                                revision_id, "sig")
298
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
299
    def fileid_involved_between_revs(self, from_revid, to_revid):
300
        """Find file_id(s) which are involved in the changes between revisions.
301
302
        This determines the set of revisions which are involved, and then
303
        finds all file ids affected by those revisions.
304
        """
305
        # TODO: jam 20060119 This code assumes that w.inclusions will
306
        #       always be correct. But because of the presence of ghosts
307
        #       it is possible to be wrong.
308
        #       One specific example from Robert Collins:
309
        #       Two branches, with revisions ABC, and AD
310
        #       C is a ghost merge of D.
311
        #       Inclusions doesn't recognize D as an ancestor.
312
        #       If D is ever merged in the future, the weave
313
        #       won't be fixed, because AD never saw revision C
314
        #       to cause a conflict which would force a reweave.
315
        w = self.get_inventory_weave()
316
        from_set = set(w.inclusions([w.lookup(from_revid)]))
317
        to_set = set(w.inclusions([w.lookup(to_revid)]))
318
        included = to_set.difference(from_set)
319
        changed = map(w.idx_to_name, included)
320
        return self._fileid_involved_by_set(changed)
321
322
    def fileid_involved(self, last_revid=None):
323
        """Find all file_ids modified in the ancestry of last_revid.
324
325
        :param last_revid: If None, last_revision() will be used.
326
        """
327
        w = self.get_inventory_weave()
328
        if not last_revid:
329
            changed = set(w._names)
330
        else:
331
            included = w.inclusions([w.lookup(last_revid)])
332
            changed = map(w.idx_to_name, included)
333
        return self._fileid_involved_by_set(changed)
334
335
    def fileid_involved_by_set(self, changes):
336
        """Find all file_ids modified by the set of revisions passed in.
337
338
        :param changes: A set() of revision ids
339
        """
340
        # TODO: jam 20060119 This line does *nothing*, remove it.
341
        #       or better yet, change _fileid_involved_by_set so
342
        #       that it takes the inventory weave, rather than
343
        #       pulling it out by itself.
344
        return self._fileid_involved_by_set(changes)
345
346
    def _fileid_involved_by_set(self, changes):
347
        """Find the set of file-ids affected by the set of revisions.
348
349
        :param changes: A set() of revision ids.
350
        :return: A set() of file ids.
351
        
352
        This peaks at the Weave, interpreting each line, looking to
353
        see if it mentions one of the revisions. And if so, includes
354
        the file id mentioned.
355
        This expects both the Weave format, and the serialization
356
        to have a single line per file/directory, and to have
357
        fileid="" and revision="" on that line.
358
        """
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
359
        assert isinstance(self._format, (RepositoryFormat5,
360
                                         RepositoryFormat6,
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
361
                                         RepositoryFormat7,
362
                                         RepositoryFormatKnit1)), \
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
363
            "fileid_involved only supported for branches which store inventory as unnested xml"
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
364
365
        w = self.get_inventory_weave()
366
        file_ids = set()
367
        for line in w._weave:
368
369
            # it is ugly, but it is due to the weave structure
370
            if not isinstance(line, basestring): continue
371
372
            start = line.find('file_id="')+9
373
            if start < 9: continue
374
            end = line.find('"', start)
375
            assert end>= 0
376
            file_id = xml.sax.saxutils.unescape(line[start:end])
377
378
            # check if file_id is already present
379
            if file_id in file_ids: continue
380
381
            start = line.find('revision="')+10
382
            if start < 10: continue
383
            end = line.find('"', start)
384
            assert end>= 0
385
            revision_id = xml.sax.saxutils.unescape(line[start:end])
386
387
            if revision_id in changes:
388
                file_ids.add(file_id)
389
        return file_ids
390
1185.65.27 by Robert Collins
Tweak storage towards mergability.
391
    @needs_read_lock
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
392
    def get_inventory_weave(self):
393
        return self.control_weaves.get_weave('inventory',
394
            self.get_transaction())
395
1185.65.27 by Robert Collins
Tweak storage towards mergability.
396
    @needs_read_lock
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
397
    def get_inventory(self, revision_id):
398
        """Get Inventory object by hash."""
399
        xml = self.get_inventory_xml(revision_id)
400
        return bzrlib.xml5.serializer_v5.read_inventory_from_string(xml)
401
1185.65.27 by Robert Collins
Tweak storage towards mergability.
402
    @needs_read_lock
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
403
    def get_inventory_xml(self, revision_id):
404
        """Get inventory XML as a file object."""
405
        try:
406
            assert isinstance(revision_id, basestring), type(revision_id)
407
            iw = self.get_inventory_weave()
408
            return iw.get_text(iw.lookup(revision_id))
409
        except IndexError:
410
            raise bzrlib.errors.HistoryMissing(self, 'inventory', revision_id)
411
1185.65.27 by Robert Collins
Tweak storage towards mergability.
412
    @needs_read_lock
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
413
    def get_inventory_sha1(self, revision_id):
414
        """Return the sha1 hash of the inventory entry
415
        """
416
        return self.get_revision(revision_id).inventory_sha1
417
1185.65.27 by Robert Collins
Tweak storage towards mergability.
418
    @needs_read_lock
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
419
    def get_revision_inventory(self, revision_id):
420
        """Return inventory of a past revision."""
421
        # TODO: Unify this with get_inventory()
422
        # bzr 0.0.6 and later imposes the constraint that the inventory_id
423
        # must be the same as its revision, so this is trivial.
1534.4.28 by Robert Collins
first cut at merge from integration.
424
        if revision_id is None:
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
425
            # This does not make sense: if there is no revision,
426
            # then it is the current tree inventory surely ?!
427
            # and thus get_root_id() is something that looks at the last
428
            # commit on the branch, and the get_root_id is an inventory check.
429
            raise NotImplementedError
430
            # return Inventory(self.get_root_id())
431
        else:
432
            return self.get_inventory(revision_id)
433
1185.65.27 by Robert Collins
Tweak storage towards mergability.
434
    @needs_read_lock
1534.6.3 by Robert Collins
find_repository sufficiently robust.
435
    def is_shared(self):
436
        """Return True if this repository is flagged as a shared repository."""
437
        # FIXME format 4-6 cannot be shared, this is technically faulty.
438
        return self.control_files._transport.has('shared-storage')
439
440
    @needs_read_lock
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
441
    def revision_tree(self, revision_id):
442
        """Return Tree for a revision on this branch.
443
444
        `revision_id` may be None for the null revision, in which case
445
        an `EmptyTree` is returned."""
446
        # TODO: refactor this to use an existing revision object
447
        # so we don't need to read it in twice.
1534.4.28 by Robert Collins
first cut at merge from integration.
448
        if revision_id is None or revision_id == NULL_REVISION:
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
449
            return EmptyTree()
450
        else:
451
            inv = self.get_revision_inventory(revision_id)
1185.65.17 by Robert Collins
Merge from integration, mode-changes are broken.
452
            return RevisionTree(self, inv, revision_id)
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
453
1185.65.27 by Robert Collins
Tweak storage towards mergability.
454
    @needs_read_lock
1185.66.2 by Aaron Bentley
Moved get_ancestry to RevisionStorage
455
    def get_ancestry(self, revision_id):
456
        """Return a list of revision-ids integrated by a revision.
457
        
458
        This is topologically sorted.
459
        """
460
        if revision_id is None:
461
            return [None]
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
462
        if not self.has_revision(revision_id):
463
            raise errors.NoSuchRevision(self, revision_id)
1185.66.2 by Aaron Bentley
Moved get_ancestry to RevisionStorage
464
        w = self.get_inventory_weave()
465
        return [None] + map(w.idx_to_name,
466
                            w.inclusions([w.lookup(revision_id)]))
467
1185.65.4 by Aaron Bentley
Fixed cat command
468
    @needs_read_lock
469
    def print_file(self, file, revision_id):
1185.65.29 by Robert Collins
Implement final review suggestions.
470
        """Print `file` to stdout.
471
        
472
        FIXME RBC 20060125 as John Meinel points out this is a bad api
473
        - it writes to stdout, it assumes that that is valid etc. Fix
474
        by creating a new more flexible convenience function.
475
        """
1185.65.4 by Aaron Bentley
Fixed cat command
476
        tree = self.revision_tree(revision_id)
477
        # use inventory as it was in that revision
478
        file_id = tree.inventory.path2id(file)
479
        if not file_id:
480
            raise BzrError("%r is not present in revision %s" % (file, revno))
1185.65.15 by Robert Collins
Merge from integration.
481
            try:
482
                revno = self.revision_id_to_revno(revision_id)
483
            except errors.NoSuchRevision:
484
                # TODO: This should not be BzrError,
485
                # but NoSuchFile doesn't fit either
486
                raise BzrError('%r is not present in revision %s' 
487
                                % (file, revision_id))
488
            else:
489
                raise BzrError('%r is not present in revision %s'
490
                                % (file, revno))
1185.65.4 by Aaron Bentley
Fixed cat command
491
        tree.print_file(file_id)
492
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
493
    def get_transaction(self):
494
        return self.control_files.get_transaction()
495
1185.65.27 by Robert Collins
Tweak storage towards mergability.
496
    @needs_write_lock
1534.6.5 by Robert Collins
Cloning of repos preserves shared and make-working-tree attributes.
497
    def set_make_working_trees(self, new_value):
498
        """Set the policy flag for making working trees when creating branches.
499
500
        This only applies to branches that use this repository.
501
502
        The default is 'True'.
503
        :param new_value: True to restore the default, False to disable making
504
                          working trees.
505
        """
506
        # FIXME: split out into a new class/strategy ?
507
        if isinstance(self._format, (RepositoryFormat4,
508
                                     RepositoryFormat5,
509
                                     RepositoryFormat6)):
510
            raise NotImplementedError(self.set_make_working_trees)
511
        if new_value:
512
            try:
513
                self.control_files._transport.delete('no-working-trees')
514
            except errors.NoSuchFile:
1534.6.6 by Robert Collins
Move find_repository to bzrdir, its not quite ideal there but its simpler and until someone chooses to vary the search by branch type its completely sufficient.
515
                pass
1534.6.5 by Robert Collins
Cloning of repos preserves shared and make-working-tree attributes.
516
        else:
517
            self.control_files.put_utf8('no-working-trees', '')
518
    
519
    def make_working_trees(self):
520
        """Returns the policy for making working trees on new branches."""
521
        # FIXME: split out into a new class/strategy ?
522
        if isinstance(self._format, (RepositoryFormat4,
523
                                     RepositoryFormat5,
524
                                     RepositoryFormat6)):
525
            return True
1534.6.6 by Robert Collins
Move find_repository to bzrdir, its not quite ideal there but its simpler and until someone chooses to vary the search by branch type its completely sufficient.
526
        return not self.control_files._transport.has('no-working-trees')
1534.6.5 by Robert Collins
Cloning of repos preserves shared and make-working-tree attributes.
527
528
    @needs_write_lock
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
529
    def sign_revision(self, revision_id, gpg_strategy):
530
        plaintext = Testament.from_revision(self, revision_id).as_short_text()
531
        self.store_revision_signature(gpg_strategy, plaintext, revision_id)
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
532
533
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
534
class AllInOneRepository(Repository):
535
    """Legacy support - the repository behaviour for all-in-one branches."""
536
537
    def __init__(self, _format, a_bzrdir, revision_store):
538
        # we reuse one control files instance.
539
        dir_mode = a_bzrdir._control_files._dir_mode
540
        file_mode = a_bzrdir._control_files._file_mode
541
542
        def get_weave(name, prefixed=False):
543
            if name:
544
                name = safe_unicode(name)
545
            else:
546
                name = ''
547
            relpath = a_bzrdir._control_files._escape(name)
548
            weave_transport = a_bzrdir._control_files._transport.clone(relpath)
549
            ws = WeaveStore(weave_transport, prefixed=prefixed,
550
                            dir_mode=dir_mode,
551
                            file_mode=file_mode)
552
            if a_bzrdir._control_files._transport.should_cache():
553
                ws.enable_cache = True
554
            return ws
555
556
        def get_store(name, compressed=True, prefixed=False):
557
            # FIXME: This approach of assuming stores are all entirely compressed
558
            # or entirely uncompressed is tidy, but breaks upgrade from 
559
            # some existing branches where there's a mixture; we probably 
560
            # still want the option to look for both.
561
            relpath = a_bzrdir._control_files._escape(name)
562
            store = TextStore(a_bzrdir._control_files._transport.clone(relpath),
563
                              prefixed=prefixed, compressed=compressed,
564
                              dir_mode=dir_mode,
565
                              file_mode=file_mode)
566
            #if self._transport.should_cache():
567
            #    cache_path = os.path.join(self.cache_root, name)
568
            #    os.mkdir(cache_path)
569
            #    store = bzrlib.store.CachedStore(store, cache_path)
570
            return store
571
572
        # not broken out yet because the controlweaves|inventory_store
573
        # and text_store | weave_store bits are still different.
574
        if isinstance(_format, RepositoryFormat4):
575
            self.inventory_store = get_store('inventory-store')
576
            self.text_store = get_store('text-store')
577
        elif isinstance(_format, RepositoryFormat5):
578
            self.control_weaves = get_weave('')
579
            self.weave_store = get_weave('weaves')
580
        elif isinstance(_format, RepositoryFormat6):
581
            self.control_weaves = get_weave('')
582
            self.weave_store = get_weave('weaves', prefixed=True)
583
        else:
584
            raise errors.BzrError('unreachable code: unexpected repository'
585
                                  ' format.')
586
        revision_store.register_suffix('sig')
587
        super(AllInOneRepository, self).__init__(_format, a_bzrdir, a_bzrdir._control_files, revision_store)
588
589
590
class MetaDirRepository(Repository):
591
    """Repositories in the new meta-dir layout."""
592
593
    def __init__(self, _format, a_bzrdir, control_files, revision_store):
594
        super(MetaDirRepository, self).__init__(_format,
595
                                                a_bzrdir,
596
                                                control_files,
597
                                                revision_store)
598
599
        dir_mode = self.control_files._dir_mode
600
        file_mode = self.control_files._file_mode
601
602
        def get_weave(name, prefixed=False):
603
            if name:
604
                name = safe_unicode(name)
605
            else:
606
                name = ''
607
            relpath = self.control_files._escape(name)
608
            weave_transport = self.control_files._transport.clone(relpath)
609
            ws = WeaveStore(weave_transport, prefixed=prefixed,
610
                            dir_mode=dir_mode,
611
                            file_mode=file_mode)
612
            if self.control_files._transport.should_cache():
613
                ws.enable_cache = True
614
            return ws
615
616
        if isinstance(self._format, RepositoryFormat7):
617
            self.control_weaves = get_weave('')
618
            self.weave_store = get_weave('weaves', prefixed=True)
619
        elif isinstance(self._format, RepositoryFormatKnit1):
620
            self.control_weaves = get_weave('')
621
            self.weave_store = get_weave('knits', prefixed=True)
622
        else:
623
            raise errors.BzrError('unreachable code: unexpected repository'
624
                                  ' format.')
625
626
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
627
class RepositoryFormat(object):
628
    """A repository format.
629
630
    Formats provide three things:
631
     * An initialization routine to construct repository data on disk.
632
     * a format string which is used when the BzrDir supports versioned
633
       children.
634
     * an open routine which returns a Repository instance.
635
636
    Formats are placed in an dict by their format string for reference 
637
    during opening. These should be subclasses of RepositoryFormat
638
    for consistency.
639
640
    Once a format is deprecated, just deprecate the initialize and open
641
    methods on the format class. Do not deprecate the object, as the 
642
    object will be created every system load.
643
644
    Common instance attributes:
645
    _matchingbzrdir - the bzrdir format that the repository format was
646
    originally written to work with. This can be used if manually
647
    constructing a bzrdir and repository, or more commonly for test suite
648
    parameterisation.
649
    """
650
651
    _default_format = None
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
652
    """The default format used for new repositories."""
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
653
654
    _formats = {}
655
    """The known formats."""
656
657
    @classmethod
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
658
    def find_format(klass, a_bzrdir):
659
        """Return the format for the repository object in a_bzrdir."""
660
        try:
661
            transport = a_bzrdir.get_repository_transport(None)
662
            format_string = transport.get("format").read()
663
            return klass._formats[format_string]
664
        except errors.NoSuchFile:
665
            raise errors.NoRepositoryPresent(a_bzrdir)
666
        except KeyError:
667
            raise errors.UnknownFormatError(format_string)
668
669
    @classmethod
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
670
    def get_default_format(klass):
671
        """Return the current default format."""
672
        return klass._default_format
673
674
    def get_format_string(self):
675
        """Return the ASCII format string that identifies this format.
676
        
677
        Note that in pre format ?? repositories the format string is 
678
        not permitted nor written to disk.
679
        """
680
        raise NotImplementedError(self.get_format_string)
681
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
682
    def _get_revision_store(self, repo_transport, control_files):
683
        """Return the revision store object for this a_bzrdir."""
1556.1.5 by Robert Collins
Review feedback.
684
        raise NotImplementedError(self._get_revision_store)
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
685
686
    def _get_rev_store(self,
687
                   transport,
688
                   control_files,
689
                   name,
690
                   compressed=True,
691
                   prefixed=False):
692
        """Common logic for getting a revision store for a repository.
693
        
694
        see self._get_revision_store for the method to 
695
        get the store for a repository.
696
        """
697
        if name:
698
            name = safe_unicode(name)
699
        else:
700
            name = ''
701
        dir_mode = control_files._dir_mode
702
        file_mode = control_files._file_mode
703
        revision_store =TextStore(transport.clone(name),
704
                                  prefixed=prefixed,
705
                                  compressed=compressed,
706
                                  dir_mode=dir_mode,
707
                                  file_mode=file_mode)
708
        revision_store.register_suffix('sig')
709
        return revision_store
710
1534.6.1 by Robert Collins
allow API creation of shared repositories
711
    def initialize(self, a_bzrdir, shared=False):
712
        """Initialize a repository of this format in a_bzrdir.
713
714
        :param a_bzrdir: The bzrdir to put the new repository in it.
715
        :param shared: The repository should be initialized as a sharable one.
716
717
        This may raise UninitializableFormat if shared repository are not
718
        compatible the a_bzrdir.
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
719
        """
720
721
    def is_supported(self):
722
        """Is this format supported?
723
724
        Supported formats must be initializable and openable.
725
        Unsupported formats may not support initialization or committing or 
726
        some other features depending on the reason for not being supported.
727
        """
728
        return True
729
730
    def open(self, a_bzrdir, _found=False):
731
        """Return an instance of this format for the bzrdir a_bzrdir.
732
        
733
        _found is a private parameter, do not use it.
734
        """
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
735
        raise NotImplementedError(self.open)
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
736
737
    @classmethod
738
    def register_format(klass, format):
739
        klass._formats[format.get_format_string()] = format
740
741
    @classmethod
742
    def set_default_format(klass, format):
743
        klass._default_format = format
744
745
    @classmethod
746
    def unregister_format(klass, format):
747
        assert klass._formats[format.get_format_string()] is format
748
        del klass._formats[format.get_format_string()]
749
750
1534.6.1 by Robert Collins
allow API creation of shared repositories
751
class PreSplitOutRepositoryFormat(RepositoryFormat):
752
    """Base class for the pre split out repository formats."""
753
754
    def initialize(self, a_bzrdir, shared=False, _internal=False):
755
        """Create a weave repository.
756
        
757
        TODO: when creating split out bzr branch formats, move this to a common
758
        base for Format5, Format6. or something like that.
759
        """
760
        from bzrlib.weavefile import write_weave_v5
761
        from bzrlib.weave import Weave
762
763
        if shared:
764
            raise errors.IncompatibleFormat(self, a_bzrdir._format)
765
766
        if not _internal:
767
            # always initialized when the bzrdir is.
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
768
            return self.open(a_bzrdir, _found=True)
1534.6.1 by Robert Collins
allow API creation of shared repositories
769
        
770
        # Create an empty weave
771
        sio = StringIO()
772
        bzrlib.weavefile.write_weave_v5(Weave(), sio)
773
        empty_weave = sio.getvalue()
774
775
        mutter('creating repository in %s.', a_bzrdir.transport.base)
776
        dirs = ['revision-store', 'weaves']
777
        lock_file = 'branch-lock'
778
        files = [('inventory.weave', StringIO(empty_weave)), 
779
                 ]
780
        
781
        # FIXME: RBC 20060125 dont peek under the covers
782
        # NB: no need to escape relative paths that are url safe.
783
        control_files = LockableFiles(a_bzrdir.transport, 'branch-lock')
784
        control_files.lock_write()
785
        control_files._transport.mkdir_multi(dirs,
786
                mode=control_files._dir_mode)
787
        try:
788
            for file, content in files:
789
                control_files.put(file, content)
790
        finally:
791
            control_files.unlock()
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
792
        return self.open(a_bzrdir, _found=True)
793
794
    def open(self, a_bzrdir, _found=False):
795
        """See RepositoryFormat.open()."""
796
        if not _found:
797
            # we are being called directly and must probe.
798
            raise NotImplementedError
799
800
        repo_transport = a_bzrdir.get_repository_transport(None)
801
        control_files = a_bzrdir._control_files
802
        revision_store = self._get_revision_store(repo_transport, control_files)
803
        return AllInOneRepository(_format=self,
804
                                  a_bzrdir=a_bzrdir,
805
                                  revision_store=revision_store)
1534.6.1 by Robert Collins
allow API creation of shared repositories
806
807
808
class RepositoryFormat4(PreSplitOutRepositoryFormat):
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
809
    """Bzr repository format 4.
810
811
    This repository format has:
812
     - flat stores
813
     - TextStores for texts, inventories,revisions.
814
815
    This format is deprecated: it indexes texts using a text id which is
816
    removed in format 5; initializationa and write support for this format
817
    has been removed.
818
    """
819
820
    def __init__(self):
821
        super(RepositoryFormat4, self).__init__()
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
822
        self._matchingbzrdir = bzrlib.bzrdir.BzrDirFormat4()
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
823
1534.6.1 by Robert Collins
allow API creation of shared repositories
824
    def initialize(self, url, shared=False, _internal=False):
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
825
        """Format 4 branches cannot be created."""
826
        raise errors.UninitializableFormat(self)
827
828
    def is_supported(self):
829
        """Format 4 is not supported.
830
831
        It is not supported because the model changed from 4 to 5 and the
832
        conversion logic is expensive - so doing it on the fly was not 
833
        feasible.
834
        """
835
        return False
836
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
837
    def _get_revision_store(self, repo_transport, control_files):
838
        """See RepositoryFormat._get_revision_store()."""
839
        return self._get_rev_store(repo_transport,
840
                                   control_files,
841
                                   'revision-store')
842
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
843
1534.6.1 by Robert Collins
allow API creation of shared repositories
844
class RepositoryFormat5(PreSplitOutRepositoryFormat):
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
845
    """Bzr control format 5.
846
847
    This repository format has:
848
     - weaves for file texts and inventory
849
     - flat stores
850
     - TextStores for revisions and signatures.
851
    """
852
853
    def __init__(self):
854
        super(RepositoryFormat5, self).__init__()
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
855
        self._matchingbzrdir = bzrlib.bzrdir.BzrDirFormat5()
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
856
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
857
    def _get_revision_store(self, repo_transport, control_files):
858
        """See RepositoryFormat._get_revision_store()."""
859
        """Return the revision store object for this a_bzrdir."""
860
        return self._get_rev_store(repo_transport,
861
                                   control_files,
862
                                   'revision-store',
863
                                   compressed=False)
864
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
865
1534.6.1 by Robert Collins
allow API creation of shared repositories
866
class RepositoryFormat6(PreSplitOutRepositoryFormat):
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
867
    """Bzr control format 6.
868
869
    This repository format has:
870
     - weaves for file texts and inventory
871
     - hash subdirectory based stores.
872
     - TextStores for revisions and signatures.
873
    """
874
875
    def __init__(self):
876
        super(RepositoryFormat6, self).__init__()
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
877
        self._matchingbzrdir = bzrlib.bzrdir.BzrDirFormat6()
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
878
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
879
    def _get_revision_store(self, repo_transport, control_files):
880
        """See RepositoryFormat._get_revision_store()."""
881
        return self._get_rev_store(repo_transport,
882
                                   control_files,
883
                                   'revision-store',
884
                                   compressed=False,
885
                                   prefixed=True)
886
887
888
class MetaDirRepositoryFormat(RepositoryFormat):
889
    """Common base class for the new repositories using the metadir layour."""
890
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
891
    def __init__(self):
892
        super(MetaDirRepositoryFormat, self).__init__()
893
        self._matchingbzrdir = bzrlib.bzrdir.BzrDirMetaFormat1()
894
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
895
    def _create_control_files(self, a_bzrdir):
896
        """Create the required files and the initial control_files object."""
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
897
        # FIXME: RBC 20060125 dont peek under the covers
898
        # NB: no need to escape relative paths that are url safe.
899
        lock_file = 'lock'
900
        repository_transport = a_bzrdir.get_repository_transport(self)
901
        repository_transport.put(lock_file, StringIO()) # TODO get the file mode from the bzrdir lock files., mode=file_mode)
902
        control_files = LockableFiles(repository_transport, 'lock')
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
903
        return control_files
904
905
    def _get_revision_store(self, repo_transport, control_files):
906
        """See RepositoryFormat._get_revision_store()."""
907
        return self._get_rev_store(repo_transport,
908
                                   control_files,
909
                                   'revision-store',
910
                                   compressed=False,
911
                                   prefixed=True,
912
                                   )
913
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
914
    def open(self, a_bzrdir, _found=False, _override_transport=None):
915
        """See RepositoryFormat.open().
916
        
917
        :param _override_transport: INTERNAL USE ONLY. Allows opening the
918
                                    repository at a slightly different url
919
                                    than normal. I.e. during 'upgrade'.
920
        """
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
921
        if not _found:
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
922
            format = RepositoryFormat.find_format(a_bzrdir)
923
            assert format.__class__ ==  self.__class__
924
        if _override_transport is not None:
925
            repo_transport = _override_transport
926
        else:
927
            repo_transport = a_bzrdir.get_repository_transport(None)
928
        control_files = LockableFiles(repo_transport, 'lock')
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
929
        revision_store = self._get_revision_store(repo_transport, control_files)
930
        return MetaDirRepository(_format=self,
931
                                 a_bzrdir=a_bzrdir,
932
                                 control_files=control_files,
933
                                 revision_store=revision_store)
934
935
    def _upload_blank_content(self, a_bzrdir, dirs, files, utf8_files, shared):
936
        """Upload the initial blank content."""
937
        control_files = self._create_control_files(a_bzrdir)
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
938
        control_files.lock_write()
939
        control_files._transport.mkdir_multi(dirs,
940
                mode=control_files._dir_mode)
941
        try:
942
            for file, content in files:
943
                control_files.put(file, content)
944
            for file, content in utf8_files:
945
                control_files.put_utf8(file, content)
1534.6.1 by Robert Collins
allow API creation of shared repositories
946
            if shared == True:
947
                control_files.put_utf8('shared-storage', '')
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
948
        finally:
949
            control_files.unlock()
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
950
951
952
class RepositoryFormat7(MetaDirRepositoryFormat):
953
    """Bzr repository 7.
954
955
    This repository format has:
956
     - weaves for file texts and inventory
957
     - hash subdirectory based stores.
958
     - TextStores for revisions and signatures.
959
     - a format marker of its own
960
     - an optional 'shared-storage' flag
961
     - an optional 'no-working-trees' flag
962
    """
963
964
    def get_format_string(self):
965
        """See RepositoryFormat.get_format_string()."""
966
        return "Bazaar-NG Repository format 7"
967
968
    def initialize(self, a_bzrdir, shared=False):
969
        """Create a weave repository.
970
971
        :param shared: If true the repository will be initialized as a shared
972
                       repository.
973
        """
974
        from bzrlib.weavefile import write_weave_v5
975
        from bzrlib.weave import Weave
976
977
        # Create an empty weave
978
        sio = StringIO()
979
        bzrlib.weavefile.write_weave_v5(Weave(), sio)
980
        empty_weave = sio.getvalue()
981
982
        mutter('creating repository in %s.', a_bzrdir.transport.base)
983
        dirs = ['revision-store', 'weaves']
984
        files = [('inventory.weave', StringIO(empty_weave)), 
985
                 ]
986
        utf8_files = [('format', self.get_format_string())]
987
 
988
        self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
989
        return self.open(a_bzrdir=a_bzrdir, _found=True)
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
990
991
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
992
class RepositoryFormatKnit1(MetaDirRepositoryFormat):
993
    """Bzr repository knit format 1.
994
995
    This repository format has:
996
     - knits for file texts and inventory
997
     - hash subdirectory based stores.
998
     - knits for revisions and signatures
999
     - TextStores for revisions and signatures.
1000
     - a format marker of its own
1001
     - an optional 'shared-storage' flag
1002
     - an optional 'no-working-trees' flag
1003
    """
1004
1005
    def get_format_string(self):
1006
        """See RepositoryFormat.get_format_string()."""
1007
        return "Bazaar-NG Knit Repository Format 1"
1008
1009
    def initialize(self, a_bzrdir, shared=False):
1010
        """Create a knit format 1 repository.
1011
1012
        :param shared: If true the repository will be initialized as a shared
1013
                       repository.
1556.1.5 by Robert Collins
Review feedback.
1014
        XXX NOTE that this current uses a Weave for testing and will become 
1015
            A Knit in due course.
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
1016
        """
1017
        from bzrlib.weavefile import write_weave_v5
1018
        from bzrlib.weave import Weave
1019
1020
        # Create an empty weave
1021
        sio = StringIO()
1022
        bzrlib.weavefile.write_weave_v5(Weave(), sio)
1023
        empty_weave = sio.getvalue()
1024
1025
        mutter('creating repository in %s.', a_bzrdir.transport.base)
1026
        dirs = ['revision-store', 'knits']
1027
        files = [('inventory.weave', StringIO(empty_weave)), 
1028
                 ]
1029
        utf8_files = [('format', self.get_format_string())]
1030
        
1031
        self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
1032
        return self.open(a_bzrdir=a_bzrdir, _found=True)
1033
1034
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1035
# formats which have no format string are not discoverable
1036
# and not independently creatable, so are not registered.
1534.1.33 by Robert Collins
Move copy_content_into into InterRepository and InterWeaveRepo, and disable the default codepath test as we have optimised paths for all current combinations.
1037
_default_format = RepositoryFormat7()
1038
RepositoryFormat.register_format(_default_format)
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
1039
RepositoryFormat.register_format(RepositoryFormatKnit1())
1534.1.33 by Robert Collins
Move copy_content_into into InterRepository and InterWeaveRepo, and disable the default codepath test as we have optimised paths for all current combinations.
1040
RepositoryFormat.set_default_format(_default_format)
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1041
_legacy_formats = [RepositoryFormat4(),
1042
                   RepositoryFormat5(),
1043
                   RepositoryFormat6()]
1044
1045
1534.1.27 by Robert Collins
Start InterRepository with InterRepository.get.
1046
class InterRepository(object):
1047
    """This class represents operations taking place between two repositories.
1048
1534.1.33 by Robert Collins
Move copy_content_into into InterRepository and InterWeaveRepo, and disable the default codepath test as we have optimised paths for all current combinations.
1049
    Its instances have methods like copy_content and fetch, and contain
1534.1.27 by Robert Collins
Start InterRepository with InterRepository.get.
1050
    references to the source and target repositories these operations can be 
1051
    carried out on.
1052
1053
    Often we will provide convenience methods on 'repository' which carry out
1054
    operations with another repository - they will always forward to
1055
    InterRepository.get(other).method_name(parameters).
1056
    """
1534.1.29 by Robert Collins
Add a test environment for InterRepository objects, and remove the fetch corner case tests from test_repository.
1057
    # XXX: FIXME: FUTURE: robertc
1058
    # testing of these probably requires a factory in optimiser type, and 
1059
    # then a test adapter to test each type thoroughly.
1060
    #
1534.1.27 by Robert Collins
Start InterRepository with InterRepository.get.
1061
1534.1.28 by Robert Collins
Allow for optimised InterRepository selection.
1062
    _optimisers = set()
1063
    """The available optimised InterRepository types."""
1064
1534.1.27 by Robert Collins
Start InterRepository with InterRepository.get.
1065
    def __init__(self, source, target):
1066
        """Construct a default InterRepository instance. Please use 'get'.
1067
        
1068
        Only subclasses of InterRepository should call 
1069
        InterRepository.__init__ - clients should call InterRepository.get
1070
        instead which will create an optimised InterRepository if possible.
1071
        """
1072
        self.source = source
1073
        self.target = target
1074
1534.1.33 by Robert Collins
Move copy_content_into into InterRepository and InterWeaveRepo, and disable the default codepath test as we have optimised paths for all current combinations.
1075
    @needs_write_lock
1076
    def copy_content(self, revision_id=None, basis=None):
1077
        """Make a complete copy of the content in self into destination.
1078
        
1079
        This is a destructive operation! Do not use it on existing 
1080
        repositories.
1081
1082
        :param revision_id: Only copy the content needed to construct
1083
                            revision_id and its parents.
1084
        :param basis: Copy the needed data preferentially from basis.
1085
        """
1086
        try:
1087
            self.target.set_make_working_trees(self.source.make_working_trees())
1088
        except NotImplementedError:
1089
            pass
1090
        # grab the basis available data
1091
        if basis is not None:
1092
            self.target.fetch(basis, revision_id=revision_id)
1093
        # but dont both fetching if we have the needed data now.
1094
        if (revision_id not in (None, NULL_REVISION) and 
1095
            self.target.has_revision(revision_id)):
1096
            return
1097
        self.target.fetch(self.source, revision_id=revision_id)
1098
1534.1.34 by Robert Collins
Move missing_revision_ids from Repository to InterRepository, and eliminate the now unused Repository._compatible_formats method.
1099
    def _double_lock(self, lock_source, lock_target):
1100
        """Take out too locks, rolling back the first if the second throws."""
1101
        lock_source()
1102
        try:
1103
            lock_target()
1104
        except Exception:
1105
            # we want to ensure that we don't leave source locked by mistake.
1106
            # and any error on target should not confuse source.
1107
            self.source.unlock()
1108
            raise
1109
1534.1.33 by Robert Collins
Move copy_content_into into InterRepository and InterWeaveRepo, and disable the default codepath test as we have optimised paths for all current combinations.
1110
    @needs_write_lock
1534.1.31 by Robert Collins
Deprecated fetch.fetch and fetch.greedy_fetch for branch.fetch, and move the Repository.fetch internals to InterRepo and InterWeaveRepo.
1111
    def fetch(self, revision_id=None, pb=None):
1112
        """Fetch the content required to construct revision_id.
1113
1114
        The content is copied from source to target.
1115
1116
        :param revision_id: if None all content is copied, if NULL_REVISION no
1117
                            content is copied.
1118
        :param pb: optional progress bar to use for progress reports. If not
1119
                   provided a default one will be created.
1120
1121
        Returns the copied revision count and the failed revisions in a tuple:
1122
        (copied, failures).
1123
        """
1124
        from bzrlib.fetch import RepoFetcher
1125
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1126
               self.source, self.source._format, self.target, self.target._format)
1534.1.33 by Robert Collins
Move copy_content_into into InterRepository and InterWeaveRepo, and disable the default codepath test as we have optimised paths for all current combinations.
1127
        f = RepoFetcher(to_repository=self.target,
1128
                        from_repository=self.source,
1129
                        last_revision=revision_id,
1130
                        pb=pb)
1131
        return f.count_copied, f.failed_revisions
1534.1.31 by Robert Collins
Deprecated fetch.fetch and fetch.greedy_fetch for branch.fetch, and move the Repository.fetch internals to InterRepo and InterWeaveRepo.
1132
1534.1.27 by Robert Collins
Start InterRepository with InterRepository.get.
1133
    @classmethod
1134
    def get(klass, repository_source, repository_target):
1135
        """Retrieve a InterRepository worker object for these repositories.
1136
1137
        :param repository_source: the repository to be the 'source' member of
1138
                                  the InterRepository instance.
1139
        :param repository_target: the repository to be the 'target' member of
1140
                                the InterRepository instance.
1141
        If an optimised InterRepository worker exists it will be used otherwise
1142
        a default InterRepository instance will be created.
1143
        """
1534.1.28 by Robert Collins
Allow for optimised InterRepository selection.
1144
        for provider in klass._optimisers:
1145
            if provider.is_compatible(repository_source, repository_target):
1146
                return provider(repository_source, repository_target)
1534.1.27 by Robert Collins
Start InterRepository with InterRepository.get.
1147
        return InterRepository(repository_source, repository_target)
1148
1534.1.34 by Robert Collins
Move missing_revision_ids from Repository to InterRepository, and eliminate the now unused Repository._compatible_formats method.
1149
    def lock_read(self):
1150
        """Take out a logical read lock.
1151
1152
        This will lock the source branch and the target branch. The source gets
1153
        a read lock and the target a read lock.
1154
        """
1155
        self._double_lock(self.source.lock_read, self.target.lock_read)
1156
1534.1.33 by Robert Collins
Move copy_content_into into InterRepository and InterWeaveRepo, and disable the default codepath test as we have optimised paths for all current combinations.
1157
    def lock_write(self):
1158
        """Take out a logical write lock.
1159
1160
        This will lock the source branch and the target branch. The source gets
1161
        a read lock and the target a write lock.
1162
        """
1534.1.34 by Robert Collins
Move missing_revision_ids from Repository to InterRepository, and eliminate the now unused Repository._compatible_formats method.
1163
        self._double_lock(self.source.lock_read, self.target.lock_write)
1164
1165
    @needs_read_lock
1166
    def missing_revision_ids(self, revision_id=None):
1167
        """Return the revision ids that source has that target does not.
1168
        
1169
        These are returned in topological order.
1170
1171
        :param revision_id: only return revision ids included by this
1172
                            revision_id.
1173
        """
1174
        # generic, possibly worst case, slow code path.
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
1175
        target_ids = set(self.target.all_revision_ids())
1534.1.34 by Robert Collins
Move missing_revision_ids from Repository to InterRepository, and eliminate the now unused Repository._compatible_formats method.
1176
        if revision_id is not None:
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
1177
            source_ids = self.source.get_ancestry(revision_id)
1534.1.34 by Robert Collins
Move missing_revision_ids from Repository to InterRepository, and eliminate the now unused Repository._compatible_formats method.
1178
            assert source_ids.pop(0) == None
1179
        else:
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
1180
            source_ids = self.source.all_revision_ids()
1534.1.34 by Robert Collins
Move missing_revision_ids from Repository to InterRepository, and eliminate the now unused Repository._compatible_formats method.
1181
        result_set = set(source_ids).difference(target_ids)
1182
        # this may look like a no-op: its not. It preserves the ordering
1183
        # other_ids had while only returning the members from other_ids
1184
        # that we've decided we need.
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
1185
        return [rev_id for rev_id in source_ids if rev_id in result_set]
1534.1.33 by Robert Collins
Move copy_content_into into InterRepository and InterWeaveRepo, and disable the default codepath test as we have optimised paths for all current combinations.
1186
1534.1.28 by Robert Collins
Allow for optimised InterRepository selection.
1187
    @classmethod
1188
    def register_optimiser(klass, optimiser):
1189
        """Register an InterRepository optimiser."""
1190
        klass._optimisers.add(optimiser)
1191
1534.1.33 by Robert Collins
Move copy_content_into into InterRepository and InterWeaveRepo, and disable the default codepath test as we have optimised paths for all current combinations.
1192
    def unlock(self):
1193
        """Release the locks on source and target."""
1194
        try:
1195
            self.target.unlock()
1196
        finally:
1197
            self.source.unlock()
1198
1534.1.28 by Robert Collins
Allow for optimised InterRepository selection.
1199
    @classmethod
1200
    def unregister_optimiser(klass, optimiser):
1201
        """Unregister an InterRepository optimiser."""
1202
        klass._optimisers.remove(optimiser)
1203
1534.1.27 by Robert Collins
Start InterRepository with InterRepository.get.
1204
1534.1.31 by Robert Collins
Deprecated fetch.fetch and fetch.greedy_fetch for branch.fetch, and move the Repository.fetch internals to InterRepo and InterWeaveRepo.
1205
class InterWeaveRepo(InterRepository):
1206
    """Optimised code paths between Weave based repositories."""
1207
1534.1.33 by Robert Collins
Move copy_content_into into InterRepository and InterWeaveRepo, and disable the default codepath test as we have optimised paths for all current combinations.
1208
    _matching_repo_format = _default_format
1209
    """Repository format for testing with."""
1210
1534.1.31 by Robert Collins
Deprecated fetch.fetch and fetch.greedy_fetch for branch.fetch, and move the Repository.fetch internals to InterRepo and InterWeaveRepo.
1211
    @staticmethod
1212
    def is_compatible(source, target):
1213
        """Be compatible with known Weave formats.
1214
        
1215
        We dont test for the stores being of specific types becase that
1216
        could lead to confusing results, and there is no need to be 
1217
        overly general.
1218
        """
1534.1.33 by Robert Collins
Move copy_content_into into InterRepository and InterWeaveRepo, and disable the default codepath test as we have optimised paths for all current combinations.
1219
        try:
1220
            return (isinstance(source._format, (RepositoryFormat5,
1221
                                                RepositoryFormat6,
1222
                                                RepositoryFormat7)) and
1223
                    isinstance(target._format, (RepositoryFormat5,
1224
                                                RepositoryFormat6,
1225
                                                RepositoryFormat7)))
1226
        except AttributeError:
1227
            return False
1228
    
1229
    @needs_write_lock
1230
    def copy_content(self, revision_id=None, basis=None):
1231
        """See InterRepository.copy_content()."""
1232
        # weave specific optimised path:
1233
        if basis is not None:
1234
            # copy the basis in, then fetch remaining data.
1235
            basis.copy_content_into(self.target, revision_id)
1236
            # the basis copy_content_into could misset this.
1237
            try:
1238
                self.target.set_make_working_trees(self.source.make_working_trees())
1239
            except NotImplementedError:
1240
                pass
1241
            self.target.fetch(self.source, revision_id=revision_id)
1242
        else:
1243
            try:
1244
                self.target.set_make_working_trees(self.source.make_working_trees())
1245
            except NotImplementedError:
1246
                pass
1247
            # FIXME do not peek!
1248
            if self.source.control_files._transport.listable():
1249
                pb = bzrlib.ui.ui_factory.progress_bar()
1250
                copy_all(self.source.weave_store,
1251
                    self.target.weave_store, pb=pb)
1252
                pb.update('copying inventory', 0, 1)
1253
                self.target.control_weaves.copy_multi(
1254
                    self.source.control_weaves, ['inventory'])
1255
                copy_all(self.source.revision_store,
1256
                    self.target.revision_store, pb=pb)
1257
            else:
1258
                self.target.fetch(self.source, revision_id=revision_id)
1534.1.31 by Robert Collins
Deprecated fetch.fetch and fetch.greedy_fetch for branch.fetch, and move the Repository.fetch internals to InterRepo and InterWeaveRepo.
1259
1534.1.33 by Robert Collins
Move copy_content_into into InterRepository and InterWeaveRepo, and disable the default codepath test as we have optimised paths for all current combinations.
1260
    @needs_write_lock
1534.1.31 by Robert Collins
Deprecated fetch.fetch and fetch.greedy_fetch for branch.fetch, and move the Repository.fetch internals to InterRepo and InterWeaveRepo.
1261
    def fetch(self, revision_id=None, pb=None):
1262
        """See InterRepository.fetch()."""
1263
        from bzrlib.fetch import RepoFetcher
1264
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1265
               self.source, self.source._format, self.target, self.target._format)
1534.1.33 by Robert Collins
Move copy_content_into into InterRepository and InterWeaveRepo, and disable the default codepath test as we have optimised paths for all current combinations.
1266
        f = RepoFetcher(to_repository=self.target,
1267
                        from_repository=self.source,
1268
                        last_revision=revision_id,
1269
                        pb=pb)
1270
        return f.count_copied, f.failed_revisions
1271
1534.1.34 by Robert Collins
Move missing_revision_ids from Repository to InterRepository, and eliminate the now unused Repository._compatible_formats method.
1272
    @needs_read_lock
1273
    def missing_revision_ids(self, revision_id=None):
1274
        """See InterRepository.missing_revision_ids()."""
1275
        # we want all revisions to satisfy revision_id in source.
1276
        # but we dont want to stat every file here and there.
1277
        # we want then, all revisions other needs to satisfy revision_id 
1278
        # checked, but not those that we have locally.
1279
        # so the first thing is to get a subset of the revisions to 
1280
        # satisfy revision_id in source, and then eliminate those that
1281
        # we do already have. 
1282
        # this is slow on high latency connection to self, but as as this
1283
        # disk format scales terribly for push anyway due to rewriting 
1284
        # inventory.weave, this is considered acceptable.
1285
        # - RBC 20060209
1286
        if revision_id is not None:
1287
            source_ids = self.source.get_ancestry(revision_id)
1288
            assert source_ids.pop(0) == None
1289
        else:
1290
            source_ids = self.source._all_possible_ids()
1291
        source_ids_set = set(source_ids)
1292
        # source_ids is the worst possible case we may need to pull.
1293
        # now we want to filter source_ids against what we actually
1294
        # have in target, but dont try to check for existence where we know
1295
        # we do not have a revision as that would be pointless.
1296
        target_ids = set(self.target._all_possible_ids())
1297
        possibly_present_revisions = target_ids.intersection(source_ids_set)
1298
        actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
1299
        required_revisions = source_ids_set.difference(actually_present_revisions)
1300
        required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
1301
        if revision_id is not None:
1302
            # we used get_ancestry to determine source_ids then we are assured all
1303
            # revisions referenced are present as they are installed in topological order.
1304
            # and the tip revision was validated by get_ancestry.
1305
            return required_topo_revisions
1306
        else:
1307
            # if we just grabbed the possibly available ids, then 
1308
            # we only have an estimate of whats available and need to validate
1309
            # that against the revision records.
1310
            return self.source._eliminate_revisions_not_present(required_topo_revisions)
1311
1534.1.33 by Robert Collins
Move copy_content_into into InterRepository and InterWeaveRepo, and disable the default codepath test as we have optimised paths for all current combinations.
1312
1313
InterRepository.register_optimiser(InterWeaveRepo)
1534.1.31 by Robert Collins
Deprecated fetch.fetch and fetch.greedy_fetch for branch.fetch, and move the Repository.fetch internals to InterRepo and InterWeaveRepo.
1314
1315
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1316
class RepositoryTestProviderAdapter(object):
1317
    """A tool to generate a suite testing multiple repository formats at once.
1318
1319
    This is done by copying the test once for each transport and injecting
1320
    the transport_server, transport_readonly_server, and bzrdir_format and
1321
    repository_format classes into each copy. Each copy is also given a new id()
1322
    to make it easy to identify.
1323
    """
1324
1325
    def __init__(self, transport_server, transport_readonly_server, formats):
1326
        self._transport_server = transport_server
1327
        self._transport_readonly_server = transport_readonly_server
1328
        self._formats = formats
1329
    
1330
    def adapt(self, test):
1331
        result = TestSuite()
1332
        for repository_format, bzrdir_format in self._formats:
1333
            new_test = deepcopy(test)
1334
            new_test.transport_server = self._transport_server
1335
            new_test.transport_readonly_server = self._transport_readonly_server
1336
            new_test.bzrdir_format = bzrdir_format
1337
            new_test.repository_format = repository_format
1338
            def make_new_test_id():
1339
                new_id = "%s(%s)" % (new_test.id(), repository_format.__class__.__name__)
1340
                return lambda: new_id
1341
            new_test.id = make_new_test_id()
1342
            result.addTest(new_test)
1343
        return result
1534.1.29 by Robert Collins
Add a test environment for InterRepository objects, and remove the fetch corner case tests from test_repository.
1344
1345
1346
class InterRepositoryTestProviderAdapter(object):
1347
    """A tool to generate a suite testing multiple inter repository formats.
1348
1349
    This is done by copying the test once for each interrepo provider and injecting
1350
    the transport_server, transport_readonly_server, repository_format and 
1351
    repository_to_format classes into each copy.
1352
    Each copy is also given a new id() to make it easy to identify.
1353
    """
1354
1355
    def __init__(self, transport_server, transport_readonly_server, formats):
1356
        self._transport_server = transport_server
1357
        self._transport_readonly_server = transport_readonly_server
1358
        self._formats = formats
1359
    
1360
    def adapt(self, test):
1361
        result = TestSuite()
1362
        for interrepo_class, repository_format, repository_format_to in self._formats:
1363
            new_test = deepcopy(test)
1364
            new_test.transport_server = self._transport_server
1365
            new_test.transport_readonly_server = self._transport_readonly_server
1366
            new_test.interrepo_class = interrepo_class
1367
            new_test.repository_format = repository_format
1368
            new_test.repository_format_to = repository_format_to
1369
            def make_new_test_id():
1370
                new_id = "%s(%s)" % (new_test.id(), interrepo_class.__name__)
1371
                return lambda: new_id
1372
            new_test.id = make_new_test_id()
1373
            result.addTest(new_test)
1374
        return result
1375
1376
    @staticmethod
1377
    def default_test_list():
1378
        """Generate the default list of interrepo permutations to test."""
1379
        result = []
1380
        # test the default InterRepository between format 6 and the current 
1381
        # default format.
1534.1.33 by Robert Collins
Move copy_content_into into InterRepository and InterWeaveRepo, and disable the default codepath test as we have optimised paths for all current combinations.
1382
        # XXX: robertc 20060220 reinstate this when there are two supported
1383
        # formats which do not have an optimal code path between them.
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
1384
        result.append((InterRepository,
1385
                       RepositoryFormat6(),
1386
                       RepositoryFormatKnit1()))
1534.1.29 by Robert Collins
Add a test environment for InterRepository objects, and remove the fetch corner case tests from test_repository.
1387
        for optimiser in InterRepository._optimisers:
1388
            result.append((optimiser,
1389
                           optimiser._matching_repo_format,
1390
                           optimiser._matching_repo_format
1391
                           ))
1392
        # if there are specific combinations we want to use, we can add them 
1393
        # here.
1394
        return result
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
1395
1396
1397
class CopyConverter(object):
1398
    """A repository conversion tool which just performs a copy of the content.
1399
    
1400
    This is slow but quite reliable.
1401
    """
1402
1403
    def __init__(self, target_format):
1404
        """Create a CopyConverter.
1405
1406
        :param target_format: The format the resulting repository should be.
1407
        """
1408
        self.target_format = target_format
1409
        
1410
    def convert(self, repo, pb):
1411
        """Perform the conversion of to_convert, giving feedback via pb.
1412
1413
        :param to_convert: The disk object to convert.
1414
        :param pb: a progress bar to use for progress information.
1415
        """
1416
        self.pb = pb
1417
        self.count = 0
1418
        self.total = 3
1419
        # this is only useful with metadir layouts - separated repo content.
1420
        # trigger an assertion if not such
1421
        repo._format.get_format_string()
1422
        self.repo_dir = repo.bzrdir
1423
        self.step('Moving repository to repository.backup')
1424
        self.repo_dir.transport.move('repository', 'repository.backup')
1425
        backup_transport =  self.repo_dir.transport.clone('repository.backup')
1426
        self.source_repo = repo._format.open(self.repo_dir,
1427
            _found=True,
1428
            _override_transport=backup_transport)
1429
        self.step('Creating new repository')
1430
        converted = self.target_format.initialize(self.repo_dir,
1431
                                                  self.source_repo.is_shared())
1432
        converted.lock_write()
1433
        try:
1434
            self.step('Copying content into repository.')
1435
            self.source_repo.copy_content_into(converted)
1436
        finally:
1437
            converted.unlock()
1438
        self.step('Deleting old repository content.')
1439
        self.repo_dir.transport.delete_tree('repository.backup')
1440
        self.pb.note('repository converted')
1441
1442
    def step(self, message):
1443
        """Update the pb by a step."""
1444
        self.count +=1
1445
        self.pb.update(message, self.count, self.total)