/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

bugfix revision.MultipleRevisionSources.get_revision_graph to integrate ghosts between sources. [slow on weaves, fast on knits.

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