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 cStringIO import StringIO
 
 
19
from bzrlib.lazy_import import lazy_import
 
 
20
lazy_import(globals(), """
 
 
21
from binascii import hexlify
 
 
22
from copy import deepcopy
 
 
39
    revision as _mod_revision,
 
 
48
from bzrlib.osutils import (
 
 
53
from bzrlib.revisiontree import RevisionTree
 
 
54
from bzrlib.store.versioned import VersionedFileStore
 
 
55
from bzrlib.store.text import TextStore
 
 
56
from bzrlib.testament import Testament
 
 
59
from bzrlib.decorators import needs_read_lock, needs_write_lock
 
 
60
from bzrlib.inter import InterObject
 
 
61
from bzrlib.inventory import Inventory, InventoryDirectory, ROOT_ID
 
 
62
from bzrlib.symbol_versioning import (
 
 
66
from bzrlib.trace import mutter, note, warning
 
 
69
# Old formats display a warning, but only once
 
 
70
_deprecation_warning_done = False
 
 
73
class Repository(object):
 
 
74
    """Repository holding history for one or more branches.
 
 
76
    The repository holds and retrieves historical information including
 
 
77
    revisions and file history.  It's normally accessed only by the Branch,
 
 
78
    which views a particular line of development through that history.
 
 
80
    The Repository builds on top of Stores and a Transport, which respectively 
 
 
81
    describe the disk data format and the way of accessing the (possibly 
 
 
86
    def add_inventory(self, revid, inv, parents):
 
 
87
        """Add the inventory inv to the repository as revid.
 
 
89
        :param parents: The revision ids of the parents that revid
 
 
90
                        is known to have and are in the repository already.
 
 
92
        returns the sha1 of the serialized inventory.
 
 
94
        assert inv.revision_id is None or inv.revision_id == revid, \
 
 
95
            "Mismatch between inventory revision" \
 
 
96
            " id and insertion revid (%r, %r)" % (inv.revision_id, revid)
 
 
97
        assert inv.root is not None
 
 
98
        inv_text = self.serialise_inventory(inv)
 
 
99
        inv_sha1 = osutils.sha_string(inv_text)
 
 
100
        inv_vf = self.control_weaves.get_weave('inventory',
 
 
101
                                               self.get_transaction())
 
 
102
        self._inventory_add_lines(inv_vf, revid, parents, osutils.split_lines(inv_text))
 
 
105
    def _inventory_add_lines(self, inv_vf, revid, parents, lines):
 
 
107
        for parent in parents:
 
 
109
                final_parents.append(parent)
 
 
111
        inv_vf.add_lines(revid, final_parents, lines)
 
 
114
    def add_revision(self, rev_id, rev, inv=None, config=None):
 
 
115
        """Add rev to the revision store as rev_id.
 
 
117
        :param rev_id: the revision id to use.
 
 
118
        :param rev: The revision object.
 
 
119
        :param inv: The inventory for the revision. if None, it will be looked
 
 
120
                    up in the inventory storer
 
 
121
        :param config: If None no digital signature will be created.
 
 
122
                       If supplied its signature_needed method will be used
 
 
123
                       to determine if a signature should be made.
 
 
125
        if config is not None and config.signature_needed():
 
 
127
                inv = self.get_inventory(rev_id)
 
 
128
            plaintext = Testament(rev, inv).as_short_text()
 
 
129
            self.store_revision_signature(
 
 
130
                gpg.GPGStrategy(config), plaintext, rev_id)
 
 
131
        if not rev_id in self.get_inventory_weave():
 
 
133
                raise errors.WeaveRevisionNotPresent(rev_id,
 
 
134
                                                     self.get_inventory_weave())
 
 
136
                # yes, this is not suitable for adding with ghosts.
 
 
137
                self.add_inventory(rev_id, inv, rev.parent_ids)
 
 
138
        self._revision_store.add_revision(rev, self.get_transaction())
 
 
141
    def _all_possible_ids(self):
 
 
142
        """Return all the possible revisions that we could find."""
 
 
143
        return self.get_inventory_weave().versions()
 
 
145
    def all_revision_ids(self):
 
 
146
        """Returns a list of all the revision ids in the repository. 
 
 
148
        This is deprecated because code should generally work on the graph
 
 
149
        reachable from a particular revision, and ignore any other revisions
 
 
150
        that might be present.  There is no direct replacement method.
 
 
152
        return self._all_revision_ids()
 
 
155
    def _all_revision_ids(self):
 
 
156
        """Returns a list of all the revision ids in the repository. 
 
 
158
        These are in as much topological order as the underlying store can 
 
 
159
        present: for weaves ghosts may lead to a lack of correctness until
 
 
160
        the reweave updates the parents list.
 
 
162
        if self._revision_store.text_store.listable():
 
 
163
            return self._revision_store.all_revision_ids(self.get_transaction())
 
 
164
        result = self._all_possible_ids()
 
 
165
        return self._eliminate_revisions_not_present(result)
 
 
167
    def break_lock(self):
 
 
168
        """Break a lock if one is present from another instance.
 
 
170
        Uses the ui factory to ask for confirmation if the lock may be from
 
 
173
        self.control_files.break_lock()
 
 
176
    def _eliminate_revisions_not_present(self, revision_ids):
 
 
177
        """Check every revision id in revision_ids to see if we have it.
 
 
179
        Returns a set of the present revisions.
 
 
182
        for id in revision_ids:
 
 
183
            if self.has_revision(id):
 
 
188
    def create(a_bzrdir):
 
 
189
        """Construct the current default format repository in a_bzrdir."""
 
 
190
        return RepositoryFormat.get_default_format().initialize(a_bzrdir)
 
 
192
    def __init__(self, _format, a_bzrdir, control_files, _revision_store, control_store, text_store):
 
 
193
        """instantiate a Repository.
 
 
195
        :param _format: The format of the repository on disk.
 
 
196
        :param a_bzrdir: The BzrDir of the repository.
 
 
198
        In the future we will have a single api for all stores for
 
 
199
        getting file texts, inventories and revisions, then
 
 
200
        this construct will accept instances of those things.
 
 
202
        super(Repository, self).__init__()
 
 
203
        self._format = _format
 
 
204
        # the following are part of the public API for Repository:
 
 
205
        self.bzrdir = a_bzrdir
 
 
206
        self.control_files = control_files
 
 
207
        self._revision_store = _revision_store
 
 
208
        self.text_store = text_store
 
 
209
        # backwards compatibility
 
 
210
        self.weave_store = text_store
 
 
211
        # not right yet - should be more semantically clear ? 
 
 
213
        self.control_store = control_store
 
 
214
        self.control_weaves = control_store
 
 
215
        # TODO: make sure to construct the right store classes, etc, depending
 
 
216
        # on whether escaping is required.
 
 
217
        self._warn_if_deprecated()
 
 
218
        self._serializer = xml5.serializer_v5
 
 
221
        return '%s(%r)' % (self.__class__.__name__, 
 
 
222
                           self.bzrdir.transport.base)
 
 
225
        return self.control_files.is_locked()
 
 
227
    def lock_write(self):
 
 
228
        self.control_files.lock_write()
 
 
231
        self.control_files.lock_read()
 
 
233
    def get_physical_lock_status(self):
 
 
234
        return self.control_files.get_physical_lock_status()
 
 
237
    def missing_revision_ids(self, other, revision_id=None):
 
 
238
        """Return the revision ids that other has that this does not.
 
 
240
        These are returned in topological order.
 
 
242
        revision_id: only return revision ids included by revision_id.
 
 
244
        return InterRepository.get(other, self).missing_revision_ids(revision_id)
 
 
248
        """Open the repository rooted at base.
 
 
250
        For instance, if the repository is at URL/.bzr/repository,
 
 
251
        Repository.open(URL) -> a Repository instance.
 
 
253
        control = bzrdir.BzrDir.open(base)
 
 
254
        return control.open_repository()
 
 
256
    def copy_content_into(self, destination, revision_id=None, basis=None):
 
 
257
        """Make a complete copy of the content in self into destination.
 
 
259
        This is a destructive operation! Do not use it on existing 
 
 
262
        return InterRepository.get(self, destination).copy_content(revision_id, basis)
 
 
264
    def fetch(self, source, revision_id=None, pb=None):
 
 
265
        """Fetch the content required to construct revision_id from source.
 
 
267
        If revision_id is None all content is copied.
 
 
269
        return InterRepository.get(source, self).fetch(revision_id=revision_id,
 
 
272
    def get_commit_builder(self, branch, parents, config, timestamp=None, 
 
 
273
                           timezone=None, committer=None, revprops=None, 
 
 
275
        """Obtain a CommitBuilder for this repository.
 
 
277
        :param branch: Branch to commit to.
 
 
278
        :param parents: Revision ids of the parents of the new revision.
 
 
279
        :param config: Configuration to use.
 
 
280
        :param timestamp: Optional timestamp recorded for commit.
 
 
281
        :param timezone: Optional timezone for timestamp.
 
 
282
        :param committer: Optional committer to set for commit.
 
 
283
        :param revprops: Optional dictionary of revision properties.
 
 
284
        :param revision_id: Optional revision id.
 
 
286
        return _CommitBuilder(self, parents, config, timestamp, timezone,
 
 
287
                              committer, revprops, revision_id)
 
 
290
        self.control_files.unlock()
 
 
293
    def clone(self, a_bzrdir, revision_id=None, basis=None):
 
 
294
        """Clone this repository into a_bzrdir using the current format.
 
 
296
        Currently no check is made that the format of this repository and
 
 
297
        the bzrdir format are compatible. FIXME RBC 20060201.
 
 
299
        if not isinstance(a_bzrdir._format, self.bzrdir._format.__class__):
 
 
300
            # use target default format.
 
 
301
            result = a_bzrdir.create_repository()
 
 
302
        # FIXME RBC 20060209 split out the repository type to avoid this check ?
 
 
303
        elif isinstance(a_bzrdir._format,
 
 
304
                      (bzrdir.BzrDirFormat4,
 
 
305
                       bzrdir.BzrDirFormat5,
 
 
306
                       bzrdir.BzrDirFormat6)):
 
 
307
            result = a_bzrdir.open_repository()
 
 
309
            result = self._format.initialize(a_bzrdir, shared=self.is_shared())
 
 
310
        self.copy_content_into(result, revision_id, basis)
 
 
314
    def has_revision(self, revision_id):
 
 
315
        """True if this repository has a copy of the revision."""
 
 
316
        return self._revision_store.has_revision_id(revision_id,
 
 
317
                                                    self.get_transaction())
 
 
320
    def get_revision_reconcile(self, revision_id):
 
 
321
        """'reconcile' helper routine that allows access to a revision always.
 
 
323
        This variant of get_revision does not cross check the weave graph
 
 
324
        against the revision one as get_revision does: but it should only
 
 
325
        be used by reconcile, or reconcile-alike commands that are correcting
 
 
326
        or testing the revision graph.
 
 
328
        if not revision_id or not isinstance(revision_id, basestring):
 
 
329
            raise errors.InvalidRevisionId(revision_id=revision_id,
 
 
331
        return self._revision_store.get_revisions([revision_id],
 
 
332
                                                  self.get_transaction())[0]
 
 
334
    def get_revisions(self, revision_ids):
 
 
335
        return self._revision_store.get_revisions(revision_ids,
 
 
336
                                                  self.get_transaction())
 
 
339
    def get_revision_xml(self, revision_id):
 
 
340
        rev = self.get_revision(revision_id) 
 
 
342
        # the current serializer..
 
 
343
        self._revision_store._serializer.write_revision(rev, rev_tmp)
 
 
345
        return rev_tmp.getvalue()
 
 
348
    def get_revision(self, revision_id):
 
 
349
        """Return the Revision object for a named revision"""
 
 
350
        r = self.get_revision_reconcile(revision_id)
 
 
351
        # weave corruption can lead to absent revision markers that should be
 
 
353
        # the following test is reasonably cheap (it needs a single weave read)
 
 
354
        # and the weave is cached in read transactions. In write transactions
 
 
355
        # it is not cached but typically we only read a small number of
 
 
356
        # revisions. For knits when they are introduced we will probably want
 
 
357
        # to ensure that caching write transactions are in use.
 
 
358
        inv = self.get_inventory_weave()
 
 
359
        self._check_revision_parents(r, inv)
 
 
363
    def get_deltas_for_revisions(self, revisions):
 
 
364
        """Produce a generator of revision deltas.
 
 
366
        Note that the input is a sequence of REVISIONS, not revision_ids.
 
 
367
        Trees will be held in memory until the generator exits.
 
 
368
        Each delta is relative to the revision's lefthand predecessor.
 
 
370
        required_trees = set()
 
 
371
        for revision in revisions:
 
 
372
            required_trees.add(revision.revision_id)
 
 
373
            required_trees.update(revision.parent_ids[:1])
 
 
374
        trees = dict((t.get_revision_id(), t) for 
 
 
375
                     t in self.revision_trees(required_trees))
 
 
376
        for revision in revisions:
 
 
377
            if not revision.parent_ids:
 
 
378
                old_tree = self.revision_tree(None)
 
 
380
                old_tree = trees[revision.parent_ids[0]]
 
 
381
            yield trees[revision.revision_id].changes_from(old_tree)
 
 
384
    def get_revision_delta(self, revision_id):
 
 
385
        """Return the delta for one revision.
 
 
387
        The delta is relative to the left-hand predecessor of the
 
 
390
        r = self.get_revision(revision_id)
 
 
391
        return list(self.get_deltas_for_revisions([r]))[0]
 
 
393
    def _check_revision_parents(self, revision, inventory):
 
 
394
        """Private to Repository and Fetch.
 
 
396
        This checks the parentage of revision in an inventory weave for 
 
 
397
        consistency and is only applicable to inventory-weave-for-ancestry
 
 
398
        using repository formats & fetchers.
 
 
400
        weave_parents = inventory.get_parents(revision.revision_id)
 
 
401
        weave_names = inventory.versions()
 
 
402
        for parent_id in revision.parent_ids:
 
 
403
            if parent_id in weave_names:
 
 
404
                # this parent must not be a ghost.
 
 
405
                if not parent_id in weave_parents:
 
 
407
                    raise errors.CorruptRepository(self)
 
 
410
    def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
 
 
411
        signature = gpg_strategy.sign(plaintext)
 
 
412
        self._revision_store.add_revision_signature_text(revision_id,
 
 
414
                                                         self.get_transaction())
 
 
416
    def fileids_altered_by_revision_ids(self, revision_ids):
 
 
417
        """Find the file ids and versions affected by revisions.
 
 
419
        :param revisions: an iterable containing revision ids.
 
 
420
        :return: a dictionary mapping altered file-ids to an iterable of
 
 
421
        revision_ids. Each altered file-ids has the exact revision_ids that
 
 
422
        altered it listed explicitly.
 
 
424
        assert self._serializer.support_altered_by_hack, \
 
 
425
            ("fileids_altered_by_revision_ids only supported for branches " 
 
 
426
             "which store inventory as unnested xml, not on %r" % self)
 
 
427
        selected_revision_ids = set(revision_ids)
 
 
428
        w = self.get_inventory_weave()
 
 
431
        # this code needs to read every new line in every inventory for the
 
 
432
        # inventories [revision_ids]. Seeing a line twice is ok. Seeing a line
 
 
433
        # not present in one of those inventories is unnecessary but not 
 
 
434
        # harmful because we are filtering by the revision id marker in the
 
 
435
        # inventory lines : we only select file ids altered in one of those  
 
 
436
        # revisions. We don't need to see all lines in the inventory because
 
 
437
        # only those added in an inventory in rev X can contain a revision=X
 
 
439
        pb = ui.ui_factory.nested_progress_bar()
 
 
441
            for line in w.iter_lines_added_or_present_in_versions(
 
 
442
                selected_revision_ids, pb=pb):
 
 
443
                start = line.find('file_id="')+9
 
 
444
                if start < 9: continue
 
 
445
                end = line.find('"', start)
 
 
447
                file_id = _unescape_xml(line[start:end])
 
 
449
                start = line.find('revision="')+10
 
 
450
                if start < 10: continue
 
 
451
                end = line.find('"', start)
 
 
453
                revision_id = _unescape_xml(line[start:end])
 
 
454
                if revision_id in selected_revision_ids:
 
 
455
                    result.setdefault(file_id, set()).add(revision_id)
 
 
461
    def get_inventory_weave(self):
 
 
462
        return self.control_weaves.get_weave('inventory',
 
 
463
            self.get_transaction())
 
 
466
    def get_inventory(self, revision_id):
 
 
467
        """Get Inventory object by hash."""
 
 
468
        return self.deserialise_inventory(
 
 
469
            revision_id, self.get_inventory_xml(revision_id))
 
 
471
    def deserialise_inventory(self, revision_id, xml):
 
 
472
        """Transform the xml into an inventory object. 
 
 
474
        :param revision_id: The expected revision id of the inventory.
 
 
475
        :param xml: A serialised inventory.
 
 
477
        result = self._serializer.read_inventory_from_string(xml)
 
 
478
        result.root.revision = revision_id
 
 
481
    def serialise_inventory(self, inv):
 
 
482
        return self._serializer.write_inventory_to_string(inv)
 
 
485
    def get_inventory_xml(self, revision_id):
 
 
486
        """Get inventory XML as a file object."""
 
 
488
            assert isinstance(revision_id, basestring), type(revision_id)
 
 
489
            iw = self.get_inventory_weave()
 
 
490
            return iw.get_text(revision_id)
 
 
492
            raise errors.HistoryMissing(self, 'inventory', revision_id)
 
 
495
    def get_inventory_sha1(self, revision_id):
 
 
496
        """Return the sha1 hash of the inventory entry
 
 
498
        return self.get_revision(revision_id).inventory_sha1
 
 
501
    def get_revision_graph(self, revision_id=None):
 
 
502
        """Return a dictionary containing the revision graph.
 
 
504
        :param revision_id: The revision_id to get a graph from. If None, then
 
 
505
        the entire revision graph is returned. This is a deprecated mode of
 
 
506
        operation and will be removed in the future.
 
 
507
        :return: a dictionary of revision_id->revision_parents_list.
 
 
509
        # special case NULL_REVISION
 
 
510
        if revision_id == _mod_revision.NULL_REVISION:
 
 
512
        a_weave = self.get_inventory_weave()
 
 
513
        all_revisions = self._eliminate_revisions_not_present(
 
 
515
        entire_graph = dict([(node, a_weave.get_parents(node)) for 
 
 
516
                             node in all_revisions])
 
 
517
        if revision_id is None:
 
 
519
        elif revision_id not in entire_graph:
 
 
520
            raise errors.NoSuchRevision(self, revision_id)
 
 
522
            # add what can be reached from revision_id
 
 
524
            pending = set([revision_id])
 
 
525
            while len(pending) > 0:
 
 
527
                result[node] = entire_graph[node]
 
 
528
                for revision_id in result[node]:
 
 
529
                    if revision_id not in result:
 
 
530
                        pending.add(revision_id)
 
 
534
    def get_revision_graph_with_ghosts(self, revision_ids=None):
 
 
535
        """Return a graph of the revisions with ghosts marked as applicable.
 
 
537
        :param revision_ids: an iterable of revisions to graph or None for all.
 
 
538
        :return: a Graph object with the graph reachable from revision_ids.
 
 
540
        result = graph.Graph()
 
 
542
            pending = set(self.all_revision_ids())
 
 
545
            pending = set(revision_ids)
 
 
546
            # special case NULL_REVISION
 
 
547
            if _mod_revision.NULL_REVISION in pending:
 
 
548
                pending.remove(_mod_revision.NULL_REVISION)
 
 
549
            required = set(pending)
 
 
552
            revision_id = pending.pop()
 
 
554
                rev = self.get_revision(revision_id)
 
 
555
            except errors.NoSuchRevision:
 
 
556
                if revision_id in required:
 
 
559
                result.add_ghost(revision_id)
 
 
561
            for parent_id in rev.parent_ids:
 
 
562
                # is this queued or done ?
 
 
563
                if (parent_id not in pending and
 
 
564
                    parent_id not in done):
 
 
566
                    pending.add(parent_id)
 
 
567
            result.add_node(revision_id, rev.parent_ids)
 
 
568
            done.add(revision_id)
 
 
572
    def get_revision_inventory(self, revision_id):
 
 
573
        """Return inventory of a past revision."""
 
 
574
        # TODO: Unify this with get_inventory()
 
 
575
        # bzr 0.0.6 and later imposes the constraint that the inventory_id
 
 
576
        # must be the same as its revision, so this is trivial.
 
 
577
        if revision_id is None:
 
 
578
            # This does not make sense: if there is no revision,
 
 
579
            # then it is the current tree inventory surely ?!
 
 
580
            # and thus get_root_id() is something that looks at the last
 
 
581
            # commit on the branch, and the get_root_id is an inventory check.
 
 
582
            raise NotImplementedError
 
 
583
            # return Inventory(self.get_root_id())
 
 
585
            return self.get_inventory(revision_id)
 
 
589
        """Return True if this repository is flagged as a shared repository."""
 
 
590
        raise NotImplementedError(self.is_shared)
 
 
593
    def reconcile(self, other=None, thorough=False):
 
 
594
        """Reconcile this repository."""
 
 
595
        from bzrlib.reconcile import RepoReconciler
 
 
596
        reconciler = RepoReconciler(self, thorough=thorough)
 
 
597
        reconciler.reconcile()
 
 
601
    def revision_tree(self, revision_id):
 
 
602
        """Return Tree for a revision on this branch.
 
 
604
        `revision_id` may be None for the empty tree revision.
 
 
606
        # TODO: refactor this to use an existing revision object
 
 
607
        # so we don't need to read it in twice.
 
 
608
        if revision_id is None or revision_id == _mod_revision.NULL_REVISION:
 
 
609
            return RevisionTree(self, Inventory(root_id=None), 
 
 
610
                                _mod_revision.NULL_REVISION)
 
 
612
            inv = self.get_revision_inventory(revision_id)
 
 
613
            return RevisionTree(self, inv, revision_id)
 
 
616
    def revision_trees(self, revision_ids):
 
 
617
        """Return Tree for a revision on this branch.
 
 
619
        `revision_id` may not be None or 'null:'"""
 
 
620
        assert None not in revision_ids
 
 
621
        assert _mod_revision.NULL_REVISION not in revision_ids
 
 
622
        texts = self.get_inventory_weave().get_texts(revision_ids)
 
 
623
        for text, revision_id in zip(texts, revision_ids):
 
 
624
            inv = self.deserialise_inventory(revision_id, text)
 
 
625
            yield RevisionTree(self, inv, revision_id)
 
 
628
    def get_ancestry(self, revision_id):
 
 
629
        """Return a list of revision-ids integrated by a revision.
 
 
631
        The first element of the list is always None, indicating the origin 
 
 
632
        revision.  This might change when we have history horizons, or 
 
 
633
        perhaps we should have a new API.
 
 
635
        This is topologically sorted.
 
 
637
        if revision_id is None:
 
 
639
        if not self.has_revision(revision_id):
 
 
640
            raise errors.NoSuchRevision(self, revision_id)
 
 
641
        w = self.get_inventory_weave()
 
 
642
        candidates = w.get_ancestry(revision_id)
 
 
643
        return [None] + candidates # self._eliminate_revisions_not_present(candidates)
 
 
646
    def print_file(self, file, revision_id):
 
 
647
        """Print `file` to stdout.
 
 
649
        FIXME RBC 20060125 as John Meinel points out this is a bad api
 
 
650
        - it writes to stdout, it assumes that that is valid etc. Fix
 
 
651
        by creating a new more flexible convenience function.
 
 
653
        tree = self.revision_tree(revision_id)
 
 
654
        # use inventory as it was in that revision
 
 
655
        file_id = tree.inventory.path2id(file)
 
 
657
            # TODO: jam 20060427 Write a test for this code path
 
 
658
            #       it had a bug in it, and was raising the wrong
 
 
660
            raise errors.BzrError("%r is not present in revision %s" % (file, revision_id))
 
 
661
        tree.print_file(file_id)
 
 
663
    def get_transaction(self):
 
 
664
        return self.control_files.get_transaction()
 
 
666
    def revision_parents(self, revid):
 
 
667
        return self.get_inventory_weave().parent_names(revid)
 
 
670
    def set_make_working_trees(self, new_value):
 
 
671
        """Set the policy flag for making working trees when creating branches.
 
 
673
        This only applies to branches that use this repository.
 
 
675
        The default is 'True'.
 
 
676
        :param new_value: True to restore the default, False to disable making
 
 
679
        raise NotImplementedError(self.set_make_working_trees)
 
 
681
    def make_working_trees(self):
 
 
682
        """Returns the policy for making working trees on new branches."""
 
 
683
        raise NotImplementedError(self.make_working_trees)
 
 
686
    def sign_revision(self, revision_id, gpg_strategy):
 
 
687
        plaintext = Testament.from_revision(self, revision_id).as_short_text()
 
 
688
        self.store_revision_signature(gpg_strategy, plaintext, revision_id)
 
 
691
    def has_signature_for_revision_id(self, revision_id):
 
 
692
        """Query for a revision signature for revision_id in the repository."""
 
 
693
        return self._revision_store.has_signature(revision_id,
 
 
694
                                                  self.get_transaction())
 
 
697
    def get_signature_text(self, revision_id):
 
 
698
        """Return the text for a signature."""
 
 
699
        return self._revision_store.get_signature_text(revision_id,
 
 
700
                                                       self.get_transaction())
 
 
703
    def check(self, revision_ids):
 
 
704
        """Check consistency of all history of given revision_ids.
 
 
706
        Different repository implementations should override _check().
 
 
708
        :param revision_ids: A non-empty list of revision_ids whose ancestry
 
 
709
             will be checked.  Typically the last revision_id of a branch.
 
 
712
            raise ValueError("revision_ids must be non-empty in %s.check" 
 
 
714
        return self._check(revision_ids)
 
 
716
    def _check(self, revision_ids):
 
 
717
        result = check.Check(self)
 
 
721
    def _warn_if_deprecated(self):
 
 
722
        global _deprecation_warning_done
 
 
723
        if _deprecation_warning_done:
 
 
725
        _deprecation_warning_done = True
 
 
726
        warning("Format %s for %s is deprecated - please use 'bzr upgrade' to get better performance"
 
 
727
                % (self._format, self.bzrdir.transport.base))
 
 
729
    def supports_rich_root(self):
 
 
730
        return self._format.rich_root_data
 
 
733
class AllInOneRepository(Repository):
 
 
734
    """Legacy support - the repository behaviour for all-in-one branches."""
 
 
736
    def __init__(self, _format, a_bzrdir, _revision_store, control_store, text_store):
 
 
737
        # we reuse one control files instance.
 
 
738
        dir_mode = a_bzrdir._control_files._dir_mode
 
 
739
        file_mode = a_bzrdir._control_files._file_mode
 
 
741
        def get_store(name, compressed=True, prefixed=False):
 
 
742
            # FIXME: This approach of assuming stores are all entirely compressed
 
 
743
            # or entirely uncompressed is tidy, but breaks upgrade from 
 
 
744
            # some existing branches where there's a mixture; we probably 
 
 
745
            # still want the option to look for both.
 
 
746
            relpath = a_bzrdir._control_files._escape(name)
 
 
747
            store = TextStore(a_bzrdir._control_files._transport.clone(relpath),
 
 
748
                              prefixed=prefixed, compressed=compressed,
 
 
751
            #if self._transport.should_cache():
 
 
752
            #    cache_path = os.path.join(self.cache_root, name)
 
 
753
            #    os.mkdir(cache_path)
 
 
754
            #    store = bzrlib.store.CachedStore(store, cache_path)
 
 
757
        # not broken out yet because the controlweaves|inventory_store
 
 
758
        # and text_store | weave_store bits are still different.
 
 
759
        if isinstance(_format, RepositoryFormat4):
 
 
760
            # cannot remove these - there is still no consistent api 
 
 
761
            # which allows access to this old info.
 
 
762
            self.inventory_store = get_store('inventory-store')
 
 
763
            text_store = get_store('text-store')
 
 
764
        super(AllInOneRepository, self).__init__(_format, a_bzrdir, a_bzrdir._control_files, _revision_store, control_store, text_store)
 
 
768
        """AllInOne repositories cannot be shared."""
 
 
772
    def set_make_working_trees(self, new_value):
 
 
773
        """Set the policy flag for making working trees when creating branches.
 
 
775
        This only applies to branches that use this repository.
 
 
777
        The default is 'True'.
 
 
778
        :param new_value: True to restore the default, False to disable making
 
 
781
        raise NotImplementedError(self.set_make_working_trees)
 
 
783
    def make_working_trees(self):
 
 
784
        """Returns the policy for making working trees on new branches."""
 
 
788
def install_revision(repository, rev, revision_tree):
 
 
789
    """Install all revision data into a repository."""
 
 
792
    for p_id in rev.parent_ids:
 
 
793
        if repository.has_revision(p_id):
 
 
794
            present_parents.append(p_id)
 
 
795
            parent_trees[p_id] = repository.revision_tree(p_id)
 
 
797
            parent_trees[p_id] = repository.revision_tree(None)
 
 
799
    inv = revision_tree.inventory
 
 
800
    entries = inv.iter_entries()
 
 
801
    # backwards compatability hack: skip the root id.
 
 
802
    if not repository.supports_rich_root():
 
 
803
        path, root = entries.next()
 
 
804
        if root.revision != rev.revision_id:
 
 
805
            raise errors.IncompatibleRevision(repr(repository))
 
 
806
    # Add the texts that are not already present
 
 
807
    for path, ie in entries:
 
 
808
        w = repository.weave_store.get_weave_or_empty(ie.file_id,
 
 
809
                repository.get_transaction())
 
 
810
        if ie.revision not in w:
 
 
812
            # FIXME: TODO: The following loop *may* be overlapping/duplicate
 
 
813
            # with InventoryEntry.find_previous_heads(). if it is, then there
 
 
814
            # is a latent bug here where the parents may have ancestors of each
 
 
816
            for revision, tree in parent_trees.iteritems():
 
 
817
                if ie.file_id not in tree:
 
 
819
                parent_id = tree.inventory[ie.file_id].revision
 
 
820
                if parent_id in text_parents:
 
 
822
                text_parents.append(parent_id)
 
 
824
            vfile = repository.weave_store.get_weave_or_empty(ie.file_id, 
 
 
825
                repository.get_transaction())
 
 
826
            lines = revision_tree.get_file(ie.file_id).readlines()
 
 
827
            vfile.add_lines(rev.revision_id, text_parents, lines)
 
 
829
        # install the inventory
 
 
830
        repository.add_inventory(rev.revision_id, inv, present_parents)
 
 
831
    except errors.RevisionAlreadyPresent:
 
 
833
    repository.add_revision(rev.revision_id, rev, inv)
 
 
836
class MetaDirRepository(Repository):
 
 
837
    """Repositories in the new meta-dir layout."""
 
 
839
    def __init__(self, _format, a_bzrdir, control_files, _revision_store, control_store, text_store):
 
 
840
        super(MetaDirRepository, self).__init__(_format,
 
 
846
        dir_mode = self.control_files._dir_mode
 
 
847
        file_mode = self.control_files._file_mode
 
 
851
        """Return True if this repository is flagged as a shared repository."""
 
 
852
        return self.control_files._transport.has('shared-storage')
 
 
855
    def set_make_working_trees(self, new_value):
 
 
856
        """Set the policy flag for making working trees when creating branches.
 
 
858
        This only applies to branches that use this repository.
 
 
860
        The default is 'True'.
 
 
861
        :param new_value: True to restore the default, False to disable making
 
 
866
                self.control_files._transport.delete('no-working-trees')
 
 
867
            except errors.NoSuchFile:
 
 
870
            self.control_files.put_utf8('no-working-trees', '')
 
 
872
    def make_working_trees(self):
 
 
873
        """Returns the policy for making working trees on new branches."""
 
 
874
        return not self.control_files._transport.has('no-working-trees')
 
 
877
class KnitRepository(MetaDirRepository):
 
 
878
    """Knit format repository."""
 
 
880
    def _warn_if_deprecated(self):
 
 
881
        # This class isn't deprecated
 
 
884
    def _inventory_add_lines(self, inv_vf, revid, parents, lines):
 
 
885
        inv_vf.add_lines_with_ghosts(revid, parents, lines)
 
 
888
    def _all_revision_ids(self):
 
 
889
        """See Repository.all_revision_ids()."""
 
 
890
        # Knits get the revision graph from the index of the revision knit, so
 
 
891
        # it's always possible even if they're on an unlistable transport.
 
 
892
        return self._revision_store.all_revision_ids(self.get_transaction())
 
 
894
    def fileid_involved_between_revs(self, from_revid, to_revid):
 
 
895
        """Find file_id(s) which are involved in the changes between revisions.
 
 
897
        This determines the set of revisions which are involved, and then
 
 
898
        finds all file ids affected by those revisions.
 
 
900
        vf = self._get_revision_vf()
 
 
901
        from_set = set(vf.get_ancestry(from_revid))
 
 
902
        to_set = set(vf.get_ancestry(to_revid))
 
 
903
        changed = to_set.difference(from_set)
 
 
904
        return self._fileid_involved_by_set(changed)
 
 
906
    def fileid_involved(self, last_revid=None):
 
 
907
        """Find all file_ids modified in the ancestry of last_revid.
 
 
909
        :param last_revid: If None, last_revision() will be used.
 
 
912
            changed = set(self.all_revision_ids())
 
 
914
            changed = set(self.get_ancestry(last_revid))
 
 
917
        return self._fileid_involved_by_set(changed)
 
 
920
    def get_ancestry(self, revision_id):
 
 
921
        """Return a list of revision-ids integrated by a revision.
 
 
923
        This is topologically sorted.
 
 
925
        if revision_id is None:
 
 
927
        vf = self._get_revision_vf()
 
 
929
            return [None] + vf.get_ancestry(revision_id)
 
 
930
        except errors.RevisionNotPresent:
 
 
931
            raise errors.NoSuchRevision(self, revision_id)
 
 
934
    def get_revision(self, revision_id):
 
 
935
        """Return the Revision object for a named revision"""
 
 
936
        return self.get_revision_reconcile(revision_id)
 
 
939
    def get_revision_graph(self, revision_id=None):
 
 
940
        """Return a dictionary containing the revision graph.
 
 
942
        :param revision_id: The revision_id to get a graph from. If None, then
 
 
943
        the entire revision graph is returned. This is a deprecated mode of
 
 
944
        operation and will be removed in the future.
 
 
945
        :return: a dictionary of revision_id->revision_parents_list.
 
 
947
        # special case NULL_REVISION
 
 
948
        if revision_id == _mod_revision.NULL_REVISION:
 
 
950
        a_weave = self._get_revision_vf()
 
 
951
        entire_graph = a_weave.get_graph()
 
 
952
        if revision_id is None:
 
 
953
            return a_weave.get_graph()
 
 
954
        elif revision_id not in a_weave:
 
 
955
            raise errors.NoSuchRevision(self, revision_id)
 
 
957
            # add what can be reached from revision_id
 
 
959
            pending = set([revision_id])
 
 
960
            while len(pending) > 0:
 
 
962
                result[node] = a_weave.get_parents(node)
 
 
963
                for revision_id in result[node]:
 
 
964
                    if revision_id not in result:
 
 
965
                        pending.add(revision_id)
 
 
969
    def get_revision_graph_with_ghosts(self, revision_ids=None):
 
 
970
        """Return a graph of the revisions with ghosts marked as applicable.
 
 
972
        :param revision_ids: an iterable of revisions to graph or None for all.
 
 
973
        :return: a Graph object with the graph reachable from revision_ids.
 
 
975
        result = graph.Graph()
 
 
976
        vf = self._get_revision_vf()
 
 
977
        versions = set(vf.versions())
 
 
979
            pending = set(self.all_revision_ids())
 
 
982
            pending = set(revision_ids)
 
 
983
            # special case NULL_REVISION
 
 
984
            if _mod_revision.NULL_REVISION in pending:
 
 
985
                pending.remove(_mod_revision.NULL_REVISION)
 
 
986
            required = set(pending)
 
 
989
            revision_id = pending.pop()
 
 
990
            if not revision_id in versions:
 
 
991
                if revision_id in required:
 
 
992
                    raise errors.NoSuchRevision(self, revision_id)
 
 
994
                result.add_ghost(revision_id)
 
 
995
                # mark it as done so we don't try for it again.
 
 
996
                done.add(revision_id)
 
 
998
            parent_ids = vf.get_parents_with_ghosts(revision_id)
 
 
999
            for parent_id in parent_ids:
 
 
1000
                # is this queued or done ?
 
 
1001
                if (parent_id not in pending and
 
 
1002
                    parent_id not in done):
 
 
1004
                    pending.add(parent_id)
 
 
1005
            result.add_node(revision_id, parent_ids)
 
 
1006
            done.add(revision_id)
 
 
1009
    def _get_revision_vf(self):
 
 
1010
        """:return: a versioned file containing the revisions."""
 
 
1011
        vf = self._revision_store.get_revision_file(self.get_transaction())
 
 
1015
    def reconcile(self, other=None, thorough=False):
 
 
1016
        """Reconcile this repository."""
 
 
1017
        from bzrlib.reconcile import KnitReconciler
 
 
1018
        reconciler = KnitReconciler(self, thorough=thorough)
 
 
1019
        reconciler.reconcile()
 
 
1022
    def revision_parents(self, revision_id):
 
 
1023
        return self._get_revision_vf().get_parents(revision_id)
 
 
1026
class KnitRepository2(KnitRepository):
 
 
1028
    def __init__(self, _format, a_bzrdir, control_files, _revision_store,
 
 
1029
                 control_store, text_store):
 
 
1030
        KnitRepository.__init__(self, _format, a_bzrdir, control_files,
 
 
1031
                              _revision_store, control_store, text_store)
 
 
1032
        self._serializer = xml6.serializer_v6
 
 
1034
    def deserialise_inventory(self, revision_id, xml):
 
 
1035
        """Transform the xml into an inventory object. 
 
 
1037
        :param revision_id: The expected revision id of the inventory.
 
 
1038
        :param xml: A serialised inventory.
 
 
1040
        result = self._serializer.read_inventory_from_string(xml)
 
 
1041
        assert result.root.revision is not None
 
 
1044
    def serialise_inventory(self, inv):
 
 
1045
        """Transform the inventory object into XML text.
 
 
1047
        :param revision_id: The expected revision id of the inventory.
 
 
1048
        :param xml: A serialised inventory.
 
 
1050
        assert inv.revision_id is not None
 
 
1051
        assert inv.root.revision is not None
 
 
1052
        return KnitRepository.serialise_inventory(self, inv)
 
 
1054
    def get_commit_builder(self, branch, parents, config, timestamp=None, 
 
 
1055
                           timezone=None, committer=None, revprops=None, 
 
 
1057
        """Obtain a CommitBuilder for this repository.
 
 
1059
        :param branch: Branch to commit to.
 
 
1060
        :param parents: Revision ids of the parents of the new revision.
 
 
1061
        :param config: Configuration to use.
 
 
1062
        :param timestamp: Optional timestamp recorded for commit.
 
 
1063
        :param timezone: Optional timezone for timestamp.
 
 
1064
        :param committer: Optional committer to set for commit.
 
 
1065
        :param revprops: Optional dictionary of revision properties.
 
 
1066
        :param revision_id: Optional revision id.
 
 
1068
        return RootCommitBuilder(self, parents, config, timestamp, timezone,
 
 
1069
                                 committer, revprops, revision_id)
 
 
1072
class RepositoryFormat(object):
 
 
1073
    """A repository format.
 
 
1075
    Formats provide three things:
 
 
1076
     * An initialization routine to construct repository data on disk.
 
 
1077
     * a format string which is used when the BzrDir supports versioned
 
 
1079
     * an open routine which returns a Repository instance.
 
 
1081
    Formats are placed in an dict by their format string for reference 
 
 
1082
    during opening. These should be subclasses of RepositoryFormat
 
 
1085
    Once a format is deprecated, just deprecate the initialize and open
 
 
1086
    methods on the format class. Do not deprecate the object, as the 
 
 
1087
    object will be created every system load.
 
 
1089
    Common instance attributes:
 
 
1090
    _matchingbzrdir - the bzrdir format that the repository format was
 
 
1091
    originally written to work with. This can be used if manually
 
 
1092
    constructing a bzrdir and repository, or more commonly for test suite
 
 
1096
    _default_format = None
 
 
1097
    """The default format used for new repositories."""
 
 
1100
    """The known formats."""
 
 
1103
        return "<%s>" % self.__class__.__name__
 
 
1106
    def find_format(klass, a_bzrdir):
 
 
1107
        """Return the format for the repository object in a_bzrdir."""
 
 
1109
            transport = a_bzrdir.get_repository_transport(None)
 
 
1110
            format_string = transport.get("format").read()
 
 
1111
            return klass._formats[format_string]
 
 
1112
        except errors.NoSuchFile:
 
 
1113
            raise errors.NoRepositoryPresent(a_bzrdir)
 
 
1115
            raise errors.UnknownFormatError(format=format_string)
 
 
1117
    def _get_control_store(self, repo_transport, control_files):
 
 
1118
        """Return the control store for this repository."""
 
 
1119
        raise NotImplementedError(self._get_control_store)
 
 
1122
    def get_default_format(klass):
 
 
1123
        """Return the current default format."""
 
 
1124
        return klass._default_format
 
 
1126
    def get_format_string(self):
 
 
1127
        """Return the ASCII format string that identifies this format.
 
 
1129
        Note that in pre format ?? repositories the format string is 
 
 
1130
        not permitted nor written to disk.
 
 
1132
        raise NotImplementedError(self.get_format_string)
 
 
1134
    def get_format_description(self):
 
 
1135
        """Return the short description for this format."""
 
 
1136
        raise NotImplementedError(self.get_format_description)
 
 
1138
    def _get_revision_store(self, repo_transport, control_files):
 
 
1139
        """Return the revision store object for this a_bzrdir."""
 
 
1140
        raise NotImplementedError(self._get_revision_store)
 
 
1142
    def _get_text_rev_store(self,
 
 
1149
        """Common logic for getting a revision store for a repository.
 
 
1151
        see self._get_revision_store for the subclass-overridable method to 
 
 
1152
        get the store for a repository.
 
 
1154
        from bzrlib.store.revision.text import TextRevisionStore
 
 
1155
        dir_mode = control_files._dir_mode
 
 
1156
        file_mode = control_files._file_mode
 
 
1157
        text_store =TextStore(transport.clone(name),
 
 
1159
                              compressed=compressed,
 
 
1161
                              file_mode=file_mode)
 
 
1162
        _revision_store = TextRevisionStore(text_store, serializer)
 
 
1163
        return _revision_store
 
 
1165
    def _get_versioned_file_store(self,
 
 
1170
                                  versionedfile_class=weave.WeaveFile,
 
 
1171
                                  versionedfile_kwargs={},
 
 
1173
        weave_transport = control_files._transport.clone(name)
 
 
1174
        dir_mode = control_files._dir_mode
 
 
1175
        file_mode = control_files._file_mode
 
 
1176
        return VersionedFileStore(weave_transport, prefixed=prefixed,
 
 
1178
                                  file_mode=file_mode,
 
 
1179
                                  versionedfile_class=versionedfile_class,
 
 
1180
                                  versionedfile_kwargs=versionedfile_kwargs,
 
 
1183
    def initialize(self, a_bzrdir, shared=False):
 
 
1184
        """Initialize a repository of this format in a_bzrdir.
 
 
1186
        :param a_bzrdir: The bzrdir to put the new repository in it.
 
 
1187
        :param shared: The repository should be initialized as a sharable one.
 
 
1189
        This may raise UninitializableFormat if shared repository are not
 
 
1190
        compatible the a_bzrdir.
 
 
1193
    def is_supported(self):
 
 
1194
        """Is this format supported?
 
 
1196
        Supported formats must be initializable and openable.
 
 
1197
        Unsupported formats may not support initialization or committing or 
 
 
1198
        some other features depending on the reason for not being supported.
 
 
1202
    def check_conversion_target(self, target_format):
 
 
1203
        raise NotImplementedError(self.check_conversion_target)
 
 
1205
    def open(self, a_bzrdir, _found=False):
 
 
1206
        """Return an instance of this format for the bzrdir a_bzrdir.
 
 
1208
        _found is a private parameter, do not use it.
 
 
1210
        raise NotImplementedError(self.open)
 
 
1213
    def register_format(klass, format):
 
 
1214
        klass._formats[format.get_format_string()] = format
 
 
1217
    def set_default_format(klass, format):
 
 
1218
        klass._default_format = format
 
 
1221
    def unregister_format(klass, format):
 
 
1222
        assert klass._formats[format.get_format_string()] is format
 
 
1223
        del klass._formats[format.get_format_string()]
 
 
1226
class PreSplitOutRepositoryFormat(RepositoryFormat):
 
 
1227
    """Base class for the pre split out repository formats."""
 
 
1229
    rich_root_data = False
 
 
1231
    def initialize(self, a_bzrdir, shared=False, _internal=False):
 
 
1232
        """Create a weave repository.
 
 
1234
        TODO: when creating split out bzr branch formats, move this to a common
 
 
1235
        base for Format5, Format6. or something like that.
 
 
1238
            raise errors.IncompatibleFormat(self, a_bzrdir._format)
 
 
1241
            # always initialized when the bzrdir is.
 
 
1242
            return self.open(a_bzrdir, _found=True)
 
 
1244
        # Create an empty weave
 
 
1246
        weavefile.write_weave_v5(weave.Weave(), sio)
 
 
1247
        empty_weave = sio.getvalue()
 
 
1249
        mutter('creating repository in %s.', a_bzrdir.transport.base)
 
 
1250
        dirs = ['revision-store', 'weaves']
 
 
1251
        files = [('inventory.weave', StringIO(empty_weave)),
 
 
1254
        # FIXME: RBC 20060125 don't peek under the covers
 
 
1255
        # NB: no need to escape relative paths that are url safe.
 
 
1256
        control_files = lockable_files.LockableFiles(a_bzrdir.transport,
 
 
1257
                                'branch-lock', lockable_files.TransportLock)
 
 
1258
        control_files.create_lock()
 
 
1259
        control_files.lock_write()
 
 
1260
        control_files._transport.mkdir_multi(dirs,
 
 
1261
                mode=control_files._dir_mode)
 
 
1263
            for file, content in files:
 
 
1264
                control_files.put(file, content)
 
 
1266
            control_files.unlock()
 
 
1267
        return self.open(a_bzrdir, _found=True)
 
 
1269
    def _get_control_store(self, repo_transport, control_files):
 
 
1270
        """Return the control store for this repository."""
 
 
1271
        return self._get_versioned_file_store('',
 
 
1276
    def _get_text_store(self, transport, control_files):
 
 
1277
        """Get a store for file texts for this format."""
 
 
1278
        raise NotImplementedError(self._get_text_store)
 
 
1280
    def open(self, a_bzrdir, _found=False):
 
 
1281
        """See RepositoryFormat.open()."""
 
 
1283
            # we are being called directly and must probe.
 
 
1284
            raise NotImplementedError
 
 
1286
        repo_transport = a_bzrdir.get_repository_transport(None)
 
 
1287
        control_files = a_bzrdir._control_files
 
 
1288
        text_store = self._get_text_store(repo_transport, control_files)
 
 
1289
        control_store = self._get_control_store(repo_transport, control_files)
 
 
1290
        _revision_store = self._get_revision_store(repo_transport, control_files)
 
 
1291
        return AllInOneRepository(_format=self,
 
 
1293
                                  _revision_store=_revision_store,
 
 
1294
                                  control_store=control_store,
 
 
1295
                                  text_store=text_store)
 
 
1297
    def check_conversion_target(self, target_format):
 
 
1301
class RepositoryFormat4(PreSplitOutRepositoryFormat):
 
 
1302
    """Bzr repository format 4.
 
 
1304
    This repository format has:
 
 
1306
     - TextStores for texts, inventories,revisions.
 
 
1308
    This format is deprecated: it indexes texts using a text id which is
 
 
1309
    removed in format 5; initialization and write support for this format
 
 
1314
        super(RepositoryFormat4, self).__init__()
 
 
1315
        self._matchingbzrdir = bzrdir.BzrDirFormat4()
 
 
1317
    def get_format_description(self):
 
 
1318
        """See RepositoryFormat.get_format_description()."""
 
 
1319
        return "Repository format 4"
 
 
1321
    def initialize(self, url, shared=False, _internal=False):
 
 
1322
        """Format 4 branches cannot be created."""
 
 
1323
        raise errors.UninitializableFormat(self)
 
 
1325
    def is_supported(self):
 
 
1326
        """Format 4 is not supported.
 
 
1328
        It is not supported because the model changed from 4 to 5 and the
 
 
1329
        conversion logic is expensive - so doing it on the fly was not 
 
 
1334
    def _get_control_store(self, repo_transport, control_files):
 
 
1335
        """Format 4 repositories have no formal control store at this point.
 
 
1337
        This will cause any control-file-needing apis to fail - this is desired.
 
 
1341
    def _get_revision_store(self, repo_transport, control_files):
 
 
1342
        """See RepositoryFormat._get_revision_store()."""
 
 
1343
        from bzrlib.xml4 import serializer_v4
 
 
1344
        return self._get_text_rev_store(repo_transport,
 
 
1347
                                        serializer=serializer_v4)
 
 
1349
    def _get_text_store(self, transport, control_files):
 
 
1350
        """See RepositoryFormat._get_text_store()."""
 
 
1353
class RepositoryFormat5(PreSplitOutRepositoryFormat):
 
 
1354
    """Bzr control format 5.
 
 
1356
    This repository format has:
 
 
1357
     - weaves for file texts and inventory
 
 
1359
     - TextStores for revisions and signatures.
 
 
1363
        super(RepositoryFormat5, self).__init__()
 
 
1364
        self._matchingbzrdir = bzrdir.BzrDirFormat5()
 
 
1366
    def get_format_description(self):
 
 
1367
        """See RepositoryFormat.get_format_description()."""
 
 
1368
        return "Weave repository format 5"
 
 
1370
    def _get_revision_store(self, repo_transport, control_files):
 
 
1371
        """See RepositoryFormat._get_revision_store()."""
 
 
1372
        """Return the revision store object for this a_bzrdir."""
 
 
1373
        return self._get_text_rev_store(repo_transport,
 
 
1378
    def _get_text_store(self, transport, control_files):
 
 
1379
        """See RepositoryFormat._get_text_store()."""
 
 
1380
        return self._get_versioned_file_store('weaves', transport, control_files, prefixed=False)
 
 
1383
class RepositoryFormat6(PreSplitOutRepositoryFormat):
 
 
1384
    """Bzr control format 6.
 
 
1386
    This repository format has:
 
 
1387
     - weaves for file texts and inventory
 
 
1388
     - hash subdirectory based stores.
 
 
1389
     - TextStores for revisions and signatures.
 
 
1393
        super(RepositoryFormat6, self).__init__()
 
 
1394
        self._matchingbzrdir = bzrdir.BzrDirFormat6()
 
 
1396
    def get_format_description(self):
 
 
1397
        """See RepositoryFormat.get_format_description()."""
 
 
1398
        return "Weave repository format 6"
 
 
1400
    def _get_revision_store(self, repo_transport, control_files):
 
 
1401
        """See RepositoryFormat._get_revision_store()."""
 
 
1402
        return self._get_text_rev_store(repo_transport,
 
 
1408
    def _get_text_store(self, transport, control_files):
 
 
1409
        """See RepositoryFormat._get_text_store()."""
 
 
1410
        return self._get_versioned_file_store('weaves', transport, control_files)
 
 
1413
class MetaDirRepositoryFormat(RepositoryFormat):
 
 
1414
    """Common base class for the new repositories using the metadir layout."""
 
 
1416
    rich_root_data = False
 
 
1419
        super(MetaDirRepositoryFormat, self).__init__()
 
 
1420
        self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
 
 
1422
    def _create_control_files(self, a_bzrdir):
 
 
1423
        """Create the required files and the initial control_files object."""
 
 
1424
        # FIXME: RBC 20060125 don't peek under the covers
 
 
1425
        # NB: no need to escape relative paths that are url safe.
 
 
1426
        repository_transport = a_bzrdir.get_repository_transport(self)
 
 
1427
        control_files = lockable_files.LockableFiles(repository_transport,
 
 
1428
                                'lock', lockdir.LockDir)
 
 
1429
        control_files.create_lock()
 
 
1430
        return control_files
 
 
1432
    def _upload_blank_content(self, a_bzrdir, dirs, files, utf8_files, shared):
 
 
1433
        """Upload the initial blank content."""
 
 
1434
        control_files = self._create_control_files(a_bzrdir)
 
 
1435
        control_files.lock_write()
 
 
1437
            control_files._transport.mkdir_multi(dirs,
 
 
1438
                    mode=control_files._dir_mode)
 
 
1439
            for file, content in files:
 
 
1440
                control_files.put(file, content)
 
 
1441
            for file, content in utf8_files:
 
 
1442
                control_files.put_utf8(file, content)
 
 
1444
                control_files.put_utf8('shared-storage', '')
 
 
1446
            control_files.unlock()
 
 
1449
class RepositoryFormat7(MetaDirRepositoryFormat):
 
 
1450
    """Bzr repository 7.
 
 
1452
    This repository format has:
 
 
1453
     - weaves for file texts and inventory
 
 
1454
     - hash subdirectory based stores.
 
 
1455
     - TextStores for revisions and signatures.
 
 
1456
     - a format marker of its own
 
 
1457
     - an optional 'shared-storage' flag
 
 
1458
     - an optional 'no-working-trees' flag
 
 
1461
    def _get_control_store(self, repo_transport, control_files):
 
 
1462
        """Return the control store for this repository."""
 
 
1463
        return self._get_versioned_file_store('',
 
 
1468
    def get_format_string(self):
 
 
1469
        """See RepositoryFormat.get_format_string()."""
 
 
1470
        return "Bazaar-NG Repository format 7"
 
 
1472
    def get_format_description(self):
 
 
1473
        """See RepositoryFormat.get_format_description()."""
 
 
1474
        return "Weave repository format 7"
 
 
1476
    def check_conversion_target(self, target_format):
 
 
1479
    def _get_revision_store(self, repo_transport, control_files):
 
 
1480
        """See RepositoryFormat._get_revision_store()."""
 
 
1481
        return self._get_text_rev_store(repo_transport,
 
 
1488
    def _get_text_store(self, transport, control_files):
 
 
1489
        """See RepositoryFormat._get_text_store()."""
 
 
1490
        return self._get_versioned_file_store('weaves',
 
 
1494
    def initialize(self, a_bzrdir, shared=False):
 
 
1495
        """Create a weave repository.
 
 
1497
        :param shared: If true the repository will be initialized as a shared
 
 
1500
        # Create an empty weave
 
 
1502
        weavefile.write_weave_v5(weave.Weave(), sio)
 
 
1503
        empty_weave = sio.getvalue()
 
 
1505
        mutter('creating repository in %s.', a_bzrdir.transport.base)
 
 
1506
        dirs = ['revision-store', 'weaves']
 
 
1507
        files = [('inventory.weave', StringIO(empty_weave)), 
 
 
1509
        utf8_files = [('format', self.get_format_string())]
 
 
1511
        self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
 
 
1512
        return self.open(a_bzrdir=a_bzrdir, _found=True)
 
 
1514
    def open(self, a_bzrdir, _found=False, _override_transport=None):
 
 
1515
        """See RepositoryFormat.open().
 
 
1517
        :param _override_transport: INTERNAL USE ONLY. Allows opening the
 
 
1518
                                    repository at a slightly different url
 
 
1519
                                    than normal. I.e. during 'upgrade'.
 
 
1522
            format = RepositoryFormat.find_format(a_bzrdir)
 
 
1523
            assert format.__class__ ==  self.__class__
 
 
1524
        if _override_transport is not None:
 
 
1525
            repo_transport = _override_transport
 
 
1527
            repo_transport = a_bzrdir.get_repository_transport(None)
 
 
1528
        control_files = lockable_files.LockableFiles(repo_transport,
 
 
1529
                                'lock', lockdir.LockDir)
 
 
1530
        text_store = self._get_text_store(repo_transport, control_files)
 
 
1531
        control_store = self._get_control_store(repo_transport, control_files)
 
 
1532
        _revision_store = self._get_revision_store(repo_transport, control_files)
 
 
1533
        return MetaDirRepository(_format=self,
 
 
1535
                                 control_files=control_files,
 
 
1536
                                 _revision_store=_revision_store,
 
 
1537
                                 control_store=control_store,
 
 
1538
                                 text_store=text_store)
 
 
1541
class RepositoryFormatKnit(MetaDirRepositoryFormat):
 
 
1542
    """Bzr repository knit format (generalized). 
 
 
1544
    This repository format has:
 
 
1545
     - knits for file texts and inventory
 
 
1546
     - hash subdirectory based stores.
 
 
1547
     - knits for revisions and signatures
 
 
1548
     - TextStores for revisions and signatures.
 
 
1549
     - a format marker of its own
 
 
1550
     - an optional 'shared-storage' flag
 
 
1551
     - an optional 'no-working-trees' flag
 
 
1555
    def _get_control_store(self, repo_transport, control_files):
 
 
1556
        """Return the control store for this repository."""
 
 
1557
        return VersionedFileStore(
 
 
1560
            file_mode=control_files._file_mode,
 
 
1561
            versionedfile_class=knit.KnitVersionedFile,
 
 
1562
            versionedfile_kwargs={'factory':knit.KnitPlainFactory()},
 
 
1565
    def _get_revision_store(self, repo_transport, control_files):
 
 
1566
        """See RepositoryFormat._get_revision_store()."""
 
 
1567
        from bzrlib.store.revision.knit import KnitRevisionStore
 
 
1568
        versioned_file_store = VersionedFileStore(
 
 
1570
            file_mode=control_files._file_mode,
 
 
1573
            versionedfile_class=knit.KnitVersionedFile,
 
 
1574
            versionedfile_kwargs={'delta':False,
 
 
1575
                                  'factory':knit.KnitPlainFactory(),
 
 
1579
        return KnitRevisionStore(versioned_file_store)
 
 
1581
    def _get_text_store(self, transport, control_files):
 
 
1582
        """See RepositoryFormat._get_text_store()."""
 
 
1583
        return self._get_versioned_file_store('knits',
 
 
1586
                                  versionedfile_class=knit.KnitVersionedFile,
 
 
1587
                                  versionedfile_kwargs={
 
 
1588
                                      'create_parent_dir':True,
 
 
1589
                                      'delay_create':True,
 
 
1590
                                      'dir_mode':control_files._dir_mode,
 
 
1594
    def initialize(self, a_bzrdir, shared=False):
 
 
1595
        """Create a knit format 1 repository.
 
 
1597
        :param a_bzrdir: bzrdir to contain the new repository; must already
 
 
1599
        :param shared: If true the repository will be initialized as a shared
 
 
1602
        mutter('creating repository in %s.', a_bzrdir.transport.base)
 
 
1603
        dirs = ['revision-store', 'knits']
 
 
1605
        utf8_files = [('format', self.get_format_string())]
 
 
1607
        self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
 
 
1608
        repo_transport = a_bzrdir.get_repository_transport(None)
 
 
1609
        control_files = lockable_files.LockableFiles(repo_transport,
 
 
1610
                                'lock', lockdir.LockDir)
 
 
1611
        control_store = self._get_control_store(repo_transport, control_files)
 
 
1612
        transaction = transactions.WriteTransaction()
 
 
1613
        # trigger a write of the inventory store.
 
 
1614
        control_store.get_weave_or_empty('inventory', transaction)
 
 
1615
        _revision_store = self._get_revision_store(repo_transport, control_files)
 
 
1616
        _revision_store.has_revision_id('A', transaction)
 
 
1617
        _revision_store.get_signature_file(transaction)
 
 
1618
        return self.open(a_bzrdir=a_bzrdir, _found=True)
 
 
1620
    def open(self, a_bzrdir, _found=False, _override_transport=None):
 
 
1621
        """See RepositoryFormat.open().
 
 
1623
        :param _override_transport: INTERNAL USE ONLY. Allows opening the
 
 
1624
                                    repository at a slightly different url
 
 
1625
                                    than normal. I.e. during 'upgrade'.
 
 
1628
            format = RepositoryFormat.find_format(a_bzrdir)
 
 
1629
            assert format.__class__ ==  self.__class__
 
 
1630
        if _override_transport is not None:
 
 
1631
            repo_transport = _override_transport
 
 
1633
            repo_transport = a_bzrdir.get_repository_transport(None)
 
 
1634
        control_files = lockable_files.LockableFiles(repo_transport,
 
 
1635
                                'lock', lockdir.LockDir)
 
 
1636
        text_store = self._get_text_store(repo_transport, control_files)
 
 
1637
        control_store = self._get_control_store(repo_transport, control_files)
 
 
1638
        _revision_store = self._get_revision_store(repo_transport, control_files)
 
 
1639
        return KnitRepository(_format=self,
 
 
1641
                              control_files=control_files,
 
 
1642
                              _revision_store=_revision_store,
 
 
1643
                              control_store=control_store,
 
 
1644
                              text_store=text_store)
 
 
1647
class RepositoryFormatKnit1(RepositoryFormatKnit):
 
 
1648
    """Bzr repository knit format 1.
 
 
1650
    This repository format has:
 
 
1651
     - knits for file texts and inventory
 
 
1652
     - hash subdirectory based stores.
 
 
1653
     - knits for revisions and signatures
 
 
1654
     - TextStores for revisions and signatures.
 
 
1655
     - a format marker of its own
 
 
1656
     - an optional 'shared-storage' flag
 
 
1657
     - an optional 'no-working-trees' flag
 
 
1660
    This format was introduced in bzr 0.8.
 
 
1662
    def get_format_string(self):
 
 
1663
        """See RepositoryFormat.get_format_string()."""
 
 
1664
        return "Bazaar-NG Knit Repository Format 1"
 
 
1666
    def get_format_description(self):
 
 
1667
        """See RepositoryFormat.get_format_description()."""
 
 
1668
        return "Knit repository format 1"
 
 
1670
    def check_conversion_target(self, target_format):
 
 
1674
class RepositoryFormatKnit2(RepositoryFormatKnit):
 
 
1675
    """Bzr repository knit format 2.
 
 
1677
    THIS FORMAT IS EXPERIMENTAL
 
 
1678
    This repository format has:
 
 
1679
     - knits for file texts and inventory
 
 
1680
     - hash subdirectory based stores.
 
 
1681
     - knits for revisions and signatures
 
 
1682
     - TextStores for revisions and signatures.
 
 
1683
     - a format marker of its own
 
 
1684
     - an optional 'shared-storage' flag
 
 
1685
     - an optional 'no-working-trees' flag
 
 
1687
     - Support for recording full info about the tree root
 
 
1691
    rich_root_data = True
 
 
1693
    def get_format_string(self):
 
 
1694
        """See RepositoryFormat.get_format_string()."""
 
 
1695
        return "Bazaar Knit Repository Format 2\n"
 
 
1697
    def get_format_description(self):
 
 
1698
        """See RepositoryFormat.get_format_description()."""
 
 
1699
        return "Knit repository format 2"
 
 
1701
    def check_conversion_target(self, target_format):
 
 
1702
        if not target_format.rich_root_data:
 
 
1703
            raise errors.BadConversionTarget(
 
 
1704
                'Does not support rich root data.', target_format)
 
 
1706
    def open(self, a_bzrdir, _found=False, _override_transport=None):
 
 
1707
        """See RepositoryFormat.open().
 
 
1709
        :param _override_transport: INTERNAL USE ONLY. Allows opening the
 
 
1710
                                    repository at a slightly different url
 
 
1711
                                    than normal. I.e. during 'upgrade'.
 
 
1714
            format = RepositoryFormat.find_format(a_bzrdir)
 
 
1715
            assert format.__class__ ==  self.__class__
 
 
1716
        if _override_transport is not None:
 
 
1717
            repo_transport = _override_transport
 
 
1719
            repo_transport = a_bzrdir.get_repository_transport(None)
 
 
1720
        control_files = lockable_files.LockableFiles(repo_transport, 'lock',
 
 
1722
        text_store = self._get_text_store(repo_transport, control_files)
 
 
1723
        control_store = self._get_control_store(repo_transport, control_files)
 
 
1724
        _revision_store = self._get_revision_store(repo_transport, control_files)
 
 
1725
        return KnitRepository2(_format=self,
 
 
1727
                               control_files=control_files,
 
 
1728
                               _revision_store=_revision_store,
 
 
1729
                               control_store=control_store,
 
 
1730
                               text_store=text_store)
 
 
1734
# formats which have no format string are not discoverable
 
 
1735
# and not independently creatable, so are not registered.
 
 
1736
RepositoryFormat.register_format(RepositoryFormat7())
 
 
1737
_default_format = RepositoryFormatKnit1()
 
 
1738
RepositoryFormat.register_format(_default_format)
 
 
1739
RepositoryFormat.register_format(RepositoryFormatKnit2())
 
 
1740
RepositoryFormat.set_default_format(_default_format)
 
 
1741
_legacy_formats = [RepositoryFormat4(),
 
 
1742
                   RepositoryFormat5(),
 
 
1743
                   RepositoryFormat6()]
 
 
1746
class InterRepository(InterObject):
 
 
1747
    """This class represents operations taking place between two repositories.
 
 
1749
    Its instances have methods like copy_content and fetch, and contain
 
 
1750
    references to the source and target repositories these operations can be 
 
 
1753
    Often we will provide convenience methods on 'repository' which carry out
 
 
1754
    operations with another repository - they will always forward to
 
 
1755
    InterRepository.get(other).method_name(parameters).
 
 
1759
    """The available optimised InterRepository types."""
 
 
1761
    def copy_content(self, revision_id=None, basis=None):
 
 
1762
        raise NotImplementedError(self.copy_content)
 
 
1764
    def fetch(self, revision_id=None, pb=None):
 
 
1765
        """Fetch the content required to construct revision_id.
 
 
1767
        The content is copied from self.source to self.target.
 
 
1769
        :param revision_id: if None all content is copied, if NULL_REVISION no
 
 
1771
        :param pb: optional progress bar to use for progress reports. If not
 
 
1772
                   provided a default one will be created.
 
 
1774
        Returns the copied revision count and the failed revisions in a tuple:
 
 
1777
        raise NotImplementedError(self.fetch)
 
 
1780
    def missing_revision_ids(self, revision_id=None):
 
 
1781
        """Return the revision ids that source has that target does not.
 
 
1783
        These are returned in topological order.
 
 
1785
        :param revision_id: only return revision ids included by this
 
 
1788
        # generic, possibly worst case, slow code path.
 
 
1789
        target_ids = set(self.target.all_revision_ids())
 
 
1790
        if revision_id is not None:
 
 
1791
            source_ids = self.source.get_ancestry(revision_id)
 
 
1792
            assert source_ids[0] is None
 
 
1795
            source_ids = self.source.all_revision_ids()
 
 
1796
        result_set = set(source_ids).difference(target_ids)
 
 
1797
        # this may look like a no-op: its not. It preserves the ordering
 
 
1798
        # other_ids had while only returning the members from other_ids
 
 
1799
        # that we've decided we need.
 
 
1800
        return [rev_id for rev_id in source_ids if rev_id in result_set]
 
 
1803
class InterSameDataRepository(InterRepository):
 
 
1804
    """Code for converting between repositories that represent the same data.
 
 
1806
    Data format and model must match for this to work.
 
 
1809
    _matching_repo_format = RepositoryFormat4()
 
 
1810
    """Repository format for testing with."""
 
 
1813
    def is_compatible(source, target):
 
 
1814
        if not isinstance(source, Repository):
 
 
1816
        if not isinstance(target, Repository):
 
 
1818
        if source._format.rich_root_data == target._format.rich_root_data:
 
 
1824
    def copy_content(self, revision_id=None, basis=None):
 
 
1825
        """Make a complete copy of the content in self into destination.
 
 
1827
        This is a destructive operation! Do not use it on existing 
 
 
1830
        :param revision_id: Only copy the content needed to construct
 
 
1831
                            revision_id and its parents.
 
 
1832
        :param basis: Copy the needed data preferentially from basis.
 
 
1835
            self.target.set_make_working_trees(self.source.make_working_trees())
 
 
1836
        except NotImplementedError:
 
 
1838
        # grab the basis available data
 
 
1839
        if basis is not None:
 
 
1840
            self.target.fetch(basis, revision_id=revision_id)
 
 
1841
        # but don't bother fetching if we have the needed data now.
 
 
1842
        if (revision_id not in (None, _mod_revision.NULL_REVISION) and 
 
 
1843
            self.target.has_revision(revision_id)):
 
 
1845
        self.target.fetch(self.source, revision_id=revision_id)
 
 
1848
    def fetch(self, revision_id=None, pb=None):
 
 
1849
        """See InterRepository.fetch()."""
 
 
1850
        from bzrlib.fetch import GenericRepoFetcher
 
 
1851
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
 
 
1852
               self.source, self.source._format, self.target, 
 
 
1853
               self.target._format)
 
 
1854
        f = GenericRepoFetcher(to_repository=self.target,
 
 
1855
                               from_repository=self.source,
 
 
1856
                               last_revision=revision_id,
 
 
1858
        return f.count_copied, f.failed_revisions
 
 
1861
class InterWeaveRepo(InterSameDataRepository):
 
 
1862
    """Optimised code paths between Weave based repositories."""
 
 
1864
    _matching_repo_format = RepositoryFormat7()
 
 
1865
    """Repository format for testing with."""
 
 
1868
    def is_compatible(source, target):
 
 
1869
        """Be compatible with known Weave formats.
 
 
1871
        We don't test for the stores being of specific types because that
 
 
1872
        could lead to confusing results, and there is no need to be 
 
 
1876
            return (isinstance(source._format, (RepositoryFormat5,
 
 
1878
                                                RepositoryFormat7)) and
 
 
1879
                    isinstance(target._format, (RepositoryFormat5,
 
 
1881
                                                RepositoryFormat7)))
 
 
1882
        except AttributeError:
 
 
1886
    def copy_content(self, revision_id=None, basis=None):
 
 
1887
        """See InterRepository.copy_content()."""
 
 
1888
        # weave specific optimised path:
 
 
1889
        if basis is not None:
 
 
1890
            # copy the basis in, then fetch remaining data.
 
 
1891
            basis.copy_content_into(self.target, revision_id)
 
 
1892
            # the basis copy_content_into could miss-set this.
 
 
1894
                self.target.set_make_working_trees(self.source.make_working_trees())
 
 
1895
            except NotImplementedError:
 
 
1897
            self.target.fetch(self.source, revision_id=revision_id)
 
 
1900
                self.target.set_make_working_trees(self.source.make_working_trees())
 
 
1901
            except NotImplementedError:
 
 
1903
            # FIXME do not peek!
 
 
1904
            if self.source.control_files._transport.listable():
 
 
1905
                pb = ui.ui_factory.nested_progress_bar()
 
 
1907
                    self.target.weave_store.copy_all_ids(
 
 
1908
                        self.source.weave_store,
 
 
1910
                        from_transaction=self.source.get_transaction(),
 
 
1911
                        to_transaction=self.target.get_transaction())
 
 
1912
                    pb.update('copying inventory', 0, 1)
 
 
1913
                    self.target.control_weaves.copy_multi(
 
 
1914
                        self.source.control_weaves, ['inventory'],
 
 
1915
                        from_transaction=self.source.get_transaction(),
 
 
1916
                        to_transaction=self.target.get_transaction())
 
 
1917
                    self.target._revision_store.text_store.copy_all_ids(
 
 
1918
                        self.source._revision_store.text_store,
 
 
1923
                self.target.fetch(self.source, revision_id=revision_id)
 
 
1926
    def fetch(self, revision_id=None, pb=None):
 
 
1927
        """See InterRepository.fetch()."""
 
 
1928
        from bzrlib.fetch import GenericRepoFetcher
 
 
1929
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
 
 
1930
               self.source, self.source._format, self.target, self.target._format)
 
 
1931
        f = GenericRepoFetcher(to_repository=self.target,
 
 
1932
                               from_repository=self.source,
 
 
1933
                               last_revision=revision_id,
 
 
1935
        return f.count_copied, f.failed_revisions
 
 
1938
    def missing_revision_ids(self, revision_id=None):
 
 
1939
        """See InterRepository.missing_revision_ids()."""
 
 
1940
        # we want all revisions to satisfy revision_id in source.
 
 
1941
        # but we don't want to stat every file here and there.
 
 
1942
        # we want then, all revisions other needs to satisfy revision_id 
 
 
1943
        # checked, but not those that we have locally.
 
 
1944
        # so the first thing is to get a subset of the revisions to 
 
 
1945
        # satisfy revision_id in source, and then eliminate those that
 
 
1946
        # we do already have. 
 
 
1947
        # this is slow on high latency connection to self, but as as this
 
 
1948
        # disk format scales terribly for push anyway due to rewriting 
 
 
1949
        # inventory.weave, this is considered acceptable.
 
 
1951
        if revision_id is not None:
 
 
1952
            source_ids = self.source.get_ancestry(revision_id)
 
 
1953
            assert source_ids[0] is None
 
 
1956
            source_ids = self.source._all_possible_ids()
 
 
1957
        source_ids_set = set(source_ids)
 
 
1958
        # source_ids is the worst possible case we may need to pull.
 
 
1959
        # now we want to filter source_ids against what we actually
 
 
1960
        # have in target, but don't try to check for existence where we know
 
 
1961
        # we do not have a revision as that would be pointless.
 
 
1962
        target_ids = set(self.target._all_possible_ids())
 
 
1963
        possibly_present_revisions = target_ids.intersection(source_ids_set)
 
 
1964
        actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
 
 
1965
        required_revisions = source_ids_set.difference(actually_present_revisions)
 
 
1966
        required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
 
 
1967
        if revision_id is not None:
 
 
1968
            # we used get_ancestry to determine source_ids then we are assured all
 
 
1969
            # revisions referenced are present as they are installed in topological order.
 
 
1970
            # and the tip revision was validated by get_ancestry.
 
 
1971
            return required_topo_revisions
 
 
1973
            # if we just grabbed the possibly available ids, then 
 
 
1974
            # we only have an estimate of whats available and need to validate
 
 
1975
            # that against the revision records.
 
 
1976
            return self.source._eliminate_revisions_not_present(required_topo_revisions)
 
 
1979
class InterKnitRepo(InterSameDataRepository):
 
 
1980
    """Optimised code paths between Knit based repositories."""
 
 
1982
    _matching_repo_format = RepositoryFormatKnit1()
 
 
1983
    """Repository format for testing with."""
 
 
1986
    def is_compatible(source, target):
 
 
1987
        """Be compatible with known Knit formats.
 
 
1989
        We don't test for the stores being of specific types because that
 
 
1990
        could lead to confusing results, and there is no need to be 
 
 
1994
            return (isinstance(source._format, (RepositoryFormatKnit1)) and
 
 
1995
                    isinstance(target._format, (RepositoryFormatKnit1)))
 
 
1996
        except AttributeError:
 
 
2000
    def fetch(self, revision_id=None, pb=None):
 
 
2001
        """See InterRepository.fetch()."""
 
 
2002
        from bzrlib.fetch import KnitRepoFetcher
 
 
2003
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
 
 
2004
               self.source, self.source._format, self.target, self.target._format)
 
 
2005
        f = KnitRepoFetcher(to_repository=self.target,
 
 
2006
                            from_repository=self.source,
 
 
2007
                            last_revision=revision_id,
 
 
2009
        return f.count_copied, f.failed_revisions
 
 
2012
    def missing_revision_ids(self, revision_id=None):
 
 
2013
        """See InterRepository.missing_revision_ids()."""
 
 
2014
        if revision_id is not None:
 
 
2015
            source_ids = self.source.get_ancestry(revision_id)
 
 
2016
            assert source_ids[0] is None
 
 
2019
            source_ids = self.source._all_possible_ids()
 
 
2020
        source_ids_set = set(source_ids)
 
 
2021
        # source_ids is the worst possible case we may need to pull.
 
 
2022
        # now we want to filter source_ids against what we actually
 
 
2023
        # have in target, but don't try to check for existence where we know
 
 
2024
        # we do not have a revision as that would be pointless.
 
 
2025
        target_ids = set(self.target._all_possible_ids())
 
 
2026
        possibly_present_revisions = target_ids.intersection(source_ids_set)
 
 
2027
        actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
 
 
2028
        required_revisions = source_ids_set.difference(actually_present_revisions)
 
 
2029
        required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
 
 
2030
        if revision_id is not None:
 
 
2031
            # we used get_ancestry to determine source_ids then we are assured all
 
 
2032
            # revisions referenced are present as they are installed in topological order.
 
 
2033
            # and the tip revision was validated by get_ancestry.
 
 
2034
            return required_topo_revisions
 
 
2036
            # if we just grabbed the possibly available ids, then 
 
 
2037
            # we only have an estimate of whats available and need to validate
 
 
2038
            # that against the revision records.
 
 
2039
            return self.source._eliminate_revisions_not_present(required_topo_revisions)
 
 
2042
class InterModel1and2(InterRepository):
 
 
2044
    _matching_repo_format = None
 
 
2047
    def is_compatible(source, target):
 
 
2048
        if not isinstance(source, Repository):
 
 
2050
        if not isinstance(target, Repository):
 
 
2052
        if not source._format.rich_root_data and target._format.rich_root_data:
 
 
2058
    def fetch(self, revision_id=None, pb=None):
 
 
2059
        """See InterRepository.fetch()."""
 
 
2060
        from bzrlib.fetch import Model1toKnit2Fetcher
 
 
2061
        f = Model1toKnit2Fetcher(to_repository=self.target,
 
 
2062
                                 from_repository=self.source,
 
 
2063
                                 last_revision=revision_id,
 
 
2065
        return f.count_copied, f.failed_revisions
 
 
2068
    def copy_content(self, revision_id=None, basis=None):
 
 
2069
        """Make a complete copy of the content in self into destination.
 
 
2071
        This is a destructive operation! Do not use it on existing 
 
 
2074
        :param revision_id: Only copy the content needed to construct
 
 
2075
                            revision_id and its parents.
 
 
2076
        :param basis: Copy the needed data preferentially from basis.
 
 
2079
            self.target.set_make_working_trees(self.source.make_working_trees())
 
 
2080
        except NotImplementedError:
 
 
2082
        # grab the basis available data
 
 
2083
        if basis is not None:
 
 
2084
            self.target.fetch(basis, revision_id=revision_id)
 
 
2085
        # but don't bother fetching if we have the needed data now.
 
 
2086
        if (revision_id not in (None, _mod_revision.NULL_REVISION) and 
 
 
2087
            self.target.has_revision(revision_id)):
 
 
2089
        self.target.fetch(self.source, revision_id=revision_id)
 
 
2092
class InterKnit1and2(InterKnitRepo):
 
 
2094
    _matching_repo_format = None
 
 
2097
    def is_compatible(source, target):
 
 
2098
        """Be compatible with Knit1 source and Knit2 target"""
 
 
2100
            return (isinstance(source._format, (RepositoryFormatKnit1)) and
 
 
2101
                    isinstance(target._format, (RepositoryFormatKnit2)))
 
 
2102
        except AttributeError:
 
 
2106
    def fetch(self, revision_id=None, pb=None):
 
 
2107
        """See InterRepository.fetch()."""
 
 
2108
        from bzrlib.fetch import Knit1to2Fetcher
 
 
2109
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
 
 
2110
               self.source, self.source._format, self.target, 
 
 
2111
               self.target._format)
 
 
2112
        f = Knit1to2Fetcher(to_repository=self.target,
 
 
2113
                            from_repository=self.source,
 
 
2114
                            last_revision=revision_id,
 
 
2116
        return f.count_copied, f.failed_revisions
 
 
2119
InterRepository.register_optimiser(InterSameDataRepository)
 
 
2120
InterRepository.register_optimiser(InterWeaveRepo)
 
 
2121
InterRepository.register_optimiser(InterKnitRepo)
 
 
2122
InterRepository.register_optimiser(InterModel1and2)
 
 
2123
InterRepository.register_optimiser(InterKnit1and2)
 
 
2126
class RepositoryTestProviderAdapter(object):
 
 
2127
    """A tool to generate a suite testing multiple repository formats at once.
 
 
2129
    This is done by copying the test once for each transport and injecting
 
 
2130
    the transport_server, transport_readonly_server, and bzrdir_format and
 
 
2131
    repository_format classes into each copy. Each copy is also given a new id()
 
 
2132
    to make it easy to identify.
 
 
2135
    def __init__(self, transport_server, transport_readonly_server, formats):
 
 
2136
        self._transport_server = transport_server
 
 
2137
        self._transport_readonly_server = transport_readonly_server
 
 
2138
        self._formats = formats
 
 
2140
    def adapt(self, test):
 
 
2141
        result = unittest.TestSuite()
 
 
2142
        for repository_format, bzrdir_format in self._formats:
 
 
2143
            new_test = deepcopy(test)
 
 
2144
            new_test.transport_server = self._transport_server
 
 
2145
            new_test.transport_readonly_server = self._transport_readonly_server
 
 
2146
            new_test.bzrdir_format = bzrdir_format
 
 
2147
            new_test.repository_format = repository_format
 
 
2148
            def make_new_test_id():
 
 
2149
                new_id = "%s(%s)" % (new_test.id(), repository_format.__class__.__name__)
 
 
2150
                return lambda: new_id
 
 
2151
            new_test.id = make_new_test_id()
 
 
2152
            result.addTest(new_test)
 
 
2156
class InterRepositoryTestProviderAdapter(object):
 
 
2157
    """A tool to generate a suite testing multiple inter repository formats.
 
 
2159
    This is done by copying the test once for each interrepo provider and injecting
 
 
2160
    the transport_server, transport_readonly_server, repository_format and 
 
 
2161
    repository_to_format classes into each copy.
 
 
2162
    Each copy is also given a new id() to make it easy to identify.
 
 
2165
    def __init__(self, transport_server, transport_readonly_server, formats):
 
 
2166
        self._transport_server = transport_server
 
 
2167
        self._transport_readonly_server = transport_readonly_server
 
 
2168
        self._formats = formats
 
 
2170
    def adapt(self, test):
 
 
2171
        result = unittest.TestSuite()
 
 
2172
        for interrepo_class, repository_format, repository_format_to in self._formats:
 
 
2173
            new_test = deepcopy(test)
 
 
2174
            new_test.transport_server = self._transport_server
 
 
2175
            new_test.transport_readonly_server = self._transport_readonly_server
 
 
2176
            new_test.interrepo_class = interrepo_class
 
 
2177
            new_test.repository_format = repository_format
 
 
2178
            new_test.repository_format_to = repository_format_to
 
 
2179
            def make_new_test_id():
 
 
2180
                new_id = "%s(%s)" % (new_test.id(), interrepo_class.__name__)
 
 
2181
                return lambda: new_id
 
 
2182
            new_test.id = make_new_test_id()
 
 
2183
            result.addTest(new_test)
 
 
2187
    def default_test_list():
 
 
2188
        """Generate the default list of interrepo permutations to test."""
 
 
2190
        # test the default InterRepository between format 6 and the current 
 
 
2192
        # XXX: robertc 20060220 reinstate this when there are two supported
 
 
2193
        # formats which do not have an optimal code path between them.
 
 
2194
        #result.append((InterRepository,
 
 
2195
        #               RepositoryFormat6(),
 
 
2196
        #               RepositoryFormatKnit1()))
 
 
2197
        for optimiser in InterRepository._optimisers:
 
 
2198
            if optimiser._matching_repo_format is not None:
 
 
2199
                result.append((optimiser,
 
 
2200
                               optimiser._matching_repo_format,
 
 
2201
                               optimiser._matching_repo_format
 
 
2203
        # if there are specific combinations we want to use, we can add them 
 
 
2205
        result.append((InterModel1and2, RepositoryFormat5(),
 
 
2206
                       RepositoryFormatKnit2()))
 
 
2207
        result.append((InterKnit1and2, RepositoryFormatKnit1(),
 
 
2208
                       RepositoryFormatKnit2()))
 
 
2212
class CopyConverter(object):
 
 
2213
    """A repository conversion tool which just performs a copy of the content.
 
 
2215
    This is slow but quite reliable.
 
 
2218
    def __init__(self, target_format):
 
 
2219
        """Create a CopyConverter.
 
 
2221
        :param target_format: The format the resulting repository should be.
 
 
2223
        self.target_format = target_format
 
 
2225
    def convert(self, repo, pb):
 
 
2226
        """Perform the conversion of to_convert, giving feedback via pb.
 
 
2228
        :param to_convert: The disk object to convert.
 
 
2229
        :param pb: a progress bar to use for progress information.
 
 
2234
        # this is only useful with metadir layouts - separated repo content.
 
 
2235
        # trigger an assertion if not such
 
 
2236
        repo._format.get_format_string()
 
 
2237
        self.repo_dir = repo.bzrdir
 
 
2238
        self.step('Moving repository to repository.backup')
 
 
2239
        self.repo_dir.transport.move('repository', 'repository.backup')
 
 
2240
        backup_transport =  self.repo_dir.transport.clone('repository.backup')
 
 
2241
        repo._format.check_conversion_target(self.target_format)
 
 
2242
        self.source_repo = repo._format.open(self.repo_dir,
 
 
2244
            _override_transport=backup_transport)
 
 
2245
        self.step('Creating new repository')
 
 
2246
        converted = self.target_format.initialize(self.repo_dir,
 
 
2247
                                                  self.source_repo.is_shared())
 
 
2248
        converted.lock_write()
 
 
2250
            self.step('Copying content into repository.')
 
 
2251
            self.source_repo.copy_content_into(converted)
 
 
2254
        self.step('Deleting old repository content.')
 
 
2255
        self.repo_dir.transport.delete_tree('repository.backup')
 
 
2256
        self.pb.note('repository converted')
 
 
2258
    def step(self, message):
 
 
2259
        """Update the pb by a step."""
 
 
2261
        self.pb.update(message, self.count, self.total)
 
 
2264
class CommitBuilder(object):
 
 
2265
    """Provides an interface to build up a commit.
 
 
2267
    This allows describing a tree to be committed without needing to 
 
 
2268
    know the internals of the format of the repository.
 
 
2271
    record_root_entry = False
 
 
2272
    def __init__(self, repository, parents, config, timestamp=None, 
 
 
2273
                 timezone=None, committer=None, revprops=None, 
 
 
2275
        """Initiate a CommitBuilder.
 
 
2277
        :param repository: Repository to commit to.
 
 
2278
        :param parents: Revision ids of the parents of the new revision.
 
 
2279
        :param config: Configuration to use.
 
 
2280
        :param timestamp: Optional timestamp recorded for commit.
 
 
2281
        :param timezone: Optional timezone for timestamp.
 
 
2282
        :param committer: Optional committer to set for commit.
 
 
2283
        :param revprops: Optional dictionary of revision properties.
 
 
2284
        :param revision_id: Optional revision id.
 
 
2286
        self._config = config
 
 
2288
        if committer is None:
 
 
2289
            self._committer = self._config.username()
 
 
2291
            assert isinstance(committer, basestring), type(committer)
 
 
2292
            self._committer = committer
 
 
2294
        self.new_inventory = Inventory(None)
 
 
2295
        self._new_revision_id = revision_id
 
 
2296
        self.parents = parents
 
 
2297
        self.repository = repository
 
 
2300
        if revprops is not None:
 
 
2301
            self._revprops.update(revprops)
 
 
2303
        if timestamp is None:
 
 
2304
            timestamp = time.time()
 
 
2305
        # Restrict resolution to 1ms
 
 
2306
        self._timestamp = round(timestamp, 3)
 
 
2308
        if timezone is None:
 
 
2309
            self._timezone = local_time_offset()
 
 
2311
            self._timezone = int(timezone)
 
 
2313
        self._generate_revision_if_needed()
 
 
2315
    def commit(self, message):
 
 
2316
        """Make the actual commit.
 
 
2318
        :return: The revision id of the recorded revision.
 
 
2320
        rev = _mod_revision.Revision(
 
 
2321
                       timestamp=self._timestamp,
 
 
2322
                       timezone=self._timezone,
 
 
2323
                       committer=self._committer,
 
 
2325
                       inventory_sha1=self.inv_sha1,
 
 
2326
                       revision_id=self._new_revision_id,
 
 
2327
                       properties=self._revprops)
 
 
2328
        rev.parent_ids = self.parents
 
 
2329
        self.repository.add_revision(self._new_revision_id, rev, 
 
 
2330
            self.new_inventory, self._config)
 
 
2331
        return self._new_revision_id
 
 
2333
    def revision_tree(self):
 
 
2334
        """Return the tree that was just committed.
 
 
2336
        After calling commit() this can be called to get a RevisionTree
 
 
2337
        representing the newly committed tree. This is preferred to
 
 
2338
        calling Repository.revision_tree() because that may require
 
 
2339
        deserializing the inventory, while we already have a copy in
 
 
2342
        return RevisionTree(self.repository, self.new_inventory,
 
 
2343
                            self._new_revision_id)
 
 
2345
    def finish_inventory(self):
 
 
2346
        """Tell the builder that the inventory is finished."""
 
 
2347
        if self.new_inventory.root is None:
 
 
2348
            symbol_versioning.warn('Root entry should be supplied to'
 
 
2349
                ' record_entry_contents, as of bzr 0.10.',
 
 
2350
                 DeprecationWarning, stacklevel=2)
 
 
2351
            self.new_inventory.add(InventoryDirectory(ROOT_ID, '', None))
 
 
2352
        self.new_inventory.revision_id = self._new_revision_id
 
 
2353
        self.inv_sha1 = self.repository.add_inventory(
 
 
2354
            self._new_revision_id,
 
 
2360
    def _sanitize_for_revision_id(text):
 
 
2361
        """This just removes whitespace, etc to make friendlier ids.
 
 
2364
    def _gen_revision_id(self):
 
 
2365
        """Return new revision-id."""
 
 
2366
        return generate_ids.gen_revision_id(self._config.username(),
 
 
2369
    def _generate_revision_if_needed(self):
 
 
2370
        """Create a revision id if None was supplied.
 
 
2372
        If the repository can not support user-specified revision ids
 
 
2373
        they should override this function and raise UnsupportedOperation
 
 
2374
        if _new_revision_id is not None.
 
 
2376
        :raises: UnsupportedOperation
 
 
2378
        if self._new_revision_id is None:
 
 
2379
            self._new_revision_id = self._gen_revision_id()
 
 
2381
    def record_entry_contents(self, ie, parent_invs, path, tree):
 
 
2382
        """Record the content of ie from tree into the commit if needed.
 
 
2384
        Side effect: sets ie.revision when unchanged
 
 
2386
        :param ie: An inventory entry present in the commit.
 
 
2387
        :param parent_invs: The inventories of the parent revisions of the
 
 
2389
        :param path: The path the entry is at in the tree.
 
 
2390
        :param tree: The tree which contains this entry and should be used to 
 
 
2393
        if self.new_inventory.root is None and ie.parent_id is not None:
 
 
2394
            symbol_versioning.warn('Root entry should be supplied to'
 
 
2395
                ' record_entry_contents, as of bzr 0.10.',
 
 
2396
                 DeprecationWarning, stacklevel=2)
 
 
2397
            self.record_entry_contents(tree.inventory.root.copy(), parent_invs,
 
 
2399
        self.new_inventory.add(ie)
 
 
2401
        # ie.revision is always None if the InventoryEntry is considered
 
 
2402
        # for committing. ie.snapshot will record the correct revision 
 
 
2403
        # which may be the sole parent if it is untouched.
 
 
2404
        if ie.revision is not None:
 
 
2407
        # In this revision format, root entries have no knit or weave
 
 
2408
        if ie is self.new_inventory.root:
 
 
2409
            # When serializing out to disk and back in
 
 
2410
            # root.revision is always _new_revision_id
 
 
2411
            ie.revision = self._new_revision_id
 
 
2413
        previous_entries = ie.find_previous_heads(
 
 
2415
            self.repository.weave_store,
 
 
2416
            self.repository.get_transaction())
 
 
2417
        # we are creating a new revision for ie in the history store
 
 
2419
        ie.snapshot(self._new_revision_id, path, previous_entries, tree, self)
 
 
2421
    def modified_directory(self, file_id, file_parents):
 
 
2422
        """Record the presence of a symbolic link.
 
 
2424
        :param file_id: The file_id of the link to record.
 
 
2425
        :param file_parents: The per-file parent revision ids.
 
 
2427
        self._add_text_to_weave(file_id, [], file_parents.keys())
 
 
2429
    def modified_file_text(self, file_id, file_parents,
 
 
2430
                           get_content_byte_lines, text_sha1=None,
 
 
2432
        """Record the text of file file_id
 
 
2434
        :param file_id: The file_id of the file to record the text of.
 
 
2435
        :param file_parents: The per-file parent revision ids.
 
 
2436
        :param get_content_byte_lines: A callable which will return the byte
 
 
2438
        :param text_sha1: Optional SHA1 of the file contents.
 
 
2439
        :param text_size: Optional size of the file contents.
 
 
2441
        # mutter('storing text of file {%s} in revision {%s} into %r',
 
 
2442
        #        file_id, self._new_revision_id, self.repository.weave_store)
 
 
2443
        # special case to avoid diffing on renames or 
 
 
2445
        if (len(file_parents) == 1
 
 
2446
            and text_sha1 == file_parents.values()[0].text_sha1
 
 
2447
            and text_size == file_parents.values()[0].text_size):
 
 
2448
            previous_ie = file_parents.values()[0]
 
 
2449
            versionedfile = self.repository.weave_store.get_weave(file_id, 
 
 
2450
                self.repository.get_transaction())
 
 
2451
            versionedfile.clone_text(self._new_revision_id, 
 
 
2452
                previous_ie.revision, file_parents.keys())
 
 
2453
            return text_sha1, text_size
 
 
2455
            new_lines = get_content_byte_lines()
 
 
2456
            # TODO: Rather than invoking sha_strings here, _add_text_to_weave
 
 
2457
            # should return the SHA1 and size
 
 
2458
            self._add_text_to_weave(file_id, new_lines, file_parents.keys())
 
 
2459
            return osutils.sha_strings(new_lines), \
 
 
2460
                sum(map(len, new_lines))
 
 
2462
    def modified_link(self, file_id, file_parents, link_target):
 
 
2463
        """Record the presence of a symbolic link.
 
 
2465
        :param file_id: The file_id of the link to record.
 
 
2466
        :param file_parents: The per-file parent revision ids.
 
 
2467
        :param link_target: Target location of this link.
 
 
2469
        self._add_text_to_weave(file_id, [], file_parents.keys())
 
 
2471
    def _add_text_to_weave(self, file_id, new_lines, parents):
 
 
2472
        versionedfile = self.repository.weave_store.get_weave_or_empty(
 
 
2473
            file_id, self.repository.get_transaction())
 
 
2474
        versionedfile.add_lines(self._new_revision_id, parents, new_lines)
 
 
2475
        versionedfile.clear_cache()
 
 
2478
class _CommitBuilder(CommitBuilder):
 
 
2479
    """Temporary class so old CommitBuilders are detected properly
 
 
2481
    Note: CommitBuilder works whether or not root entry is recorded.
 
 
2484
    record_root_entry = True
 
 
2487
class RootCommitBuilder(CommitBuilder):
 
 
2488
    """This commitbuilder actually records the root id"""
 
 
2490
    record_root_entry = True
 
 
2492
    def record_entry_contents(self, ie, parent_invs, path, tree):
 
 
2493
        """Record the content of ie from tree into the commit if needed.
 
 
2495
        Side effect: sets ie.revision when unchanged
 
 
2497
        :param ie: An inventory entry present in the commit.
 
 
2498
        :param parent_invs: The inventories of the parent revisions of the
 
 
2500
        :param path: The path the entry is at in the tree.
 
 
2501
        :param tree: The tree which contains this entry and should be used to 
 
 
2504
        assert self.new_inventory.root is not None or ie.parent_id is None
 
 
2505
        self.new_inventory.add(ie)
 
 
2507
        # ie.revision is always None if the InventoryEntry is considered
 
 
2508
        # for committing. ie.snapshot will record the correct revision 
 
 
2509
        # which may be the sole parent if it is untouched.
 
 
2510
        if ie.revision is not None:
 
 
2513
        previous_entries = ie.find_previous_heads(
 
 
2515
            self.repository.weave_store,
 
 
2516
            self.repository.get_transaction())
 
 
2517
        # we are creating a new revision for ie in the history store
 
 
2519
        ie.snapshot(self._new_revision_id, path, previous_entries, tree, self)
 
 
2531
def _unescaper(match, _map=_unescape_map):
 
 
2532
    return _map[match.group(1)]
 
 
2538
def _unescape_xml(data):
 
 
2539
    """Unescape predefined XML entities in a string of data."""
 
 
2541
    if _unescape_re is None:
 
 
2542
        _unescape_re = re.compile('\&([^;]*);')
 
 
2543
    return _unescape_re.sub(_unescaper, data)