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
 
 
40
    revision as _mod_revision,
 
 
49
from bzrlib.osutils import (
 
 
54
from bzrlib.revisiontree import RevisionTree
 
 
55
from bzrlib.store.versioned import VersionedFileStore
 
 
56
from bzrlib.store.text import TextStore
 
 
57
from bzrlib.testament import Testament
 
 
60
from bzrlib.decorators import needs_read_lock, needs_write_lock
 
 
61
from bzrlib.inter import InterObject
 
 
62
from bzrlib.inventory import Inventory, InventoryDirectory, ROOT_ID
 
 
63
from bzrlib.symbol_versioning import (
 
 
67
from bzrlib.trace import mutter, note, warning
 
 
70
# Old formats display a warning, but only once
 
 
71
_deprecation_warning_done = False
 
 
74
class Repository(object):
 
 
75
    """Repository holding history for one or more branches.
 
 
77
    The repository holds and retrieves historical information including
 
 
78
    revisions and file history.  It's normally accessed only by the Branch,
 
 
79
    which views a particular line of development through that history.
 
 
81
    The Repository builds on top of Stores and a Transport, which respectively 
 
 
82
    describe the disk data format and the way of accessing the (possibly 
 
 
86
    _file_ids_altered_regex = lazy_regex.lazy_compile(
 
 
87
        r'file_id="(?P<file_id>[^"]+)"'
 
 
88
        r'.*revision="(?P<revision_id>[^"]+)"'
 
 
92
    def add_inventory(self, revid, inv, parents):
 
 
93
        """Add the inventory inv to the repository as revid.
 
 
95
        :param parents: The revision ids of the parents that revid
 
 
96
                        is known to have and are in the repository already.
 
 
98
        returns the sha1 of the serialized inventory.
 
 
100
        assert inv.revision_id is None or inv.revision_id == revid, \
 
 
101
            "Mismatch between inventory revision" \
 
 
102
            " id and insertion revid (%r, %r)" % (inv.revision_id, revid)
 
 
103
        assert inv.root is not None
 
 
104
        inv_text = self.serialise_inventory(inv)
 
 
105
        inv_sha1 = osutils.sha_string(inv_text)
 
 
106
        inv_vf = self.control_weaves.get_weave('inventory',
 
 
107
                                               self.get_transaction())
 
 
108
        self._inventory_add_lines(inv_vf, revid, parents, osutils.split_lines(inv_text))
 
 
111
    def _inventory_add_lines(self, inv_vf, revid, parents, lines):
 
 
113
        for parent in parents:
 
 
115
                final_parents.append(parent)
 
 
117
        inv_vf.add_lines(revid, final_parents, lines)
 
 
120
    def add_revision(self, rev_id, rev, inv=None, config=None):
 
 
121
        """Add rev to the revision store as rev_id.
 
 
123
        :param rev_id: the revision id to use.
 
 
124
        :param rev: The revision object.
 
 
125
        :param inv: The inventory for the revision. if None, it will be looked
 
 
126
                    up in the inventory storer
 
 
127
        :param config: If None no digital signature will be created.
 
 
128
                       If supplied its signature_needed method will be used
 
 
129
                       to determine if a signature should be made.
 
 
131
        if config is not None and config.signature_needed():
 
 
133
                inv = self.get_inventory(rev_id)
 
 
134
            plaintext = Testament(rev, inv).as_short_text()
 
 
135
            self.store_revision_signature(
 
 
136
                gpg.GPGStrategy(config), plaintext, rev_id)
 
 
137
        if not rev_id in self.get_inventory_weave():
 
 
139
                raise errors.WeaveRevisionNotPresent(rev_id,
 
 
140
                                                     self.get_inventory_weave())
 
 
142
                # yes, this is not suitable for adding with ghosts.
 
 
143
                self.add_inventory(rev_id, inv, rev.parent_ids)
 
 
144
        self._revision_store.add_revision(rev, self.get_transaction())
 
 
147
    def _all_possible_ids(self):
 
 
148
        """Return all the possible revisions that we could find."""
 
 
149
        return self.get_inventory_weave().versions()
 
 
151
    def all_revision_ids(self):
 
 
152
        """Returns a list of all the revision ids in the repository. 
 
 
154
        This is deprecated because code should generally work on the graph
 
 
155
        reachable from a particular revision, and ignore any other revisions
 
 
156
        that might be present.  There is no direct replacement method.
 
 
158
        return self._all_revision_ids()
 
 
161
    def _all_revision_ids(self):
 
 
162
        """Returns a list of all the revision ids in the repository. 
 
 
164
        These are in as much topological order as the underlying store can 
 
 
165
        present: for weaves ghosts may lead to a lack of correctness until
 
 
166
        the reweave updates the parents list.
 
 
168
        if self._revision_store.text_store.listable():
 
 
169
            return self._revision_store.all_revision_ids(self.get_transaction())
 
 
170
        result = self._all_possible_ids()
 
 
171
        return self._eliminate_revisions_not_present(result)
 
 
173
    def break_lock(self):
 
 
174
        """Break a lock if one is present from another instance.
 
 
176
        Uses the ui factory to ask for confirmation if the lock may be from
 
 
179
        self.control_files.break_lock()
 
 
182
    def _eliminate_revisions_not_present(self, revision_ids):
 
 
183
        """Check every revision id in revision_ids to see if we have it.
 
 
185
        Returns a set of the present revisions.
 
 
188
        for id in revision_ids:
 
 
189
            if self.has_revision(id):
 
 
194
    def create(a_bzrdir):
 
 
195
        """Construct the current default format repository in a_bzrdir."""
 
 
196
        return RepositoryFormat.get_default_format().initialize(a_bzrdir)
 
 
198
    def __init__(self, _format, a_bzrdir, control_files, _revision_store, control_store, text_store):
 
 
199
        """instantiate a Repository.
 
 
201
        :param _format: The format of the repository on disk.
 
 
202
        :param a_bzrdir: The BzrDir of the repository.
 
 
204
        In the future we will have a single api for all stores for
 
 
205
        getting file texts, inventories and revisions, then
 
 
206
        this construct will accept instances of those things.
 
 
208
        super(Repository, self).__init__()
 
 
209
        self._format = _format
 
 
210
        # the following are part of the public API for Repository:
 
 
211
        self.bzrdir = a_bzrdir
 
 
212
        self.control_files = control_files
 
 
213
        self._revision_store = _revision_store
 
 
214
        self.text_store = text_store
 
 
215
        # backwards compatibility
 
 
216
        self.weave_store = text_store
 
 
217
        # not right yet - should be more semantically clear ? 
 
 
219
        self.control_store = control_store
 
 
220
        self.control_weaves = control_store
 
 
221
        # TODO: make sure to construct the right store classes, etc, depending
 
 
222
        # on whether escaping is required.
 
 
223
        self._warn_if_deprecated()
 
 
224
        self._serializer = xml5.serializer_v5
 
 
227
        return '%s(%r)' % (self.__class__.__name__, 
 
 
228
                           self.bzrdir.transport.base)
 
 
231
        return self.control_files.is_locked()
 
 
233
    def lock_write(self):
 
 
234
        self.control_files.lock_write()
 
 
237
        self.control_files.lock_read()
 
 
239
    def get_physical_lock_status(self):
 
 
240
        return self.control_files.get_physical_lock_status()
 
 
243
    def missing_revision_ids(self, other, revision_id=None):
 
 
244
        """Return the revision ids that other has that this does not.
 
 
246
        These are returned in topological order.
 
 
248
        revision_id: only return revision ids included by revision_id.
 
 
250
        return InterRepository.get(other, self).missing_revision_ids(revision_id)
 
 
254
        """Open the repository rooted at base.
 
 
256
        For instance, if the repository is at URL/.bzr/repository,
 
 
257
        Repository.open(URL) -> a Repository instance.
 
 
259
        control = bzrdir.BzrDir.open(base)
 
 
260
        return control.open_repository()
 
 
262
    def copy_content_into(self, destination, revision_id=None, basis=None):
 
 
263
        """Make a complete copy of the content in self into destination.
 
 
265
        This is a destructive operation! Do not use it on existing 
 
 
268
        return InterRepository.get(self, destination).copy_content(revision_id, basis)
 
 
270
    def fetch(self, source, revision_id=None, pb=None):
 
 
271
        """Fetch the content required to construct revision_id from source.
 
 
273
        If revision_id is None all content is copied.
 
 
275
        return InterRepository.get(source, self).fetch(revision_id=revision_id,
 
 
278
    def get_commit_builder(self, branch, parents, config, timestamp=None, 
 
 
279
                           timezone=None, committer=None, revprops=None, 
 
 
281
        """Obtain a CommitBuilder for this repository.
 
 
283
        :param branch: Branch to commit to.
 
 
284
        :param parents: Revision ids of the parents of the new revision.
 
 
285
        :param config: Configuration to use.
 
 
286
        :param timestamp: Optional timestamp recorded for commit.
 
 
287
        :param timezone: Optional timezone for timestamp.
 
 
288
        :param committer: Optional committer to set for commit.
 
 
289
        :param revprops: Optional dictionary of revision properties.
 
 
290
        :param revision_id: Optional revision id.
 
 
292
        return _CommitBuilder(self, parents, config, timestamp, timezone,
 
 
293
                              committer, revprops, revision_id)
 
 
296
        self.control_files.unlock()
 
 
299
    def clone(self, a_bzrdir, revision_id=None, basis=None):
 
 
300
        """Clone this repository into a_bzrdir using the current format.
 
 
302
        Currently no check is made that the format of this repository and
 
 
303
        the bzrdir format are compatible. FIXME RBC 20060201.
 
 
305
        if not isinstance(a_bzrdir._format, self.bzrdir._format.__class__):
 
 
306
            # use target default format.
 
 
307
            result = a_bzrdir.create_repository()
 
 
308
        # FIXME RBC 20060209 split out the repository type to avoid this check ?
 
 
309
        elif isinstance(a_bzrdir._format,
 
 
310
                      (bzrdir.BzrDirFormat4,
 
 
311
                       bzrdir.BzrDirFormat5,
 
 
312
                       bzrdir.BzrDirFormat6)):
 
 
313
            result = a_bzrdir.open_repository()
 
 
315
            result = self._format.initialize(a_bzrdir, shared=self.is_shared())
 
 
316
        self.copy_content_into(result, revision_id, basis)
 
 
320
    def has_revision(self, revision_id):
 
 
321
        """True if this repository has a copy of the revision."""
 
 
322
        return self._revision_store.has_revision_id(revision_id,
 
 
323
                                                    self.get_transaction())
 
 
326
    def get_revision_reconcile(self, revision_id):
 
 
327
        """'reconcile' helper routine that allows access to a revision always.
 
 
329
        This variant of get_revision does not cross check the weave graph
 
 
330
        against the revision one as get_revision does: but it should only
 
 
331
        be used by reconcile, or reconcile-alike commands that are correcting
 
 
332
        or testing the revision graph.
 
 
334
        if not revision_id or not isinstance(revision_id, basestring):
 
 
335
            raise errors.InvalidRevisionId(revision_id=revision_id,
 
 
337
        return self._revision_store.get_revisions([revision_id],
 
 
338
                                                  self.get_transaction())[0]
 
 
340
    def get_revisions(self, revision_ids):
 
 
341
        return self._revision_store.get_revisions(revision_ids,
 
 
342
                                                  self.get_transaction())
 
 
345
    def get_revision_xml(self, revision_id):
 
 
346
        rev = self.get_revision(revision_id) 
 
 
348
        # the current serializer..
 
 
349
        self._revision_store._serializer.write_revision(rev, rev_tmp)
 
 
351
        return rev_tmp.getvalue()
 
 
354
    def get_revision(self, revision_id):
 
 
355
        """Return the Revision object for a named revision"""
 
 
356
        r = self.get_revision_reconcile(revision_id)
 
 
357
        # weave corruption can lead to absent revision markers that should be
 
 
359
        # the following test is reasonably cheap (it needs a single weave read)
 
 
360
        # and the weave is cached in read transactions. In write transactions
 
 
361
        # it is not cached but typically we only read a small number of
 
 
362
        # revisions. For knits when they are introduced we will probably want
 
 
363
        # to ensure that caching write transactions are in use.
 
 
364
        inv = self.get_inventory_weave()
 
 
365
        self._check_revision_parents(r, inv)
 
 
369
    def get_deltas_for_revisions(self, revisions):
 
 
370
        """Produce a generator of revision deltas.
 
 
372
        Note that the input is a sequence of REVISIONS, not revision_ids.
 
 
373
        Trees will be held in memory until the generator exits.
 
 
374
        Each delta is relative to the revision's lefthand predecessor.
 
 
376
        required_trees = set()
 
 
377
        for revision in revisions:
 
 
378
            required_trees.add(revision.revision_id)
 
 
379
            required_trees.update(revision.parent_ids[:1])
 
 
380
        trees = dict((t.get_revision_id(), t) for 
 
 
381
                     t in self.revision_trees(required_trees))
 
 
382
        for revision in revisions:
 
 
383
            if not revision.parent_ids:
 
 
384
                old_tree = self.revision_tree(None)
 
 
386
                old_tree = trees[revision.parent_ids[0]]
 
 
387
            yield trees[revision.revision_id].changes_from(old_tree)
 
 
390
    def get_revision_delta(self, revision_id):
 
 
391
        """Return the delta for one revision.
 
 
393
        The delta is relative to the left-hand predecessor of the
 
 
396
        r = self.get_revision(revision_id)
 
 
397
        return list(self.get_deltas_for_revisions([r]))[0]
 
 
399
    def _check_revision_parents(self, revision, inventory):
 
 
400
        """Private to Repository and Fetch.
 
 
402
        This checks the parentage of revision in an inventory weave for 
 
 
403
        consistency and is only applicable to inventory-weave-for-ancestry
 
 
404
        using repository formats & fetchers.
 
 
406
        weave_parents = inventory.get_parents(revision.revision_id)
 
 
407
        weave_names = inventory.versions()
 
 
408
        for parent_id in revision.parent_ids:
 
 
409
            if parent_id in weave_names:
 
 
410
                # this parent must not be a ghost.
 
 
411
                if not parent_id in weave_parents:
 
 
413
                    raise errors.CorruptRepository(self)
 
 
416
    def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
 
 
417
        signature = gpg_strategy.sign(plaintext)
 
 
418
        self._revision_store.add_revision_signature_text(revision_id,
 
 
420
                                                         self.get_transaction())
 
 
422
    def fileids_altered_by_revision_ids(self, revision_ids):
 
 
423
        """Find the file ids and versions affected by revisions.
 
 
425
        :param revisions: an iterable containing revision ids.
 
 
426
        :return: a dictionary mapping altered file-ids to an iterable of
 
 
427
        revision_ids. Each altered file-ids has the exact revision_ids that
 
 
428
        altered it listed explicitly.
 
 
430
        assert self._serializer.support_altered_by_hack, \
 
 
431
            ("fileids_altered_by_revision_ids only supported for branches " 
 
 
432
             "which store inventory as unnested xml, not on %r" % self)
 
 
433
        selected_revision_ids = set(revision_ids)
 
 
434
        w = self.get_inventory_weave()
 
 
437
        # this code needs to read every new line in every inventory for the
 
 
438
        # inventories [revision_ids]. Seeing a line twice is ok. Seeing a line
 
 
439
        # not present in one of those inventories is unnecessary but not 
 
 
440
        # harmful because we are filtering by the revision id marker in the
 
 
441
        # inventory lines : we only select file ids altered in one of those  
 
 
442
        # revisions. We don't need to see all lines in the inventory because
 
 
443
        # only those added in an inventory in rev X can contain a revision=X
 
 
445
        unescape_revid_cache = {}
 
 
446
        unescape_fileid_cache = {}
 
 
448
        # jam 20061218 In a big fetch, this handles hundreds of thousands
 
 
449
        # of lines, so it has had a lot of inlining and optimizing done.
 
 
450
        # Sorry that it is a little bit messy.
 
 
451
        # Move several functions to be local variables, since this is a long
 
 
453
        search = self._file_ids_altered_regex.search
 
 
454
        unescape = _unescape_xml
 
 
455
        setdefault = result.setdefault
 
 
456
        pb = ui.ui_factory.nested_progress_bar()
 
 
458
            for line in w.iter_lines_added_or_present_in_versions(
 
 
459
                                        selected_revision_ids, pb=pb):
 
 
463
                # One call to match.group() returning multiple items is quite a
 
 
464
                # bit faster than 2 calls to match.group() each returning 1
 
 
465
                file_id, revision_id = match.group('file_id', 'revision_id')
 
 
467
                # Inlining the cache lookups helps a lot when you make 170,000
 
 
468
                # lines and 350k ids, versus 8.4 unique ids.
 
 
469
                # Using a cache helps in 2 ways:
 
 
470
                #   1) Avoids unnecessary decoding calls
 
 
471
                #   2) Re-uses cached strings, which helps in future set and
 
 
473
                # (2) is enough that removing encoding entirely along with
 
 
474
                # the cache (so we are using plain strings) results in no
 
 
475
                # performance improvement.
 
 
477
                    revision_id = unescape_revid_cache[revision_id]
 
 
479
                    unescaped = unescape(revision_id)
 
 
480
                    unescape_revid_cache[revision_id] = unescaped
 
 
481
                    revision_id = unescaped
 
 
483
                if revision_id in selected_revision_ids:
 
 
485
                        file_id = unescape_fileid_cache[file_id]
 
 
487
                        unescaped = unescape(file_id)
 
 
488
                        unescape_fileid_cache[file_id] = unescaped
 
 
490
                    setdefault(file_id, set()).add(revision_id)
 
 
496
    def get_inventory_weave(self):
 
 
497
        return self.control_weaves.get_weave('inventory',
 
 
498
            self.get_transaction())
 
 
501
    def get_inventory(self, revision_id):
 
 
502
        """Get Inventory object by hash."""
 
 
503
        return self.deserialise_inventory(
 
 
504
            revision_id, self.get_inventory_xml(revision_id))
 
 
506
    def deserialise_inventory(self, revision_id, xml):
 
 
507
        """Transform the xml into an inventory object. 
 
 
509
        :param revision_id: The expected revision id of the inventory.
 
 
510
        :param xml: A serialised inventory.
 
 
512
        result = self._serializer.read_inventory_from_string(xml)
 
 
513
        result.root.revision = revision_id
 
 
516
    def serialise_inventory(self, inv):
 
 
517
        return self._serializer.write_inventory_to_string(inv)
 
 
520
    def get_inventory_xml(self, revision_id):
 
 
521
        """Get inventory XML as a file object."""
 
 
523
            assert isinstance(revision_id, basestring), type(revision_id)
 
 
524
            iw = self.get_inventory_weave()
 
 
525
            return iw.get_text(revision_id)
 
 
527
            raise errors.HistoryMissing(self, 'inventory', revision_id)
 
 
530
    def get_inventory_sha1(self, revision_id):
 
 
531
        """Return the sha1 hash of the inventory entry
 
 
533
        return self.get_revision(revision_id).inventory_sha1
 
 
536
    def get_revision_graph(self, revision_id=None):
 
 
537
        """Return a dictionary containing the revision graph.
 
 
539
        :param revision_id: The revision_id to get a graph from. If None, then
 
 
540
        the entire revision graph is returned. This is a deprecated mode of
 
 
541
        operation and will be removed in the future.
 
 
542
        :return: a dictionary of revision_id->revision_parents_list.
 
 
544
        # special case NULL_REVISION
 
 
545
        if revision_id == _mod_revision.NULL_REVISION:
 
 
547
        a_weave = self.get_inventory_weave()
 
 
548
        all_revisions = self._eliminate_revisions_not_present(
 
 
550
        entire_graph = dict([(node, a_weave.get_parents(node)) for 
 
 
551
                             node in all_revisions])
 
 
552
        if revision_id is None:
 
 
554
        elif revision_id not in entire_graph:
 
 
555
            raise errors.NoSuchRevision(self, revision_id)
 
 
557
            # add what can be reached from revision_id
 
 
559
            pending = set([revision_id])
 
 
560
            while len(pending) > 0:
 
 
562
                result[node] = entire_graph[node]
 
 
563
                for revision_id in result[node]:
 
 
564
                    if revision_id not in result:
 
 
565
                        pending.add(revision_id)
 
 
569
    def get_revision_graph_with_ghosts(self, revision_ids=None):
 
 
570
        """Return a graph of the revisions with ghosts marked as applicable.
 
 
572
        :param revision_ids: an iterable of revisions to graph or None for all.
 
 
573
        :return: a Graph object with the graph reachable from revision_ids.
 
 
575
        result = graph.Graph()
 
 
577
            pending = set(self.all_revision_ids())
 
 
580
            pending = set(revision_ids)
 
 
581
            # special case NULL_REVISION
 
 
582
            if _mod_revision.NULL_REVISION in pending:
 
 
583
                pending.remove(_mod_revision.NULL_REVISION)
 
 
584
            required = set(pending)
 
 
587
            revision_id = pending.pop()
 
 
589
                rev = self.get_revision(revision_id)
 
 
590
            except errors.NoSuchRevision:
 
 
591
                if revision_id in required:
 
 
594
                result.add_ghost(revision_id)
 
 
596
            for parent_id in rev.parent_ids:
 
 
597
                # is this queued or done ?
 
 
598
                if (parent_id not in pending and
 
 
599
                    parent_id not in done):
 
 
601
                    pending.add(parent_id)
 
 
602
            result.add_node(revision_id, rev.parent_ids)
 
 
603
            done.add(revision_id)
 
 
607
    def get_revision_inventory(self, revision_id):
 
 
608
        """Return inventory of a past revision."""
 
 
609
        # TODO: Unify this with get_inventory()
 
 
610
        # bzr 0.0.6 and later imposes the constraint that the inventory_id
 
 
611
        # must be the same as its revision, so this is trivial.
 
 
612
        if revision_id is None:
 
 
613
            # This does not make sense: if there is no revision,
 
 
614
            # then it is the current tree inventory surely ?!
 
 
615
            # and thus get_root_id() is something that looks at the last
 
 
616
            # commit on the branch, and the get_root_id is an inventory check.
 
 
617
            raise NotImplementedError
 
 
618
            # return Inventory(self.get_root_id())
 
 
620
            return self.get_inventory(revision_id)
 
 
624
        """Return True if this repository is flagged as a shared repository."""
 
 
625
        raise NotImplementedError(self.is_shared)
 
 
628
    def reconcile(self, other=None, thorough=False):
 
 
629
        """Reconcile this repository."""
 
 
630
        from bzrlib.reconcile import RepoReconciler
 
 
631
        reconciler = RepoReconciler(self, thorough=thorough)
 
 
632
        reconciler.reconcile()
 
 
636
    def revision_tree(self, revision_id):
 
 
637
        """Return Tree for a revision on this branch.
 
 
639
        `revision_id` may be None for the empty tree revision.
 
 
641
        # TODO: refactor this to use an existing revision object
 
 
642
        # so we don't need to read it in twice.
 
 
643
        if revision_id is None or revision_id == _mod_revision.NULL_REVISION:
 
 
644
            return RevisionTree(self, Inventory(root_id=None), 
 
 
645
                                _mod_revision.NULL_REVISION)
 
 
647
            inv = self.get_revision_inventory(revision_id)
 
 
648
            return RevisionTree(self, inv, revision_id)
 
 
651
    def revision_trees(self, revision_ids):
 
 
652
        """Return Tree for a revision on this branch.
 
 
654
        `revision_id` may not be None or 'null:'"""
 
 
655
        assert None not in revision_ids
 
 
656
        assert _mod_revision.NULL_REVISION not in revision_ids
 
 
657
        texts = self.get_inventory_weave().get_texts(revision_ids)
 
 
658
        for text, revision_id in zip(texts, revision_ids):
 
 
659
            inv = self.deserialise_inventory(revision_id, text)
 
 
660
            yield RevisionTree(self, inv, revision_id)
 
 
663
    def get_ancestry(self, revision_id):
 
 
664
        """Return a list of revision-ids integrated by a revision.
 
 
666
        The first element of the list is always None, indicating the origin 
 
 
667
        revision.  This might change when we have history horizons, or 
 
 
668
        perhaps we should have a new API.
 
 
670
        This is topologically sorted.
 
 
672
        if revision_id is None:
 
 
674
        if not self.has_revision(revision_id):
 
 
675
            raise errors.NoSuchRevision(self, revision_id)
 
 
676
        w = self.get_inventory_weave()
 
 
677
        candidates = w.get_ancestry(revision_id)
 
 
678
        return [None] + candidates # self._eliminate_revisions_not_present(candidates)
 
 
681
    def print_file(self, file, revision_id):
 
 
682
        """Print `file` to stdout.
 
 
684
        FIXME RBC 20060125 as John Meinel points out this is a bad api
 
 
685
        - it writes to stdout, it assumes that that is valid etc. Fix
 
 
686
        by creating a new more flexible convenience function.
 
 
688
        tree = self.revision_tree(revision_id)
 
 
689
        # use inventory as it was in that revision
 
 
690
        file_id = tree.inventory.path2id(file)
 
 
692
            # TODO: jam 20060427 Write a test for this code path
 
 
693
            #       it had a bug in it, and was raising the wrong
 
 
695
            raise errors.BzrError("%r is not present in revision %s" % (file, revision_id))
 
 
696
        tree.print_file(file_id)
 
 
698
    def get_transaction(self):
 
 
699
        return self.control_files.get_transaction()
 
 
701
    def revision_parents(self, revid):
 
 
702
        return self.get_inventory_weave().parent_names(revid)
 
 
705
    def set_make_working_trees(self, new_value):
 
 
706
        """Set the policy flag for making working trees when creating branches.
 
 
708
        This only applies to branches that use this repository.
 
 
710
        The default is 'True'.
 
 
711
        :param new_value: True to restore the default, False to disable making
 
 
714
        raise NotImplementedError(self.set_make_working_trees)
 
 
716
    def make_working_trees(self):
 
 
717
        """Returns the policy for making working trees on new branches."""
 
 
718
        raise NotImplementedError(self.make_working_trees)
 
 
721
    def sign_revision(self, revision_id, gpg_strategy):
 
 
722
        plaintext = Testament.from_revision(self, revision_id).as_short_text()
 
 
723
        self.store_revision_signature(gpg_strategy, plaintext, revision_id)
 
 
726
    def has_signature_for_revision_id(self, revision_id):
 
 
727
        """Query for a revision signature for revision_id in the repository."""
 
 
728
        return self._revision_store.has_signature(revision_id,
 
 
729
                                                  self.get_transaction())
 
 
732
    def get_signature_text(self, revision_id):
 
 
733
        """Return the text for a signature."""
 
 
734
        return self._revision_store.get_signature_text(revision_id,
 
 
735
                                                       self.get_transaction())
 
 
738
    def check(self, revision_ids):
 
 
739
        """Check consistency of all history of given revision_ids.
 
 
741
        Different repository implementations should override _check().
 
 
743
        :param revision_ids: A non-empty list of revision_ids whose ancestry
 
 
744
             will be checked.  Typically the last revision_id of a branch.
 
 
747
            raise ValueError("revision_ids must be non-empty in %s.check" 
 
 
749
        return self._check(revision_ids)
 
 
751
    def _check(self, revision_ids):
 
 
752
        result = check.Check(self)
 
 
756
    def _warn_if_deprecated(self):
 
 
757
        global _deprecation_warning_done
 
 
758
        if _deprecation_warning_done:
 
 
760
        _deprecation_warning_done = True
 
 
761
        warning("Format %s for %s is deprecated - please use 'bzr upgrade' to get better performance"
 
 
762
                % (self._format, self.bzrdir.transport.base))
 
 
764
    def supports_rich_root(self):
 
 
765
        return self._format.rich_root_data
 
 
767
    def _check_ascii_revisionid(self, revision_id, method):
 
 
768
        """Private helper for ascii-only repositories."""
 
 
769
        # weave repositories refuse to store revisionids that are non-ascii.
 
 
770
        if revision_id is not None:
 
 
771
            # weaves require ascii revision ids.
 
 
772
            if isinstance(revision_id, unicode):
 
 
774
                    revision_id.encode('ascii')
 
 
775
                except UnicodeEncodeError:
 
 
776
                    raise errors.NonAsciiRevisionId(method, self)
 
 
779
class AllInOneRepository(Repository):
 
 
780
    """Legacy support - the repository behaviour for all-in-one branches."""
 
 
782
    def __init__(self, _format, a_bzrdir, _revision_store, control_store, text_store):
 
 
783
        # we reuse one control files instance.
 
 
784
        dir_mode = a_bzrdir._control_files._dir_mode
 
 
785
        file_mode = a_bzrdir._control_files._file_mode
 
 
787
        def get_store(name, compressed=True, prefixed=False):
 
 
788
            # FIXME: This approach of assuming stores are all entirely compressed
 
 
789
            # or entirely uncompressed is tidy, but breaks upgrade from 
 
 
790
            # some existing branches where there's a mixture; we probably 
 
 
791
            # still want the option to look for both.
 
 
792
            relpath = a_bzrdir._control_files._escape(name)
 
 
793
            store = TextStore(a_bzrdir._control_files._transport.clone(relpath),
 
 
794
                              prefixed=prefixed, compressed=compressed,
 
 
797
            #if self._transport.should_cache():
 
 
798
            #    cache_path = os.path.join(self.cache_root, name)
 
 
799
            #    os.mkdir(cache_path)
 
 
800
            #    store = bzrlib.store.CachedStore(store, cache_path)
 
 
803
        # not broken out yet because the controlweaves|inventory_store
 
 
804
        # and text_store | weave_store bits are still different.
 
 
805
        if isinstance(_format, RepositoryFormat4):
 
 
806
            # cannot remove these - there is still no consistent api 
 
 
807
            # which allows access to this old info.
 
 
808
            self.inventory_store = get_store('inventory-store')
 
 
809
            text_store = get_store('text-store')
 
 
810
        super(AllInOneRepository, self).__init__(_format, a_bzrdir, a_bzrdir._control_files, _revision_store, control_store, text_store)
 
 
812
    def get_commit_builder(self, branch, parents, config, timestamp=None,
 
 
813
                           timezone=None, committer=None, revprops=None,
 
 
815
        self._check_ascii_revisionid(revision_id, self.get_commit_builder)
 
 
816
        return Repository.get_commit_builder(self, branch, parents, config,
 
 
817
            timestamp, timezone, committer, revprops, revision_id)
 
 
821
        """AllInOne repositories cannot be shared."""
 
 
825
    def set_make_working_trees(self, new_value):
 
 
826
        """Set the policy flag for making working trees when creating branches.
 
 
828
        This only applies to branches that use this repository.
 
 
830
        The default is 'True'.
 
 
831
        :param new_value: True to restore the default, False to disable making
 
 
834
        raise NotImplementedError(self.set_make_working_trees)
 
 
836
    def make_working_trees(self):
 
 
837
        """Returns the policy for making working trees on new branches."""
 
 
841
def install_revision(repository, rev, revision_tree):
 
 
842
    """Install all revision data into a repository."""
 
 
845
    for p_id in rev.parent_ids:
 
 
846
        if repository.has_revision(p_id):
 
 
847
            present_parents.append(p_id)
 
 
848
            parent_trees[p_id] = repository.revision_tree(p_id)
 
 
850
            parent_trees[p_id] = repository.revision_tree(None)
 
 
852
    inv = revision_tree.inventory
 
 
853
    entries = inv.iter_entries()
 
 
854
    # backwards compatability hack: skip the root id.
 
 
855
    if not repository.supports_rich_root():
 
 
856
        path, root = entries.next()
 
 
857
        if root.revision != rev.revision_id:
 
 
858
            raise errors.IncompatibleRevision(repr(repository))
 
 
859
    # Add the texts that are not already present
 
 
860
    for path, ie in entries:
 
 
861
        w = repository.weave_store.get_weave_or_empty(ie.file_id,
 
 
862
                repository.get_transaction())
 
 
863
        if ie.revision not in w:
 
 
865
            # FIXME: TODO: The following loop *may* be overlapping/duplicate
 
 
866
            # with InventoryEntry.find_previous_heads(). if it is, then there
 
 
867
            # is a latent bug here where the parents may have ancestors of each
 
 
869
            for revision, tree in parent_trees.iteritems():
 
 
870
                if ie.file_id not in tree:
 
 
872
                parent_id = tree.inventory[ie.file_id].revision
 
 
873
                if parent_id in text_parents:
 
 
875
                text_parents.append(parent_id)
 
 
877
            vfile = repository.weave_store.get_weave_or_empty(ie.file_id, 
 
 
878
                repository.get_transaction())
 
 
879
            lines = revision_tree.get_file(ie.file_id).readlines()
 
 
880
            vfile.add_lines(rev.revision_id, text_parents, lines)
 
 
882
        # install the inventory
 
 
883
        repository.add_inventory(rev.revision_id, inv, present_parents)
 
 
884
    except errors.RevisionAlreadyPresent:
 
 
886
    repository.add_revision(rev.revision_id, rev, inv)
 
 
889
class MetaDirRepository(Repository):
 
 
890
    """Repositories in the new meta-dir layout."""
 
 
892
    def __init__(self, _format, a_bzrdir, control_files, _revision_store, control_store, text_store):
 
 
893
        super(MetaDirRepository, self).__init__(_format,
 
 
899
        dir_mode = self.control_files._dir_mode
 
 
900
        file_mode = self.control_files._file_mode
 
 
904
        """Return True if this repository is flagged as a shared repository."""
 
 
905
        return self.control_files._transport.has('shared-storage')
 
 
908
    def set_make_working_trees(self, new_value):
 
 
909
        """Set the policy flag for making working trees when creating branches.
 
 
911
        This only applies to branches that use this repository.
 
 
913
        The default is 'True'.
 
 
914
        :param new_value: True to restore the default, False to disable making
 
 
919
                self.control_files._transport.delete('no-working-trees')
 
 
920
            except errors.NoSuchFile:
 
 
923
            self.control_files.put_utf8('no-working-trees', '')
 
 
925
    def make_working_trees(self):
 
 
926
        """Returns the policy for making working trees on new branches."""
 
 
927
        return not self.control_files._transport.has('no-working-trees')
 
 
930
class WeaveMetaDirRepository(MetaDirRepository):
 
 
931
    """A subclass of MetaDirRepository to set weave specific policy."""
 
 
933
    def get_commit_builder(self, branch, parents, config, timestamp=None,
 
 
934
                           timezone=None, committer=None, revprops=None,
 
 
936
        self._check_ascii_revisionid(revision_id, self.get_commit_builder)
 
 
937
        return MetaDirRepository.get_commit_builder(self, branch, parents,
 
 
938
            config, timestamp, timezone, committer, revprops, revision_id)
 
 
941
class KnitRepository(MetaDirRepository):
 
 
942
    """Knit format repository."""
 
 
944
    def _warn_if_deprecated(self):
 
 
945
        # This class isn't deprecated
 
 
948
    def _inventory_add_lines(self, inv_vf, revid, parents, lines):
 
 
949
        inv_vf.add_lines_with_ghosts(revid, parents, lines)
 
 
952
    def _all_revision_ids(self):
 
 
953
        """See Repository.all_revision_ids()."""
 
 
954
        # Knits get the revision graph from the index of the revision knit, so
 
 
955
        # it's always possible even if they're on an unlistable transport.
 
 
956
        return self._revision_store.all_revision_ids(self.get_transaction())
 
 
958
    def fileid_involved_between_revs(self, from_revid, to_revid):
 
 
959
        """Find file_id(s) which are involved in the changes between revisions.
 
 
961
        This determines the set of revisions which are involved, and then
 
 
962
        finds all file ids affected by those revisions.
 
 
964
        vf = self._get_revision_vf()
 
 
965
        from_set = set(vf.get_ancestry(from_revid))
 
 
966
        to_set = set(vf.get_ancestry(to_revid))
 
 
967
        changed = to_set.difference(from_set)
 
 
968
        return self._fileid_involved_by_set(changed)
 
 
970
    def fileid_involved(self, last_revid=None):
 
 
971
        """Find all file_ids modified in the ancestry of last_revid.
 
 
973
        :param last_revid: If None, last_revision() will be used.
 
 
976
            changed = set(self.all_revision_ids())
 
 
978
            changed = set(self.get_ancestry(last_revid))
 
 
981
        return self._fileid_involved_by_set(changed)
 
 
984
    def get_ancestry(self, revision_id):
 
 
985
        """Return a list of revision-ids integrated by a revision.
 
 
987
        This is topologically sorted.
 
 
989
        if revision_id is None:
 
 
991
        vf = self._get_revision_vf()
 
 
993
            return [None] + vf.get_ancestry(revision_id)
 
 
994
        except errors.RevisionNotPresent:
 
 
995
            raise errors.NoSuchRevision(self, revision_id)
 
 
998
    def get_revision(self, revision_id):
 
 
999
        """Return the Revision object for a named revision"""
 
 
1000
        return self.get_revision_reconcile(revision_id)
 
 
1003
    def get_revision_graph(self, revision_id=None):
 
 
1004
        """Return a dictionary containing the revision graph.
 
 
1006
        :param revision_id: The revision_id to get a graph from. If None, then
 
 
1007
        the entire revision graph is returned. This is a deprecated mode of
 
 
1008
        operation and will be removed in the future.
 
 
1009
        :return: a dictionary of revision_id->revision_parents_list.
 
 
1011
        # special case NULL_REVISION
 
 
1012
        if revision_id == _mod_revision.NULL_REVISION:
 
 
1014
        a_weave = self._get_revision_vf()
 
 
1015
        entire_graph = a_weave.get_graph()
 
 
1016
        if revision_id is None:
 
 
1017
            return a_weave.get_graph()
 
 
1018
        elif revision_id not in a_weave:
 
 
1019
            raise errors.NoSuchRevision(self, revision_id)
 
 
1021
            # add what can be reached from revision_id
 
 
1023
            pending = set([revision_id])
 
 
1024
            while len(pending) > 0:
 
 
1025
                node = pending.pop()
 
 
1026
                result[node] = a_weave.get_parents(node)
 
 
1027
                for revision_id in result[node]:
 
 
1028
                    if revision_id not in result:
 
 
1029
                        pending.add(revision_id)
 
 
1033
    def get_revision_graph_with_ghosts(self, revision_ids=None):
 
 
1034
        """Return a graph of the revisions with ghosts marked as applicable.
 
 
1036
        :param revision_ids: an iterable of revisions to graph or None for all.
 
 
1037
        :return: a Graph object with the graph reachable from revision_ids.
 
 
1039
        result = graph.Graph()
 
 
1040
        vf = self._get_revision_vf()
 
 
1041
        versions = set(vf.versions())
 
 
1042
        if not revision_ids:
 
 
1043
            pending = set(self.all_revision_ids())
 
 
1046
            pending = set(revision_ids)
 
 
1047
            # special case NULL_REVISION
 
 
1048
            if _mod_revision.NULL_REVISION in pending:
 
 
1049
                pending.remove(_mod_revision.NULL_REVISION)
 
 
1050
            required = set(pending)
 
 
1053
            revision_id = pending.pop()
 
 
1054
            if not revision_id in versions:
 
 
1055
                if revision_id in required:
 
 
1056
                    raise errors.NoSuchRevision(self, revision_id)
 
 
1058
                result.add_ghost(revision_id)
 
 
1059
                # mark it as done so we don't try for it again.
 
 
1060
                done.add(revision_id)
 
 
1062
            parent_ids = vf.get_parents_with_ghosts(revision_id)
 
 
1063
            for parent_id in parent_ids:
 
 
1064
                # is this queued or done ?
 
 
1065
                if (parent_id not in pending and
 
 
1066
                    parent_id not in done):
 
 
1068
                    pending.add(parent_id)
 
 
1069
            result.add_node(revision_id, parent_ids)
 
 
1070
            done.add(revision_id)
 
 
1073
    def _get_revision_vf(self):
 
 
1074
        """:return: a versioned file containing the revisions."""
 
 
1075
        vf = self._revision_store.get_revision_file(self.get_transaction())
 
 
1079
    def reconcile(self, other=None, thorough=False):
 
 
1080
        """Reconcile this repository."""
 
 
1081
        from bzrlib.reconcile import KnitReconciler
 
 
1082
        reconciler = KnitReconciler(self, thorough=thorough)
 
 
1083
        reconciler.reconcile()
 
 
1086
    def revision_parents(self, revision_id):
 
 
1087
        return self._get_revision_vf().get_parents(revision_id)
 
 
1090
class KnitRepository2(KnitRepository):
 
 
1092
    def __init__(self, _format, a_bzrdir, control_files, _revision_store,
 
 
1093
                 control_store, text_store):
 
 
1094
        KnitRepository.__init__(self, _format, a_bzrdir, control_files,
 
 
1095
                              _revision_store, control_store, text_store)
 
 
1096
        self._serializer = xml6.serializer_v6
 
 
1098
    def deserialise_inventory(self, revision_id, xml):
 
 
1099
        """Transform the xml into an inventory object. 
 
 
1101
        :param revision_id: The expected revision id of the inventory.
 
 
1102
        :param xml: A serialised inventory.
 
 
1104
        result = self._serializer.read_inventory_from_string(xml)
 
 
1105
        assert result.root.revision is not None
 
 
1108
    def serialise_inventory(self, inv):
 
 
1109
        """Transform the inventory object into XML text.
 
 
1111
        :param revision_id: The expected revision id of the inventory.
 
 
1112
        :param xml: A serialised inventory.
 
 
1114
        assert inv.revision_id is not None
 
 
1115
        assert inv.root.revision is not None
 
 
1116
        return KnitRepository.serialise_inventory(self, inv)
 
 
1118
    def get_commit_builder(self, branch, parents, config, timestamp=None, 
 
 
1119
                           timezone=None, committer=None, revprops=None, 
 
 
1121
        """Obtain a CommitBuilder for this repository.
 
 
1123
        :param branch: Branch to commit to.
 
 
1124
        :param parents: Revision ids of the parents of the new revision.
 
 
1125
        :param config: Configuration to use.
 
 
1126
        :param timestamp: Optional timestamp recorded for commit.
 
 
1127
        :param timezone: Optional timezone for timestamp.
 
 
1128
        :param committer: Optional committer to set for commit.
 
 
1129
        :param revprops: Optional dictionary of revision properties.
 
 
1130
        :param revision_id: Optional revision id.
 
 
1132
        return RootCommitBuilder(self, parents, config, timestamp, timezone,
 
 
1133
                                 committer, revprops, revision_id)
 
 
1136
class RepositoryFormat(object):
 
 
1137
    """A repository format.
 
 
1139
    Formats provide three things:
 
 
1140
     * An initialization routine to construct repository data on disk.
 
 
1141
     * a format string which is used when the BzrDir supports versioned
 
 
1143
     * an open routine which returns a Repository instance.
 
 
1145
    Formats are placed in an dict by their format string for reference 
 
 
1146
    during opening. These should be subclasses of RepositoryFormat
 
 
1149
    Once a format is deprecated, just deprecate the initialize and open
 
 
1150
    methods on the format class. Do not deprecate the object, as the 
 
 
1151
    object will be created every system load.
 
 
1153
    Common instance attributes:
 
 
1154
    _matchingbzrdir - the bzrdir format that the repository format was
 
 
1155
    originally written to work with. This can be used if manually
 
 
1156
    constructing a bzrdir and repository, or more commonly for test suite
 
 
1160
    _default_format = None
 
 
1161
    """The default format used for new repositories."""
 
 
1164
    """The known formats."""
 
 
1167
        return "<%s>" % self.__class__.__name__
 
 
1170
    def find_format(klass, a_bzrdir):
 
 
1171
        """Return the format for the repository object in a_bzrdir."""
 
 
1173
            transport = a_bzrdir.get_repository_transport(None)
 
 
1174
            format_string = transport.get("format").read()
 
 
1175
            return klass._formats[format_string]
 
 
1176
        except errors.NoSuchFile:
 
 
1177
            raise errors.NoRepositoryPresent(a_bzrdir)
 
 
1179
            raise errors.UnknownFormatError(format=format_string)
 
 
1181
    def _get_control_store(self, repo_transport, control_files):
 
 
1182
        """Return the control store for this repository."""
 
 
1183
        raise NotImplementedError(self._get_control_store)
 
 
1186
    def get_default_format(klass):
 
 
1187
        """Return the current default format."""
 
 
1188
        return klass._default_format
 
 
1190
    def get_format_string(self):
 
 
1191
        """Return the ASCII format string that identifies this format.
 
 
1193
        Note that in pre format ?? repositories the format string is 
 
 
1194
        not permitted nor written to disk.
 
 
1196
        raise NotImplementedError(self.get_format_string)
 
 
1198
    def get_format_description(self):
 
 
1199
        """Return the short description for this format."""
 
 
1200
        raise NotImplementedError(self.get_format_description)
 
 
1202
    def _get_revision_store(self, repo_transport, control_files):
 
 
1203
        """Return the revision store object for this a_bzrdir."""
 
 
1204
        raise NotImplementedError(self._get_revision_store)
 
 
1206
    def _get_text_rev_store(self,
 
 
1213
        """Common logic for getting a revision store for a repository.
 
 
1215
        see self._get_revision_store for the subclass-overridable method to 
 
 
1216
        get the store for a repository.
 
 
1218
        from bzrlib.store.revision.text import TextRevisionStore
 
 
1219
        dir_mode = control_files._dir_mode
 
 
1220
        file_mode = control_files._file_mode
 
 
1221
        text_store =TextStore(transport.clone(name),
 
 
1223
                              compressed=compressed,
 
 
1225
                              file_mode=file_mode)
 
 
1226
        _revision_store = TextRevisionStore(text_store, serializer)
 
 
1227
        return _revision_store
 
 
1229
    def _get_versioned_file_store(self,
 
 
1234
                                  versionedfile_class=weave.WeaveFile,
 
 
1235
                                  versionedfile_kwargs={},
 
 
1237
        weave_transport = control_files._transport.clone(name)
 
 
1238
        dir_mode = control_files._dir_mode
 
 
1239
        file_mode = control_files._file_mode
 
 
1240
        return VersionedFileStore(weave_transport, prefixed=prefixed,
 
 
1242
                                  file_mode=file_mode,
 
 
1243
                                  versionedfile_class=versionedfile_class,
 
 
1244
                                  versionedfile_kwargs=versionedfile_kwargs,
 
 
1247
    def initialize(self, a_bzrdir, shared=False):
 
 
1248
        """Initialize a repository of this format in a_bzrdir.
 
 
1250
        :param a_bzrdir: The bzrdir to put the new repository in it.
 
 
1251
        :param shared: The repository should be initialized as a sharable one.
 
 
1253
        This may raise UninitializableFormat if shared repository are not
 
 
1254
        compatible the a_bzrdir.
 
 
1257
    def is_supported(self):
 
 
1258
        """Is this format supported?
 
 
1260
        Supported formats must be initializable and openable.
 
 
1261
        Unsupported formats may not support initialization or committing or 
 
 
1262
        some other features depending on the reason for not being supported.
 
 
1266
    def check_conversion_target(self, target_format):
 
 
1267
        raise NotImplementedError(self.check_conversion_target)
 
 
1269
    def open(self, a_bzrdir, _found=False):
 
 
1270
        """Return an instance of this format for the bzrdir a_bzrdir.
 
 
1272
        _found is a private parameter, do not use it.
 
 
1274
        raise NotImplementedError(self.open)
 
 
1277
    def register_format(klass, format):
 
 
1278
        klass._formats[format.get_format_string()] = format
 
 
1281
    def set_default_format(klass, format):
 
 
1282
        klass._default_format = format
 
 
1285
    def unregister_format(klass, format):
 
 
1286
        assert klass._formats[format.get_format_string()] is format
 
 
1287
        del klass._formats[format.get_format_string()]
 
 
1290
class PreSplitOutRepositoryFormat(RepositoryFormat):
 
 
1291
    """Base class for the pre split out repository formats."""
 
 
1293
    rich_root_data = False
 
 
1295
    def initialize(self, a_bzrdir, shared=False, _internal=False):
 
 
1296
        """Create a weave repository.
 
 
1298
        TODO: when creating split out bzr branch formats, move this to a common
 
 
1299
        base for Format5, Format6. or something like that.
 
 
1302
            raise errors.IncompatibleFormat(self, a_bzrdir._format)
 
 
1305
            # always initialized when the bzrdir is.
 
 
1306
            return self.open(a_bzrdir, _found=True)
 
 
1308
        # Create an empty weave
 
 
1310
        weavefile.write_weave_v5(weave.Weave(), sio)
 
 
1311
        empty_weave = sio.getvalue()
 
 
1313
        mutter('creating repository in %s.', a_bzrdir.transport.base)
 
 
1314
        dirs = ['revision-store', 'weaves']
 
 
1315
        files = [('inventory.weave', StringIO(empty_weave)),
 
 
1318
        # FIXME: RBC 20060125 don't peek under the covers
 
 
1319
        # NB: no need to escape relative paths that are url safe.
 
 
1320
        control_files = lockable_files.LockableFiles(a_bzrdir.transport,
 
 
1321
                                'branch-lock', lockable_files.TransportLock)
 
 
1322
        control_files.create_lock()
 
 
1323
        control_files.lock_write()
 
 
1324
        control_files._transport.mkdir_multi(dirs,
 
 
1325
                mode=control_files._dir_mode)
 
 
1327
            for file, content in files:
 
 
1328
                control_files.put(file, content)
 
 
1330
            control_files.unlock()
 
 
1331
        return self.open(a_bzrdir, _found=True)
 
 
1333
    def _get_control_store(self, repo_transport, control_files):
 
 
1334
        """Return the control store for this repository."""
 
 
1335
        return self._get_versioned_file_store('',
 
 
1340
    def _get_text_store(self, transport, control_files):
 
 
1341
        """Get a store for file texts for this format."""
 
 
1342
        raise NotImplementedError(self._get_text_store)
 
 
1344
    def open(self, a_bzrdir, _found=False):
 
 
1345
        """See RepositoryFormat.open()."""
 
 
1347
            # we are being called directly and must probe.
 
 
1348
            raise NotImplementedError
 
 
1350
        repo_transport = a_bzrdir.get_repository_transport(None)
 
 
1351
        control_files = a_bzrdir._control_files
 
 
1352
        text_store = self._get_text_store(repo_transport, control_files)
 
 
1353
        control_store = self._get_control_store(repo_transport, control_files)
 
 
1354
        _revision_store = self._get_revision_store(repo_transport, control_files)
 
 
1355
        return AllInOneRepository(_format=self,
 
 
1357
                                  _revision_store=_revision_store,
 
 
1358
                                  control_store=control_store,
 
 
1359
                                  text_store=text_store)
 
 
1361
    def check_conversion_target(self, target_format):
 
 
1365
class RepositoryFormat4(PreSplitOutRepositoryFormat):
 
 
1366
    """Bzr repository format 4.
 
 
1368
    This repository format has:
 
 
1370
     - TextStores for texts, inventories,revisions.
 
 
1372
    This format is deprecated: it indexes texts using a text id which is
 
 
1373
    removed in format 5; initialization and write support for this format
 
 
1378
        super(RepositoryFormat4, self).__init__()
 
 
1379
        self._matchingbzrdir = bzrdir.BzrDirFormat4()
 
 
1381
    def get_format_description(self):
 
 
1382
        """See RepositoryFormat.get_format_description()."""
 
 
1383
        return "Repository format 4"
 
 
1385
    def initialize(self, url, shared=False, _internal=False):
 
 
1386
        """Format 4 branches cannot be created."""
 
 
1387
        raise errors.UninitializableFormat(self)
 
 
1389
    def is_supported(self):
 
 
1390
        """Format 4 is not supported.
 
 
1392
        It is not supported because the model changed from 4 to 5 and the
 
 
1393
        conversion logic is expensive - so doing it on the fly was not 
 
 
1398
    def _get_control_store(self, repo_transport, control_files):
 
 
1399
        """Format 4 repositories have no formal control store at this point.
 
 
1401
        This will cause any control-file-needing apis to fail - this is desired.
 
 
1405
    def _get_revision_store(self, repo_transport, control_files):
 
 
1406
        """See RepositoryFormat._get_revision_store()."""
 
 
1407
        from bzrlib.xml4 import serializer_v4
 
 
1408
        return self._get_text_rev_store(repo_transport,
 
 
1411
                                        serializer=serializer_v4)
 
 
1413
    def _get_text_store(self, transport, control_files):
 
 
1414
        """See RepositoryFormat._get_text_store()."""
 
 
1417
class RepositoryFormat5(PreSplitOutRepositoryFormat):
 
 
1418
    """Bzr control format 5.
 
 
1420
    This repository format has:
 
 
1421
     - weaves for file texts and inventory
 
 
1423
     - TextStores for revisions and signatures.
 
 
1427
        super(RepositoryFormat5, self).__init__()
 
 
1428
        self._matchingbzrdir = bzrdir.BzrDirFormat5()
 
 
1430
    def get_format_description(self):
 
 
1431
        """See RepositoryFormat.get_format_description()."""
 
 
1432
        return "Weave repository format 5"
 
 
1434
    def _get_revision_store(self, repo_transport, control_files):
 
 
1435
        """See RepositoryFormat._get_revision_store()."""
 
 
1436
        """Return the revision store object for this a_bzrdir."""
 
 
1437
        return self._get_text_rev_store(repo_transport,
 
 
1442
    def _get_text_store(self, transport, control_files):
 
 
1443
        """See RepositoryFormat._get_text_store()."""
 
 
1444
        return self._get_versioned_file_store('weaves', transport, control_files, prefixed=False)
 
 
1447
class RepositoryFormat6(PreSplitOutRepositoryFormat):
 
 
1448
    """Bzr control format 6.
 
 
1450
    This repository format has:
 
 
1451
     - weaves for file texts and inventory
 
 
1452
     - hash subdirectory based stores.
 
 
1453
     - TextStores for revisions and signatures.
 
 
1457
        super(RepositoryFormat6, self).__init__()
 
 
1458
        self._matchingbzrdir = bzrdir.BzrDirFormat6()
 
 
1460
    def get_format_description(self):
 
 
1461
        """See RepositoryFormat.get_format_description()."""
 
 
1462
        return "Weave repository format 6"
 
 
1464
    def _get_revision_store(self, repo_transport, control_files):
 
 
1465
        """See RepositoryFormat._get_revision_store()."""
 
 
1466
        return self._get_text_rev_store(repo_transport,
 
 
1472
    def _get_text_store(self, transport, control_files):
 
 
1473
        """See RepositoryFormat._get_text_store()."""
 
 
1474
        return self._get_versioned_file_store('weaves', transport, control_files)
 
 
1477
class MetaDirRepositoryFormat(RepositoryFormat):
 
 
1478
    """Common base class for the new repositories using the metadir layout."""
 
 
1480
    rich_root_data = False
 
 
1483
        super(MetaDirRepositoryFormat, self).__init__()
 
 
1484
        self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
 
 
1486
    def _create_control_files(self, a_bzrdir):
 
 
1487
        """Create the required files and the initial control_files object."""
 
 
1488
        # FIXME: RBC 20060125 don't peek under the covers
 
 
1489
        # NB: no need to escape relative paths that are url safe.
 
 
1490
        repository_transport = a_bzrdir.get_repository_transport(self)
 
 
1491
        control_files = lockable_files.LockableFiles(repository_transport,
 
 
1492
                                'lock', lockdir.LockDir)
 
 
1493
        control_files.create_lock()
 
 
1494
        return control_files
 
 
1496
    def _upload_blank_content(self, a_bzrdir, dirs, files, utf8_files, shared):
 
 
1497
        """Upload the initial blank content."""
 
 
1498
        control_files = self._create_control_files(a_bzrdir)
 
 
1499
        control_files.lock_write()
 
 
1501
            control_files._transport.mkdir_multi(dirs,
 
 
1502
                    mode=control_files._dir_mode)
 
 
1503
            for file, content in files:
 
 
1504
                control_files.put(file, content)
 
 
1505
            for file, content in utf8_files:
 
 
1506
                control_files.put_utf8(file, content)
 
 
1508
                control_files.put_utf8('shared-storage', '')
 
 
1510
            control_files.unlock()
 
 
1513
class RepositoryFormat7(MetaDirRepositoryFormat):
 
 
1514
    """Bzr repository 7.
 
 
1516
    This repository format has:
 
 
1517
     - weaves for file texts and inventory
 
 
1518
     - hash subdirectory based stores.
 
 
1519
     - TextStores for revisions and signatures.
 
 
1520
     - a format marker of its own
 
 
1521
     - an optional 'shared-storage' flag
 
 
1522
     - an optional 'no-working-trees' flag
 
 
1525
    def _get_control_store(self, repo_transport, control_files):
 
 
1526
        """Return the control store for this repository."""
 
 
1527
        return self._get_versioned_file_store('',
 
 
1532
    def get_format_string(self):
 
 
1533
        """See RepositoryFormat.get_format_string()."""
 
 
1534
        return "Bazaar-NG Repository format 7"
 
 
1536
    def get_format_description(self):
 
 
1537
        """See RepositoryFormat.get_format_description()."""
 
 
1538
        return "Weave repository format 7"
 
 
1540
    def check_conversion_target(self, target_format):
 
 
1543
    def _get_revision_store(self, repo_transport, control_files):
 
 
1544
        """See RepositoryFormat._get_revision_store()."""
 
 
1545
        return self._get_text_rev_store(repo_transport,
 
 
1552
    def _get_text_store(self, transport, control_files):
 
 
1553
        """See RepositoryFormat._get_text_store()."""
 
 
1554
        return self._get_versioned_file_store('weaves',
 
 
1558
    def initialize(self, a_bzrdir, shared=False):
 
 
1559
        """Create a weave repository.
 
 
1561
        :param shared: If true the repository will be initialized as a shared
 
 
1564
        # Create an empty weave
 
 
1566
        weavefile.write_weave_v5(weave.Weave(), sio)
 
 
1567
        empty_weave = sio.getvalue()
 
 
1569
        mutter('creating repository in %s.', a_bzrdir.transport.base)
 
 
1570
        dirs = ['revision-store', 'weaves']
 
 
1571
        files = [('inventory.weave', StringIO(empty_weave)), 
 
 
1573
        utf8_files = [('format', self.get_format_string())]
 
 
1575
        self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
 
 
1576
        return self.open(a_bzrdir=a_bzrdir, _found=True)
 
 
1578
    def open(self, a_bzrdir, _found=False, _override_transport=None):
 
 
1579
        """See RepositoryFormat.open().
 
 
1581
        :param _override_transport: INTERNAL USE ONLY. Allows opening the
 
 
1582
                                    repository at a slightly different url
 
 
1583
                                    than normal. I.e. during 'upgrade'.
 
 
1586
            format = RepositoryFormat.find_format(a_bzrdir)
 
 
1587
            assert format.__class__ ==  self.__class__
 
 
1588
        if _override_transport is not None:
 
 
1589
            repo_transport = _override_transport
 
 
1591
            repo_transport = a_bzrdir.get_repository_transport(None)
 
 
1592
        control_files = lockable_files.LockableFiles(repo_transport,
 
 
1593
                                'lock', lockdir.LockDir)
 
 
1594
        text_store = self._get_text_store(repo_transport, control_files)
 
 
1595
        control_store = self._get_control_store(repo_transport, control_files)
 
 
1596
        _revision_store = self._get_revision_store(repo_transport, control_files)
 
 
1597
        return WeaveMetaDirRepository(_format=self,
 
 
1599
            control_files=control_files,
 
 
1600
            _revision_store=_revision_store,
 
 
1601
            control_store=control_store,
 
 
1602
            text_store=text_store)
 
 
1605
class RepositoryFormatKnit(MetaDirRepositoryFormat):
 
 
1606
    """Bzr repository knit format (generalized). 
 
 
1608
    This repository format has:
 
 
1609
     - knits for file texts and inventory
 
 
1610
     - hash subdirectory based stores.
 
 
1611
     - knits for revisions and signatures
 
 
1612
     - TextStores for revisions and signatures.
 
 
1613
     - a format marker of its own
 
 
1614
     - an optional 'shared-storage' flag
 
 
1615
     - an optional 'no-working-trees' flag
 
 
1619
    def _get_control_store(self, repo_transport, control_files):
 
 
1620
        """Return the control store for this repository."""
 
 
1621
        return VersionedFileStore(
 
 
1624
            file_mode=control_files._file_mode,
 
 
1625
            versionedfile_class=knit.KnitVersionedFile,
 
 
1626
            versionedfile_kwargs={'factory':knit.KnitPlainFactory()},
 
 
1629
    def _get_revision_store(self, repo_transport, control_files):
 
 
1630
        """See RepositoryFormat._get_revision_store()."""
 
 
1631
        from bzrlib.store.revision.knit import KnitRevisionStore
 
 
1632
        versioned_file_store = VersionedFileStore(
 
 
1634
            file_mode=control_files._file_mode,
 
 
1637
            versionedfile_class=knit.KnitVersionedFile,
 
 
1638
            versionedfile_kwargs={'delta':False,
 
 
1639
                                  'factory':knit.KnitPlainFactory(),
 
 
1643
        return KnitRevisionStore(versioned_file_store)
 
 
1645
    def _get_text_store(self, transport, control_files):
 
 
1646
        """See RepositoryFormat._get_text_store()."""
 
 
1647
        return self._get_versioned_file_store('knits',
 
 
1650
                                  versionedfile_class=knit.KnitVersionedFile,
 
 
1651
                                  versionedfile_kwargs={
 
 
1652
                                      'create_parent_dir':True,
 
 
1653
                                      'delay_create':True,
 
 
1654
                                      'dir_mode':control_files._dir_mode,
 
 
1658
    def initialize(self, a_bzrdir, shared=False):
 
 
1659
        """Create a knit format 1 repository.
 
 
1661
        :param a_bzrdir: bzrdir to contain the new repository; must already
 
 
1663
        :param shared: If true the repository will be initialized as a shared
 
 
1666
        mutter('creating repository in %s.', a_bzrdir.transport.base)
 
 
1667
        dirs = ['revision-store', 'knits']
 
 
1669
        utf8_files = [('format', self.get_format_string())]
 
 
1671
        self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
 
 
1672
        repo_transport = a_bzrdir.get_repository_transport(None)
 
 
1673
        control_files = lockable_files.LockableFiles(repo_transport,
 
 
1674
                                'lock', lockdir.LockDir)
 
 
1675
        control_store = self._get_control_store(repo_transport, control_files)
 
 
1676
        transaction = transactions.WriteTransaction()
 
 
1677
        # trigger a write of the inventory store.
 
 
1678
        control_store.get_weave_or_empty('inventory', transaction)
 
 
1679
        _revision_store = self._get_revision_store(repo_transport, control_files)
 
 
1680
        # the revision id here is irrelevant: it will not be stored, and cannot
 
 
1682
        _revision_store.has_revision_id('A', transaction)
 
 
1683
        _revision_store.get_signature_file(transaction)
 
 
1684
        return self.open(a_bzrdir=a_bzrdir, _found=True)
 
 
1686
    def open(self, a_bzrdir, _found=False, _override_transport=None):
 
 
1687
        """See RepositoryFormat.open().
 
 
1689
        :param _override_transport: INTERNAL USE ONLY. Allows opening the
 
 
1690
                                    repository at a slightly different url
 
 
1691
                                    than normal. I.e. during 'upgrade'.
 
 
1694
            format = RepositoryFormat.find_format(a_bzrdir)
 
 
1695
            assert format.__class__ ==  self.__class__
 
 
1696
        if _override_transport is not None:
 
 
1697
            repo_transport = _override_transport
 
 
1699
            repo_transport = a_bzrdir.get_repository_transport(None)
 
 
1700
        control_files = lockable_files.LockableFiles(repo_transport,
 
 
1701
                                'lock', lockdir.LockDir)
 
 
1702
        text_store = self._get_text_store(repo_transport, control_files)
 
 
1703
        control_store = self._get_control_store(repo_transport, control_files)
 
 
1704
        _revision_store = self._get_revision_store(repo_transport, control_files)
 
 
1705
        return KnitRepository(_format=self,
 
 
1707
                              control_files=control_files,
 
 
1708
                              _revision_store=_revision_store,
 
 
1709
                              control_store=control_store,
 
 
1710
                              text_store=text_store)
 
 
1713
class RepositoryFormatKnit1(RepositoryFormatKnit):
 
 
1714
    """Bzr repository knit format 1.
 
 
1716
    This repository format has:
 
 
1717
     - knits for file texts and inventory
 
 
1718
     - hash subdirectory based stores.
 
 
1719
     - knits for revisions and signatures
 
 
1720
     - TextStores for revisions and signatures.
 
 
1721
     - a format marker of its own
 
 
1722
     - an optional 'shared-storage' flag
 
 
1723
     - an optional 'no-working-trees' flag
 
 
1726
    This format was introduced in bzr 0.8.
 
 
1728
    def get_format_string(self):
 
 
1729
        """See RepositoryFormat.get_format_string()."""
 
 
1730
        return "Bazaar-NG Knit Repository Format 1"
 
 
1732
    def get_format_description(self):
 
 
1733
        """See RepositoryFormat.get_format_description()."""
 
 
1734
        return "Knit repository format 1"
 
 
1736
    def check_conversion_target(self, target_format):
 
 
1740
class RepositoryFormatKnit2(RepositoryFormatKnit):
 
 
1741
    """Bzr repository knit format 2.
 
 
1743
    THIS FORMAT IS EXPERIMENTAL
 
 
1744
    This repository format has:
 
 
1745
     - knits for file texts and inventory
 
 
1746
     - hash subdirectory based stores.
 
 
1747
     - knits for revisions and signatures
 
 
1748
     - TextStores for revisions and signatures.
 
 
1749
     - a format marker of its own
 
 
1750
     - an optional 'shared-storage' flag
 
 
1751
     - an optional 'no-working-trees' flag
 
 
1753
     - Support for recording full info about the tree root
 
 
1757
    rich_root_data = True
 
 
1759
    def get_format_string(self):
 
 
1760
        """See RepositoryFormat.get_format_string()."""
 
 
1761
        return "Bazaar Knit Repository Format 2\n"
 
 
1763
    def get_format_description(self):
 
 
1764
        """See RepositoryFormat.get_format_description()."""
 
 
1765
        return "Knit repository format 2"
 
 
1767
    def check_conversion_target(self, target_format):
 
 
1768
        if not target_format.rich_root_data:
 
 
1769
            raise errors.BadConversionTarget(
 
 
1770
                'Does not support rich root data.', target_format)
 
 
1772
    def open(self, a_bzrdir, _found=False, _override_transport=None):
 
 
1773
        """See RepositoryFormat.open().
 
 
1775
        :param _override_transport: INTERNAL USE ONLY. Allows opening the
 
 
1776
                                    repository at a slightly different url
 
 
1777
                                    than normal. I.e. during 'upgrade'.
 
 
1780
            format = RepositoryFormat.find_format(a_bzrdir)
 
 
1781
            assert format.__class__ ==  self.__class__
 
 
1782
        if _override_transport is not None:
 
 
1783
            repo_transport = _override_transport
 
 
1785
            repo_transport = a_bzrdir.get_repository_transport(None)
 
 
1786
        control_files = lockable_files.LockableFiles(repo_transport, 'lock',
 
 
1788
        text_store = self._get_text_store(repo_transport, control_files)
 
 
1789
        control_store = self._get_control_store(repo_transport, control_files)
 
 
1790
        _revision_store = self._get_revision_store(repo_transport, control_files)
 
 
1791
        return KnitRepository2(_format=self,
 
 
1793
                               control_files=control_files,
 
 
1794
                               _revision_store=_revision_store,
 
 
1795
                               control_store=control_store,
 
 
1796
                               text_store=text_store)
 
 
1800
# formats which have no format string are not discoverable
 
 
1801
# and not independently creatable, so are not registered.
 
 
1802
RepositoryFormat.register_format(RepositoryFormat7())
 
 
1803
_default_format = RepositoryFormatKnit1()
 
 
1804
RepositoryFormat.register_format(_default_format)
 
 
1805
RepositoryFormat.register_format(RepositoryFormatKnit2())
 
 
1806
RepositoryFormat.set_default_format(_default_format)
 
 
1807
_legacy_formats = [RepositoryFormat4(),
 
 
1808
                   RepositoryFormat5(),
 
 
1809
                   RepositoryFormat6()]
 
 
1812
class InterRepository(InterObject):
 
 
1813
    """This class represents operations taking place between two repositories.
 
 
1815
    Its instances have methods like copy_content and fetch, and contain
 
 
1816
    references to the source and target repositories these operations can be 
 
 
1819
    Often we will provide convenience methods on 'repository' which carry out
 
 
1820
    operations with another repository - they will always forward to
 
 
1821
    InterRepository.get(other).method_name(parameters).
 
 
1825
    """The available optimised InterRepository types."""
 
 
1827
    def copy_content(self, revision_id=None, basis=None):
 
 
1828
        raise NotImplementedError(self.copy_content)
 
 
1830
    def fetch(self, revision_id=None, pb=None):
 
 
1831
        """Fetch the content required to construct revision_id.
 
 
1833
        The content is copied from self.source to self.target.
 
 
1835
        :param revision_id: if None all content is copied, if NULL_REVISION no
 
 
1837
        :param pb: optional progress bar to use for progress reports. If not
 
 
1838
                   provided a default one will be created.
 
 
1840
        Returns the copied revision count and the failed revisions in a tuple:
 
 
1843
        raise NotImplementedError(self.fetch)
 
 
1846
    def missing_revision_ids(self, revision_id=None):
 
 
1847
        """Return the revision ids that source has that target does not.
 
 
1849
        These are returned in topological order.
 
 
1851
        :param revision_id: only return revision ids included by this
 
 
1854
        # generic, possibly worst case, slow code path.
 
 
1855
        target_ids = set(self.target.all_revision_ids())
 
 
1856
        if revision_id is not None:
 
 
1857
            source_ids = self.source.get_ancestry(revision_id)
 
 
1858
            assert source_ids[0] is None
 
 
1861
            source_ids = self.source.all_revision_ids()
 
 
1862
        result_set = set(source_ids).difference(target_ids)
 
 
1863
        # this may look like a no-op: its not. It preserves the ordering
 
 
1864
        # other_ids had while only returning the members from other_ids
 
 
1865
        # that we've decided we need.
 
 
1866
        return [rev_id for rev_id in source_ids if rev_id in result_set]
 
 
1869
class InterSameDataRepository(InterRepository):
 
 
1870
    """Code for converting between repositories that represent the same data.
 
 
1872
    Data format and model must match for this to work.
 
 
1875
    _matching_repo_format = RepositoryFormat4()
 
 
1876
    """Repository format for testing with."""
 
 
1879
    def is_compatible(source, target):
 
 
1880
        if not isinstance(source, Repository):
 
 
1882
        if not isinstance(target, Repository):
 
 
1884
        if source._format.rich_root_data == target._format.rich_root_data:
 
 
1890
    def copy_content(self, revision_id=None, basis=None):
 
 
1891
        """Make a complete copy of the content in self into destination.
 
 
1893
        This is a destructive operation! Do not use it on existing 
 
 
1896
        :param revision_id: Only copy the content needed to construct
 
 
1897
                            revision_id and its parents.
 
 
1898
        :param basis: Copy the needed data preferentially from basis.
 
 
1901
            self.target.set_make_working_trees(self.source.make_working_trees())
 
 
1902
        except NotImplementedError:
 
 
1904
        # grab the basis available data
 
 
1905
        if basis is not None:
 
 
1906
            self.target.fetch(basis, revision_id=revision_id)
 
 
1907
        # but don't bother fetching if we have the needed data now.
 
 
1908
        if (revision_id not in (None, _mod_revision.NULL_REVISION) and 
 
 
1909
            self.target.has_revision(revision_id)):
 
 
1911
        self.target.fetch(self.source, revision_id=revision_id)
 
 
1914
    def fetch(self, revision_id=None, pb=None):
 
 
1915
        """See InterRepository.fetch()."""
 
 
1916
        from bzrlib.fetch import GenericRepoFetcher
 
 
1917
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
 
 
1918
               self.source, self.source._format, self.target, 
 
 
1919
               self.target._format)
 
 
1920
        f = GenericRepoFetcher(to_repository=self.target,
 
 
1921
                               from_repository=self.source,
 
 
1922
                               last_revision=revision_id,
 
 
1924
        return f.count_copied, f.failed_revisions
 
 
1927
class InterWeaveRepo(InterSameDataRepository):
 
 
1928
    """Optimised code paths between Weave based repositories."""
 
 
1930
    _matching_repo_format = RepositoryFormat7()
 
 
1931
    """Repository format for testing with."""
 
 
1934
    def is_compatible(source, target):
 
 
1935
        """Be compatible with known Weave formats.
 
 
1937
        We don't test for the stores being of specific types because that
 
 
1938
        could lead to confusing results, and there is no need to be 
 
 
1942
            return (isinstance(source._format, (RepositoryFormat5,
 
 
1944
                                                RepositoryFormat7)) and
 
 
1945
                    isinstance(target._format, (RepositoryFormat5,
 
 
1947
                                                RepositoryFormat7)))
 
 
1948
        except AttributeError:
 
 
1952
    def copy_content(self, revision_id=None, basis=None):
 
 
1953
        """See InterRepository.copy_content()."""
 
 
1954
        # weave specific optimised path:
 
 
1955
        if basis is not None:
 
 
1956
            # copy the basis in, then fetch remaining data.
 
 
1957
            basis.copy_content_into(self.target, revision_id)
 
 
1958
            # the basis copy_content_into could miss-set this.
 
 
1960
                self.target.set_make_working_trees(self.source.make_working_trees())
 
 
1961
            except NotImplementedError:
 
 
1963
            self.target.fetch(self.source, revision_id=revision_id)
 
 
1966
                self.target.set_make_working_trees(self.source.make_working_trees())
 
 
1967
            except NotImplementedError:
 
 
1969
            # FIXME do not peek!
 
 
1970
            if self.source.control_files._transport.listable():
 
 
1971
                pb = ui.ui_factory.nested_progress_bar()
 
 
1973
                    self.target.weave_store.copy_all_ids(
 
 
1974
                        self.source.weave_store,
 
 
1976
                        from_transaction=self.source.get_transaction(),
 
 
1977
                        to_transaction=self.target.get_transaction())
 
 
1978
                    pb.update('copying inventory', 0, 1)
 
 
1979
                    self.target.control_weaves.copy_multi(
 
 
1980
                        self.source.control_weaves, ['inventory'],
 
 
1981
                        from_transaction=self.source.get_transaction(),
 
 
1982
                        to_transaction=self.target.get_transaction())
 
 
1983
                    self.target._revision_store.text_store.copy_all_ids(
 
 
1984
                        self.source._revision_store.text_store,
 
 
1989
                self.target.fetch(self.source, revision_id=revision_id)
 
 
1992
    def fetch(self, revision_id=None, pb=None):
 
 
1993
        """See InterRepository.fetch()."""
 
 
1994
        from bzrlib.fetch import GenericRepoFetcher
 
 
1995
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
 
 
1996
               self.source, self.source._format, self.target, self.target._format)
 
 
1997
        f = GenericRepoFetcher(to_repository=self.target,
 
 
1998
                               from_repository=self.source,
 
 
1999
                               last_revision=revision_id,
 
 
2001
        return f.count_copied, f.failed_revisions
 
 
2004
    def missing_revision_ids(self, revision_id=None):
 
 
2005
        """See InterRepository.missing_revision_ids()."""
 
 
2006
        # we want all revisions to satisfy revision_id in source.
 
 
2007
        # but we don't want to stat every file here and there.
 
 
2008
        # we want then, all revisions other needs to satisfy revision_id 
 
 
2009
        # checked, but not those that we have locally.
 
 
2010
        # so the first thing is to get a subset of the revisions to 
 
 
2011
        # satisfy revision_id in source, and then eliminate those that
 
 
2012
        # we do already have. 
 
 
2013
        # this is slow on high latency connection to self, but as as this
 
 
2014
        # disk format scales terribly for push anyway due to rewriting 
 
 
2015
        # inventory.weave, this is considered acceptable.
 
 
2017
        if revision_id is not None:
 
 
2018
            source_ids = self.source.get_ancestry(revision_id)
 
 
2019
            assert source_ids[0] is None
 
 
2022
            source_ids = self.source._all_possible_ids()
 
 
2023
        source_ids_set = set(source_ids)
 
 
2024
        # source_ids is the worst possible case we may need to pull.
 
 
2025
        # now we want to filter source_ids against what we actually
 
 
2026
        # have in target, but don't try to check for existence where we know
 
 
2027
        # we do not have a revision as that would be pointless.
 
 
2028
        target_ids = set(self.target._all_possible_ids())
 
 
2029
        possibly_present_revisions = target_ids.intersection(source_ids_set)
 
 
2030
        actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
 
 
2031
        required_revisions = source_ids_set.difference(actually_present_revisions)
 
 
2032
        required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
 
 
2033
        if revision_id is not None:
 
 
2034
            # we used get_ancestry to determine source_ids then we are assured all
 
 
2035
            # revisions referenced are present as they are installed in topological order.
 
 
2036
            # and the tip revision was validated by get_ancestry.
 
 
2037
            return required_topo_revisions
 
 
2039
            # if we just grabbed the possibly available ids, then 
 
 
2040
            # we only have an estimate of whats available and need to validate
 
 
2041
            # that against the revision records.
 
 
2042
            return self.source._eliminate_revisions_not_present(required_topo_revisions)
 
 
2045
class InterKnitRepo(InterSameDataRepository):
 
 
2046
    """Optimised code paths between Knit based repositories."""
 
 
2048
    _matching_repo_format = RepositoryFormatKnit1()
 
 
2049
    """Repository format for testing with."""
 
 
2052
    def is_compatible(source, target):
 
 
2053
        """Be compatible with known Knit formats.
 
 
2055
        We don't test for the stores being of specific types because that
 
 
2056
        could lead to confusing results, and there is no need to be 
 
 
2060
            return (isinstance(source._format, (RepositoryFormatKnit1)) and
 
 
2061
                    isinstance(target._format, (RepositoryFormatKnit1)))
 
 
2062
        except AttributeError:
 
 
2066
    def fetch(self, revision_id=None, pb=None):
 
 
2067
        """See InterRepository.fetch()."""
 
 
2068
        from bzrlib.fetch import KnitRepoFetcher
 
 
2069
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
 
 
2070
               self.source, self.source._format, self.target, self.target._format)
 
 
2071
        f = KnitRepoFetcher(to_repository=self.target,
 
 
2072
                            from_repository=self.source,
 
 
2073
                            last_revision=revision_id,
 
 
2075
        return f.count_copied, f.failed_revisions
 
 
2078
    def missing_revision_ids(self, revision_id=None):
 
 
2079
        """See InterRepository.missing_revision_ids()."""
 
 
2080
        if revision_id is not None:
 
 
2081
            source_ids = self.source.get_ancestry(revision_id)
 
 
2082
            assert source_ids[0] is None
 
 
2085
            source_ids = self.source._all_possible_ids()
 
 
2086
        source_ids_set = set(source_ids)
 
 
2087
        # source_ids is the worst possible case we may need to pull.
 
 
2088
        # now we want to filter source_ids against what we actually
 
 
2089
        # have in target, but don't try to check for existence where we know
 
 
2090
        # we do not have a revision as that would be pointless.
 
 
2091
        target_ids = set(self.target._all_possible_ids())
 
 
2092
        possibly_present_revisions = target_ids.intersection(source_ids_set)
 
 
2093
        actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
 
 
2094
        required_revisions = source_ids_set.difference(actually_present_revisions)
 
 
2095
        required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
 
 
2096
        if revision_id is not None:
 
 
2097
            # we used get_ancestry to determine source_ids then we are assured all
 
 
2098
            # revisions referenced are present as they are installed in topological order.
 
 
2099
            # and the tip revision was validated by get_ancestry.
 
 
2100
            return required_topo_revisions
 
 
2102
            # if we just grabbed the possibly available ids, then 
 
 
2103
            # we only have an estimate of whats available and need to validate
 
 
2104
            # that against the revision records.
 
 
2105
            return self.source._eliminate_revisions_not_present(required_topo_revisions)
 
 
2108
class InterModel1and2(InterRepository):
 
 
2110
    _matching_repo_format = None
 
 
2113
    def is_compatible(source, target):
 
 
2114
        if not isinstance(source, Repository):
 
 
2116
        if not isinstance(target, Repository):
 
 
2118
        if not source._format.rich_root_data and target._format.rich_root_data:
 
 
2124
    def fetch(self, revision_id=None, pb=None):
 
 
2125
        """See InterRepository.fetch()."""
 
 
2126
        from bzrlib.fetch import Model1toKnit2Fetcher
 
 
2127
        f = Model1toKnit2Fetcher(to_repository=self.target,
 
 
2128
                                 from_repository=self.source,
 
 
2129
                                 last_revision=revision_id,
 
 
2131
        return f.count_copied, f.failed_revisions
 
 
2134
    def copy_content(self, revision_id=None, basis=None):
 
 
2135
        """Make a complete copy of the content in self into destination.
 
 
2137
        This is a destructive operation! Do not use it on existing 
 
 
2140
        :param revision_id: Only copy the content needed to construct
 
 
2141
                            revision_id and its parents.
 
 
2142
        :param basis: Copy the needed data preferentially from basis.
 
 
2145
            self.target.set_make_working_trees(self.source.make_working_trees())
 
 
2146
        except NotImplementedError:
 
 
2148
        # grab the basis available data
 
 
2149
        if basis is not None:
 
 
2150
            self.target.fetch(basis, revision_id=revision_id)
 
 
2151
        # but don't bother fetching if we have the needed data now.
 
 
2152
        if (revision_id not in (None, _mod_revision.NULL_REVISION) and 
 
 
2153
            self.target.has_revision(revision_id)):
 
 
2155
        self.target.fetch(self.source, revision_id=revision_id)
 
 
2158
class InterKnit1and2(InterKnitRepo):
 
 
2160
    _matching_repo_format = None
 
 
2163
    def is_compatible(source, target):
 
 
2164
        """Be compatible with Knit1 source and Knit2 target"""
 
 
2166
            return (isinstance(source._format, (RepositoryFormatKnit1)) and
 
 
2167
                    isinstance(target._format, (RepositoryFormatKnit2)))
 
 
2168
        except AttributeError:
 
 
2172
    def fetch(self, revision_id=None, pb=None):
 
 
2173
        """See InterRepository.fetch()."""
 
 
2174
        from bzrlib.fetch import Knit1to2Fetcher
 
 
2175
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
 
 
2176
               self.source, self.source._format, self.target, 
 
 
2177
               self.target._format)
 
 
2178
        f = Knit1to2Fetcher(to_repository=self.target,
 
 
2179
                            from_repository=self.source,
 
 
2180
                            last_revision=revision_id,
 
 
2182
        return f.count_copied, f.failed_revisions
 
 
2185
InterRepository.register_optimiser(InterSameDataRepository)
 
 
2186
InterRepository.register_optimiser(InterWeaveRepo)
 
 
2187
InterRepository.register_optimiser(InterKnitRepo)
 
 
2188
InterRepository.register_optimiser(InterModel1and2)
 
 
2189
InterRepository.register_optimiser(InterKnit1and2)
 
 
2192
class RepositoryTestProviderAdapter(object):
 
 
2193
    """A tool to generate a suite testing multiple repository formats at once.
 
 
2195
    This is done by copying the test once for each transport and injecting
 
 
2196
    the transport_server, transport_readonly_server, and bzrdir_format and
 
 
2197
    repository_format classes into each copy. Each copy is also given a new id()
 
 
2198
    to make it easy to identify.
 
 
2201
    def __init__(self, transport_server, transport_readonly_server, formats):
 
 
2202
        self._transport_server = transport_server
 
 
2203
        self._transport_readonly_server = transport_readonly_server
 
 
2204
        self._formats = formats
 
 
2206
    def adapt(self, test):
 
 
2207
        result = unittest.TestSuite()
 
 
2208
        for repository_format, bzrdir_format in self._formats:
 
 
2209
            new_test = deepcopy(test)
 
 
2210
            new_test.transport_server = self._transport_server
 
 
2211
            new_test.transport_readonly_server = self._transport_readonly_server
 
 
2212
            new_test.bzrdir_format = bzrdir_format
 
 
2213
            new_test.repository_format = repository_format
 
 
2214
            def make_new_test_id():
 
 
2215
                new_id = "%s(%s)" % (new_test.id(), repository_format.__class__.__name__)
 
 
2216
                return lambda: new_id
 
 
2217
            new_test.id = make_new_test_id()
 
 
2218
            result.addTest(new_test)
 
 
2222
class InterRepositoryTestProviderAdapter(object):
 
 
2223
    """A tool to generate a suite testing multiple inter repository formats.
 
 
2225
    This is done by copying the test once for each interrepo provider and injecting
 
 
2226
    the transport_server, transport_readonly_server, repository_format and 
 
 
2227
    repository_to_format classes into each copy.
 
 
2228
    Each copy is also given a new id() to make it easy to identify.
 
 
2231
    def __init__(self, transport_server, transport_readonly_server, formats):
 
 
2232
        self._transport_server = transport_server
 
 
2233
        self._transport_readonly_server = transport_readonly_server
 
 
2234
        self._formats = formats
 
 
2236
    def adapt(self, test):
 
 
2237
        result = unittest.TestSuite()
 
 
2238
        for interrepo_class, repository_format, repository_format_to in self._formats:
 
 
2239
            new_test = deepcopy(test)
 
 
2240
            new_test.transport_server = self._transport_server
 
 
2241
            new_test.transport_readonly_server = self._transport_readonly_server
 
 
2242
            new_test.interrepo_class = interrepo_class
 
 
2243
            new_test.repository_format = repository_format
 
 
2244
            new_test.repository_format_to = repository_format_to
 
 
2245
            def make_new_test_id():
 
 
2246
                new_id = "%s(%s)" % (new_test.id(), interrepo_class.__name__)
 
 
2247
                return lambda: new_id
 
 
2248
            new_test.id = make_new_test_id()
 
 
2249
            result.addTest(new_test)
 
 
2253
    def default_test_list():
 
 
2254
        """Generate the default list of interrepo permutations to test."""
 
 
2256
        # test the default InterRepository between format 6 and the current 
 
 
2258
        # XXX: robertc 20060220 reinstate this when there are two supported
 
 
2259
        # formats which do not have an optimal code path between them.
 
 
2260
        #result.append((InterRepository,
 
 
2261
        #               RepositoryFormat6(),
 
 
2262
        #               RepositoryFormatKnit1()))
 
 
2263
        for optimiser in InterRepository._optimisers:
 
 
2264
            if optimiser._matching_repo_format is not None:
 
 
2265
                result.append((optimiser,
 
 
2266
                               optimiser._matching_repo_format,
 
 
2267
                               optimiser._matching_repo_format
 
 
2269
        # if there are specific combinations we want to use, we can add them 
 
 
2271
        result.append((InterModel1and2, RepositoryFormat5(),
 
 
2272
                       RepositoryFormatKnit2()))
 
 
2273
        result.append((InterKnit1and2, RepositoryFormatKnit1(),
 
 
2274
                       RepositoryFormatKnit2()))
 
 
2278
class CopyConverter(object):
 
 
2279
    """A repository conversion tool which just performs a copy of the content.
 
 
2281
    This is slow but quite reliable.
 
 
2284
    def __init__(self, target_format):
 
 
2285
        """Create a CopyConverter.
 
 
2287
        :param target_format: The format the resulting repository should be.
 
 
2289
        self.target_format = target_format
 
 
2291
    def convert(self, repo, pb):
 
 
2292
        """Perform the conversion of to_convert, giving feedback via pb.
 
 
2294
        :param to_convert: The disk object to convert.
 
 
2295
        :param pb: a progress bar to use for progress information.
 
 
2300
        # this is only useful with metadir layouts - separated repo content.
 
 
2301
        # trigger an assertion if not such
 
 
2302
        repo._format.get_format_string()
 
 
2303
        self.repo_dir = repo.bzrdir
 
 
2304
        self.step('Moving repository to repository.backup')
 
 
2305
        self.repo_dir.transport.move('repository', 'repository.backup')
 
 
2306
        backup_transport =  self.repo_dir.transport.clone('repository.backup')
 
 
2307
        repo._format.check_conversion_target(self.target_format)
 
 
2308
        self.source_repo = repo._format.open(self.repo_dir,
 
 
2310
            _override_transport=backup_transport)
 
 
2311
        self.step('Creating new repository')
 
 
2312
        converted = self.target_format.initialize(self.repo_dir,
 
 
2313
                                                  self.source_repo.is_shared())
 
 
2314
        converted.lock_write()
 
 
2316
            self.step('Copying content into repository.')
 
 
2317
            self.source_repo.copy_content_into(converted)
 
 
2320
        self.step('Deleting old repository content.')
 
 
2321
        self.repo_dir.transport.delete_tree('repository.backup')
 
 
2322
        self.pb.note('repository converted')
 
 
2324
    def step(self, message):
 
 
2325
        """Update the pb by a step."""
 
 
2327
        self.pb.update(message, self.count, self.total)
 
 
2330
class CommitBuilder(object):
 
 
2331
    """Provides an interface to build up a commit.
 
 
2333
    This allows describing a tree to be committed without needing to 
 
 
2334
    know the internals of the format of the repository.
 
 
2337
    record_root_entry = False
 
 
2338
    def __init__(self, repository, parents, config, timestamp=None, 
 
 
2339
                 timezone=None, committer=None, revprops=None, 
 
 
2341
        """Initiate a CommitBuilder.
 
 
2343
        :param repository: Repository to commit to.
 
 
2344
        :param parents: Revision ids of the parents of the new revision.
 
 
2345
        :param config: Configuration to use.
 
 
2346
        :param timestamp: Optional timestamp recorded for commit.
 
 
2347
        :param timezone: Optional timezone for timestamp.
 
 
2348
        :param committer: Optional committer to set for commit.
 
 
2349
        :param revprops: Optional dictionary of revision properties.
 
 
2350
        :param revision_id: Optional revision id.
 
 
2352
        self._config = config
 
 
2354
        if committer is None:
 
 
2355
            self._committer = self._config.username()
 
 
2357
            assert isinstance(committer, basestring), type(committer)
 
 
2358
            self._committer = committer
 
 
2360
        self.new_inventory = Inventory(None)
 
 
2361
        self._new_revision_id = revision_id
 
 
2362
        self.parents = parents
 
 
2363
        self.repository = repository
 
 
2366
        if revprops is not None:
 
 
2367
            self._revprops.update(revprops)
 
 
2369
        if timestamp is None:
 
 
2370
            timestamp = time.time()
 
 
2371
        # Restrict resolution to 1ms
 
 
2372
        self._timestamp = round(timestamp, 3)
 
 
2374
        if timezone is None:
 
 
2375
            self._timezone = local_time_offset()
 
 
2377
            self._timezone = int(timezone)
 
 
2379
        self._generate_revision_if_needed()
 
 
2381
    def commit(self, message):
 
 
2382
        """Make the actual commit.
 
 
2384
        :return: The revision id of the recorded revision.
 
 
2386
        rev = _mod_revision.Revision(
 
 
2387
                       timestamp=self._timestamp,
 
 
2388
                       timezone=self._timezone,
 
 
2389
                       committer=self._committer,
 
 
2391
                       inventory_sha1=self.inv_sha1,
 
 
2392
                       revision_id=self._new_revision_id,
 
 
2393
                       properties=self._revprops)
 
 
2394
        rev.parent_ids = self.parents
 
 
2395
        self.repository.add_revision(self._new_revision_id, rev, 
 
 
2396
            self.new_inventory, self._config)
 
 
2397
        return self._new_revision_id
 
 
2399
    def revision_tree(self):
 
 
2400
        """Return the tree that was just committed.
 
 
2402
        After calling commit() this can be called to get a RevisionTree
 
 
2403
        representing the newly committed tree. This is preferred to
 
 
2404
        calling Repository.revision_tree() because that may require
 
 
2405
        deserializing the inventory, while we already have a copy in
 
 
2408
        return RevisionTree(self.repository, self.new_inventory,
 
 
2409
                            self._new_revision_id)
 
 
2411
    def finish_inventory(self):
 
 
2412
        """Tell the builder that the inventory is finished."""
 
 
2413
        if self.new_inventory.root is None:
 
 
2414
            symbol_versioning.warn('Root entry should be supplied to'
 
 
2415
                ' record_entry_contents, as of bzr 0.10.',
 
 
2416
                 DeprecationWarning, stacklevel=2)
 
 
2417
            self.new_inventory.add(InventoryDirectory(ROOT_ID, '', None))
 
 
2418
        self.new_inventory.revision_id = self._new_revision_id
 
 
2419
        self.inv_sha1 = self.repository.add_inventory(
 
 
2420
            self._new_revision_id,
 
 
2425
    def _gen_revision_id(self):
 
 
2426
        """Return new revision-id."""
 
 
2427
        return generate_ids.gen_revision_id(self._config.username(),
 
 
2430
    def _generate_revision_if_needed(self):
 
 
2431
        """Create a revision id if None was supplied.
 
 
2433
        If the repository can not support user-specified revision ids
 
 
2434
        they should override this function and raise CannotSetRevisionId
 
 
2435
        if _new_revision_id is not None.
 
 
2437
        :raises: CannotSetRevisionId
 
 
2439
        if self._new_revision_id is None:
 
 
2440
            self._new_revision_id = self._gen_revision_id()
 
 
2442
    def record_entry_contents(self, ie, parent_invs, path, tree):
 
 
2443
        """Record the content of ie from tree into the commit if needed.
 
 
2445
        Side effect: sets ie.revision when unchanged
 
 
2447
        :param ie: An inventory entry present in the commit.
 
 
2448
        :param parent_invs: The inventories of the parent revisions of the
 
 
2450
        :param path: The path the entry is at in the tree.
 
 
2451
        :param tree: The tree which contains this entry and should be used to 
 
 
2454
        if self.new_inventory.root is None and ie.parent_id is not None:
 
 
2455
            symbol_versioning.warn('Root entry should be supplied to'
 
 
2456
                ' record_entry_contents, as of bzr 0.10.',
 
 
2457
                 DeprecationWarning, stacklevel=2)
 
 
2458
            self.record_entry_contents(tree.inventory.root.copy(), parent_invs,
 
 
2460
        self.new_inventory.add(ie)
 
 
2462
        # ie.revision is always None if the InventoryEntry is considered
 
 
2463
        # for committing. ie.snapshot will record the correct revision 
 
 
2464
        # which may be the sole parent if it is untouched.
 
 
2465
        if ie.revision is not None:
 
 
2468
        # In this revision format, root entries have no knit or weave
 
 
2469
        if ie is self.new_inventory.root:
 
 
2470
            # When serializing out to disk and back in
 
 
2471
            # root.revision is always _new_revision_id
 
 
2472
            ie.revision = self._new_revision_id
 
 
2474
        previous_entries = ie.find_previous_heads(
 
 
2476
            self.repository.weave_store,
 
 
2477
            self.repository.get_transaction())
 
 
2478
        # we are creating a new revision for ie in the history store
 
 
2480
        ie.snapshot(self._new_revision_id, path, previous_entries, tree, self)
 
 
2482
    def modified_directory(self, file_id, file_parents):
 
 
2483
        """Record the presence of a symbolic link.
 
 
2485
        :param file_id: The file_id of the link to record.
 
 
2486
        :param file_parents: The per-file parent revision ids.
 
 
2488
        self._add_text_to_weave(file_id, [], file_parents.keys())
 
 
2490
    def modified_file_text(self, file_id, file_parents,
 
 
2491
                           get_content_byte_lines, text_sha1=None,
 
 
2493
        """Record the text of file file_id
 
 
2495
        :param file_id: The file_id of the file to record the text of.
 
 
2496
        :param file_parents: The per-file parent revision ids.
 
 
2497
        :param get_content_byte_lines: A callable which will return the byte
 
 
2499
        :param text_sha1: Optional SHA1 of the file contents.
 
 
2500
        :param text_size: Optional size of the file contents.
 
 
2502
        # mutter('storing text of file {%s} in revision {%s} into %r',
 
 
2503
        #        file_id, self._new_revision_id, self.repository.weave_store)
 
 
2504
        # special case to avoid diffing on renames or 
 
 
2506
        if (len(file_parents) == 1
 
 
2507
            and text_sha1 == file_parents.values()[0].text_sha1
 
 
2508
            and text_size == file_parents.values()[0].text_size):
 
 
2509
            previous_ie = file_parents.values()[0]
 
 
2510
            versionedfile = self.repository.weave_store.get_weave(file_id, 
 
 
2511
                self.repository.get_transaction())
 
 
2512
            versionedfile.clone_text(self._new_revision_id, 
 
 
2513
                previous_ie.revision, file_parents.keys())
 
 
2514
            return text_sha1, text_size
 
 
2516
            new_lines = get_content_byte_lines()
 
 
2517
            # TODO: Rather than invoking sha_strings here, _add_text_to_weave
 
 
2518
            # should return the SHA1 and size
 
 
2519
            self._add_text_to_weave(file_id, new_lines, file_parents.keys())
 
 
2520
            return osutils.sha_strings(new_lines), \
 
 
2521
                sum(map(len, new_lines))
 
 
2523
    def modified_link(self, file_id, file_parents, link_target):
 
 
2524
        """Record the presence of a symbolic link.
 
 
2526
        :param file_id: The file_id of the link to record.
 
 
2527
        :param file_parents: The per-file parent revision ids.
 
 
2528
        :param link_target: Target location of this link.
 
 
2530
        self._add_text_to_weave(file_id, [], file_parents.keys())
 
 
2532
    def _add_text_to_weave(self, file_id, new_lines, parents):
 
 
2533
        versionedfile = self.repository.weave_store.get_weave_or_empty(
 
 
2534
            file_id, self.repository.get_transaction())
 
 
2535
        versionedfile.add_lines(self._new_revision_id, parents, new_lines)
 
 
2536
        versionedfile.clear_cache()
 
 
2539
class _CommitBuilder(CommitBuilder):
 
 
2540
    """Temporary class so old CommitBuilders are detected properly
 
 
2542
    Note: CommitBuilder works whether or not root entry is recorded.
 
 
2545
    record_root_entry = True
 
 
2548
class RootCommitBuilder(CommitBuilder):
 
 
2549
    """This commitbuilder actually records the root id"""
 
 
2551
    record_root_entry = True
 
 
2553
    def record_entry_contents(self, ie, parent_invs, path, tree):
 
 
2554
        """Record the content of ie from tree into the commit if needed.
 
 
2556
        Side effect: sets ie.revision when unchanged
 
 
2558
        :param ie: An inventory entry present in the commit.
 
 
2559
        :param parent_invs: The inventories of the parent revisions of the
 
 
2561
        :param path: The path the entry is at in the tree.
 
 
2562
        :param tree: The tree which contains this entry and should be used to 
 
 
2565
        assert self.new_inventory.root is not None or ie.parent_id is None
 
 
2566
        self.new_inventory.add(ie)
 
 
2568
        # ie.revision is always None if the InventoryEntry is considered
 
 
2569
        # for committing. ie.snapshot will record the correct revision 
 
 
2570
        # which may be the sole parent if it is untouched.
 
 
2571
        if ie.revision is not None:
 
 
2574
        previous_entries = ie.find_previous_heads(
 
 
2576
            self.repository.weave_store,
 
 
2577
            self.repository.get_transaction())
 
 
2578
        # we are creating a new revision for ie in the history store
 
 
2580
        ie.snapshot(self._new_revision_id, path, previous_entries, tree, self)
 
 
2592
def _unescaper(match, _map=_unescape_map):
 
 
2593
    return _map[match.group(1)]
 
 
2599
def _unescape_xml(data):
 
 
2600
    """Unescape predefined XML entities in a string of data."""
 
 
2602
    if _unescape_re is None:
 
 
2603
        _unescape_re = re.compile('\&([^;]*);')
 
 
2604
    return _unescape_re.sub(_unescaper, data)