1
# Copyright (C) 2005, 2006 Canonical Ltd
 
 
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.
 
 
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.
 
 
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
 
 
17
from copy import deepcopy
 
 
18
from cStringIO import StringIO
 
 
19
from unittest import TestSuite
 
 
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
 
 
42
from bzrlib.weave import WeaveFile
 
 
46
class Repository(object):
 
 
47
    """Repository holding history for one or more branches.
 
 
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.
 
 
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 
 
 
59
    def add_inventory(self, revid, inv, parents):
 
 
60
        """Add the inventory inv to the repository as revid.
 
 
62
        :param parents: The revision ids of the parents that revid
 
 
63
                        is known to have and are in the repository already.
 
 
65
        returns the sha1 of the serialized inventory.
 
 
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))
 
 
78
    def add_revision(self, rev_id, rev, inv=None, config=None):
 
 
79
        """Add rev to the revision store as rev_id.
 
 
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.
 
 
89
        if config is not None and config.signature_needed():
 
 
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():
 
 
97
                raise errors.WeaveRevisionNotPresent(rev_id,
 
 
98
                                                     self.get_inventory_weave())
 
 
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())
 
 
105
    def _all_possible_ids(self):
 
 
106
        """Return all the possible revisions that we could find."""
 
 
107
        return self.get_inventory_weave().versions()
 
 
110
    def all_revision_ids(self):
 
 
111
        """Returns a list of all the revision ids in the repository. 
 
 
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.
 
 
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)
 
 
122
    def break_lock(self):
 
 
123
        """Break a lock if one is present from another instance.
 
 
125
        Uses the ui factory to ask for confirmation if the lock may be from
 
 
128
        self.control_files.break_lock()
 
 
131
    def _eliminate_revisions_not_present(self, revision_ids):
 
 
132
        """Check every revision id in revision_ids to see if we have it.
 
 
134
        Returns a set of the present revisions.
 
 
137
        for id in revision_ids:
 
 
138
            if self.has_revision(id):
 
 
143
    def create(a_bzrdir):
 
 
144
        """Construct the current default format repository in a_bzrdir."""
 
 
145
        return RepositoryFormat.get_default_format().initialize(a_bzrdir)
 
 
147
    def __init__(self, _format, a_bzrdir, control_files, _revision_store, control_store, text_store):
 
 
148
        """instantiate a Repository.
 
 
150
        :param _format: The format of the repository on disk.
 
 
151
        :param a_bzrdir: The BzrDir of the repository.
 
 
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.
 
 
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 ? 
 
 
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.
 
 
174
        return '%s(%r)' % (self.__class__.__name__, 
 
 
175
                           self.bzrdir.transport.base)
 
 
178
        return self.control_files.is_locked()
 
 
180
    def lock_write(self):
 
 
181
        self.control_files.lock_write()
 
 
184
        self.control_files.lock_read()
 
 
186
    def get_physical_lock_status(self):
 
 
187
        return self.control_files.get_physical_lock_status()
 
 
190
    def missing_revision_ids(self, other, revision_id=None):
 
 
191
        """Return the revision ids that other has that this does not.
 
 
193
        These are returned in topological order.
 
 
195
        revision_id: only return revision ids included by revision_id.
 
 
197
        return InterRepository.get(other, self).missing_revision_ids(revision_id)
 
 
201
        """Open the repository rooted at base.
 
 
203
        For instance, if the repository is at URL/.bzr/repository,
 
 
204
        Repository.open(URL) -> a Repository instance.
 
 
206
        control = bzrlib.bzrdir.BzrDir.open(base)
 
 
207
        return control.open_repository()
 
 
209
    def copy_content_into(self, destination, revision_id=None, basis=None):
 
 
210
        """Make a complete copy of the content in self into destination.
 
 
212
        This is a destructive operation! Do not use it on existing 
 
 
215
        return InterRepository.get(self, destination).copy_content(revision_id, basis)
 
 
217
    def fetch(self, source, revision_id=None, pb=None):
 
 
218
        """Fetch the content required to construct revision_id from source.
 
 
220
        If revision_id is None all content is copied.
 
 
222
        return InterRepository.get(source, self).fetch(revision_id=revision_id,
 
 
226
        self.control_files.unlock()
 
 
229
    def clone(self, a_bzrdir, revision_id=None, basis=None):
 
 
230
        """Clone this repository into a_bzrdir using the current format.
 
 
232
        Currently no check is made that the format of this repository and
 
 
233
        the bzrdir format are compatible. FIXME RBC 20060201.
 
 
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()
 
 
245
            result = self._format.initialize(a_bzrdir, shared=self.is_shared())
 
 
246
        self.copy_content_into(result, revision_id, basis)
 
 
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())
 
 
256
    def get_revision_reconcile(self, revision_id):
 
 
257
        """'reconcile' helper routine that allows access to a revision always.
 
 
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.
 
 
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())
 
 
270
    def get_revision_xml(self, revision_id):
 
 
271
        rev = self.get_revision(revision_id) 
 
 
273
        # the current serializer..
 
 
274
        self._revision_store._serializer.write_revision(rev, rev_tmp)
 
 
276
        return rev_tmp.getvalue()
 
 
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
 
 
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)
 
 
293
    def _check_revision_parents(self, revision, inventory):
 
 
294
        """Private to Repository and Fetch.
 
 
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.
 
 
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:
 
 
307
                    raise errors.CorruptRepository(self)
 
 
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,
 
 
314
                                                         self.get_transaction())
 
 
316
    def fileids_altered_by_revision_ids(self, revision_ids):
 
 
317
        """Find the file ids and versions affected by revisions.
 
 
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.
 
 
324
        assert isinstance(self._format, (RepositoryFormat5,
 
 
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()
 
 
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
 
 
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)
 
 
346
            file_id = _unescape_xml(line[start:end])
 
 
348
            start = line.find('revision="')+10
 
 
349
            if start < 10: continue
 
 
350
            end = line.find('"', start)
 
 
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)
 
 
358
    def get_inventory_weave(self):
 
 
359
        return self.control_weaves.get_weave('inventory',
 
 
360
            self.get_transaction())
 
 
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))
 
 
368
    def deserialise_inventory(self, revision_id, xml):
 
 
369
        """Transform the xml into an inventory object. 
 
 
371
        :param revision_id: The expected revision id of the inventory.
 
 
372
        :param xml: A serialised inventory.
 
 
374
        return bzrlib.xml5.serializer_v5.read_inventory_from_string(xml)
 
 
377
    def get_inventory_xml(self, revision_id):
 
 
378
        """Get inventory XML as a file object."""
 
 
380
            assert isinstance(revision_id, basestring), type(revision_id)
 
 
381
            iw = self.get_inventory_weave()
 
 
382
            return iw.get_text(revision_id)
 
 
384
            raise bzrlib.errors.HistoryMissing(self, 'inventory', revision_id)
 
 
387
    def get_inventory_sha1(self, revision_id):
 
 
388
        """Return the sha1 hash of the inventory entry
 
 
390
        return self.get_revision(revision_id).inventory_sha1
 
 
393
    def get_revision_graph(self, revision_id=None):
 
 
394
        """Return a dictionary containing the revision graph.
 
 
396
        :return: a dictionary of revision_id->revision_parents_list.
 
 
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:
 
 
404
        elif revision_id not in entire_graph:
 
 
405
            raise errors.NoSuchRevision(self, revision_id)
 
 
407
            # add what can be reached from revision_id
 
 
409
            pending = set([revision_id])
 
 
410
            while len(pending) > 0:
 
 
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)
 
 
419
    def get_revision_graph_with_ghosts(self, revision_ids=None):
 
 
420
        """Return a graph of the revisions with ghosts marked as applicable.
 
 
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.
 
 
427
            pending = set(self.all_revision_ids())
 
 
430
            pending = set(revision_ids)
 
 
431
            required = set(revision_ids)
 
 
434
            revision_id = pending.pop()
 
 
436
                rev = self.get_revision(revision_id)
 
 
437
            except errors.NoSuchRevision:
 
 
438
                if revision_id in required:
 
 
441
                result.add_ghost(revision_id)
 
 
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):
 
 
448
                    pending.add(parent_id)
 
 
449
            result.add_node(revision_id, rev.parent_ids)
 
 
450
            done.add(revision_id)
 
 
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())
 
 
467
            return self.get_inventory(revision_id)
 
 
471
        """Return True if this repository is flagged as a shared repository."""
 
 
472
        raise NotImplementedError(self.is_shared)
 
 
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()
 
 
483
    def revision_tree(self, revision_id):
 
 
484
        """Return Tree for a revision on this branch.
 
 
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:
 
 
493
            inv = self.get_revision_inventory(revision_id)
 
 
494
            return RevisionTree(self, inv, revision_id)
 
 
497
    def get_ancestry(self, revision_id):
 
 
498
        """Return a list of revision-ids integrated by a revision.
 
 
500
        This is topologically sorted.
 
 
502
        if revision_id is 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)
 
 
511
    def print_file(self, file, revision_id):
 
 
512
        """Print `file` to stdout.
 
 
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.
 
 
518
        tree = self.revision_tree(revision_id)
 
 
519
        # use inventory as it was in that revision
 
 
520
        file_id = tree.inventory.path2id(file)
 
 
522
            # TODO: jam 20060427 Write a test for this code path
 
 
523
            #       it had a bug in it, and was raising the wrong
 
 
525
            raise errors.BzrError("%r is not present in revision %s" % (file, revision_id))
 
 
526
        tree.print_file(file_id)
 
 
528
    def get_transaction(self):
 
 
529
        return self.control_files.get_transaction()
 
 
531
    def revision_parents(self, revid):
 
 
532
        return self.get_inventory_weave().parent_names(revid)
 
 
535
    def set_make_working_trees(self, new_value):
 
 
536
        """Set the policy flag for making working trees when creating branches.
 
 
538
        This only applies to branches that use this repository.
 
 
540
        The default is 'True'.
 
 
541
        :param new_value: True to restore the default, False to disable making
 
 
544
        raise NotImplementedError(self.set_make_working_trees)
 
 
546
    def make_working_trees(self):
 
 
547
        """Returns the policy for making working trees on new branches."""
 
 
548
        raise NotImplementedError(self.make_working_trees)
 
 
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)
 
 
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())
 
 
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())
 
 
568
class AllInOneRepository(Repository):
 
 
569
    """Legacy support - the repository behaviour for all-in-one branches."""
 
 
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
 
 
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,
 
 
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)
 
 
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)
 
 
603
        """AllInOne repositories cannot be shared."""
 
 
607
    def set_make_working_trees(self, new_value):
 
 
608
        """Set the policy flag for making working trees when creating branches.
 
 
610
        This only applies to branches that use this repository.
 
 
612
        The default is 'True'.
 
 
613
        :param new_value: True to restore the default, False to disable making
 
 
616
        raise NotImplementedError(self.set_make_working_trees)
 
 
618
    def make_working_trees(self):
 
 
619
        """Returns the policy for making working trees on new branches."""
 
 
623
def install_revision(repository, rev, revision_tree):
 
 
624
    """Install all revision data into a repository."""
 
 
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)
 
 
632
            parent_trees[p_id] = EmptyTree()
 
 
634
    inv = revision_tree.inventory
 
 
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:
 
 
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
 
 
646
            for revision, tree in parent_trees.iteritems():
 
 
647
                if ie.file_id not in tree:
 
 
649
                parent_id = tree.inventory[ie.file_id].revision
 
 
650
                if parent_id in text_parents:
 
 
652
                text_parents.append(parent_id)
 
 
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)
 
 
659
        # install the inventory
 
 
660
        repository.add_inventory(rev.revision_id, inv, present_parents)
 
 
661
    except errors.RevisionAlreadyPresent:
 
 
663
    repository.add_revision(rev.revision_id, rev, inv)
 
 
666
class MetaDirRepository(Repository):
 
 
667
    """Repositories in the new meta-dir layout."""
 
 
669
    def __init__(self, _format, a_bzrdir, control_files, _revision_store, control_store, text_store):
 
 
670
        super(MetaDirRepository, self).__init__(_format,
 
 
677
        dir_mode = self.control_files._dir_mode
 
 
678
        file_mode = self.control_files._file_mode
 
 
682
        """Return True if this repository is flagged as a shared repository."""
 
 
683
        return self.control_files._transport.has('shared-storage')
 
 
686
    def set_make_working_trees(self, new_value):
 
 
687
        """Set the policy flag for making working trees when creating branches.
 
 
689
        This only applies to branches that use this repository.
 
 
691
        The default is 'True'.
 
 
692
        :param new_value: True to restore the default, False to disable making
 
 
697
                self.control_files._transport.delete('no-working-trees')
 
 
698
            except errors.NoSuchFile:
 
 
701
            self.control_files.put_utf8('no-working-trees', '')
 
 
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')
 
 
708
class KnitRepository(MetaDirRepository):
 
 
709
    """Knit format repository."""
 
 
712
    def all_revision_ids(self):
 
 
713
        """See Repository.all_revision_ids()."""
 
 
714
        return self._revision_store.all_revision_ids(self.get_transaction())
 
 
716
    def fileid_involved_between_revs(self, from_revid, to_revid):
 
 
717
        """Find file_id(s) which are involved in the changes between revisions.
 
 
719
        This determines the set of revisions which are involved, and then
 
 
720
        finds all file ids affected by those revisions.
 
 
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)
 
 
728
    def fileid_involved(self, last_revid=None):
 
 
729
        """Find all file_ids modified in the ancestry of last_revid.
 
 
731
        :param last_revid: If None, last_revision() will be used.
 
 
734
            changed = set(self.all_revision_ids())
 
 
736
            changed = set(self.get_ancestry(last_revid))
 
 
739
        return self._fileid_involved_by_set(changed)
 
 
742
    def get_ancestry(self, revision_id):
 
 
743
        """Return a list of revision-ids integrated by a revision.
 
 
745
        This is topologically sorted.
 
 
747
        if revision_id is None:
 
 
749
        vf = self._get_revision_vf()
 
 
751
            return [None] + vf.get_ancestry(revision_id)
 
 
752
        except errors.RevisionNotPresent:
 
 
753
            raise errors.NoSuchRevision(self, revision_id)
 
 
756
    def get_revision(self, revision_id):
 
 
757
        """Return the Revision object for a named revision"""
 
 
758
        return self.get_revision_reconcile(revision_id)
 
 
761
    def get_revision_graph(self, revision_id=None):
 
 
762
        """Return a dictionary containing the revision graph.
 
 
764
        :return: a dictionary of revision_id->revision_parents_list.
 
 
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)
 
 
773
            # add what can be reached from revision_id
 
 
775
            pending = set([revision_id])
 
 
776
            while len(pending) > 0:
 
 
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)
 
 
785
    def get_revision_graph_with_ghosts(self, revision_ids=None):
 
 
786
        """Return a graph of the revisions with ghosts marked as applicable.
 
 
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.
 
 
792
        vf = self._get_revision_vf()
 
 
793
        versions = set(vf.versions())
 
 
795
            pending = set(self.all_revision_ids())
 
 
798
            pending = set(revision_ids)
 
 
799
            required = set(revision_ids)
 
 
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)
 
 
807
                result.add_ghost(revision_id)
 
 
808
                # mark it as done so we dont try for it again.
 
 
809
                done.add(revision_id)
 
 
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):
 
 
817
                    pending.add(parent_id)
 
 
818
            result.add_node(revision_id, parent_ids)
 
 
819
            done.add(revision_id)
 
 
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())
 
 
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()
 
 
835
    def revision_parents(self, revid):
 
 
836
        return self._get_revision_vf().get_parents(rev_id)
 
 
838
class RepositoryFormat(object):
 
 
839
    """A repository format.
 
 
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
 
 
845
     * an open routine which returns a Repository instance.
 
 
847
    Formats are placed in an dict by their format string for reference 
 
 
848
    during opening. These should be subclasses of RepositoryFormat
 
 
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.
 
 
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
 
 
862
    _default_format = None
 
 
863
    """The default format used for new repositories."""
 
 
866
    """The known formats."""
 
 
869
    def find_format(klass, a_bzrdir):
 
 
870
        """Return the format for the repository object in a_bzrdir."""
 
 
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)
 
 
878
            raise errors.UnknownFormatError(format_string)
 
 
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)
 
 
885
    def get_default_format(klass):
 
 
886
        """Return the current default format."""
 
 
887
        return klass._default_format
 
 
889
    def get_format_string(self):
 
 
890
        """Return the ASCII format string that identifies this format.
 
 
892
        Note that in pre format ?? repositories the format string is 
 
 
893
        not permitted nor written to disk.
 
 
895
        raise NotImplementedError(self.get_format_string)
 
 
897
    def get_format_description(self):
 
 
898
        """Return the short desciption for this format."""
 
 
899
        raise NotImplementedError(self.get_format_description)
 
 
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)
 
 
905
    def _get_text_rev_store(self,
 
 
912
        """Common logic for getting a revision store for a repository.
 
 
914
        see self._get_revision_store for the subclass-overridable method to 
 
 
915
        get the store for a repository.
 
 
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),
 
 
922
                              compressed=compressed,
 
 
925
        _revision_store = TextRevisionStore(text_store, serializer)
 
 
926
        return _revision_store
 
 
928
    def _get_versioned_file_store(self,
 
 
933
                                  versionedfile_class=WeaveFile,
 
 
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,
 
 
941
                                  versionedfile_class=versionedfile_class,
 
 
944
    def initialize(self, a_bzrdir, shared=False):
 
 
945
        """Initialize a repository of this format in a_bzrdir.
 
 
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.
 
 
950
        This may raise UninitializableFormat if shared repository are not
 
 
951
        compatible the a_bzrdir.
 
 
954
    def is_supported(self):
 
 
955
        """Is this format supported?
 
 
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.
 
 
963
    def open(self, a_bzrdir, _found=False):
 
 
964
        """Return an instance of this format for the bzrdir a_bzrdir.
 
 
966
        _found is a private parameter, do not use it.
 
 
968
        raise NotImplementedError(self.open)
 
 
971
    def register_format(klass, format):
 
 
972
        klass._formats[format.get_format_string()] = format
 
 
975
    def set_default_format(klass, format):
 
 
976
        klass._default_format = format
 
 
979
    def unregister_format(klass, format):
 
 
980
        assert klass._formats[format.get_format_string()] is format
 
 
981
        del klass._formats[format.get_format_string()]
 
 
984
class PreSplitOutRepositoryFormat(RepositoryFormat):
 
 
985
    """Base class for the pre split out repository formats."""
 
 
987
    def initialize(self, a_bzrdir, shared=False, _internal=False):
 
 
988
        """Create a weave repository.
 
 
990
        TODO: when creating split out bzr branch formats, move this to a common
 
 
991
        base for Format5, Format6. or something like that.
 
 
993
        from bzrlib.weavefile import write_weave_v5
 
 
994
        from bzrlib.weave import Weave
 
 
997
            raise errors.IncompatibleFormat(self, a_bzrdir._format)
 
 
1000
            # always initialized when the bzrdir is.
 
 
1001
            return self.open(a_bzrdir, _found=True)
 
 
1003
        # Create an empty weave
 
 
1005
        bzrlib.weavefile.write_weave_v5(Weave(), sio)
 
 
1006
        empty_weave = sio.getvalue()
 
 
1008
        mutter('creating repository in %s.', a_bzrdir.transport.base)
 
 
1009
        dirs = ['revision-store', 'weaves']
 
 
1010
        files = [('inventory.weave', StringIO(empty_weave)),
 
 
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',
 
 
1017
        control_files.create_lock()
 
 
1018
        control_files.lock_write()
 
 
1019
        control_files._transport.mkdir_multi(dirs,
 
 
1020
                mode=control_files._dir_mode)
 
 
1022
            for file, content in files:
 
 
1023
                control_files.put(file, content)
 
 
1025
            control_files.unlock()
 
 
1026
        return self.open(a_bzrdir, _found=True)
 
 
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('',
 
 
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)
 
 
1039
    def open(self, a_bzrdir, _found=False):
 
 
1040
        """See RepositoryFormat.open()."""
 
 
1042
            # we are being called directly and must probe.
 
 
1043
            raise NotImplementedError
 
 
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,
 
 
1052
                                  _revision_store=_revision_store,
 
 
1053
                                  control_store=control_store,
 
 
1054
                                  text_store=text_store)
 
 
1057
class RepositoryFormat4(PreSplitOutRepositoryFormat):
 
 
1058
    """Bzr repository format 4.
 
 
1060
    This repository format has:
 
 
1062
     - TextStores for texts, inventories,revisions.
 
 
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
 
 
1070
        super(RepositoryFormat4, self).__init__()
 
 
1071
        self._matchingbzrdir = bzrlib.bzrdir.BzrDirFormat4()
 
 
1073
    def get_format_description(self):
 
 
1074
        """See RepositoryFormat.get_format_description()."""
 
 
1075
        return "Repository format 4"
 
 
1077
    def initialize(self, url, shared=False, _internal=False):
 
 
1078
        """Format 4 branches cannot be created."""
 
 
1079
        raise errors.UninitializableFormat(self)
 
 
1081
    def is_supported(self):
 
 
1082
        """Format 4 is not supported.
 
 
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 
 
 
1090
    def _get_control_store(self, repo_transport, control_files):
 
 
1091
        """Format 4 repositories have no formal control store at this point.
 
 
1093
        This will cause any control-file-needing apis to fail - this is desired.
 
 
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,
 
 
1103
                                        serializer=serializer_v4)
 
 
1105
    def _get_text_store(self, transport, control_files):
 
 
1106
        """See RepositoryFormat._get_text_store()."""
 
 
1109
class RepositoryFormat5(PreSplitOutRepositoryFormat):
 
 
1110
    """Bzr control format 5.
 
 
1112
    This repository format has:
 
 
1113
     - weaves for file texts and inventory
 
 
1115
     - TextStores for revisions and signatures.
 
 
1119
        super(RepositoryFormat5, self).__init__()
 
 
1120
        self._matchingbzrdir = bzrlib.bzrdir.BzrDirFormat5()
 
 
1122
    def get_format_description(self):
 
 
1123
        """See RepositoryFormat.get_format_description()."""
 
 
1124
        return "Weave repository format 5"
 
 
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,
 
 
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)
 
 
1139
class RepositoryFormat6(PreSplitOutRepositoryFormat):
 
 
1140
    """Bzr control format 6.
 
 
1142
    This repository format has:
 
 
1143
     - weaves for file texts and inventory
 
 
1144
     - hash subdirectory based stores.
 
 
1145
     - TextStores for revisions and signatures.
 
 
1149
        super(RepositoryFormat6, self).__init__()
 
 
1150
        self._matchingbzrdir = bzrlib.bzrdir.BzrDirFormat6()
 
 
1152
    def get_format_description(self):
 
 
1153
        """See RepositoryFormat.get_format_description()."""
 
 
1154
        return "Weave repository format 6"
 
 
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,
 
 
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)
 
 
1169
class MetaDirRepositoryFormat(RepositoryFormat):
 
 
1170
    """Common base class for the new repositories using the metadir layour."""
 
 
1173
        super(MetaDirRepositoryFormat, self).__init__()
 
 
1174
        self._matchingbzrdir = bzrlib.bzrdir.BzrDirMetaFormat1()
 
 
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
 
 
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()
 
 
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)
 
 
1197
                control_files.put_utf8('shared-storage', '')
 
 
1199
            control_files.unlock()
 
 
1202
class RepositoryFormat7(MetaDirRepositoryFormat):
 
 
1203
    """Bzr repository 7.
 
 
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
 
 
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('',
 
 
1221
    def get_format_string(self):
 
 
1222
        """See RepositoryFormat.get_format_string()."""
 
 
1223
        return "Bazaar-NG Repository format 7"
 
 
1225
    def get_format_description(self):
 
 
1226
        """See RepositoryFormat.get_format_description()."""
 
 
1227
        return "Weave repository format 7"
 
 
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,
 
 
1238
    def _get_text_store(self, transport, control_files):
 
 
1239
        """See RepositoryFormat._get_text_store()."""
 
 
1240
        return self._get_versioned_file_store('weaves',
 
 
1244
    def initialize(self, a_bzrdir, shared=False):
 
 
1245
        """Create a weave repository.
 
 
1247
        :param shared: If true the repository will be initialized as a shared
 
 
1250
        from bzrlib.weavefile import write_weave_v5
 
 
1251
        from bzrlib.weave import Weave
 
 
1253
        # Create an empty weave
 
 
1255
        bzrlib.weavefile.write_weave_v5(Weave(), sio)
 
 
1256
        empty_weave = sio.getvalue()
 
 
1258
        mutter('creating repository in %s.', a_bzrdir.transport.base)
 
 
1259
        dirs = ['revision-store', 'weaves']
 
 
1260
        files = [('inventory.weave', StringIO(empty_weave)), 
 
 
1262
        utf8_files = [('format', self.get_format_string())]
 
 
1264
        self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
 
 
1265
        return self.open(a_bzrdir=a_bzrdir, _found=True)
 
 
1267
    def open(self, a_bzrdir, _found=False, _override_transport=None):
 
 
1268
        """See RepositoryFormat.open().
 
 
1270
        :param _override_transport: INTERNAL USE ONLY. Allows opening the
 
 
1271
                                    repository at a slightly different url
 
 
1272
                                    than normal. I.e. during 'upgrade'.
 
 
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
 
 
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,
 
 
1287
                                 control_files=control_files,
 
 
1288
                                 _revision_store=_revision_store,
 
 
1289
                                 control_store=control_store,
 
 
1290
                                 text_store=text_store)
 
 
1293
class RepositoryFormatKnit1(MetaDirRepositoryFormat):
 
 
1294
    """Bzr repository knit format 1.
 
 
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
 
 
1306
    This format was introduced in bzr 0.8.
 
 
1309
    def _get_control_store(self, repo_transport, control_files):
 
 
1310
        """Return the control store for this repository."""
 
 
1311
        return VersionedFileStore(
 
 
1314
            file_mode=control_files._file_mode,
 
 
1315
            versionedfile_class=KnitVersionedFile,
 
 
1316
            versionedfile_kwargs={'factory':KnitPlainFactory()},
 
 
1319
    def get_format_string(self):
 
 
1320
        """See RepositoryFormat.get_format_string()."""
 
 
1321
        return "Bazaar-NG Knit Repository Format 1"
 
 
1323
    def get_format_description(self):
 
 
1324
        """See RepositoryFormat.get_format_description()."""
 
 
1325
        return "Knit repository format 1"
 
 
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(
 
 
1332
            file_mode=control_files._file_mode,
 
 
1335
            versionedfile_class=KnitVersionedFile,
 
 
1336
            versionedfile_kwargs={'delta':False, 'factory':KnitPlainFactory()},
 
 
1339
        return KnitRevisionStore(versioned_file_store)
 
 
1341
    def _get_text_store(self, transport, control_files):
 
 
1342
        """See RepositoryFormat._get_text_store()."""
 
 
1343
        return self._get_versioned_file_store('knits',
 
 
1346
                                              versionedfile_class=KnitVersionedFile,
 
 
1349
    def initialize(self, a_bzrdir, shared=False):
 
 
1350
        """Create a knit format 1 repository.
 
 
1352
        :param a_bzrdir: bzrdir to contain the new repository; must already
 
 
1354
        :param shared: If true the repository will be initialized as a shared
 
 
1357
        mutter('creating repository in %s.', a_bzrdir.transport.base)
 
 
1358
        dirs = ['revision-store', 'knits']
 
 
1360
        utf8_files = [('format', self.get_format_string())]
 
 
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)
 
 
1374
    def open(self, a_bzrdir, _found=False, _override_transport=None):
 
 
1375
        """See RepositoryFormat.open().
 
 
1377
        :param _override_transport: INTERNAL USE ONLY. Allows opening the
 
 
1378
                                    repository at a slightly different url
 
 
1379
                                    than normal. I.e. during 'upgrade'.
 
 
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
 
 
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,
 
 
1394
                              control_files=control_files,
 
 
1395
                              _revision_store=_revision_store,
 
 
1396
                              control_store=control_store,
 
 
1397
                              text_store=text_store)
 
 
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()]
 
 
1411
class InterRepository(InterObject):
 
 
1412
    """This class represents operations taking place between two repositories.
 
 
1414
    Its instances have methods like copy_content and fetch, and contain
 
 
1415
    references to the source and target repositories these operations can be 
 
 
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).
 
 
1424
    """The available optimised InterRepository types."""
 
 
1427
    def copy_content(self, revision_id=None, basis=None):
 
 
1428
        """Make a complete copy of the content in self into destination.
 
 
1430
        This is a destructive operation! Do not use it on existing 
 
 
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.
 
 
1438
            self.target.set_make_working_trees(self.source.make_working_trees())
 
 
1439
        except NotImplementedError:
 
 
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)):
 
 
1448
        self.target.fetch(self.source, revision_id=revision_id)
 
 
1450
    def _double_lock(self, lock_source, lock_target):
 
 
1451
        """Take out too locks, rolling back the first if the second throws."""
 
 
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()
 
 
1462
    def fetch(self, revision_id=None, pb=None):
 
 
1463
        """Fetch the content required to construct revision_id.
 
 
1465
        The content is copied from source to target.
 
 
1467
        :param revision_id: if None all content is copied, if NULL_REVISION no
 
 
1469
        :param pb: optional progress bar to use for progress reports. If not
 
 
1470
                   provided a default one will be created.
 
 
1472
        Returns the copied revision count and the failed revisions in a tuple:
 
 
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,
 
 
1482
        return f.count_copied, f.failed_revisions
 
 
1484
    def lock_read(self):
 
 
1485
        """Take out a logical read lock.
 
 
1487
        This will lock the source branch and the target branch. The source gets
 
 
1488
        a read lock and the target a read lock.
 
 
1490
        self._double_lock(self.source.lock_read, self.target.lock_read)
 
 
1492
    def lock_write(self):
 
 
1493
        """Take out a logical write lock.
 
 
1495
        This will lock the source branch and the target branch. The source gets
 
 
1496
        a read lock and the target a write lock.
 
 
1498
        self._double_lock(self.source.lock_read, self.target.lock_write)
 
 
1501
    def missing_revision_ids(self, revision_id=None):
 
 
1502
        """Return the revision ids that source has that target does not.
 
 
1504
        These are returned in topological order.
 
 
1506
        :param revision_id: only return revision ids included by this
 
 
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
 
 
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]
 
 
1524
        """Release the locks on source and target."""
 
 
1526
            self.target.unlock()
 
 
1528
            self.source.unlock()
 
 
1531
class InterWeaveRepo(InterRepository):
 
 
1532
    """Optimised code paths between Weave based repositories."""
 
 
1534
    _matching_repo_format = RepositoryFormat7()
 
 
1535
    """Repository format for testing with."""
 
 
1538
    def is_compatible(source, target):
 
 
1539
        """Be compatible with known Weave formats.
 
 
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 
 
 
1546
            return (isinstance(source._format, (RepositoryFormat5,
 
 
1548
                                                RepositoryFormat7)) and
 
 
1549
                    isinstance(target._format, (RepositoryFormat5,
 
 
1551
                                                RepositoryFormat7)))
 
 
1552
        except AttributeError:
 
 
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.
 
 
1564
                self.target.set_make_working_trees(self.source.make_working_trees())
 
 
1565
            except NotImplementedError:
 
 
1567
            self.target.fetch(self.source, revision_id=revision_id)
 
 
1570
                self.target.set_make_working_trees(self.source.make_working_trees())
 
 
1571
            except NotImplementedError:
 
 
1573
            # FIXME do not peek!
 
 
1574
            if self.source.control_files._transport.listable():
 
 
1575
                pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
 
1577
                    self.target.weave_store.copy_all_ids(
 
 
1578
                        self.source.weave_store,
 
 
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,
 
 
1593
                self.target.fetch(self.source, revision_id=revision_id)
 
 
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,
 
 
1605
        return f.count_copied, f.failed_revisions
 
 
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.
 
 
1621
        if revision_id is not None:
 
 
1622
            source_ids = self.source.get_ancestry(revision_id)
 
 
1623
            assert source_ids[0] == None
 
 
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
 
 
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)
 
 
1649
class InterKnitRepo(InterRepository):
 
 
1650
    """Optimised code paths between Knit based repositories."""
 
 
1652
    _matching_repo_format = RepositoryFormatKnit1()
 
 
1653
    """Repository format for testing with."""
 
 
1656
    def is_compatible(source, target):
 
 
1657
        """Be compatible with known Knit formats.
 
 
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 
 
 
1664
            return (isinstance(source._format, (RepositoryFormatKnit1)) and
 
 
1665
                    isinstance(target._format, (RepositoryFormatKnit1)))
 
 
1666
        except AttributeError:
 
 
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,
 
 
1679
        return f.count_copied, f.failed_revisions
 
 
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
 
 
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
 
 
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)
 
 
1711
InterRepository.register_optimiser(InterWeaveRepo)
 
 
1712
InterRepository.register_optimiser(InterKnitRepo)
 
 
1715
class RepositoryTestProviderAdapter(object):
 
 
1716
    """A tool to generate a suite testing multiple repository formats at once.
 
 
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.
 
 
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
 
 
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)
 
 
1745
class InterRepositoryTestProviderAdapter(object):
 
 
1746
    """A tool to generate a suite testing multiple inter repository formats.
 
 
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.
 
 
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
 
 
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)
 
 
1776
    def default_test_list():
 
 
1777
        """Generate the default list of interrepo permutations to test."""
 
 
1779
        # test the default InterRepository between format 6 and the current 
 
 
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
 
 
1791
        # if there are specific combinations we want to use, we can add them 
 
 
1796
class CopyConverter(object):
 
 
1797
    """A repository conversion tool which just performs a copy of the content.
 
 
1799
    This is slow but quite reliable.
 
 
1802
    def __init__(self, target_format):
 
 
1803
        """Create a CopyConverter.
 
 
1805
        :param target_format: The format the resulting repository should be.
 
 
1807
        self.target_format = target_format
 
 
1809
    def convert(self, repo, pb):
 
 
1810
        """Perform the conversion of to_convert, giving feedback via pb.
 
 
1812
        :param to_convert: The disk object to convert.
 
 
1813
        :param pb: a progress bar to use for progress information.
 
 
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,
 
 
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()
 
 
1833
            self.step('Copying content into repository.')
 
 
1834
            self.source_repo.copy_content_into(converted)
 
 
1837
        self.step('Deleting old repository content.')
 
 
1838
        self.repo_dir.transport.delete_tree('repository.backup')
 
 
1839
        self.pb.note('repository converted')
 
 
1841
    def step(self, message):
 
 
1842
        """Update the pb by a step."""
 
 
1844
        self.pb.update(message, self.count, self.total)
 
 
1847
# Copied from xml.sax.saxutils
 
 
1848
def _unescape_xml(data):
 
 
1849
    """Unescape &, <, and > in a string of data.
 
 
1851
    data = data.replace("<", "<")
 
 
1852
    data = data.replace(">", ">")
 
 
1853
    # must do ampersand last
 
 
1854
    return data.replace("&", "&")