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