/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 11:06:23 UTC
  • mto: This revision was merged to the branch mainline in revision 1752.
  • Revision ID: larstiq@larstiq.dyndns.org-20060607110623-ababc7dc508f613f
StubSFTPServer should use bytestreams rather than unicode

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