/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: Wouter van Heyst
  • Date: 2006-06-07 17:23:59 UTC
  • mto: This revision was merged to the branch mainline in revision 1752.
  • Revision ID: larstiq@larstiq.dyndns.org-20060607172359-6023dec74344453d
more code cleanup

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