/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/repository.py

  • Committer: Robert Collins
  • Date: 2006-05-04 11:53:51 UTC
  • mto: (1697.1.1 integration)
  • mto: This revision was merged to the branch mainline in revision 1701.
  • Revision ID: robertc@robertcollins.net-20060504115351-79122d06d443d4a8
Teach Branch about break_lock.

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