/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 09:38:37 UTC
  • mto: (1594.2.4 integration)
  • mto: This revision was merged to the branch mainline in revision 1596.
  • Revision ID: robertc@robertcollins.net-20060306093837-b151989e9572895e
Remove all but fetch references to repository.revision_store.

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