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 binascii import hexlify
 
 
18
from copy import deepcopy
 
 
19
from cStringIO import StringIO
 
 
22
from unittest import TestSuite
 
 
24
from bzrlib import bzrdir, check, delta, gpg, errors, xml5, ui, transactions, osutils
 
 
25
from bzrlib.decorators import needs_read_lock, needs_write_lock
 
 
26
from bzrlib.errors import InvalidRevisionId
 
 
27
from bzrlib.graph import Graph
 
 
28
from bzrlib.inter import InterObject
 
 
29
from bzrlib.inventory import Inventory
 
 
30
from bzrlib.knit import KnitVersionedFile, KnitPlainFactory
 
 
31
from bzrlib.lockable_files import LockableFiles, TransportLock
 
 
32
from bzrlib.lockdir import LockDir
 
 
33
from bzrlib.osutils import (safe_unicode, rand_bytes, compact_date, 
 
 
35
from bzrlib.revision import NULL_REVISION, Revision
 
 
36
from bzrlib.store.versioned import VersionedFileStore, WeaveStore
 
 
37
from bzrlib.store.text import TextStore
 
 
38
from bzrlib.symbol_versioning import (deprecated_method,
 
 
41
from bzrlib.trace import mutter, note
 
 
42
from bzrlib.tree import RevisionTree, EmptyTree
 
 
43
from bzrlib.tsort import topo_sort
 
 
44
from bzrlib.testament import Testament
 
 
45
from bzrlib.tree import EmptyTree
 
 
46
from bzrlib.weave import WeaveFile
 
 
49
class Repository(object):
 
 
50
    """Repository holding history for one or more branches.
 
 
52
    The repository holds and retrieves historical information including
 
 
53
    revisions and file history.  It's normally accessed only by the Branch,
 
 
54
    which views a particular line of development through that history.
 
 
56
    The Repository builds on top of Stores and a Transport, which respectively 
 
 
57
    describe the disk data format and the way of accessing the (possibly 
 
 
62
    def add_inventory(self, revid, inv, parents):
 
 
63
        """Add the inventory inv to the repository as revid.
 
 
65
        :param parents: The revision ids of the parents that revid
 
 
66
                        is known to have and are in the repository already.
 
 
68
        returns the sha1 of the serialized inventory.
 
 
70
        assert inv.revision_id is None or inv.revision_id == revid, \
 
 
71
            "Mismatch between inventory revision" \
 
 
72
            " id and insertion revid (%r, %r)" % (inv.revision_id, revid)
 
 
73
        inv_text = xml5.serializer_v5.write_inventory_to_string(inv)
 
 
74
        inv_sha1 = osutils.sha_string(inv_text)
 
 
75
        inv_vf = self.control_weaves.get_weave('inventory',
 
 
76
                                               self.get_transaction())
 
 
77
        self._inventory_add_lines(inv_vf, revid, parents, osutils.split_lines(inv_text))
 
 
80
    def _inventory_add_lines(self, inv_vf, revid, parents, lines):
 
 
82
        for parent in parents:
 
 
84
                final_parents.append(parent)
 
 
86
        inv_vf.add_lines(revid, final_parents, lines)
 
 
89
    def add_revision(self, rev_id, rev, inv=None, config=None):
 
 
90
        """Add rev to the revision store as rev_id.
 
 
92
        :param rev_id: the revision id to use.
 
 
93
        :param rev: The revision object.
 
 
94
        :param inv: The inventory for the revision. if None, it will be looked
 
 
95
                    up in the inventory storer
 
 
96
        :param config: If None no digital signature will be created.
 
 
97
                       If supplied its signature_needed method will be used
 
 
98
                       to determine if a signature should be made.
 
 
100
        if config is not None and config.signature_needed():
 
 
102
                inv = self.get_inventory(rev_id)
 
 
103
            plaintext = Testament(rev, inv).as_short_text()
 
 
104
            self.store_revision_signature(
 
 
105
                gpg.GPGStrategy(config), plaintext, rev_id)
 
 
106
        if not rev_id in self.get_inventory_weave():
 
 
108
                raise errors.WeaveRevisionNotPresent(rev_id,
 
 
109
                                                     self.get_inventory_weave())
 
 
111
                # yes, this is not suitable for adding with ghosts.
 
 
112
                self.add_inventory(rev_id, inv, rev.parent_ids)
 
 
113
        self._revision_store.add_revision(rev, self.get_transaction())
 
 
116
    def _all_possible_ids(self):
 
 
117
        """Return all the possible revisions that we could find."""
 
 
118
        return self.get_inventory_weave().versions()
 
 
120
    def all_revision_ids(self):
 
 
121
        """Returns a list of all the revision ids in the repository. 
 
 
123
        This is deprecated because code should generally work on the graph
 
 
124
        reachable from a particular revision, and ignore any other revisions
 
 
125
        that might be present.  There is no direct replacement method.
 
 
127
        return self._all_revision_ids()
 
 
130
    def _all_revision_ids(self):
 
 
131
        """Returns a list of all the revision ids in the repository. 
 
 
133
        These are in as much topological order as the underlying store can 
 
 
134
        present: for weaves ghosts may lead to a lack of correctness until
 
 
135
        the reweave updates the parents list.
 
 
137
        if self._revision_store.text_store.listable():
 
 
138
            return self._revision_store.all_revision_ids(self.get_transaction())
 
 
139
        result = self._all_possible_ids()
 
 
140
        return self._eliminate_revisions_not_present(result)
 
 
142
    def break_lock(self):
 
 
143
        """Break a lock if one is present from another instance.
 
 
145
        Uses the ui factory to ask for confirmation if the lock may be from
 
 
148
        self.control_files.break_lock()
 
 
151
    def _eliminate_revisions_not_present(self, revision_ids):
 
 
152
        """Check every revision id in revision_ids to see if we have it.
 
 
154
        Returns a set of the present revisions.
 
 
157
        for id in revision_ids:
 
 
158
            if self.has_revision(id):
 
 
163
    def create(a_bzrdir):
 
 
164
        """Construct the current default format repository in a_bzrdir."""
 
 
165
        return RepositoryFormat.get_default_format().initialize(a_bzrdir)
 
 
167
    def __init__(self, _format, a_bzrdir, control_files, _revision_store, control_store, text_store):
 
 
168
        """instantiate a Repository.
 
 
170
        :param _format: The format of the repository on disk.
 
 
171
        :param a_bzrdir: The BzrDir of the repository.
 
 
173
        In the future we will have a single api for all stores for
 
 
174
        getting file texts, inventories and revisions, then
 
 
175
        this construct will accept instances of those things.
 
 
177
        super(Repository, self).__init__()
 
 
178
        self._format = _format
 
 
179
        # the following are part of the public API for Repository:
 
 
180
        self.bzrdir = a_bzrdir
 
 
181
        self.control_files = control_files
 
 
182
        self._revision_store = _revision_store
 
 
183
        self.text_store = text_store
 
 
184
        # backwards compatibility
 
 
185
        self.weave_store = text_store
 
 
186
        # not right yet - should be more semantically clear ? 
 
 
188
        self.control_store = control_store
 
 
189
        self.control_weaves = control_store
 
 
190
        # TODO: make sure to construct the right store classes, etc, depending
 
 
191
        # on whether escaping is required.
 
 
194
        return '%s(%r)' % (self.__class__.__name__, 
 
 
195
                           self.bzrdir.transport.base)
 
 
198
        return self.control_files.is_locked()
 
 
200
    def lock_write(self):
 
 
201
        self.control_files.lock_write()
 
 
204
        self.control_files.lock_read()
 
 
206
    def get_physical_lock_status(self):
 
 
207
        return self.control_files.get_physical_lock_status()
 
 
210
    def missing_revision_ids(self, other, revision_id=None):
 
 
211
        """Return the revision ids that other has that this does not.
 
 
213
        These are returned in topological order.
 
 
215
        revision_id: only return revision ids included by revision_id.
 
 
217
        return InterRepository.get(other, self).missing_revision_ids(revision_id)
 
 
221
        """Open the repository rooted at base.
 
 
223
        For instance, if the repository is at URL/.bzr/repository,
 
 
224
        Repository.open(URL) -> a Repository instance.
 
 
226
        control = bzrdir.BzrDir.open(base)
 
 
227
        return control.open_repository()
 
 
229
    def copy_content_into(self, destination, revision_id=None, basis=None):
 
 
230
        """Make a complete copy of the content in self into destination.
 
 
232
        This is a destructive operation! Do not use it on existing 
 
 
235
        return InterRepository.get(self, destination).copy_content(revision_id, basis)
 
 
237
    def fetch(self, source, revision_id=None, pb=None):
 
 
238
        """Fetch the content required to construct revision_id from source.
 
 
240
        If revision_id is None all content is copied.
 
 
242
        return InterRepository.get(source, self).fetch(revision_id=revision_id,
 
 
245
    def get_commit_builder(self, branch, parents, config, timestamp=None, 
 
 
246
                           timezone=None, committer=None, revprops=None, 
 
 
248
        """Obtain a CommitBuilder for this repository.
 
 
250
        :param branch: Branch to commit to.
 
 
251
        :param parents: Revision ids of the parents of the new revision.
 
 
252
        :param config: Configuration to use.
 
 
253
        :param timestamp: Optional timestamp recorded for commit.
 
 
254
        :param timezone: Optional timezone for timestamp.
 
 
255
        :param committer: Optional committer to set for commit.
 
 
256
        :param revprops: Optional dictionary of revision properties.
 
 
257
        :param revision_id: Optional revision id.
 
 
259
        return CommitBuilder(self, parents, config, timestamp, timezone,
 
 
260
                             committer, revprops, revision_id)
 
 
263
        self.control_files.unlock()
 
 
266
    def clone(self, a_bzrdir, revision_id=None, basis=None):
 
 
267
        """Clone this repository into a_bzrdir using the current format.
 
 
269
        Currently no check is made that the format of this repository and
 
 
270
        the bzrdir format are compatible. FIXME RBC 20060201.
 
 
272
        if not isinstance(a_bzrdir._format, self.bzrdir._format.__class__):
 
 
273
            # use target default format.
 
 
274
            result = a_bzrdir.create_repository()
 
 
275
        # FIXME RBC 20060209 split out the repository type to avoid this check ?
 
 
276
        elif isinstance(a_bzrdir._format,
 
 
277
                      (bzrdir.BzrDirFormat4,
 
 
278
                       bzrdir.BzrDirFormat5,
 
 
279
                       bzrdir.BzrDirFormat6)):
 
 
280
            result = a_bzrdir.open_repository()
 
 
282
            result = self._format.initialize(a_bzrdir, shared=self.is_shared())
 
 
283
        self.copy_content_into(result, revision_id, basis)
 
 
287
    def has_revision(self, revision_id):
 
 
288
        """True if this repository has a copy of the revision."""
 
 
289
        return self._revision_store.has_revision_id(revision_id,
 
 
290
                                                    self.get_transaction())
 
 
293
    def get_revision_reconcile(self, revision_id):
 
 
294
        """'reconcile' helper routine that allows access to a revision always.
 
 
296
        This variant of get_revision does not cross check the weave graph
 
 
297
        against the revision one as get_revision does: but it should only
 
 
298
        be used by reconcile, or reconcile-alike commands that are correcting
 
 
299
        or testing the revision graph.
 
 
301
        if not revision_id or not isinstance(revision_id, basestring):
 
 
302
            raise InvalidRevisionId(revision_id=revision_id, branch=self)
 
 
303
        return self._revision_store.get_revisions([revision_id],
 
 
304
                                                  self.get_transaction())[0]
 
 
306
    def get_revisions(self, revision_ids):
 
 
307
        return self._revision_store.get_revisions(revision_ids,
 
 
308
                                                  self.get_transaction())
 
 
311
    def get_revision_xml(self, revision_id):
 
 
312
        rev = self.get_revision(revision_id) 
 
 
314
        # the current serializer..
 
 
315
        self._revision_store._serializer.write_revision(rev, rev_tmp)
 
 
317
        return rev_tmp.getvalue()
 
 
320
    def get_revision(self, revision_id):
 
 
321
        """Return the Revision object for a named revision"""
 
 
322
        r = self.get_revision_reconcile(revision_id)
 
 
323
        # weave corruption can lead to absent revision markers that should be
 
 
325
        # the following test is reasonably cheap (it needs a single weave read)
 
 
326
        # and the weave is cached in read transactions. In write transactions
 
 
327
        # it is not cached but typically we only read a small number of
 
 
328
        # revisions. For knits when they are introduced we will probably want
 
 
329
        # to ensure that caching write transactions are in use.
 
 
330
        inv = self.get_inventory_weave()
 
 
331
        self._check_revision_parents(r, inv)
 
 
335
    def get_deltas_for_revisions(self, revisions):
 
 
336
        """Produce a generator of revision deltas.
 
 
338
        Note that the input is a sequence of REVISIONS, not revision_ids.
 
 
339
        Trees will be held in memory until the generator exits.
 
 
340
        Each delta is relative to the revision's lefthand predecessor.
 
 
342
        required_trees = set()
 
 
343
        for revision in revisions:
 
 
344
            required_trees.add(revision.revision_id)
 
 
345
            required_trees.update(revision.parent_ids[:1])
 
 
346
        trees = dict((t.get_revision_id(), t) for 
 
 
347
                     t in self.revision_trees(required_trees))
 
 
348
        for revision in revisions:
 
 
349
            if not revision.parent_ids:
 
 
350
                old_tree = EmptyTree()
 
 
352
                old_tree = trees[revision.parent_ids[0]]
 
 
353
            yield delta.compare_trees(old_tree, trees[revision.revision_id])
 
 
356
    def get_revision_delta(self, revision_id):
 
 
357
        """Return the delta for one revision.
 
 
359
        The delta is relative to the left-hand predecessor of the
 
 
362
        r = self.get_revision(revision_id)
 
 
363
        return list(self.get_deltas_for_revisions([r]))[0]
 
 
365
    def _check_revision_parents(self, revision, inventory):
 
 
366
        """Private to Repository and Fetch.
 
 
368
        This checks the parentage of revision in an inventory weave for 
 
 
369
        consistency and is only applicable to inventory-weave-for-ancestry
 
 
370
        using repository formats & fetchers.
 
 
372
        weave_parents = inventory.get_parents(revision.revision_id)
 
 
373
        weave_names = inventory.versions()
 
 
374
        for parent_id in revision.parent_ids:
 
 
375
            if parent_id in weave_names:
 
 
376
                # this parent must not be a ghost.
 
 
377
                if not parent_id in weave_parents:
 
 
379
                    raise errors.CorruptRepository(self)
 
 
382
    def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
 
 
383
        signature = gpg_strategy.sign(plaintext)
 
 
384
        self._revision_store.add_revision_signature_text(revision_id,
 
 
386
                                                         self.get_transaction())
 
 
388
    def fileids_altered_by_revision_ids(self, revision_ids):
 
 
389
        """Find the file ids and versions affected by revisions.
 
 
391
        :param revisions: an iterable containing revision ids.
 
 
392
        :return: a dictionary mapping altered file-ids to an iterable of
 
 
393
        revision_ids. Each altered file-ids has the exact revision_ids that
 
 
394
        altered it listed explicitly.
 
 
396
        assert isinstance(self._format, (RepositoryFormat5,
 
 
399
                                         RepositoryFormatKnit1)), \
 
 
400
            ("fileids_altered_by_revision_ids only supported for branches " 
 
 
401
             "which store inventory as unnested xml, not on %r" % self)
 
 
402
        selected_revision_ids = set(revision_ids)
 
 
403
        w = self.get_inventory_weave()
 
 
406
        # this code needs to read every new line in every inventory for the
 
 
407
        # inventories [revision_ids]. Seeing a line twice is ok. Seeing a line
 
 
408
        # not present in one of those inventories is unnecessary but not 
 
 
409
        # harmful because we are filtering by the revision id marker in the
 
 
410
        # inventory lines : we only select file ids altered in one of those  
 
 
411
        # revisions. We don't need to see all lines in the inventory because
 
 
412
        # only those added in an inventory in rev X can contain a revision=X
 
 
414
        for line in w.iter_lines_added_or_present_in_versions(selected_revision_ids):
 
 
415
            start = line.find('file_id="')+9
 
 
416
            if start < 9: continue
 
 
417
            end = line.find('"', start)
 
 
419
            file_id = _unescape_xml(line[start:end])
 
 
421
            start = line.find('revision="')+10
 
 
422
            if start < 10: continue
 
 
423
            end = line.find('"', start)
 
 
425
            revision_id = _unescape_xml(line[start:end])
 
 
426
            if revision_id in selected_revision_ids:
 
 
427
                result.setdefault(file_id, set()).add(revision_id)
 
 
431
    def get_inventory_weave(self):
 
 
432
        return self.control_weaves.get_weave('inventory',
 
 
433
            self.get_transaction())
 
 
436
    def get_inventory(self, revision_id):
 
 
437
        """Get Inventory object by hash."""
 
 
438
        return self.deserialise_inventory(
 
 
439
            revision_id, self.get_inventory_xml(revision_id))
 
 
441
    def deserialise_inventory(self, revision_id, xml):
 
 
442
        """Transform the xml into an inventory object. 
 
 
444
        :param revision_id: The expected revision id of the inventory.
 
 
445
        :param xml: A serialised inventory.
 
 
447
        return xml5.serializer_v5.read_inventory_from_string(xml)
 
 
450
    def get_inventory_xml(self, revision_id):
 
 
451
        """Get inventory XML as a file object."""
 
 
453
            assert isinstance(revision_id, basestring), type(revision_id)
 
 
454
            iw = self.get_inventory_weave()
 
 
455
            return iw.get_text(revision_id)
 
 
457
            raise errors.HistoryMissing(self, 'inventory', revision_id)
 
 
460
    def get_inventory_sha1(self, revision_id):
 
 
461
        """Return the sha1 hash of the inventory entry
 
 
463
        return self.get_revision(revision_id).inventory_sha1
 
 
466
    def get_revision_graph(self, revision_id=None):
 
 
467
        """Return a dictionary containing the revision graph.
 
 
469
        :return: a dictionary of revision_id->revision_parents_list.
 
 
471
        weave = self.get_inventory_weave()
 
 
472
        all_revisions = self._eliminate_revisions_not_present(weave.versions())
 
 
473
        entire_graph = dict([(node, weave.get_parents(node)) for 
 
 
474
                             node in all_revisions])
 
 
475
        if revision_id is None:
 
 
477
        elif revision_id not in entire_graph:
 
 
478
            raise errors.NoSuchRevision(self, revision_id)
 
 
480
            # add what can be reached from revision_id
 
 
482
            pending = set([revision_id])
 
 
483
            while len(pending) > 0:
 
 
485
                result[node] = entire_graph[node]
 
 
486
                for revision_id in result[node]:
 
 
487
                    if revision_id not in result:
 
 
488
                        pending.add(revision_id)
 
 
492
    def get_revision_graph_with_ghosts(self, revision_ids=None):
 
 
493
        """Return a graph of the revisions with ghosts marked as applicable.
 
 
495
        :param revision_ids: an iterable of revisions to graph or None for all.
 
 
496
        :return: a Graph object with the graph reachable from revision_ids.
 
 
500
            pending = set(self.all_revision_ids())
 
 
503
            pending = set(revision_ids)
 
 
504
            required = set(revision_ids)
 
 
507
            revision_id = pending.pop()
 
 
509
                rev = self.get_revision(revision_id)
 
 
510
            except errors.NoSuchRevision:
 
 
511
                if revision_id in required:
 
 
514
                result.add_ghost(revision_id)
 
 
516
            for parent_id in rev.parent_ids:
 
 
517
                # is this queued or done ?
 
 
518
                if (parent_id not in pending and
 
 
519
                    parent_id not in done):
 
 
521
                    pending.add(parent_id)
 
 
522
            result.add_node(revision_id, rev.parent_ids)
 
 
523
            done.add(revision_id)
 
 
527
    def get_revision_inventory(self, revision_id):
 
 
528
        """Return inventory of a past revision."""
 
 
529
        # TODO: Unify this with get_inventory()
 
 
530
        # bzr 0.0.6 and later imposes the constraint that the inventory_id
 
 
531
        # must be the same as its revision, so this is trivial.
 
 
532
        if revision_id is None:
 
 
533
            # This does not make sense: if there is no revision,
 
 
534
            # then it is the current tree inventory surely ?!
 
 
535
            # and thus get_root_id() is something that looks at the last
 
 
536
            # commit on the branch, and the get_root_id is an inventory check.
 
 
537
            raise NotImplementedError
 
 
538
            # return Inventory(self.get_root_id())
 
 
540
            return self.get_inventory(revision_id)
 
 
544
        """Return True if this repository is flagged as a shared repository."""
 
 
545
        raise NotImplementedError(self.is_shared)
 
 
548
    def reconcile(self, other=None, thorough=False):
 
 
549
        """Reconcile this repository."""
 
 
550
        from bzrlib.reconcile import RepoReconciler
 
 
551
        reconciler = RepoReconciler(self, thorough=thorough)
 
 
552
        reconciler.reconcile()
 
 
556
    def revision_tree(self, revision_id):
 
 
557
        """Return Tree for a revision on this branch.
 
 
559
        `revision_id` may be None for the null revision, in which case
 
 
560
        an `EmptyTree` is returned."""
 
 
561
        # TODO: refactor this to use an existing revision object
 
 
562
        # so we don't need to read it in twice.
 
 
563
        if revision_id is None or revision_id == NULL_REVISION:
 
 
566
            inv = self.get_revision_inventory(revision_id)
 
 
567
            return RevisionTree(self, inv, revision_id)
 
 
570
    def revision_trees(self, revision_ids):
 
 
571
        """Return Tree for a revision on this branch.
 
 
573
        `revision_id` may not be None or 'null:'"""
 
 
574
        assert None not in revision_ids
 
 
575
        assert NULL_REVISION not in revision_ids
 
 
576
        texts = self.get_inventory_weave().get_texts(revision_ids)
 
 
577
        for text, revision_id in zip(texts, revision_ids):
 
 
578
            inv = self.deserialise_inventory(revision_id, text)
 
 
579
            yield RevisionTree(self, inv, revision_id)
 
 
582
    def get_ancestry(self, revision_id):
 
 
583
        """Return a list of revision-ids integrated by a revision.
 
 
585
        The first element of the list is always None, indicating the origin 
 
 
586
        revision.  This might change when we have history horizons, or 
 
 
587
        perhaps we should have a new API.
 
 
589
        This is topologically sorted.
 
 
591
        if revision_id is None:
 
 
593
        if not self.has_revision(revision_id):
 
 
594
            raise errors.NoSuchRevision(self, revision_id)
 
 
595
        w = self.get_inventory_weave()
 
 
596
        candidates = w.get_ancestry(revision_id)
 
 
597
        return [None] + candidates # self._eliminate_revisions_not_present(candidates)
 
 
600
    def print_file(self, file, revision_id):
 
 
601
        """Print `file` to stdout.
 
 
603
        FIXME RBC 20060125 as John Meinel points out this is a bad api
 
 
604
        - it writes to stdout, it assumes that that is valid etc. Fix
 
 
605
        by creating a new more flexible convenience function.
 
 
607
        tree = self.revision_tree(revision_id)
 
 
608
        # use inventory as it was in that revision
 
 
609
        file_id = tree.inventory.path2id(file)
 
 
611
            # TODO: jam 20060427 Write a test for this code path
 
 
612
            #       it had a bug in it, and was raising the wrong
 
 
614
            raise errors.BzrError("%r is not present in revision %s" % (file, revision_id))
 
 
615
        tree.print_file(file_id)
 
 
617
    def get_transaction(self):
 
 
618
        return self.control_files.get_transaction()
 
 
620
    def revision_parents(self, revid):
 
 
621
        return self.get_inventory_weave().parent_names(revid)
 
 
624
    def set_make_working_trees(self, new_value):
 
 
625
        """Set the policy flag for making working trees when creating branches.
 
 
627
        This only applies to branches that use this repository.
 
 
629
        The default is 'True'.
 
 
630
        :param new_value: True to restore the default, False to disable making
 
 
633
        raise NotImplementedError(self.set_make_working_trees)
 
 
635
    def make_working_trees(self):
 
 
636
        """Returns the policy for making working trees on new branches."""
 
 
637
        raise NotImplementedError(self.make_working_trees)
 
 
640
    def sign_revision(self, revision_id, gpg_strategy):
 
 
641
        plaintext = Testament.from_revision(self, revision_id).as_short_text()
 
 
642
        self.store_revision_signature(gpg_strategy, plaintext, revision_id)
 
 
645
    def has_signature_for_revision_id(self, revision_id):
 
 
646
        """Query for a revision signature for revision_id in the repository."""
 
 
647
        return self._revision_store.has_signature(revision_id,
 
 
648
                                                  self.get_transaction())
 
 
651
    def get_signature_text(self, revision_id):
 
 
652
        """Return the text for a signature."""
 
 
653
        return self._revision_store.get_signature_text(revision_id,
 
 
654
                                                       self.get_transaction())
 
 
657
    def check(self, revision_ids):
 
 
658
        """Check consistency of all history of given revision_ids.
 
 
660
        Different repository implementations should override _check().
 
 
662
        :param revision_ids: A non-empty list of revision_ids whose ancestry
 
 
663
             will be checked.  Typically the last revision_id of a branch.
 
 
666
            raise ValueError("revision_ids must be non-empty in %s.check" 
 
 
668
        return self._check(revision_ids)
 
 
670
    def _check(self, revision_ids):
 
 
671
        result = check.Check(self)
 
 
676
class AllInOneRepository(Repository):
 
 
677
    """Legacy support - the repository behaviour for all-in-one branches."""
 
 
679
    def __init__(self, _format, a_bzrdir, _revision_store, control_store, text_store):
 
 
680
        # we reuse one control files instance.
 
 
681
        dir_mode = a_bzrdir._control_files._dir_mode
 
 
682
        file_mode = a_bzrdir._control_files._file_mode
 
 
684
        def get_store(name, compressed=True, prefixed=False):
 
 
685
            # FIXME: This approach of assuming stores are all entirely compressed
 
 
686
            # or entirely uncompressed is tidy, but breaks upgrade from 
 
 
687
            # some existing branches where there's a mixture; we probably 
 
 
688
            # still want the option to look for both.
 
 
689
            relpath = a_bzrdir._control_files._escape(name)
 
 
690
            store = TextStore(a_bzrdir._control_files._transport.clone(relpath),
 
 
691
                              prefixed=prefixed, compressed=compressed,
 
 
694
            #if self._transport.should_cache():
 
 
695
            #    cache_path = os.path.join(self.cache_root, name)
 
 
696
            #    os.mkdir(cache_path)
 
 
697
            #    store = bzrlib.store.CachedStore(store, cache_path)
 
 
700
        # not broken out yet because the controlweaves|inventory_store
 
 
701
        # and text_store | weave_store bits are still different.
 
 
702
        if isinstance(_format, RepositoryFormat4):
 
 
703
            # cannot remove these - there is still no consistent api 
 
 
704
            # which allows access to this old info.
 
 
705
            self.inventory_store = get_store('inventory-store')
 
 
706
            text_store = get_store('text-store')
 
 
707
        super(AllInOneRepository, self).__init__(_format, a_bzrdir, a_bzrdir._control_files, _revision_store, control_store, text_store)
 
 
711
        """AllInOne repositories cannot be shared."""
 
 
715
    def set_make_working_trees(self, new_value):
 
 
716
        """Set the policy flag for making working trees when creating branches.
 
 
718
        This only applies to branches that use this repository.
 
 
720
        The default is 'True'.
 
 
721
        :param new_value: True to restore the default, False to disable making
 
 
724
        raise NotImplementedError(self.set_make_working_trees)
 
 
726
    def make_working_trees(self):
 
 
727
        """Returns the policy for making working trees on new branches."""
 
 
731
def install_revision(repository, rev, revision_tree):
 
 
732
    """Install all revision data into a repository."""
 
 
735
    for p_id in rev.parent_ids:
 
 
736
        if repository.has_revision(p_id):
 
 
737
            present_parents.append(p_id)
 
 
738
            parent_trees[p_id] = repository.revision_tree(p_id)
 
 
740
            parent_trees[p_id] = EmptyTree()
 
 
742
    inv = revision_tree.inventory
 
 
744
    # Add the texts that are not already present
 
 
745
    for path, ie in inv.iter_entries():
 
 
746
        w = repository.weave_store.get_weave_or_empty(ie.file_id,
 
 
747
                repository.get_transaction())
 
 
748
        if ie.revision not in w:
 
 
750
            # FIXME: TODO: The following loop *may* be overlapping/duplicate
 
 
751
            # with InventoryEntry.find_previous_heads(). if it is, then there
 
 
752
            # is a latent bug here where the parents may have ancestors of each
 
 
754
            for revision, tree in parent_trees.iteritems():
 
 
755
                if ie.file_id not in tree:
 
 
757
                parent_id = tree.inventory[ie.file_id].revision
 
 
758
                if parent_id in text_parents:
 
 
760
                text_parents.append(parent_id)
 
 
762
            vfile = repository.weave_store.get_weave_or_empty(ie.file_id, 
 
 
763
                repository.get_transaction())
 
 
764
            lines = revision_tree.get_file(ie.file_id).readlines()
 
 
765
            vfile.add_lines(rev.revision_id, text_parents, lines)
 
 
767
        # install the inventory
 
 
768
        repository.add_inventory(rev.revision_id, inv, present_parents)
 
 
769
    except errors.RevisionAlreadyPresent:
 
 
771
    repository.add_revision(rev.revision_id, rev, inv)
 
 
774
class MetaDirRepository(Repository):
 
 
775
    """Repositories in the new meta-dir layout."""
 
 
777
    def __init__(self, _format, a_bzrdir, control_files, _revision_store, control_store, text_store):
 
 
778
        super(MetaDirRepository, self).__init__(_format,
 
 
785
        dir_mode = self.control_files._dir_mode
 
 
786
        file_mode = self.control_files._file_mode
 
 
790
        """Return True if this repository is flagged as a shared repository."""
 
 
791
        return self.control_files._transport.has('shared-storage')
 
 
794
    def set_make_working_trees(self, new_value):
 
 
795
        """Set the policy flag for making working trees when creating branches.
 
 
797
        This only applies to branches that use this repository.
 
 
799
        The default is 'True'.
 
 
800
        :param new_value: True to restore the default, False to disable making
 
 
805
                self.control_files._transport.delete('no-working-trees')
 
 
806
            except errors.NoSuchFile:
 
 
809
            self.control_files.put_utf8('no-working-trees', '')
 
 
811
    def make_working_trees(self):
 
 
812
        """Returns the policy for making working trees on new branches."""
 
 
813
        return not self.control_files._transport.has('no-working-trees')
 
 
816
class KnitRepository(MetaDirRepository):
 
 
817
    """Knit format repository."""
 
 
819
    def _inventory_add_lines(self, inv_vf, revid, parents, lines):
 
 
820
        inv_vf.add_lines_with_ghosts(revid, parents, lines)
 
 
823
    def _all_revision_ids(self):
 
 
824
        """See Repository.all_revision_ids()."""
 
 
825
        # Knits get the revision graph from the index of the revision knit, so
 
 
826
        # it's always possible even if they're on an unlistable transport.
 
 
827
        return self._revision_store.all_revision_ids(self.get_transaction())
 
 
829
    def fileid_involved_between_revs(self, from_revid, to_revid):
 
 
830
        """Find file_id(s) which are involved in the changes between revisions.
 
 
832
        This determines the set of revisions which are involved, and then
 
 
833
        finds all file ids affected by those revisions.
 
 
835
        vf = self._get_revision_vf()
 
 
836
        from_set = set(vf.get_ancestry(from_revid))
 
 
837
        to_set = set(vf.get_ancestry(to_revid))
 
 
838
        changed = to_set.difference(from_set)
 
 
839
        return self._fileid_involved_by_set(changed)
 
 
841
    def fileid_involved(self, last_revid=None):
 
 
842
        """Find all file_ids modified in the ancestry of last_revid.
 
 
844
        :param last_revid: If None, last_revision() will be used.
 
 
847
            changed = set(self.all_revision_ids())
 
 
849
            changed = set(self.get_ancestry(last_revid))
 
 
852
        return self._fileid_involved_by_set(changed)
 
 
855
    def get_ancestry(self, revision_id):
 
 
856
        """Return a list of revision-ids integrated by a revision.
 
 
858
        This is topologically sorted.
 
 
860
        if revision_id is None:
 
 
862
        vf = self._get_revision_vf()
 
 
864
            return [None] + vf.get_ancestry(revision_id)
 
 
865
        except errors.RevisionNotPresent:
 
 
866
            raise errors.NoSuchRevision(self, revision_id)
 
 
869
    def get_revision(self, revision_id):
 
 
870
        """Return the Revision object for a named revision"""
 
 
871
        return self.get_revision_reconcile(revision_id)
 
 
874
    def get_revision_graph(self, revision_id=None):
 
 
875
        """Return a dictionary containing the revision graph.
 
 
877
        :return: a dictionary of revision_id->revision_parents_list.
 
 
879
        weave = self._get_revision_vf()
 
 
880
        entire_graph = weave.get_graph()
 
 
881
        if revision_id is None:
 
 
882
            return weave.get_graph()
 
 
883
        elif revision_id not in weave:
 
 
884
            raise errors.NoSuchRevision(self, revision_id)
 
 
886
            # add what can be reached from revision_id
 
 
888
            pending = set([revision_id])
 
 
889
            while len(pending) > 0:
 
 
891
                result[node] = weave.get_parents(node)
 
 
892
                for revision_id in result[node]:
 
 
893
                    if revision_id not in result:
 
 
894
                        pending.add(revision_id)
 
 
898
    def get_revision_graph_with_ghosts(self, revision_ids=None):
 
 
899
        """Return a graph of the revisions with ghosts marked as applicable.
 
 
901
        :param revision_ids: an iterable of revisions to graph or None for all.
 
 
902
        :return: a Graph object with the graph reachable from revision_ids.
 
 
905
        vf = self._get_revision_vf()
 
 
906
        versions = set(vf.versions())
 
 
908
            pending = set(self.all_revision_ids())
 
 
911
            pending = set(revision_ids)
 
 
912
            required = set(revision_ids)
 
 
915
            revision_id = pending.pop()
 
 
916
            if not revision_id in versions:
 
 
917
                if revision_id in required:
 
 
918
                    raise errors.NoSuchRevision(self, revision_id)
 
 
920
                result.add_ghost(revision_id)
 
 
921
                # mark it as done so we don't try for it again.
 
 
922
                done.add(revision_id)
 
 
924
            parent_ids = vf.get_parents_with_ghosts(revision_id)
 
 
925
            for parent_id in parent_ids:
 
 
926
                # is this queued or done ?
 
 
927
                if (parent_id not in pending and
 
 
928
                    parent_id not in done):
 
 
930
                    pending.add(parent_id)
 
 
931
            result.add_node(revision_id, parent_ids)
 
 
932
            done.add(revision_id)
 
 
935
    def _get_revision_vf(self):
 
 
936
        """:return: a versioned file containing the revisions."""
 
 
937
        vf = self._revision_store.get_revision_file(self.get_transaction())
 
 
941
    def reconcile(self, other=None, thorough=False):
 
 
942
        """Reconcile this repository."""
 
 
943
        from bzrlib.reconcile import KnitReconciler
 
 
944
        reconciler = KnitReconciler(self, thorough=thorough)
 
 
945
        reconciler.reconcile()
 
 
948
    def revision_parents(self, revision_id):
 
 
949
        return self._get_revision_vf().get_parents(revision_id)
 
 
952
class RepositoryFormat(object):
 
 
953
    """A repository format.
 
 
955
    Formats provide three things:
 
 
956
     * An initialization routine to construct repository data on disk.
 
 
957
     * a format string which is used when the BzrDir supports versioned
 
 
959
     * an open routine which returns a Repository instance.
 
 
961
    Formats are placed in an dict by their format string for reference 
 
 
962
    during opening. These should be subclasses of RepositoryFormat
 
 
965
    Once a format is deprecated, just deprecate the initialize and open
 
 
966
    methods on the format class. Do not deprecate the object, as the 
 
 
967
    object will be created every system load.
 
 
969
    Common instance attributes:
 
 
970
    _matchingbzrdir - the bzrdir format that the repository format was
 
 
971
    originally written to work with. This can be used if manually
 
 
972
    constructing a bzrdir and repository, or more commonly for test suite
 
 
976
    _default_format = None
 
 
977
    """The default format used for new repositories."""
 
 
980
    """The known formats."""
 
 
983
    def find_format(klass, a_bzrdir):
 
 
984
        """Return the format for the repository object in a_bzrdir."""
 
 
986
            transport = a_bzrdir.get_repository_transport(None)
 
 
987
            format_string = transport.get("format").read()
 
 
988
            return klass._formats[format_string]
 
 
989
        except errors.NoSuchFile:
 
 
990
            raise errors.NoRepositoryPresent(a_bzrdir)
 
 
992
            raise errors.UnknownFormatError(format=format_string)
 
 
994
    def _get_control_store(self, repo_transport, control_files):
 
 
995
        """Return the control store for this repository."""
 
 
996
        raise NotImplementedError(self._get_control_store)
 
 
999
    def get_default_format(klass):
 
 
1000
        """Return the current default format."""
 
 
1001
        return klass._default_format
 
 
1003
    def get_format_string(self):
 
 
1004
        """Return the ASCII format string that identifies this format.
 
 
1006
        Note that in pre format ?? repositories the format string is 
 
 
1007
        not permitted nor written to disk.
 
 
1009
        raise NotImplementedError(self.get_format_string)
 
 
1011
    def get_format_description(self):
 
 
1012
        """Return the short description for this format."""
 
 
1013
        raise NotImplementedError(self.get_format_description)
 
 
1015
    def _get_revision_store(self, repo_transport, control_files):
 
 
1016
        """Return the revision store object for this a_bzrdir."""
 
 
1017
        raise NotImplementedError(self._get_revision_store)
 
 
1019
    def _get_text_rev_store(self,
 
 
1026
        """Common logic for getting a revision store for a repository.
 
 
1028
        see self._get_revision_store for the subclass-overridable method to 
 
 
1029
        get the store for a repository.
 
 
1031
        from bzrlib.store.revision.text import TextRevisionStore
 
 
1032
        dir_mode = control_files._dir_mode
 
 
1033
        file_mode = control_files._file_mode
 
 
1034
        text_store =TextStore(transport.clone(name),
 
 
1036
                              compressed=compressed,
 
 
1038
                              file_mode=file_mode)
 
 
1039
        _revision_store = TextRevisionStore(text_store, serializer)
 
 
1040
        return _revision_store
 
 
1042
    def _get_versioned_file_store(self,
 
 
1047
                                  versionedfile_class=WeaveFile,
 
 
1049
        weave_transport = control_files._transport.clone(name)
 
 
1050
        dir_mode = control_files._dir_mode
 
 
1051
        file_mode = control_files._file_mode
 
 
1052
        return VersionedFileStore(weave_transport, prefixed=prefixed,
 
 
1054
                                  file_mode=file_mode,
 
 
1055
                                  versionedfile_class=versionedfile_class,
 
 
1058
    def initialize(self, a_bzrdir, shared=False):
 
 
1059
        """Initialize a repository of this format in a_bzrdir.
 
 
1061
        :param a_bzrdir: The bzrdir to put the new repository in it.
 
 
1062
        :param shared: The repository should be initialized as a sharable one.
 
 
1064
        This may raise UninitializableFormat if shared repository are not
 
 
1065
        compatible the a_bzrdir.
 
 
1068
    def is_supported(self):
 
 
1069
        """Is this format supported?
 
 
1071
        Supported formats must be initializable and openable.
 
 
1072
        Unsupported formats may not support initialization or committing or 
 
 
1073
        some other features depending on the reason for not being supported.
 
 
1077
    def open(self, a_bzrdir, _found=False):
 
 
1078
        """Return an instance of this format for the bzrdir a_bzrdir.
 
 
1080
        _found is a private parameter, do not use it.
 
 
1082
        raise NotImplementedError(self.open)
 
 
1085
    def register_format(klass, format):
 
 
1086
        klass._formats[format.get_format_string()] = format
 
 
1089
    def set_default_format(klass, format):
 
 
1090
        klass._default_format = format
 
 
1093
    def unregister_format(klass, format):
 
 
1094
        assert klass._formats[format.get_format_string()] is format
 
 
1095
        del klass._formats[format.get_format_string()]
 
 
1098
class PreSplitOutRepositoryFormat(RepositoryFormat):
 
 
1099
    """Base class for the pre split out repository formats."""
 
 
1101
    def initialize(self, a_bzrdir, shared=False, _internal=False):
 
 
1102
        """Create a weave repository.
 
 
1104
        TODO: when creating split out bzr branch formats, move this to a common
 
 
1105
        base for Format5, Format6. or something like that.
 
 
1107
        from bzrlib.weavefile import write_weave_v5
 
 
1108
        from bzrlib.weave import Weave
 
 
1111
            raise errors.IncompatibleFormat(self, a_bzrdir._format)
 
 
1114
            # always initialized when the bzrdir is.
 
 
1115
            return self.open(a_bzrdir, _found=True)
 
 
1117
        # Create an empty weave
 
 
1119
        write_weave_v5(Weave(), sio)
 
 
1120
        empty_weave = sio.getvalue()
 
 
1122
        mutter('creating repository in %s.', a_bzrdir.transport.base)
 
 
1123
        dirs = ['revision-store', 'weaves']
 
 
1124
        files = [('inventory.weave', StringIO(empty_weave)),
 
 
1127
        # FIXME: RBC 20060125 don't peek under the covers
 
 
1128
        # NB: no need to escape relative paths that are url safe.
 
 
1129
        control_files = LockableFiles(a_bzrdir.transport, 'branch-lock',
 
 
1131
        control_files.create_lock()
 
 
1132
        control_files.lock_write()
 
 
1133
        control_files._transport.mkdir_multi(dirs,
 
 
1134
                mode=control_files._dir_mode)
 
 
1136
            for file, content in files:
 
 
1137
                control_files.put(file, content)
 
 
1139
            control_files.unlock()
 
 
1140
        return self.open(a_bzrdir, _found=True)
 
 
1142
    def _get_control_store(self, repo_transport, control_files):
 
 
1143
        """Return the control store for this repository."""
 
 
1144
        return self._get_versioned_file_store('',
 
 
1149
    def _get_text_store(self, transport, control_files):
 
 
1150
        """Get a store for file texts for this format."""
 
 
1151
        raise NotImplementedError(self._get_text_store)
 
 
1153
    def open(self, a_bzrdir, _found=False):
 
 
1154
        """See RepositoryFormat.open()."""
 
 
1156
            # we are being called directly and must probe.
 
 
1157
            raise NotImplementedError
 
 
1159
        repo_transport = a_bzrdir.get_repository_transport(None)
 
 
1160
        control_files = a_bzrdir._control_files
 
 
1161
        text_store = self._get_text_store(repo_transport, control_files)
 
 
1162
        control_store = self._get_control_store(repo_transport, control_files)
 
 
1163
        _revision_store = self._get_revision_store(repo_transport, control_files)
 
 
1164
        return AllInOneRepository(_format=self,
 
 
1166
                                  _revision_store=_revision_store,
 
 
1167
                                  control_store=control_store,
 
 
1168
                                  text_store=text_store)
 
 
1171
class RepositoryFormat4(PreSplitOutRepositoryFormat):
 
 
1172
    """Bzr repository format 4.
 
 
1174
    This repository format has:
 
 
1176
     - TextStores for texts, inventories,revisions.
 
 
1178
    This format is deprecated: it indexes texts using a text id which is
 
 
1179
    removed in format 5; initialization and write support for this format
 
 
1184
        super(RepositoryFormat4, self).__init__()
 
 
1185
        self._matchingbzrdir = bzrdir.BzrDirFormat4()
 
 
1187
    def get_format_description(self):
 
 
1188
        """See RepositoryFormat.get_format_description()."""
 
 
1189
        return "Repository format 4"
 
 
1191
    def initialize(self, url, shared=False, _internal=False):
 
 
1192
        """Format 4 branches cannot be created."""
 
 
1193
        raise errors.UninitializableFormat(self)
 
 
1195
    def is_supported(self):
 
 
1196
        """Format 4 is not supported.
 
 
1198
        It is not supported because the model changed from 4 to 5 and the
 
 
1199
        conversion logic is expensive - so doing it on the fly was not 
 
 
1204
    def _get_control_store(self, repo_transport, control_files):
 
 
1205
        """Format 4 repositories have no formal control store at this point.
 
 
1207
        This will cause any control-file-needing apis to fail - this is desired.
 
 
1211
    def _get_revision_store(self, repo_transport, control_files):
 
 
1212
        """See RepositoryFormat._get_revision_store()."""
 
 
1213
        from bzrlib.xml4 import serializer_v4
 
 
1214
        return self._get_text_rev_store(repo_transport,
 
 
1217
                                        serializer=serializer_v4)
 
 
1219
    def _get_text_store(self, transport, control_files):
 
 
1220
        """See RepositoryFormat._get_text_store()."""
 
 
1223
class RepositoryFormat5(PreSplitOutRepositoryFormat):
 
 
1224
    """Bzr control format 5.
 
 
1226
    This repository format has:
 
 
1227
     - weaves for file texts and inventory
 
 
1229
     - TextStores for revisions and signatures.
 
 
1233
        super(RepositoryFormat5, self).__init__()
 
 
1234
        self._matchingbzrdir = bzrdir.BzrDirFormat5()
 
 
1236
    def get_format_description(self):
 
 
1237
        """See RepositoryFormat.get_format_description()."""
 
 
1238
        return "Weave repository format 5"
 
 
1240
    def _get_revision_store(self, repo_transport, control_files):
 
 
1241
        """See RepositoryFormat._get_revision_store()."""
 
 
1242
        """Return the revision store object for this a_bzrdir."""
 
 
1243
        return self._get_text_rev_store(repo_transport,
 
 
1248
    def _get_text_store(self, transport, control_files):
 
 
1249
        """See RepositoryFormat._get_text_store()."""
 
 
1250
        return self._get_versioned_file_store('weaves', transport, control_files, prefixed=False)
 
 
1253
class RepositoryFormat6(PreSplitOutRepositoryFormat):
 
 
1254
    """Bzr control format 6.
 
 
1256
    This repository format has:
 
 
1257
     - weaves for file texts and inventory
 
 
1258
     - hash subdirectory based stores.
 
 
1259
     - TextStores for revisions and signatures.
 
 
1263
        super(RepositoryFormat6, self).__init__()
 
 
1264
        self._matchingbzrdir = bzrdir.BzrDirFormat6()
 
 
1266
    def get_format_description(self):
 
 
1267
        """See RepositoryFormat.get_format_description()."""
 
 
1268
        return "Weave repository format 6"
 
 
1270
    def _get_revision_store(self, repo_transport, control_files):
 
 
1271
        """See RepositoryFormat._get_revision_store()."""
 
 
1272
        return self._get_text_rev_store(repo_transport,
 
 
1278
    def _get_text_store(self, transport, control_files):
 
 
1279
        """See RepositoryFormat._get_text_store()."""
 
 
1280
        return self._get_versioned_file_store('weaves', transport, control_files)
 
 
1283
class MetaDirRepositoryFormat(RepositoryFormat):
 
 
1284
    """Common base class for the new repositories using the metadir layout."""
 
 
1287
        super(MetaDirRepositoryFormat, self).__init__()
 
 
1288
        self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
 
 
1290
    def _create_control_files(self, a_bzrdir):
 
 
1291
        """Create the required files and the initial control_files object."""
 
 
1292
        # FIXME: RBC 20060125 don't peek under the covers
 
 
1293
        # NB: no need to escape relative paths that are url safe.
 
 
1294
        repository_transport = a_bzrdir.get_repository_transport(self)
 
 
1295
        control_files = LockableFiles(repository_transport, 'lock', LockDir)
 
 
1296
        control_files.create_lock()
 
 
1297
        return control_files
 
 
1299
    def _upload_blank_content(self, a_bzrdir, dirs, files, utf8_files, shared):
 
 
1300
        """Upload the initial blank content."""
 
 
1301
        control_files = self._create_control_files(a_bzrdir)
 
 
1302
        control_files.lock_write()
 
 
1304
            control_files._transport.mkdir_multi(dirs,
 
 
1305
                    mode=control_files._dir_mode)
 
 
1306
            for file, content in files:
 
 
1307
                control_files.put(file, content)
 
 
1308
            for file, content in utf8_files:
 
 
1309
                control_files.put_utf8(file, content)
 
 
1311
                control_files.put_utf8('shared-storage', '')
 
 
1313
            control_files.unlock()
 
 
1316
class RepositoryFormat7(MetaDirRepositoryFormat):
 
 
1317
    """Bzr repository 7.
 
 
1319
    This repository format has:
 
 
1320
     - weaves for file texts and inventory
 
 
1321
     - hash subdirectory based stores.
 
 
1322
     - TextStores for revisions and signatures.
 
 
1323
     - a format marker of its own
 
 
1324
     - an optional 'shared-storage' flag
 
 
1325
     - an optional 'no-working-trees' flag
 
 
1328
    def _get_control_store(self, repo_transport, control_files):
 
 
1329
        """Return the control store for this repository."""
 
 
1330
        return self._get_versioned_file_store('',
 
 
1335
    def get_format_string(self):
 
 
1336
        """See RepositoryFormat.get_format_string()."""
 
 
1337
        return "Bazaar-NG Repository format 7"
 
 
1339
    def get_format_description(self):
 
 
1340
        """See RepositoryFormat.get_format_description()."""
 
 
1341
        return "Weave repository format 7"
 
 
1343
    def _get_revision_store(self, repo_transport, control_files):
 
 
1344
        """See RepositoryFormat._get_revision_store()."""
 
 
1345
        return self._get_text_rev_store(repo_transport,
 
 
1352
    def _get_text_store(self, transport, control_files):
 
 
1353
        """See RepositoryFormat._get_text_store()."""
 
 
1354
        return self._get_versioned_file_store('weaves',
 
 
1358
    def initialize(self, a_bzrdir, shared=False):
 
 
1359
        """Create a weave repository.
 
 
1361
        :param shared: If true the repository will be initialized as a shared
 
 
1364
        from bzrlib.weavefile import write_weave_v5
 
 
1365
        from bzrlib.weave import Weave
 
 
1367
        # Create an empty weave
 
 
1369
        write_weave_v5(Weave(), sio)
 
 
1370
        empty_weave = sio.getvalue()
 
 
1372
        mutter('creating repository in %s.', a_bzrdir.transport.base)
 
 
1373
        dirs = ['revision-store', 'weaves']
 
 
1374
        files = [('inventory.weave', StringIO(empty_weave)), 
 
 
1376
        utf8_files = [('format', self.get_format_string())]
 
 
1378
        self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
 
 
1379
        return self.open(a_bzrdir=a_bzrdir, _found=True)
 
 
1381
    def open(self, a_bzrdir, _found=False, _override_transport=None):
 
 
1382
        """See RepositoryFormat.open().
 
 
1384
        :param _override_transport: INTERNAL USE ONLY. Allows opening the
 
 
1385
                                    repository at a slightly different url
 
 
1386
                                    than normal. I.e. during 'upgrade'.
 
 
1389
            format = RepositoryFormat.find_format(a_bzrdir)
 
 
1390
            assert format.__class__ ==  self.__class__
 
 
1391
        if _override_transport is not None:
 
 
1392
            repo_transport = _override_transport
 
 
1394
            repo_transport = a_bzrdir.get_repository_transport(None)
 
 
1395
        control_files = LockableFiles(repo_transport, 'lock', LockDir)
 
 
1396
        text_store = self._get_text_store(repo_transport, control_files)
 
 
1397
        control_store = self._get_control_store(repo_transport, control_files)
 
 
1398
        _revision_store = self._get_revision_store(repo_transport, control_files)
 
 
1399
        return MetaDirRepository(_format=self,
 
 
1401
                                 control_files=control_files,
 
 
1402
                                 _revision_store=_revision_store,
 
 
1403
                                 control_store=control_store,
 
 
1404
                                 text_store=text_store)
 
 
1407
class RepositoryFormatKnit1(MetaDirRepositoryFormat):
 
 
1408
    """Bzr repository knit format 1.
 
 
1410
    This repository format has:
 
 
1411
     - knits for file texts and inventory
 
 
1412
     - hash subdirectory based stores.
 
 
1413
     - knits for revisions and signatures
 
 
1414
     - TextStores for revisions and signatures.
 
 
1415
     - a format marker of its own
 
 
1416
     - an optional 'shared-storage' flag
 
 
1417
     - an optional 'no-working-trees' flag
 
 
1420
    This format was introduced in bzr 0.8.
 
 
1423
    def _get_control_store(self, repo_transport, control_files):
 
 
1424
        """Return the control store for this repository."""
 
 
1425
        return VersionedFileStore(
 
 
1428
            file_mode=control_files._file_mode,
 
 
1429
            versionedfile_class=KnitVersionedFile,
 
 
1430
            versionedfile_kwargs={'factory':KnitPlainFactory()},
 
 
1433
    def get_format_string(self):
 
 
1434
        """See RepositoryFormat.get_format_string()."""
 
 
1435
        return "Bazaar-NG Knit Repository Format 1"
 
 
1437
    def get_format_description(self):
 
 
1438
        """See RepositoryFormat.get_format_description()."""
 
 
1439
        return "Knit repository format 1"
 
 
1441
    def _get_revision_store(self, repo_transport, control_files):
 
 
1442
        """See RepositoryFormat._get_revision_store()."""
 
 
1443
        from bzrlib.store.revision.knit import KnitRevisionStore
 
 
1444
        versioned_file_store = VersionedFileStore(
 
 
1446
            file_mode=control_files._file_mode,
 
 
1449
            versionedfile_class=KnitVersionedFile,
 
 
1450
            versionedfile_kwargs={'delta':False, 'factory':KnitPlainFactory()},
 
 
1453
        return KnitRevisionStore(versioned_file_store)
 
 
1455
    def _get_text_store(self, transport, control_files):
 
 
1456
        """See RepositoryFormat._get_text_store()."""
 
 
1457
        return self._get_versioned_file_store('knits',
 
 
1460
                                              versionedfile_class=KnitVersionedFile,
 
 
1463
    def initialize(self, a_bzrdir, shared=False):
 
 
1464
        """Create a knit format 1 repository.
 
 
1466
        :param a_bzrdir: bzrdir to contain the new repository; must already
 
 
1468
        :param shared: If true the repository will be initialized as a shared
 
 
1471
        mutter('creating repository in %s.', a_bzrdir.transport.base)
 
 
1472
        dirs = ['revision-store', 'knits']
 
 
1474
        utf8_files = [('format', self.get_format_string())]
 
 
1476
        self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
 
 
1477
        repo_transport = a_bzrdir.get_repository_transport(None)
 
 
1478
        control_files = LockableFiles(repo_transport, 'lock', LockDir)
 
 
1479
        control_store = self._get_control_store(repo_transport, control_files)
 
 
1480
        transaction = transactions.WriteTransaction()
 
 
1481
        # trigger a write of the inventory store.
 
 
1482
        control_store.get_weave_or_empty('inventory', transaction)
 
 
1483
        _revision_store = self._get_revision_store(repo_transport, control_files)
 
 
1484
        _revision_store.has_revision_id('A', transaction)
 
 
1485
        _revision_store.get_signature_file(transaction)
 
 
1486
        return self.open(a_bzrdir=a_bzrdir, _found=True)
 
 
1488
    def open(self, a_bzrdir, _found=False, _override_transport=None):
 
 
1489
        """See RepositoryFormat.open().
 
 
1491
        :param _override_transport: INTERNAL USE ONLY. Allows opening the
 
 
1492
                                    repository at a slightly different url
 
 
1493
                                    than normal. I.e. during 'upgrade'.
 
 
1496
            format = RepositoryFormat.find_format(a_bzrdir)
 
 
1497
            assert format.__class__ ==  self.__class__
 
 
1498
        if _override_transport is not None:
 
 
1499
            repo_transport = _override_transport
 
 
1501
            repo_transport = a_bzrdir.get_repository_transport(None)
 
 
1502
        control_files = LockableFiles(repo_transport, 'lock', LockDir)
 
 
1503
        text_store = self._get_text_store(repo_transport, control_files)
 
 
1504
        control_store = self._get_control_store(repo_transport, control_files)
 
 
1505
        _revision_store = self._get_revision_store(repo_transport, control_files)
 
 
1506
        return KnitRepository(_format=self,
 
 
1508
                              control_files=control_files,
 
 
1509
                              _revision_store=_revision_store,
 
 
1510
                              control_store=control_store,
 
 
1511
                              text_store=text_store)
 
 
1514
# formats which have no format string are not discoverable
 
 
1515
# and not independently creatable, so are not registered.
 
 
1516
RepositoryFormat.register_format(RepositoryFormat7())
 
 
1517
_default_format = RepositoryFormatKnit1()
 
 
1518
RepositoryFormat.register_format(_default_format)
 
 
1519
RepositoryFormat.set_default_format(_default_format)
 
 
1520
_legacy_formats = [RepositoryFormat4(),
 
 
1521
                   RepositoryFormat5(),
 
 
1522
                   RepositoryFormat6()]
 
 
1525
class InterRepository(InterObject):
 
 
1526
    """This class represents operations taking place between two repositories.
 
 
1528
    Its instances have methods like copy_content and fetch, and contain
 
 
1529
    references to the source and target repositories these operations can be 
 
 
1532
    Often we will provide convenience methods on 'repository' which carry out
 
 
1533
    operations with another repository - they will always forward to
 
 
1534
    InterRepository.get(other).method_name(parameters).
 
 
1538
    """The available optimised InterRepository types."""
 
 
1541
    def copy_content(self, revision_id=None, basis=None):
 
 
1542
        """Make a complete copy of the content in self into destination.
 
 
1544
        This is a destructive operation! Do not use it on existing 
 
 
1547
        :param revision_id: Only copy the content needed to construct
 
 
1548
                            revision_id and its parents.
 
 
1549
        :param basis: Copy the needed data preferentially from basis.
 
 
1552
            self.target.set_make_working_trees(self.source.make_working_trees())
 
 
1553
        except NotImplementedError:
 
 
1555
        # grab the basis available data
 
 
1556
        if basis is not None:
 
 
1557
            self.target.fetch(basis, revision_id=revision_id)
 
 
1558
        # but don't bother fetching if we have the needed data now.
 
 
1559
        if (revision_id not in (None, NULL_REVISION) and 
 
 
1560
            self.target.has_revision(revision_id)):
 
 
1562
        self.target.fetch(self.source, revision_id=revision_id)
 
 
1564
    def _double_lock(self, lock_source, lock_target):
 
 
1565
        """Take out too locks, rolling back the first if the second throws."""
 
 
1570
            # we want to ensure that we don't leave source locked by mistake.
 
 
1571
            # and any error on target should not confuse source.
 
 
1572
            self.source.unlock()
 
 
1576
    def fetch(self, revision_id=None, pb=None):
 
 
1577
        """Fetch the content required to construct revision_id.
 
 
1579
        The content is copied from source to target.
 
 
1581
        :param revision_id: if None all content is copied, if NULL_REVISION no
 
 
1583
        :param pb: optional progress bar to use for progress reports. If not
 
 
1584
                   provided a default one will be created.
 
 
1586
        Returns the copied revision count and the failed revisions in a tuple:
 
 
1589
        from bzrlib.fetch import GenericRepoFetcher
 
 
1590
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
 
 
1591
               self.source, self.source._format, self.target, self.target._format)
 
 
1592
        f = GenericRepoFetcher(to_repository=self.target,
 
 
1593
                               from_repository=self.source,
 
 
1594
                               last_revision=revision_id,
 
 
1596
        return f.count_copied, f.failed_revisions
 
 
1598
    def lock_read(self):
 
 
1599
        """Take out a logical read lock.
 
 
1601
        This will lock the source branch and the target branch. The source gets
 
 
1602
        a read lock and the target a read lock.
 
 
1604
        self._double_lock(self.source.lock_read, self.target.lock_read)
 
 
1606
    def lock_write(self):
 
 
1607
        """Take out a logical write lock.
 
 
1609
        This will lock the source branch and the target branch. The source gets
 
 
1610
        a read lock and the target a write lock.
 
 
1612
        self._double_lock(self.source.lock_read, self.target.lock_write)
 
 
1615
    def missing_revision_ids(self, revision_id=None):
 
 
1616
        """Return the revision ids that source has that target does not.
 
 
1618
        These are returned in topological order.
 
 
1620
        :param revision_id: only return revision ids included by this
 
 
1623
        # generic, possibly worst case, slow code path.
 
 
1624
        target_ids = set(self.target.all_revision_ids())
 
 
1625
        if revision_id is not None:
 
 
1626
            source_ids = self.source.get_ancestry(revision_id)
 
 
1627
            assert source_ids[0] == None
 
 
1630
            source_ids = self.source.all_revision_ids()
 
 
1631
        result_set = set(source_ids).difference(target_ids)
 
 
1632
        # this may look like a no-op: its not. It preserves the ordering
 
 
1633
        # other_ids had while only returning the members from other_ids
 
 
1634
        # that we've decided we need.
 
 
1635
        return [rev_id for rev_id in source_ids if rev_id in result_set]
 
 
1638
        """Release the locks on source and target."""
 
 
1640
            self.target.unlock()
 
 
1642
            self.source.unlock()
 
 
1645
class InterWeaveRepo(InterRepository):
 
 
1646
    """Optimised code paths between Weave based repositories."""
 
 
1648
    _matching_repo_format = RepositoryFormat7()
 
 
1649
    """Repository format for testing with."""
 
 
1652
    def is_compatible(source, target):
 
 
1653
        """Be compatible with known Weave formats.
 
 
1655
        We don't test for the stores being of specific types because that
 
 
1656
        could lead to confusing results, and there is no need to be 
 
 
1660
            return (isinstance(source._format, (RepositoryFormat5,
 
 
1662
                                                RepositoryFormat7)) and
 
 
1663
                    isinstance(target._format, (RepositoryFormat5,
 
 
1665
                                                RepositoryFormat7)))
 
 
1666
        except AttributeError:
 
 
1670
    def copy_content(self, revision_id=None, basis=None):
 
 
1671
        """See InterRepository.copy_content()."""
 
 
1672
        # weave specific optimised path:
 
 
1673
        if basis is not None:
 
 
1674
            # copy the basis in, then fetch remaining data.
 
 
1675
            basis.copy_content_into(self.target, revision_id)
 
 
1676
            # the basis copy_content_into could miss-set this.
 
 
1678
                self.target.set_make_working_trees(self.source.make_working_trees())
 
 
1679
            except NotImplementedError:
 
 
1681
            self.target.fetch(self.source, revision_id=revision_id)
 
 
1684
                self.target.set_make_working_trees(self.source.make_working_trees())
 
 
1685
            except NotImplementedError:
 
 
1687
            # FIXME do not peek!
 
 
1688
            if self.source.control_files._transport.listable():
 
 
1689
                pb = ui.ui_factory.nested_progress_bar()
 
 
1691
                    self.target.weave_store.copy_all_ids(
 
 
1692
                        self.source.weave_store,
 
 
1694
                        from_transaction=self.source.get_transaction(),
 
 
1695
                        to_transaction=self.target.get_transaction())
 
 
1696
                    pb.update('copying inventory', 0, 1)
 
 
1697
                    self.target.control_weaves.copy_multi(
 
 
1698
                        self.source.control_weaves, ['inventory'],
 
 
1699
                        from_transaction=self.source.get_transaction(),
 
 
1700
                        to_transaction=self.target.get_transaction())
 
 
1701
                    self.target._revision_store.text_store.copy_all_ids(
 
 
1702
                        self.source._revision_store.text_store,
 
 
1707
                self.target.fetch(self.source, revision_id=revision_id)
 
 
1710
    def fetch(self, revision_id=None, pb=None):
 
 
1711
        """See InterRepository.fetch()."""
 
 
1712
        from bzrlib.fetch import GenericRepoFetcher
 
 
1713
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
 
 
1714
               self.source, self.source._format, self.target, self.target._format)
 
 
1715
        f = GenericRepoFetcher(to_repository=self.target,
 
 
1716
                               from_repository=self.source,
 
 
1717
                               last_revision=revision_id,
 
 
1719
        return f.count_copied, f.failed_revisions
 
 
1722
    def missing_revision_ids(self, revision_id=None):
 
 
1723
        """See InterRepository.missing_revision_ids()."""
 
 
1724
        # we want all revisions to satisfy revision_id in source.
 
 
1725
        # but we don't want to stat every file here and there.
 
 
1726
        # we want then, all revisions other needs to satisfy revision_id 
 
 
1727
        # checked, but not those that we have locally.
 
 
1728
        # so the first thing is to get a subset of the revisions to 
 
 
1729
        # satisfy revision_id in source, and then eliminate those that
 
 
1730
        # we do already have. 
 
 
1731
        # this is slow on high latency connection to self, but as as this
 
 
1732
        # disk format scales terribly for push anyway due to rewriting 
 
 
1733
        # inventory.weave, this is considered acceptable.
 
 
1735
        if revision_id is not None:
 
 
1736
            source_ids = self.source.get_ancestry(revision_id)
 
 
1737
            assert source_ids[0] == None
 
 
1740
            source_ids = self.source._all_possible_ids()
 
 
1741
        source_ids_set = set(source_ids)
 
 
1742
        # source_ids is the worst possible case we may need to pull.
 
 
1743
        # now we want to filter source_ids against what we actually
 
 
1744
        # have in target, but don't try to check for existence where we know
 
 
1745
        # we do not have a revision as that would be pointless.
 
 
1746
        target_ids = set(self.target._all_possible_ids())
 
 
1747
        possibly_present_revisions = target_ids.intersection(source_ids_set)
 
 
1748
        actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
 
 
1749
        required_revisions = source_ids_set.difference(actually_present_revisions)
 
 
1750
        required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
 
 
1751
        if revision_id is not None:
 
 
1752
            # we used get_ancestry to determine source_ids then we are assured all
 
 
1753
            # revisions referenced are present as they are installed in topological order.
 
 
1754
            # and the tip revision was validated by get_ancestry.
 
 
1755
            return required_topo_revisions
 
 
1757
            # if we just grabbed the possibly available ids, then 
 
 
1758
            # we only have an estimate of whats available and need to validate
 
 
1759
            # that against the revision records.
 
 
1760
            return self.source._eliminate_revisions_not_present(required_topo_revisions)
 
 
1763
class InterKnitRepo(InterRepository):
 
 
1764
    """Optimised code paths between Knit based repositories."""
 
 
1766
    _matching_repo_format = RepositoryFormatKnit1()
 
 
1767
    """Repository format for testing with."""
 
 
1770
    def is_compatible(source, target):
 
 
1771
        """Be compatible with known Knit formats.
 
 
1773
        We don't test for the stores being of specific types because that
 
 
1774
        could lead to confusing results, and there is no need to be 
 
 
1778
            return (isinstance(source._format, (RepositoryFormatKnit1)) and
 
 
1779
                    isinstance(target._format, (RepositoryFormatKnit1)))
 
 
1780
        except AttributeError:
 
 
1784
    def fetch(self, revision_id=None, pb=None):
 
 
1785
        """See InterRepository.fetch()."""
 
 
1786
        from bzrlib.fetch import KnitRepoFetcher
 
 
1787
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
 
 
1788
               self.source, self.source._format, self.target, self.target._format)
 
 
1789
        f = KnitRepoFetcher(to_repository=self.target,
 
 
1790
                            from_repository=self.source,
 
 
1791
                            last_revision=revision_id,
 
 
1793
        return f.count_copied, f.failed_revisions
 
 
1796
    def missing_revision_ids(self, revision_id=None):
 
 
1797
        """See InterRepository.missing_revision_ids()."""
 
 
1798
        if revision_id is not None:
 
 
1799
            source_ids = self.source.get_ancestry(revision_id)
 
 
1800
            assert source_ids[0] == None
 
 
1803
            source_ids = self.source._all_possible_ids()
 
 
1804
        source_ids_set = set(source_ids)
 
 
1805
        # source_ids is the worst possible case we may need to pull.
 
 
1806
        # now we want to filter source_ids against what we actually
 
 
1807
        # have in target, but don't try to check for existence where we know
 
 
1808
        # we do not have a revision as that would be pointless.
 
 
1809
        target_ids = set(self.target._all_possible_ids())
 
 
1810
        possibly_present_revisions = target_ids.intersection(source_ids_set)
 
 
1811
        actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
 
 
1812
        required_revisions = source_ids_set.difference(actually_present_revisions)
 
 
1813
        required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
 
 
1814
        if revision_id is not None:
 
 
1815
            # we used get_ancestry to determine source_ids then we are assured all
 
 
1816
            # revisions referenced are present as they are installed in topological order.
 
 
1817
            # and the tip revision was validated by get_ancestry.
 
 
1818
            return required_topo_revisions
 
 
1820
            # if we just grabbed the possibly available ids, then 
 
 
1821
            # we only have an estimate of whats available and need to validate
 
 
1822
            # that against the revision records.
 
 
1823
            return self.source._eliminate_revisions_not_present(required_topo_revisions)
 
 
1825
InterRepository.register_optimiser(InterWeaveRepo)
 
 
1826
InterRepository.register_optimiser(InterKnitRepo)
 
 
1829
class RepositoryTestProviderAdapter(object):
 
 
1830
    """A tool to generate a suite testing multiple repository formats at once.
 
 
1832
    This is done by copying the test once for each transport and injecting
 
 
1833
    the transport_server, transport_readonly_server, and bzrdir_format and
 
 
1834
    repository_format classes into each copy. Each copy is also given a new id()
 
 
1835
    to make it easy to identify.
 
 
1838
    def __init__(self, transport_server, transport_readonly_server, formats):
 
 
1839
        self._transport_server = transport_server
 
 
1840
        self._transport_readonly_server = transport_readonly_server
 
 
1841
        self._formats = formats
 
 
1843
    def adapt(self, test):
 
 
1844
        result = TestSuite()
 
 
1845
        for repository_format, bzrdir_format in self._formats:
 
 
1846
            new_test = deepcopy(test)
 
 
1847
            new_test.transport_server = self._transport_server
 
 
1848
            new_test.transport_readonly_server = self._transport_readonly_server
 
 
1849
            new_test.bzrdir_format = bzrdir_format
 
 
1850
            new_test.repository_format = repository_format
 
 
1851
            def make_new_test_id():
 
 
1852
                new_id = "%s(%s)" % (new_test.id(), repository_format.__class__.__name__)
 
 
1853
                return lambda: new_id
 
 
1854
            new_test.id = make_new_test_id()
 
 
1855
            result.addTest(new_test)
 
 
1859
class InterRepositoryTestProviderAdapter(object):
 
 
1860
    """A tool to generate a suite testing multiple inter repository formats.
 
 
1862
    This is done by copying the test once for each interrepo provider and injecting
 
 
1863
    the transport_server, transport_readonly_server, repository_format and 
 
 
1864
    repository_to_format classes into each copy.
 
 
1865
    Each copy is also given a new id() to make it easy to identify.
 
 
1868
    def __init__(self, transport_server, transport_readonly_server, formats):
 
 
1869
        self._transport_server = transport_server
 
 
1870
        self._transport_readonly_server = transport_readonly_server
 
 
1871
        self._formats = formats
 
 
1873
    def adapt(self, test):
 
 
1874
        result = TestSuite()
 
 
1875
        for interrepo_class, repository_format, repository_format_to in self._formats:
 
 
1876
            new_test = deepcopy(test)
 
 
1877
            new_test.transport_server = self._transport_server
 
 
1878
            new_test.transport_readonly_server = self._transport_readonly_server
 
 
1879
            new_test.interrepo_class = interrepo_class
 
 
1880
            new_test.repository_format = repository_format
 
 
1881
            new_test.repository_format_to = repository_format_to
 
 
1882
            def make_new_test_id():
 
 
1883
                new_id = "%s(%s)" % (new_test.id(), interrepo_class.__name__)
 
 
1884
                return lambda: new_id
 
 
1885
            new_test.id = make_new_test_id()
 
 
1886
            result.addTest(new_test)
 
 
1890
    def default_test_list():
 
 
1891
        """Generate the default list of interrepo permutations to test."""
 
 
1893
        # test the default InterRepository between format 6 and the current 
 
 
1895
        # XXX: robertc 20060220 reinstate this when there are two supported
 
 
1896
        # formats which do not have an optimal code path between them.
 
 
1897
        result.append((InterRepository,
 
 
1898
                       RepositoryFormat6(),
 
 
1899
                       RepositoryFormatKnit1()))
 
 
1900
        for optimiser in InterRepository._optimisers:
 
 
1901
            result.append((optimiser,
 
 
1902
                           optimiser._matching_repo_format,
 
 
1903
                           optimiser._matching_repo_format
 
 
1905
        # if there are specific combinations we want to use, we can add them 
 
 
1910
class CopyConverter(object):
 
 
1911
    """A repository conversion tool which just performs a copy of the content.
 
 
1913
    This is slow but quite reliable.
 
 
1916
    def __init__(self, target_format):
 
 
1917
        """Create a CopyConverter.
 
 
1919
        :param target_format: The format the resulting repository should be.
 
 
1921
        self.target_format = target_format
 
 
1923
    def convert(self, repo, pb):
 
 
1924
        """Perform the conversion of to_convert, giving feedback via pb.
 
 
1926
        :param to_convert: The disk object to convert.
 
 
1927
        :param pb: a progress bar to use for progress information.
 
 
1932
        # this is only useful with metadir layouts - separated repo content.
 
 
1933
        # trigger an assertion if not such
 
 
1934
        repo._format.get_format_string()
 
 
1935
        self.repo_dir = repo.bzrdir
 
 
1936
        self.step('Moving repository to repository.backup')
 
 
1937
        self.repo_dir.transport.move('repository', 'repository.backup')
 
 
1938
        backup_transport =  self.repo_dir.transport.clone('repository.backup')
 
 
1939
        self.source_repo = repo._format.open(self.repo_dir,
 
 
1941
            _override_transport=backup_transport)
 
 
1942
        self.step('Creating new repository')
 
 
1943
        converted = self.target_format.initialize(self.repo_dir,
 
 
1944
                                                  self.source_repo.is_shared())
 
 
1945
        converted.lock_write()
 
 
1947
            self.step('Copying content into repository.')
 
 
1948
            self.source_repo.copy_content_into(converted)
 
 
1951
        self.step('Deleting old repository content.')
 
 
1952
        self.repo_dir.transport.delete_tree('repository.backup')
 
 
1953
        self.pb.note('repository converted')
 
 
1955
    def step(self, message):
 
 
1956
        """Update the pb by a step."""
 
 
1958
        self.pb.update(message, self.count, self.total)
 
 
1961
class CommitBuilder(object):
 
 
1962
    """Provides an interface to build up a commit.
 
 
1964
    This allows describing a tree to be committed without needing to 
 
 
1965
    know the internals of the format of the repository.
 
 
1967
    def __init__(self, repository, parents, config, timestamp=None, 
 
 
1968
                 timezone=None, committer=None, revprops=None, 
 
 
1970
        """Initiate a CommitBuilder.
 
 
1972
        :param repository: Repository to commit to.
 
 
1973
        :param parents: Revision ids of the parents of the new revision.
 
 
1974
        :param config: Configuration to use.
 
 
1975
        :param timestamp: Optional timestamp recorded for commit.
 
 
1976
        :param timezone: Optional timezone for timestamp.
 
 
1977
        :param committer: Optional committer to set for commit.
 
 
1978
        :param revprops: Optional dictionary of revision properties.
 
 
1979
        :param revision_id: Optional revision id.
 
 
1981
        self._config = config
 
 
1983
        if committer is None:
 
 
1984
            self._committer = self._config.username()
 
 
1986
            assert isinstance(committer, basestring), type(committer)
 
 
1987
            self._committer = committer
 
 
1989
        self.new_inventory = Inventory()
 
 
1990
        self._new_revision_id = revision_id
 
 
1991
        self.parents = parents
 
 
1992
        self.repository = repository
 
 
1995
        if revprops is not None:
 
 
1996
            self._revprops.update(revprops)
 
 
1998
        if timestamp is None:
 
 
1999
            self._timestamp = time.time()
 
 
2001
            self._timestamp = long(timestamp)
 
 
2003
        if timezone is None:
 
 
2004
            self._timezone = local_time_offset()
 
 
2006
            self._timezone = int(timezone)
 
 
2008
        self._generate_revision_if_needed()
 
 
2010
    def commit(self, message):
 
 
2011
        """Make the actual commit.
 
 
2013
        :return: The revision id of the recorded revision.
 
 
2015
        rev = Revision(timestamp=self._timestamp,
 
 
2016
                       timezone=self._timezone,
 
 
2017
                       committer=self._committer,
 
 
2019
                       inventory_sha1=self.inv_sha1,
 
 
2020
                       revision_id=self._new_revision_id,
 
 
2021
                       properties=self._revprops)
 
 
2022
        rev.parent_ids = self.parents
 
 
2023
        self.repository.add_revision(self._new_revision_id, rev, 
 
 
2024
            self.new_inventory, self._config)
 
 
2025
        return self._new_revision_id
 
 
2027
    def finish_inventory(self):
 
 
2028
        """Tell the builder that the inventory is finished."""
 
 
2029
        self.new_inventory.revision_id = self._new_revision_id
 
 
2030
        self.inv_sha1 = self.repository.add_inventory(
 
 
2031
            self._new_revision_id,
 
 
2036
    def _gen_revision_id(self):
 
 
2037
        """Return new revision-id."""
 
 
2038
        s = '%s-%s-' % (self._config.user_email(), 
 
 
2039
                        compact_date(self._timestamp))
 
 
2040
        s += hexlify(rand_bytes(8))
 
 
2043
    def _generate_revision_if_needed(self):
 
 
2044
        """Create a revision id if None was supplied.
 
 
2046
        If the repository can not support user-specified revision ids
 
 
2047
        they should override this function and raise UnsupportedOperation
 
 
2048
        if _new_revision_id is not None.
 
 
2050
        :raises: UnsupportedOperation
 
 
2052
        if self._new_revision_id is None:
 
 
2053
            self._new_revision_id = self._gen_revision_id()
 
 
2055
    def record_entry_contents(self, ie, parent_invs, path, tree):
 
 
2056
        """Record the content of ie from tree into the commit if needed.
 
 
2058
        :param ie: An inventory entry present in the commit.
 
 
2059
        :param parent_invs: The inventories of the parent revisions of the
 
 
2061
        :param path: The path the entry is at in the tree.
 
 
2062
        :param tree: The tree which contains this entry and should be used to 
 
 
2065
        self.new_inventory.add(ie)
 
 
2067
        # ie.revision is always None if the InventoryEntry is considered
 
 
2068
        # for committing. ie.snapshot will record the correct revision 
 
 
2069
        # which may be the sole parent if it is untouched.
 
 
2070
        if ie.revision is not None:
 
 
2072
        previous_entries = ie.find_previous_heads(
 
 
2074
            self.repository.weave_store,
 
 
2075
            self.repository.get_transaction())
 
 
2076
        # we are creating a new revision for ie in the history store
 
 
2078
        ie.snapshot(self._new_revision_id, path, previous_entries, tree, self)
 
 
2080
    def modified_directory(self, file_id, file_parents):
 
 
2081
        """Record the presence of a symbolic link.
 
 
2083
        :param file_id: The file_id of the link to record.
 
 
2084
        :param file_parents: The per-file parent revision ids.
 
 
2086
        self._add_text_to_weave(file_id, [], file_parents.keys())
 
 
2088
    def modified_file_text(self, file_id, file_parents,
 
 
2089
                           get_content_byte_lines, text_sha1=None,
 
 
2091
        """Record the text of file file_id
 
 
2093
        :param file_id: The file_id of the file to record the text of.
 
 
2094
        :param file_parents: The per-file parent revision ids.
 
 
2095
        :param get_content_byte_lines: A callable which will return the byte
 
 
2097
        :param text_sha1: Optional SHA1 of the file contents.
 
 
2098
        :param text_size: Optional size of the file contents.
 
 
2100
        mutter('storing text of file {%s} in revision {%s} into %r',
 
 
2101
               file_id, self._new_revision_id, self.repository.weave_store)
 
 
2102
        # special case to avoid diffing on renames or 
 
 
2104
        if (len(file_parents) == 1
 
 
2105
            and text_sha1 == file_parents.values()[0].text_sha1
 
 
2106
            and text_size == file_parents.values()[0].text_size):
 
 
2107
            previous_ie = file_parents.values()[0]
 
 
2108
            versionedfile = self.repository.weave_store.get_weave(file_id, 
 
 
2109
                self.repository.get_transaction())
 
 
2110
            versionedfile.clone_text(self._new_revision_id, 
 
 
2111
                previous_ie.revision, file_parents.keys())
 
 
2112
            return text_sha1, text_size
 
 
2114
            new_lines = get_content_byte_lines()
 
 
2115
            # TODO: Rather than invoking sha_strings here, _add_text_to_weave
 
 
2116
            # should return the SHA1 and size
 
 
2117
            self._add_text_to_weave(file_id, new_lines, file_parents.keys())
 
 
2118
            return osutils.sha_strings(new_lines), \
 
 
2119
                sum(map(len, new_lines))
 
 
2121
    def modified_link(self, file_id, file_parents, link_target):
 
 
2122
        """Record the presence of a symbolic link.
 
 
2124
        :param file_id: The file_id of the link to record.
 
 
2125
        :param file_parents: The per-file parent revision ids.
 
 
2126
        :param link_target: Target location of this link.
 
 
2128
        self._add_text_to_weave(file_id, [], file_parents.keys())
 
 
2130
    def _add_text_to_weave(self, file_id, new_lines, parents):
 
 
2131
        versionedfile = self.repository.weave_store.get_weave_or_empty(
 
 
2132
            file_id, self.repository.get_transaction())
 
 
2133
        versionedfile.add_lines(self._new_revision_id, parents, new_lines)
 
 
2134
        versionedfile.clear_cache()
 
 
2137
# Copied from xml.sax.saxutils
 
 
2138
def _unescape_xml(data):
 
 
2139
    """Unescape &, <, and > in a string of data.
 
 
2141
    data = data.replace("<", "<")
 
 
2142
    data = data.replace(">", ">")
 
 
2143
    # must do ampersand last
 
 
2144
    return data.replace("&", "&")