/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

Improve common_ancestor performance.

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