/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/repository.py

  • Committer: Robert Collins
  • Date: 2006-03-06 12:11:25 UTC
  • mto: (1594.2.4 integration)
  • mto: This revision was merged to the branch mainline in revision 1596.
  • Revision ID: robertc@robertcollins.net-20060306121125-4f05992d44e3bda8
Convert Knit repositories to use knits.

Show diffs side-by-side

added added

removed removed

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