~bzr-pqm/bzr/bzr.dev

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