/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-07 20:34:47 UTC
  • mto: (1594.2.4 integration)
  • mto: This revision was merged to the branch mainline in revision 1596.
  • Revision ID: robertc@robertcollins.net-20060307203447-b7432f11cbd54c29
make push preserve tree formats.

Show diffs side-by-side

added added

removed removed

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