/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/repository.py

  • Committer: Aaron Bentley
  • Date: 2007-06-20 00:25:11 UTC
  • mto: (2520.5.2 bzr.mpbundle)
  • mto: This revision was merged to the branch mainline in revision 2631.
  • Revision ID: aaron.bentley@utoronto.ca-20070620002511-6mylajxf4mipn7g7
refactor bundle serialization to make write_bundle primary

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
 
2
#
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
 
 
17
from cStringIO import StringIO
 
18
 
 
19
from bzrlib.lazy_import import lazy_import
 
20
lazy_import(globals(), """
 
21
import re
 
22
import time
 
23
import unittest
 
24
 
 
25
from bzrlib import (
 
26
    bzrdir,
 
27
    check,
 
28
    deprecated_graph,
 
29
    errors,
 
30
    generate_ids,
 
31
    gpg,
 
32
    graph,
 
33
    lazy_regex,
 
34
    lockable_files,
 
35
    lockdir,
 
36
    osutils,
 
37
    registry,
 
38
    remote,
 
39
    revision as _mod_revision,
 
40
    symbol_versioning,
 
41
    transactions,
 
42
    ui,
 
43
    )
 
44
from bzrlib.revisiontree import RevisionTree
 
45
from bzrlib.store.versioned import VersionedFileStore
 
46
from bzrlib.store.text import TextStore
 
47
from bzrlib.testament import Testament
 
48
 
 
49
""")
 
50
 
 
51
from bzrlib.decorators import needs_read_lock, needs_write_lock
 
52
from bzrlib.inter import InterObject
 
53
from bzrlib.inventory import Inventory, InventoryDirectory, ROOT_ID
 
54
from bzrlib.symbol_versioning import (
 
55
        deprecated_method,
 
56
        zero_nine,
 
57
        )
 
58
from bzrlib.trace import mutter, note, warning
 
59
 
 
60
 
 
61
# Old formats display a warning, but only once
 
62
_deprecation_warning_done = False
 
63
 
 
64
 
 
65
######################################################################
 
66
# Repositories
 
67
 
 
68
class Repository(object):
 
69
    """Repository holding history for one or more branches.
 
70
 
 
71
    The repository holds and retrieves historical information including
 
72
    revisions and file history.  It's normally accessed only by the Branch,
 
73
    which views a particular line of development through that history.
 
74
 
 
75
    The Repository builds on top of Stores and a Transport, which respectively 
 
76
    describe the disk data format and the way of accessing the (possibly 
 
77
    remote) disk.
 
78
    """
 
79
 
 
80
    _file_ids_altered_regex = lazy_regex.lazy_compile(
 
81
        r'file_id="(?P<file_id>[^"]+)"'
 
82
        r'.*revision="(?P<revision_id>[^"]+)"'
 
83
        )
 
84
 
 
85
    @needs_write_lock
 
86
    def add_inventory(self, revision_id, inv, parents):
 
87
        """Add the inventory inv to the repository as revision_id.
 
88
        
 
89
        :param parents: The revision ids of the parents that revision_id
 
90
                        is known to have and are in the repository already.
 
91
 
 
92
        returns the sha1 of the serialized inventory.
 
93
        """
 
94
        revision_id = osutils.safe_revision_id(revision_id)
 
95
        _mod_revision.check_not_reserved_id(revision_id)
 
96
        assert inv.revision_id is None or inv.revision_id == revision_id, \
 
97
            "Mismatch between inventory revision" \
 
98
            " id and insertion revid (%r, %r)" % (inv.revision_id, revision_id)
 
99
        assert inv.root is not None
 
100
        inv_text = self.serialise_inventory(inv)
 
101
        inv_sha1 = osutils.sha_string(inv_text)
 
102
        inv_vf = self.control_weaves.get_weave('inventory',
 
103
                                               self.get_transaction())
 
104
        self._inventory_add_lines(inv_vf, revision_id, parents,
 
105
                                  osutils.split_lines(inv_text))
 
106
        return inv_sha1
 
107
 
 
108
    def _inventory_add_lines(self, inv_vf, revision_id, parents, lines):
 
109
        final_parents = []
 
110
        for parent in parents:
 
111
            if parent in inv_vf:
 
112
                final_parents.append(parent)
 
113
 
 
114
        inv_vf.add_lines(revision_id, final_parents, lines)
 
115
 
 
116
    @needs_write_lock
 
117
    def add_revision(self, revision_id, rev, inv=None, config=None):
 
118
        """Add rev to the revision store as revision_id.
 
119
 
 
120
        :param revision_id: the revision id to use.
 
121
        :param rev: The revision object.
 
122
        :param inv: The inventory for the revision. if None, it will be looked
 
123
                    up in the inventory storer
 
124
        :param config: If None no digital signature will be created.
 
125
                       If supplied its signature_needed method will be used
 
126
                       to determine if a signature should be made.
 
127
        """
 
128
        revision_id = osutils.safe_revision_id(revision_id)
 
129
        # TODO: jam 20070210 Shouldn't we check rev.revision_id and
 
130
        #       rev.parent_ids?
 
131
        _mod_revision.check_not_reserved_id(revision_id)
 
132
        if config is not None and config.signature_needed():
 
133
            if inv is None:
 
134
                inv = self.get_inventory(revision_id)
 
135
            plaintext = Testament(rev, inv).as_short_text()
 
136
            self.store_revision_signature(
 
137
                gpg.GPGStrategy(config), plaintext, revision_id)
 
138
        if not revision_id in self.get_inventory_weave():
 
139
            if inv is None:
 
140
                raise errors.WeaveRevisionNotPresent(revision_id,
 
141
                                                     self.get_inventory_weave())
 
142
            else:
 
143
                # yes, this is not suitable for adding with ghosts.
 
144
                self.add_inventory(revision_id, inv, rev.parent_ids)
 
145
        self._revision_store.add_revision(rev, self.get_transaction())
 
146
 
 
147
    def _add_revision_text(self, revision_id, text):
 
148
        revision = self._revision_store._serializer.read_revision_from_string(
 
149
            text)
 
150
        self._revision_store._add_revision(revision, StringIO(text),
 
151
                                           self.get_transaction())
 
152
 
 
153
    @needs_read_lock
 
154
    def _all_possible_ids(self):
 
155
        """Return all the possible revisions that we could find."""
 
156
        return self.get_inventory_weave().versions()
 
157
 
 
158
    def all_revision_ids(self):
 
159
        """Returns a list of all the revision ids in the repository. 
 
160
 
 
161
        This is deprecated because code should generally work on the graph
 
162
        reachable from a particular revision, and ignore any other revisions
 
163
        that might be present.  There is no direct replacement method.
 
164
        """
 
165
        return self._all_revision_ids()
 
166
 
 
167
    @needs_read_lock
 
168
    def _all_revision_ids(self):
 
169
        """Returns a list of all the revision ids in the repository. 
 
170
 
 
171
        These are in as much topological order as the underlying store can 
 
172
        present: for weaves ghosts may lead to a lack of correctness until
 
173
        the reweave updates the parents list.
 
174
        """
 
175
        if self._revision_store.text_store.listable():
 
176
            return self._revision_store.all_revision_ids(self.get_transaction())
 
177
        result = self._all_possible_ids()
 
178
        # TODO: jam 20070210 Ensure that _all_possible_ids returns non-unicode
 
179
        #       ids. (It should, since _revision_store's API should change to
 
180
        #       return utf8 revision_ids)
 
181
        return self._eliminate_revisions_not_present(result)
 
182
 
 
183
    def break_lock(self):
 
184
        """Break a lock if one is present from another instance.
 
185
 
 
186
        Uses the ui factory to ask for confirmation if the lock may be from
 
187
        an active process.
 
188
        """
 
189
        self.control_files.break_lock()
 
190
 
 
191
    @needs_read_lock
 
192
    def _eliminate_revisions_not_present(self, revision_ids):
 
193
        """Check every revision id in revision_ids to see if we have it.
 
194
 
 
195
        Returns a set of the present revisions.
 
196
        """
 
197
        result = []
 
198
        for id in revision_ids:
 
199
            if self.has_revision(id):
 
200
               result.append(id)
 
201
        return result
 
202
 
 
203
    @staticmethod
 
204
    def create(a_bzrdir):
 
205
        """Construct the current default format repository in a_bzrdir."""
 
206
        return RepositoryFormat.get_default_format().initialize(a_bzrdir)
 
207
 
 
208
    def __init__(self, _format, a_bzrdir, control_files, _revision_store, control_store, text_store):
 
209
        """instantiate a Repository.
 
210
 
 
211
        :param _format: The format of the repository on disk.
 
212
        :param a_bzrdir: The BzrDir of the repository.
 
213
 
 
214
        In the future we will have a single api for all stores for
 
215
        getting file texts, inventories and revisions, then
 
216
        this construct will accept instances of those things.
 
217
        """
 
218
        super(Repository, self).__init__()
 
219
        self._format = _format
 
220
        # the following are part of the public API for Repository:
 
221
        self.bzrdir = a_bzrdir
 
222
        self.control_files = control_files
 
223
        self._revision_store = _revision_store
 
224
        self.text_store = text_store
 
225
        # backwards compatibility
 
226
        self.weave_store = text_store
 
227
        # not right yet - should be more semantically clear ? 
 
228
        # 
 
229
        self.control_store = control_store
 
230
        self.control_weaves = control_store
 
231
        # TODO: make sure to construct the right store classes, etc, depending
 
232
        # on whether escaping is required.
 
233
        self._warn_if_deprecated()
 
234
 
 
235
    def __repr__(self):
 
236
        return '%s(%r)' % (self.__class__.__name__, 
 
237
                           self.bzrdir.transport.base)
 
238
 
 
239
    def is_locked(self):
 
240
        return self.control_files.is_locked()
 
241
 
 
242
    def lock_write(self, token=None):
 
243
        """Lock this repository for writing.
 
244
        
 
245
        :param token: if this is already locked, then lock_write will fail
 
246
            unless the token matches the existing lock.
 
247
        :returns: a token if this instance supports tokens, otherwise None.
 
248
        :raises TokenLockingNotSupported: when a token is given but this
 
249
            instance doesn't support using token locks.
 
250
        :raises MismatchedToken: if the specified token doesn't match the token
 
251
            of the existing lock.
 
252
 
 
253
        A token should be passed in if you know that you have locked the object
 
254
        some other way, and need to synchronise this object's state with that
 
255
        fact.
 
256
 
 
257
        XXX: this docstring is duplicated in many places, e.g. lockable_files.py
 
258
        """
 
259
        return self.control_files.lock_write(token=token)
 
260
 
 
261
    def lock_read(self):
 
262
        self.control_files.lock_read()
 
263
 
 
264
    def get_physical_lock_status(self):
 
265
        return self.control_files.get_physical_lock_status()
 
266
 
 
267
    def leave_lock_in_place(self):
 
268
        """Tell this repository not to release the physical lock when this
 
269
        object is unlocked.
 
270
        
 
271
        If lock_write doesn't return a token, then this method is not supported.
 
272
        """
 
273
        self.control_files.leave_in_place()
 
274
 
 
275
    def dont_leave_lock_in_place(self):
 
276
        """Tell this repository to release the physical lock when this
 
277
        object is unlocked, even if it didn't originally acquire it.
 
278
 
 
279
        If lock_write doesn't return a token, then this method is not supported.
 
280
        """
 
281
        self.control_files.dont_leave_in_place()
 
282
 
 
283
    @needs_read_lock
 
284
    def gather_stats(self, revid=None, committers=None):
 
285
        """Gather statistics from a revision id.
 
286
 
 
287
        :param revid: The revision id to gather statistics from, if None, then
 
288
            no revision specific statistics are gathered.
 
289
        :param committers: Optional parameter controlling whether to grab
 
290
            a count of committers from the revision specific statistics.
 
291
        :return: A dictionary of statistics. Currently this contains:
 
292
            committers: The number of committers if requested.
 
293
            firstrev: A tuple with timestamp, timezone for the penultimate left
 
294
                most ancestor of revid, if revid is not the NULL_REVISION.
 
295
            latestrev: A tuple with timestamp, timezone for revid, if revid is
 
296
                not the NULL_REVISION.
 
297
            revisions: The total revision count in the repository.
 
298
            size: An estimate disk size of the repository in bytes.
 
299
        """
 
300
        result = {}
 
301
        if revid and committers:
 
302
            result['committers'] = 0
 
303
        if revid and revid != _mod_revision.NULL_REVISION:
 
304
            if committers:
 
305
                all_committers = set()
 
306
            revisions = self.get_ancestry(revid)
 
307
            # pop the leading None
 
308
            revisions.pop(0)
 
309
            first_revision = None
 
310
            if not committers:
 
311
                # ignore the revisions in the middle - just grab first and last
 
312
                revisions = revisions[0], revisions[-1]
 
313
            for revision in self.get_revisions(revisions):
 
314
                if not first_revision:
 
315
                    first_revision = revision
 
316
                if committers:
 
317
                    all_committers.add(revision.committer)
 
318
            last_revision = revision
 
319
            if committers:
 
320
                result['committers'] = len(all_committers)
 
321
            result['firstrev'] = (first_revision.timestamp,
 
322
                first_revision.timezone)
 
323
            result['latestrev'] = (last_revision.timestamp,
 
324
                last_revision.timezone)
 
325
 
 
326
        # now gather global repository information
 
327
        if self.bzrdir.root_transport.listable():
 
328
            c, t = self._revision_store.total_size(self.get_transaction())
 
329
            result['revisions'] = c
 
330
            result['size'] = t
 
331
        return result
 
332
 
 
333
    @needs_read_lock
 
334
    def missing_revision_ids(self, other, revision_id=None):
 
335
        """Return the revision ids that other has that this does not.
 
336
        
 
337
        These are returned in topological order.
 
338
 
 
339
        revision_id: only return revision ids included by revision_id.
 
340
        """
 
341
        revision_id = osutils.safe_revision_id(revision_id)
 
342
        return InterRepository.get(other, self).missing_revision_ids(revision_id)
 
343
 
 
344
    @staticmethod
 
345
    def open(base):
 
346
        """Open the repository rooted at base.
 
347
 
 
348
        For instance, if the repository is at URL/.bzr/repository,
 
349
        Repository.open(URL) -> a Repository instance.
 
350
        """
 
351
        control = bzrdir.BzrDir.open(base)
 
352
        return control.open_repository()
 
353
 
 
354
    def copy_content_into(self, destination, revision_id=None):
 
355
        """Make a complete copy of the content in self into destination.
 
356
        
 
357
        This is a destructive operation! Do not use it on existing 
 
358
        repositories.
 
359
        """
 
360
        revision_id = osutils.safe_revision_id(revision_id)
 
361
        return InterRepository.get(self, destination).copy_content(revision_id)
 
362
 
 
363
    def fetch(self, source, revision_id=None, pb=None):
 
364
        """Fetch the content required to construct revision_id from source.
 
365
 
 
366
        If revision_id is None all content is copied.
 
367
        """
 
368
        revision_id = osutils.safe_revision_id(revision_id)
 
369
        inter = InterRepository.get(source, self)
 
370
        try:
 
371
            return inter.fetch(revision_id=revision_id, pb=pb)
 
372
        except NotImplementedError:
 
373
            raise errors.IncompatibleRepositories(source, self)
 
374
 
 
375
    def get_commit_builder(self, branch, parents, config, timestamp=None, 
 
376
                           timezone=None, committer=None, revprops=None, 
 
377
                           revision_id=None):
 
378
        """Obtain a CommitBuilder for this repository.
 
379
        
 
380
        :param branch: Branch to commit to.
 
381
        :param parents: Revision ids of the parents of the new revision.
 
382
        :param config: Configuration to use.
 
383
        :param timestamp: Optional timestamp recorded for commit.
 
384
        :param timezone: Optional timezone for timestamp.
 
385
        :param committer: Optional committer to set for commit.
 
386
        :param revprops: Optional dictionary of revision properties.
 
387
        :param revision_id: Optional revision id.
 
388
        """
 
389
        revision_id = osutils.safe_revision_id(revision_id)
 
390
        return _CommitBuilder(self, parents, config, timestamp, timezone,
 
391
                              committer, revprops, revision_id)
 
392
 
 
393
    def unlock(self):
 
394
        self.control_files.unlock()
 
395
 
 
396
    @needs_read_lock
 
397
    def clone(self, a_bzrdir, revision_id=None):
 
398
        """Clone this repository into a_bzrdir using the current format.
 
399
 
 
400
        Currently no check is made that the format of this repository and
 
401
        the bzrdir format are compatible. FIXME RBC 20060201.
 
402
 
 
403
        :return: The newly created destination repository.
 
404
        """
 
405
        # TODO: deprecate after 0.16; cloning this with all its settings is
 
406
        # probably not very useful -- mbp 20070423
 
407
        dest_repo = self._create_sprouting_repo(a_bzrdir, shared=self.is_shared())
 
408
        self.copy_content_into(dest_repo, revision_id)
 
409
        return dest_repo
 
410
 
 
411
    @needs_read_lock
 
412
    def sprout(self, to_bzrdir, revision_id=None):
 
413
        """Create a descendent repository for new development.
 
414
 
 
415
        Unlike clone, this does not copy the settings of the repository.
 
416
        """
 
417
        dest_repo = self._create_sprouting_repo(to_bzrdir, shared=False)
 
418
        dest_repo.fetch(self, revision_id=revision_id)
 
419
        return dest_repo
 
420
 
 
421
    def _create_sprouting_repo(self, a_bzrdir, shared):
 
422
        if not isinstance(a_bzrdir._format, self.bzrdir._format.__class__):
 
423
            # use target default format.
 
424
            dest_repo = a_bzrdir.create_repository()
 
425
        else:
 
426
            # Most control formats need the repository to be specifically
 
427
            # created, but on some old all-in-one formats it's not needed
 
428
            try:
 
429
                dest_repo = self._format.initialize(a_bzrdir, shared=shared)
 
430
            except errors.UninitializableFormat:
 
431
                dest_repo = a_bzrdir.open_repository()
 
432
        return dest_repo
 
433
 
 
434
    @needs_read_lock
 
435
    def has_revision(self, revision_id):
 
436
        """True if this repository has a copy of the revision."""
 
437
        revision_id = osutils.safe_revision_id(revision_id)
 
438
        return self._revision_store.has_revision_id(revision_id,
 
439
                                                    self.get_transaction())
 
440
 
 
441
    @needs_read_lock
 
442
    def get_revision_reconcile(self, revision_id):
 
443
        """'reconcile' helper routine that allows access to a revision always.
 
444
        
 
445
        This variant of get_revision does not cross check the weave graph
 
446
        against the revision one as get_revision does: but it should only
 
447
        be used by reconcile, or reconcile-alike commands that are correcting
 
448
        or testing the revision graph.
 
449
        """
 
450
        if not revision_id or not isinstance(revision_id, basestring):
 
451
            raise errors.InvalidRevisionId(revision_id=revision_id,
 
452
                                           branch=self)
 
453
        return self.get_revisions([revision_id])[0]
 
454
 
 
455
    @needs_read_lock
 
456
    def get_revisions(self, revision_ids):
 
457
        revision_ids = [osutils.safe_revision_id(r) for r in revision_ids]
 
458
        revs = self._revision_store.get_revisions(revision_ids,
 
459
                                                  self.get_transaction())
 
460
        for rev in revs:
 
461
            assert not isinstance(rev.revision_id, unicode)
 
462
            for parent_id in rev.parent_ids:
 
463
                assert not isinstance(parent_id, unicode)
 
464
        return revs
 
465
 
 
466
    @needs_read_lock
 
467
    def get_revision_xml(self, revision_id):
 
468
        # TODO: jam 20070210 This shouldn't be necessary since get_revision
 
469
        #       would have already do it.
 
470
        # TODO: jam 20070210 Just use _serializer.write_revision_to_string()
 
471
        revision_id = osutils.safe_revision_id(revision_id)
 
472
        rev = self.get_revision(revision_id)
 
473
        rev_tmp = StringIO()
 
474
        # the current serializer..
 
475
        self._revision_store._serializer.write_revision(rev, rev_tmp)
 
476
        rev_tmp.seek(0)
 
477
        return rev_tmp.getvalue()
 
478
 
 
479
    @needs_read_lock
 
480
    def get_revision(self, revision_id):
 
481
        """Return the Revision object for a named revision"""
 
482
        # TODO: jam 20070210 get_revision_reconcile should do this for us
 
483
        revision_id = osutils.safe_revision_id(revision_id)
 
484
        r = self.get_revision_reconcile(revision_id)
 
485
        # weave corruption can lead to absent revision markers that should be
 
486
        # present.
 
487
        # the following test is reasonably cheap (it needs a single weave read)
 
488
        # and the weave is cached in read transactions. In write transactions
 
489
        # it is not cached but typically we only read a small number of
 
490
        # revisions. For knits when they are introduced we will probably want
 
491
        # to ensure that caching write transactions are in use.
 
492
        inv = self.get_inventory_weave()
 
493
        self._check_revision_parents(r, inv)
 
494
        return r
 
495
 
 
496
    @needs_read_lock
 
497
    def get_deltas_for_revisions(self, revisions):
 
498
        """Produce a generator of revision deltas.
 
499
        
 
500
        Note that the input is a sequence of REVISIONS, not revision_ids.
 
501
        Trees will be held in memory until the generator exits.
 
502
        Each delta is relative to the revision's lefthand predecessor.
 
503
        """
 
504
        required_trees = set()
 
505
        for revision in revisions:
 
506
            required_trees.add(revision.revision_id)
 
507
            required_trees.update(revision.parent_ids[:1])
 
508
        trees = dict((t.get_revision_id(), t) for 
 
509
                     t in self.revision_trees(required_trees))
 
510
        for revision in revisions:
 
511
            if not revision.parent_ids:
 
512
                old_tree = self.revision_tree(None)
 
513
            else:
 
514
                old_tree = trees[revision.parent_ids[0]]
 
515
            yield trees[revision.revision_id].changes_from(old_tree)
 
516
 
 
517
    @needs_read_lock
 
518
    def get_revision_delta(self, revision_id):
 
519
        """Return the delta for one revision.
 
520
 
 
521
        The delta is relative to the left-hand predecessor of the
 
522
        revision.
 
523
        """
 
524
        r = self.get_revision(revision_id)
 
525
        return list(self.get_deltas_for_revisions([r]))[0]
 
526
 
 
527
    def _check_revision_parents(self, revision, inventory):
 
528
        """Private to Repository and Fetch.
 
529
        
 
530
        This checks the parentage of revision in an inventory weave for 
 
531
        consistency and is only applicable to inventory-weave-for-ancestry
 
532
        using repository formats & fetchers.
 
533
        """
 
534
        weave_parents = inventory.get_parents(revision.revision_id)
 
535
        weave_names = inventory.versions()
 
536
        for parent_id in revision.parent_ids:
 
537
            if parent_id in weave_names:
 
538
                # this parent must not be a ghost.
 
539
                if not parent_id in weave_parents:
 
540
                    # but it is a ghost
 
541
                    raise errors.CorruptRepository(self)
 
542
 
 
543
    @needs_write_lock
 
544
    def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
 
545
        revision_id = osutils.safe_revision_id(revision_id)
 
546
        signature = gpg_strategy.sign(plaintext)
 
547
        self._revision_store.add_revision_signature_text(revision_id,
 
548
                                                         signature,
 
549
                                                         self.get_transaction())
 
550
 
 
551
    def fileids_altered_by_revision_ids(self, revision_ids):
 
552
        """Find the file ids and versions affected by revisions.
 
553
 
 
554
        :param revisions: an iterable containing revision ids.
 
555
        :return: a dictionary mapping altered file-ids to an iterable of
 
556
        revision_ids. Each altered file-ids has the exact revision_ids that
 
557
        altered it listed explicitly.
 
558
        """
 
559
        assert self._serializer.support_altered_by_hack, \
 
560
            ("fileids_altered_by_revision_ids only supported for branches " 
 
561
             "which store inventory as unnested xml, not on %r" % self)
 
562
        selected_revision_ids = set(osutils.safe_revision_id(r)
 
563
                                    for r in revision_ids)
 
564
        w = self.get_inventory_weave()
 
565
        result = {}
 
566
 
 
567
        # this code needs to read every new line in every inventory for the
 
568
        # inventories [revision_ids]. Seeing a line twice is ok. Seeing a line
 
569
        # not present in one of those inventories is unnecessary but not 
 
570
        # harmful because we are filtering by the revision id marker in the
 
571
        # inventory lines : we only select file ids altered in one of those  
 
572
        # revisions. We don't need to see all lines in the inventory because
 
573
        # only those added in an inventory in rev X can contain a revision=X
 
574
        # line.
 
575
        unescape_revid_cache = {}
 
576
        unescape_fileid_cache = {}
 
577
 
 
578
        # jam 20061218 In a big fetch, this handles hundreds of thousands
 
579
        # of lines, so it has had a lot of inlining and optimizing done.
 
580
        # Sorry that it is a little bit messy.
 
581
        # Move several functions to be local variables, since this is a long
 
582
        # running loop.
 
583
        search = self._file_ids_altered_regex.search
 
584
        unescape = _unescape_xml
 
585
        setdefault = result.setdefault
 
586
        pb = ui.ui_factory.nested_progress_bar()
 
587
        try:
 
588
            for line in w.iter_lines_added_or_present_in_versions(
 
589
                                        selected_revision_ids, pb=pb):
 
590
                match = search(line)
 
591
                if match is None:
 
592
                    continue
 
593
                # One call to match.group() returning multiple items is quite a
 
594
                # bit faster than 2 calls to match.group() each returning 1
 
595
                file_id, revision_id = match.group('file_id', 'revision_id')
 
596
 
 
597
                # Inlining the cache lookups helps a lot when you make 170,000
 
598
                # lines and 350k ids, versus 8.4 unique ids.
 
599
                # Using a cache helps in 2 ways:
 
600
                #   1) Avoids unnecessary decoding calls
 
601
                #   2) Re-uses cached strings, which helps in future set and
 
602
                #      equality checks.
 
603
                # (2) is enough that removing encoding entirely along with
 
604
                # the cache (so we are using plain strings) results in no
 
605
                # performance improvement.
 
606
                try:
 
607
                    revision_id = unescape_revid_cache[revision_id]
 
608
                except KeyError:
 
609
                    unescaped = unescape(revision_id)
 
610
                    unescape_revid_cache[revision_id] = unescaped
 
611
                    revision_id = unescaped
 
612
 
 
613
                if revision_id in selected_revision_ids:
 
614
                    try:
 
615
                        file_id = unescape_fileid_cache[file_id]
 
616
                    except KeyError:
 
617
                        unescaped = unescape(file_id)
 
618
                        unescape_fileid_cache[file_id] = unescaped
 
619
                        file_id = unescaped
 
620
                    setdefault(file_id, set()).add(revision_id)
 
621
        finally:
 
622
            pb.finished()
 
623
        return result
 
624
 
 
625
    @needs_read_lock
 
626
    def get_inventory_weave(self):
 
627
        return self.control_weaves.get_weave('inventory',
 
628
            self.get_transaction())
 
629
 
 
630
    @needs_read_lock
 
631
    def get_inventory(self, revision_id):
 
632
        """Get Inventory object by hash."""
 
633
        # TODO: jam 20070210 Technically we don't need to sanitize, since all
 
634
        #       called functions must sanitize.
 
635
        revision_id = osutils.safe_revision_id(revision_id)
 
636
        return self.deserialise_inventory(
 
637
            revision_id, self.get_inventory_xml(revision_id))
 
638
 
 
639
    def deserialise_inventory(self, revision_id, xml):
 
640
        """Transform the xml into an inventory object. 
 
641
 
 
642
        :param revision_id: The expected revision id of the inventory.
 
643
        :param xml: A serialised inventory.
 
644
        """
 
645
        revision_id = osutils.safe_revision_id(revision_id)
 
646
        result = self._serializer.read_inventory_from_string(xml)
 
647
        result.root.revision = revision_id
 
648
        return result
 
649
 
 
650
    def serialise_inventory(self, inv):
 
651
        return self._serializer.write_inventory_to_string(inv)
 
652
 
 
653
    @needs_read_lock
 
654
    def get_inventory_xml(self, revision_id):
 
655
        """Get inventory XML as a file object."""
 
656
        revision_id = osutils.safe_revision_id(revision_id)
 
657
        try:
 
658
            assert isinstance(revision_id, str), type(revision_id)
 
659
            iw = self.get_inventory_weave()
 
660
            return iw.get_text(revision_id)
 
661
        except IndexError:
 
662
            raise errors.HistoryMissing(self, 'inventory', revision_id)
 
663
 
 
664
    @needs_read_lock
 
665
    def get_inventory_sha1(self, revision_id):
 
666
        """Return the sha1 hash of the inventory entry
 
667
        """
 
668
        # TODO: jam 20070210 Shouldn't this be deprecated / removed?
 
669
        revision_id = osutils.safe_revision_id(revision_id)
 
670
        return self.get_revision(revision_id).inventory_sha1
 
671
 
 
672
    @needs_read_lock
 
673
    def get_revision_graph(self, revision_id=None):
 
674
        """Return a dictionary containing the revision graph.
 
675
        
 
676
        :param revision_id: The revision_id to get a graph from. If None, then
 
677
        the entire revision graph is returned. This is a deprecated mode of
 
678
        operation and will be removed in the future.
 
679
        :return: a dictionary of revision_id->revision_parents_list.
 
680
        """
 
681
        # special case NULL_REVISION
 
682
        if revision_id == _mod_revision.NULL_REVISION:
 
683
            return {}
 
684
        revision_id = osutils.safe_revision_id(revision_id)
 
685
        a_weave = self.get_inventory_weave()
 
686
        all_revisions = self._eliminate_revisions_not_present(
 
687
                                a_weave.versions())
 
688
        entire_graph = dict([(node, a_weave.get_parents(node)) for 
 
689
                             node in all_revisions])
 
690
        if revision_id is None:
 
691
            return entire_graph
 
692
        elif revision_id not in entire_graph:
 
693
            raise errors.NoSuchRevision(self, revision_id)
 
694
        else:
 
695
            # add what can be reached from revision_id
 
696
            result = {}
 
697
            pending = set([revision_id])
 
698
            while len(pending) > 0:
 
699
                node = pending.pop()
 
700
                result[node] = entire_graph[node]
 
701
                for revision_id in result[node]:
 
702
                    if revision_id not in result:
 
703
                        pending.add(revision_id)
 
704
            return result
 
705
 
 
706
    @needs_read_lock
 
707
    def get_revision_graph_with_ghosts(self, revision_ids=None):
 
708
        """Return a graph of the revisions with ghosts marked as applicable.
 
709
 
 
710
        :param revision_ids: an iterable of revisions to graph or None for all.
 
711
        :return: a Graph object with the graph reachable from revision_ids.
 
712
        """
 
713
        result = deprecated_graph.Graph()
 
714
        if not revision_ids:
 
715
            pending = set(self.all_revision_ids())
 
716
            required = set([])
 
717
        else:
 
718
            pending = set(osutils.safe_revision_id(r) for r in revision_ids)
 
719
            # special case NULL_REVISION
 
720
            if _mod_revision.NULL_REVISION in pending:
 
721
                pending.remove(_mod_revision.NULL_REVISION)
 
722
            required = set(pending)
 
723
        done = set([])
 
724
        while len(pending):
 
725
            revision_id = pending.pop()
 
726
            try:
 
727
                rev = self.get_revision(revision_id)
 
728
            except errors.NoSuchRevision:
 
729
                if revision_id in required:
 
730
                    raise
 
731
                # a ghost
 
732
                result.add_ghost(revision_id)
 
733
                continue
 
734
            for parent_id in rev.parent_ids:
 
735
                # is this queued or done ?
 
736
                if (parent_id not in pending and
 
737
                    parent_id not in done):
 
738
                    # no, queue it.
 
739
                    pending.add(parent_id)
 
740
            result.add_node(revision_id, rev.parent_ids)
 
741
            done.add(revision_id)
 
742
        return result
 
743
 
 
744
    def _get_history_vf(self):
 
745
        """Get a versionedfile whose history graph reflects all revisions.
 
746
 
 
747
        For weave repositories, this is the inventory weave.
 
748
        """
 
749
        return self.get_inventory_weave()
 
750
 
 
751
    def iter_reverse_revision_history(self, revision_id):
 
752
        """Iterate backwards through revision ids in the lefthand history
 
753
 
 
754
        :param revision_id: The revision id to start with.  All its lefthand
 
755
            ancestors will be traversed.
 
756
        """
 
757
        revision_id = osutils.safe_revision_id(revision_id)
 
758
        if revision_id in (None, _mod_revision.NULL_REVISION):
 
759
            return
 
760
        next_id = revision_id
 
761
        versionedfile = self._get_history_vf()
 
762
        while True:
 
763
            yield next_id
 
764
            parents = versionedfile.get_parents(next_id)
 
765
            if len(parents) == 0:
 
766
                return
 
767
            else:
 
768
                next_id = parents[0]
 
769
 
 
770
    @needs_read_lock
 
771
    def get_revision_inventory(self, revision_id):
 
772
        """Return inventory of a past revision."""
 
773
        # TODO: Unify this with get_inventory()
 
774
        # bzr 0.0.6 and later imposes the constraint that the inventory_id
 
775
        # must be the same as its revision, so this is trivial.
 
776
        if revision_id is None:
 
777
            # This does not make sense: if there is no revision,
 
778
            # then it is the current tree inventory surely ?!
 
779
            # and thus get_root_id() is something that looks at the last
 
780
            # commit on the branch, and the get_root_id is an inventory check.
 
781
            raise NotImplementedError
 
782
            # return Inventory(self.get_root_id())
 
783
        else:
 
784
            return self.get_inventory(revision_id)
 
785
 
 
786
    @needs_read_lock
 
787
    def is_shared(self):
 
788
        """Return True if this repository is flagged as a shared repository."""
 
789
        raise NotImplementedError(self.is_shared)
 
790
 
 
791
    @needs_write_lock
 
792
    def reconcile(self, other=None, thorough=False):
 
793
        """Reconcile this repository."""
 
794
        from bzrlib.reconcile import RepoReconciler
 
795
        reconciler = RepoReconciler(self, thorough=thorough)
 
796
        reconciler.reconcile()
 
797
        return reconciler
 
798
 
 
799
    @needs_read_lock
 
800
    def revision_tree(self, revision_id):
 
801
        """Return Tree for a revision on this branch.
 
802
 
 
803
        `revision_id` may be None for the empty tree revision.
 
804
        """
 
805
        # TODO: refactor this to use an existing revision object
 
806
        # so we don't need to read it in twice.
 
807
        if revision_id is None or revision_id == _mod_revision.NULL_REVISION:
 
808
            return RevisionTree(self, Inventory(root_id=None), 
 
809
                                _mod_revision.NULL_REVISION)
 
810
        else:
 
811
            revision_id = osutils.safe_revision_id(revision_id)
 
812
            inv = self.get_revision_inventory(revision_id)
 
813
            return RevisionTree(self, inv, revision_id)
 
814
 
 
815
    @needs_read_lock
 
816
    def revision_trees(self, revision_ids):
 
817
        """Return Tree for a revision on this branch.
 
818
 
 
819
        `revision_id` may not be None or 'null:'"""
 
820
        assert None not in revision_ids
 
821
        assert _mod_revision.NULL_REVISION not in revision_ids
 
822
        texts = self.get_inventory_weave().get_texts(revision_ids)
 
823
        for text, revision_id in zip(texts, revision_ids):
 
824
            inv = self.deserialise_inventory(revision_id, text)
 
825
            yield RevisionTree(self, inv, revision_id)
 
826
 
 
827
    @needs_read_lock
 
828
    def get_ancestry(self, revision_id):
 
829
        """Return a list of revision-ids integrated by a revision.
 
830
 
 
831
        The first element of the list is always None, indicating the origin 
 
832
        revision.  This might change when we have history horizons, or 
 
833
        perhaps we should have a new API.
 
834
        
 
835
        This is topologically sorted.
 
836
        """
 
837
        if revision_id is None:
 
838
            return [None]
 
839
        revision_id = osutils.safe_revision_id(revision_id)
 
840
        if not self.has_revision(revision_id):
 
841
            raise errors.NoSuchRevision(self, revision_id)
 
842
        w = self.get_inventory_weave()
 
843
        candidates = w.get_ancestry(revision_id)
 
844
        return [None] + candidates # self._eliminate_revisions_not_present(candidates)
 
845
 
 
846
    @needs_read_lock
 
847
    def print_file(self, file, revision_id):
 
848
        """Print `file` to stdout.
 
849
        
 
850
        FIXME RBC 20060125 as John Meinel points out this is a bad api
 
851
        - it writes to stdout, it assumes that that is valid etc. Fix
 
852
        by creating a new more flexible convenience function.
 
853
        """
 
854
        revision_id = osutils.safe_revision_id(revision_id)
 
855
        tree = self.revision_tree(revision_id)
 
856
        # use inventory as it was in that revision
 
857
        file_id = tree.inventory.path2id(file)
 
858
        if not file_id:
 
859
            # TODO: jam 20060427 Write a test for this code path
 
860
            #       it had a bug in it, and was raising the wrong
 
861
            #       exception.
 
862
            raise errors.BzrError("%r is not present in revision %s" % (file, revision_id))
 
863
        tree.print_file(file_id)
 
864
 
 
865
    def get_transaction(self):
 
866
        return self.control_files.get_transaction()
 
867
 
 
868
    def revision_parents(self, revision_id):
 
869
        revision_id = osutils.safe_revision_id(revision_id)
 
870
        return self.get_inventory_weave().parent_names(revision_id)
 
871
 
 
872
    def get_parents(self, revision_ids):
 
873
        """See StackedParentsProvider.get_parents"""
 
874
        parents_list = []
 
875
        for revision_id in revision_ids:
 
876
            if revision_id == _mod_revision.NULL_REVISION:
 
877
                parents = []
 
878
            else:
 
879
                try:
 
880
                    parents = self.get_revision(revision_id).parent_ids
 
881
                except errors.NoSuchRevision:
 
882
                    parents = None
 
883
                else:
 
884
                    if len(parents) == 0:
 
885
                        parents = [_mod_revision.NULL_REVISION]
 
886
            parents_list.append(parents)
 
887
        return parents_list
 
888
 
 
889
    def _make_parents_provider(self):
 
890
        return self
 
891
 
 
892
    def get_graph(self, other_repository=None):
 
893
        """Return the graph walker for this repository format"""
 
894
        parents_provider = self._make_parents_provider()
 
895
        if (other_repository is not None and
 
896
            other_repository.bzrdir.transport.base !=
 
897
            self.bzrdir.transport.base):
 
898
            parents_provider = graph._StackedParentsProvider(
 
899
                [parents_provider, other_repository._make_parents_provider()])
 
900
        return graph.Graph(parents_provider)
 
901
 
 
902
    @needs_write_lock
 
903
    def set_make_working_trees(self, new_value):
 
904
        """Set the policy flag for making working trees when creating branches.
 
905
 
 
906
        This only applies to branches that use this repository.
 
907
 
 
908
        The default is 'True'.
 
909
        :param new_value: True to restore the default, False to disable making
 
910
                          working trees.
 
911
        """
 
912
        raise NotImplementedError(self.set_make_working_trees)
 
913
    
 
914
    def make_working_trees(self):
 
915
        """Returns the policy for making working trees on new branches."""
 
916
        raise NotImplementedError(self.make_working_trees)
 
917
 
 
918
    @needs_write_lock
 
919
    def sign_revision(self, revision_id, gpg_strategy):
 
920
        revision_id = osutils.safe_revision_id(revision_id)
 
921
        plaintext = Testament.from_revision(self, revision_id).as_short_text()
 
922
        self.store_revision_signature(gpg_strategy, plaintext, revision_id)
 
923
 
 
924
    @needs_read_lock
 
925
    def has_signature_for_revision_id(self, revision_id):
 
926
        """Query for a revision signature for revision_id in the repository."""
 
927
        revision_id = osutils.safe_revision_id(revision_id)
 
928
        return self._revision_store.has_signature(revision_id,
 
929
                                                  self.get_transaction())
 
930
 
 
931
    @needs_read_lock
 
932
    def get_signature_text(self, revision_id):
 
933
        """Return the text for a signature."""
 
934
        revision_id = osutils.safe_revision_id(revision_id)
 
935
        return self._revision_store.get_signature_text(revision_id,
 
936
                                                       self.get_transaction())
 
937
 
 
938
    @needs_read_lock
 
939
    def check(self, revision_ids):
 
940
        """Check consistency of all history of given revision_ids.
 
941
 
 
942
        Different repository implementations should override _check().
 
943
 
 
944
        :param revision_ids: A non-empty list of revision_ids whose ancestry
 
945
             will be checked.  Typically the last revision_id of a branch.
 
946
        """
 
947
        if not revision_ids:
 
948
            raise ValueError("revision_ids must be non-empty in %s.check" 
 
949
                    % (self,))
 
950
        revision_ids = [osutils.safe_revision_id(r) for r in revision_ids]
 
951
        return self._check(revision_ids)
 
952
 
 
953
    def _check(self, revision_ids):
 
954
        result = check.Check(self)
 
955
        result.check()
 
956
        return result
 
957
 
 
958
    def _warn_if_deprecated(self):
 
959
        global _deprecation_warning_done
 
960
        if _deprecation_warning_done:
 
961
            return
 
962
        _deprecation_warning_done = True
 
963
        warning("Format %s for %s is deprecated - please use 'bzr upgrade' to get better performance"
 
964
                % (self._format, self.bzrdir.transport.base))
 
965
 
 
966
    def supports_rich_root(self):
 
967
        return self._format.rich_root_data
 
968
 
 
969
    def _check_ascii_revisionid(self, revision_id, method):
 
970
        """Private helper for ascii-only repositories."""
 
971
        # weave repositories refuse to store revisionids that are non-ascii.
 
972
        if revision_id is not None:
 
973
            # weaves require ascii revision ids.
 
974
            if isinstance(revision_id, unicode):
 
975
                try:
 
976
                    revision_id.encode('ascii')
 
977
                except UnicodeEncodeError:
 
978
                    raise errors.NonAsciiRevisionId(method, self)
 
979
            else:
 
980
                try:
 
981
                    revision_id.decode('ascii')
 
982
                except UnicodeDecodeError:
 
983
                    raise errors.NonAsciiRevisionId(method, self)
 
984
 
 
985
 
 
986
 
 
987
# remove these delegates a while after bzr 0.15
 
988
def __make_delegated(name, from_module):
 
989
    def _deprecated_repository_forwarder():
 
990
        symbol_versioning.warn('%s moved to %s in bzr 0.15'
 
991
            % (name, from_module),
 
992
            DeprecationWarning,
 
993
            stacklevel=2)
 
994
        m = __import__(from_module, globals(), locals(), [name])
 
995
        try:
 
996
            return getattr(m, name)
 
997
        except AttributeError:
 
998
            raise AttributeError('module %s has no name %s'
 
999
                    % (m, name))
 
1000
    globals()[name] = _deprecated_repository_forwarder
 
1001
 
 
1002
for _name in [
 
1003
        'AllInOneRepository',
 
1004
        'WeaveMetaDirRepository',
 
1005
        'PreSplitOutRepositoryFormat',
 
1006
        'RepositoryFormat4',
 
1007
        'RepositoryFormat5',
 
1008
        'RepositoryFormat6',
 
1009
        'RepositoryFormat7',
 
1010
        ]:
 
1011
    __make_delegated(_name, 'bzrlib.repofmt.weaverepo')
 
1012
 
 
1013
for _name in [
 
1014
        'KnitRepository',
 
1015
        'RepositoryFormatKnit',
 
1016
        'RepositoryFormatKnit1',
 
1017
        ]:
 
1018
    __make_delegated(_name, 'bzrlib.repofmt.knitrepo')
 
1019
 
 
1020
 
 
1021
def install_revision(repository, rev, revision_tree):
 
1022
    """Install all revision data into a repository."""
 
1023
    present_parents = []
 
1024
    parent_trees = {}
 
1025
    for p_id in rev.parent_ids:
 
1026
        if repository.has_revision(p_id):
 
1027
            present_parents.append(p_id)
 
1028
            parent_trees[p_id] = repository.revision_tree(p_id)
 
1029
        else:
 
1030
            parent_trees[p_id] = repository.revision_tree(None)
 
1031
 
 
1032
    inv = revision_tree.inventory
 
1033
    entries = inv.iter_entries()
 
1034
    # backwards compatability hack: skip the root id.
 
1035
    if not repository.supports_rich_root():
 
1036
        path, root = entries.next()
 
1037
        if root.revision != rev.revision_id:
 
1038
            raise errors.IncompatibleRevision(repr(repository))
 
1039
    # Add the texts that are not already present
 
1040
    for path, ie in entries:
 
1041
        w = repository.weave_store.get_weave_or_empty(ie.file_id,
 
1042
                repository.get_transaction())
 
1043
        if ie.revision not in w:
 
1044
            text_parents = []
 
1045
            # FIXME: TODO: The following loop *may* be overlapping/duplicate
 
1046
            # with InventoryEntry.find_previous_heads(). if it is, then there
 
1047
            # is a latent bug here where the parents may have ancestors of each
 
1048
            # other. RBC, AB
 
1049
            for revision, tree in parent_trees.iteritems():
 
1050
                if ie.file_id not in tree:
 
1051
                    continue
 
1052
                parent_id = tree.inventory[ie.file_id].revision
 
1053
                if parent_id in text_parents:
 
1054
                    continue
 
1055
                text_parents.append(parent_id)
 
1056
                    
 
1057
            vfile = repository.weave_store.get_weave_or_empty(ie.file_id, 
 
1058
                repository.get_transaction())
 
1059
            lines = revision_tree.get_file(ie.file_id).readlines()
 
1060
            vfile.add_lines(rev.revision_id, text_parents, lines)
 
1061
    try:
 
1062
        # install the inventory
 
1063
        repository.add_inventory(rev.revision_id, inv, present_parents)
 
1064
    except errors.RevisionAlreadyPresent:
 
1065
        pass
 
1066
    repository.add_revision(rev.revision_id, rev, inv)
 
1067
 
 
1068
 
 
1069
class MetaDirRepository(Repository):
 
1070
    """Repositories in the new meta-dir layout."""
 
1071
 
 
1072
    def __init__(self, _format, a_bzrdir, control_files, _revision_store, control_store, text_store):
 
1073
        super(MetaDirRepository, self).__init__(_format,
 
1074
                                                a_bzrdir,
 
1075
                                                control_files,
 
1076
                                                _revision_store,
 
1077
                                                control_store,
 
1078
                                                text_store)
 
1079
        dir_mode = self.control_files._dir_mode
 
1080
        file_mode = self.control_files._file_mode
 
1081
 
 
1082
    @needs_read_lock
 
1083
    def is_shared(self):
 
1084
        """Return True if this repository is flagged as a shared repository."""
 
1085
        return self.control_files._transport.has('shared-storage')
 
1086
 
 
1087
    @needs_write_lock
 
1088
    def set_make_working_trees(self, new_value):
 
1089
        """Set the policy flag for making working trees when creating branches.
 
1090
 
 
1091
        This only applies to branches that use this repository.
 
1092
 
 
1093
        The default is 'True'.
 
1094
        :param new_value: True to restore the default, False to disable making
 
1095
                          working trees.
 
1096
        """
 
1097
        if new_value:
 
1098
            try:
 
1099
                self.control_files._transport.delete('no-working-trees')
 
1100
            except errors.NoSuchFile:
 
1101
                pass
 
1102
        else:
 
1103
            self.control_files.put_utf8('no-working-trees', '')
 
1104
    
 
1105
    def make_working_trees(self):
 
1106
        """Returns the policy for making working trees on new branches."""
 
1107
        return not self.control_files._transport.has('no-working-trees')
 
1108
 
 
1109
 
 
1110
class RepositoryFormatRegistry(registry.Registry):
 
1111
    """Registry of RepositoryFormats.
 
1112
    """
 
1113
 
 
1114
    def get(self, format_string):
 
1115
        r = registry.Registry.get(self, format_string)
 
1116
        if callable(r):
 
1117
            r = r()
 
1118
        return r
 
1119
    
 
1120
 
 
1121
format_registry = RepositoryFormatRegistry()
 
1122
"""Registry of formats, indexed by their identifying format string.
 
1123
 
 
1124
This can contain either format instances themselves, or classes/factories that
 
1125
can be called to obtain one.
 
1126
"""
 
1127
 
 
1128
 
 
1129
#####################################################################
 
1130
# Repository Formats
 
1131
 
 
1132
class RepositoryFormat(object):
 
1133
    """A repository format.
 
1134
 
 
1135
    Formats provide three things:
 
1136
     * An initialization routine to construct repository data on disk.
 
1137
     * a format string which is used when the BzrDir supports versioned
 
1138
       children.
 
1139
     * an open routine which returns a Repository instance.
 
1140
 
 
1141
    Formats are placed in an dict by their format string for reference 
 
1142
    during opening. These should be subclasses of RepositoryFormat
 
1143
    for consistency.
 
1144
 
 
1145
    Once a format is deprecated, just deprecate the initialize and open
 
1146
    methods on the format class. Do not deprecate the object, as the 
 
1147
    object will be created every system load.
 
1148
 
 
1149
    Common instance attributes:
 
1150
    _matchingbzrdir - the bzrdir format that the repository format was
 
1151
    originally written to work with. This can be used if manually
 
1152
    constructing a bzrdir and repository, or more commonly for test suite
 
1153
    parameterisation.
 
1154
    """
 
1155
 
 
1156
    def __str__(self):
 
1157
        return "<%s>" % self.__class__.__name__
 
1158
 
 
1159
    def __eq__(self, other):
 
1160
        # format objects are generally stateless
 
1161
        return isinstance(other, self.__class__)
 
1162
 
 
1163
    def __ne__(self, other):
 
1164
        return not self == other
 
1165
 
 
1166
    @classmethod
 
1167
    def find_format(klass, a_bzrdir):
 
1168
        """Return the format for the repository object in a_bzrdir.
 
1169
        
 
1170
        This is used by bzr native formats that have a "format" file in
 
1171
        the repository.  Other methods may be used by different types of 
 
1172
        control directory.
 
1173
        """
 
1174
        try:
 
1175
            transport = a_bzrdir.get_repository_transport(None)
 
1176
            format_string = transport.get("format").read()
 
1177
            return format_registry.get(format_string)
 
1178
        except errors.NoSuchFile:
 
1179
            raise errors.NoRepositoryPresent(a_bzrdir)
 
1180
        except KeyError:
 
1181
            raise errors.UnknownFormatError(format=format_string)
 
1182
 
 
1183
    @classmethod
 
1184
    def register_format(klass, format):
 
1185
        format_registry.register(format.get_format_string(), format)
 
1186
 
 
1187
    @classmethod
 
1188
    def unregister_format(klass, format):
 
1189
        format_registry.remove(format.get_format_string())
 
1190
    
 
1191
    @classmethod
 
1192
    def get_default_format(klass):
 
1193
        """Return the current default format."""
 
1194
        from bzrlib import bzrdir
 
1195
        return bzrdir.format_registry.make_bzrdir('default').repository_format
 
1196
 
 
1197
    def _get_control_store(self, repo_transport, control_files):
 
1198
        """Return the control store for this repository."""
 
1199
        raise NotImplementedError(self._get_control_store)
 
1200
 
 
1201
    def get_format_string(self):
 
1202
        """Return the ASCII format string that identifies this format.
 
1203
        
 
1204
        Note that in pre format ?? repositories the format string is 
 
1205
        not permitted nor written to disk.
 
1206
        """
 
1207
        raise NotImplementedError(self.get_format_string)
 
1208
 
 
1209
    def get_format_description(self):
 
1210
        """Return the short description for this format."""
 
1211
        raise NotImplementedError(self.get_format_description)
 
1212
 
 
1213
    def _get_revision_store(self, repo_transport, control_files):
 
1214
        """Return the revision store object for this a_bzrdir."""
 
1215
        raise NotImplementedError(self._get_revision_store)
 
1216
 
 
1217
    def _get_text_rev_store(self,
 
1218
                            transport,
 
1219
                            control_files,
 
1220
                            name,
 
1221
                            compressed=True,
 
1222
                            prefixed=False,
 
1223
                            serializer=None):
 
1224
        """Common logic for getting a revision store for a repository.
 
1225
        
 
1226
        see self._get_revision_store for the subclass-overridable method to 
 
1227
        get the store for a repository.
 
1228
        """
 
1229
        from bzrlib.store.revision.text import TextRevisionStore
 
1230
        dir_mode = control_files._dir_mode
 
1231
        file_mode = control_files._file_mode
 
1232
        text_store = TextStore(transport.clone(name),
 
1233
                              prefixed=prefixed,
 
1234
                              compressed=compressed,
 
1235
                              dir_mode=dir_mode,
 
1236
                              file_mode=file_mode)
 
1237
        _revision_store = TextRevisionStore(text_store, serializer)
 
1238
        return _revision_store
 
1239
 
 
1240
    # TODO: this shouldn't be in the base class, it's specific to things that
 
1241
    # use weaves or knits -- mbp 20070207
 
1242
    def _get_versioned_file_store(self,
 
1243
                                  name,
 
1244
                                  transport,
 
1245
                                  control_files,
 
1246
                                  prefixed=True,
 
1247
                                  versionedfile_class=None,
 
1248
                                  versionedfile_kwargs={},
 
1249
                                  escaped=False):
 
1250
        if versionedfile_class is None:
 
1251
            versionedfile_class = self._versionedfile_class
 
1252
        weave_transport = control_files._transport.clone(name)
 
1253
        dir_mode = control_files._dir_mode
 
1254
        file_mode = control_files._file_mode
 
1255
        return VersionedFileStore(weave_transport, prefixed=prefixed,
 
1256
                                  dir_mode=dir_mode,
 
1257
                                  file_mode=file_mode,
 
1258
                                  versionedfile_class=versionedfile_class,
 
1259
                                  versionedfile_kwargs=versionedfile_kwargs,
 
1260
                                  escaped=escaped)
 
1261
 
 
1262
    def initialize(self, a_bzrdir, shared=False):
 
1263
        """Initialize a repository of this format in a_bzrdir.
 
1264
 
 
1265
        :param a_bzrdir: The bzrdir to put the new repository in it.
 
1266
        :param shared: The repository should be initialized as a sharable one.
 
1267
        :returns: The new repository object.
 
1268
        
 
1269
        This may raise UninitializableFormat if shared repository are not
 
1270
        compatible the a_bzrdir.
 
1271
        """
 
1272
        raise NotImplementedError(self.initialize)
 
1273
 
 
1274
    def is_supported(self):
 
1275
        """Is this format supported?
 
1276
 
 
1277
        Supported formats must be initializable and openable.
 
1278
        Unsupported formats may not support initialization or committing or 
 
1279
        some other features depending on the reason for not being supported.
 
1280
        """
 
1281
        return True
 
1282
 
 
1283
    def check_conversion_target(self, target_format):
 
1284
        raise NotImplementedError(self.check_conversion_target)
 
1285
 
 
1286
    def open(self, a_bzrdir, _found=False):
 
1287
        """Return an instance of this format for the bzrdir a_bzrdir.
 
1288
        
 
1289
        _found is a private parameter, do not use it.
 
1290
        """
 
1291
        raise NotImplementedError(self.open)
 
1292
 
 
1293
 
 
1294
class MetaDirRepositoryFormat(RepositoryFormat):
 
1295
    """Common base class for the new repositories using the metadir layout."""
 
1296
 
 
1297
    rich_root_data = False
 
1298
    supports_tree_reference = False
 
1299
    _matchingbzrdir = bzrdir.BzrDirMetaFormat1()
 
1300
 
 
1301
    def __init__(self):
 
1302
        super(MetaDirRepositoryFormat, self).__init__()
 
1303
 
 
1304
    def _create_control_files(self, a_bzrdir):
 
1305
        """Create the required files and the initial control_files object."""
 
1306
        # FIXME: RBC 20060125 don't peek under the covers
 
1307
        # NB: no need to escape relative paths that are url safe.
 
1308
        repository_transport = a_bzrdir.get_repository_transport(self)
 
1309
        control_files = lockable_files.LockableFiles(repository_transport,
 
1310
                                'lock', lockdir.LockDir)
 
1311
        control_files.create_lock()
 
1312
        return control_files
 
1313
 
 
1314
    def _upload_blank_content(self, a_bzrdir, dirs, files, utf8_files, shared):
 
1315
        """Upload the initial blank content."""
 
1316
        control_files = self._create_control_files(a_bzrdir)
 
1317
        control_files.lock_write()
 
1318
        try:
 
1319
            control_files._transport.mkdir_multi(dirs,
 
1320
                    mode=control_files._dir_mode)
 
1321
            for file, content in files:
 
1322
                control_files.put(file, content)
 
1323
            for file, content in utf8_files:
 
1324
                control_files.put_utf8(file, content)
 
1325
            if shared == True:
 
1326
                control_files.put_utf8('shared-storage', '')
 
1327
        finally:
 
1328
            control_files.unlock()
 
1329
 
 
1330
 
 
1331
# formats which have no format string are not discoverable
 
1332
# and not independently creatable, so are not registered.  They're 
 
1333
# all in bzrlib.repofmt.weaverepo now.  When an instance of one of these is
 
1334
# needed, it's constructed directly by the BzrDir.  Non-native formats where
 
1335
# the repository is not separately opened are similar.
 
1336
 
 
1337
format_registry.register_lazy(
 
1338
    'Bazaar-NG Repository format 7',
 
1339
    'bzrlib.repofmt.weaverepo',
 
1340
    'RepositoryFormat7'
 
1341
    )
 
1342
# KEEP in sync with bzrdir.format_registry default, which controls the overall
 
1343
# default control directory format
 
1344
 
 
1345
format_registry.register_lazy(
 
1346
    'Bazaar-NG Knit Repository Format 1',
 
1347
    'bzrlib.repofmt.knitrepo',
 
1348
    'RepositoryFormatKnit1',
 
1349
    )
 
1350
format_registry.default_key = 'Bazaar-NG Knit Repository Format 1'
 
1351
 
 
1352
format_registry.register_lazy(
 
1353
    'Bazaar Knit Repository Format 3 (bzr 0.15)\n',
 
1354
    'bzrlib.repofmt.knitrepo',
 
1355
    'RepositoryFormatKnit3',
 
1356
    )
 
1357
 
 
1358
 
 
1359
class InterRepository(InterObject):
 
1360
    """This class represents operations taking place between two repositories.
 
1361
 
 
1362
    Its instances have methods like copy_content and fetch, and contain
 
1363
    references to the source and target repositories these operations can be 
 
1364
    carried out on.
 
1365
 
 
1366
    Often we will provide convenience methods on 'repository' which carry out
 
1367
    operations with another repository - they will always forward to
 
1368
    InterRepository.get(other).method_name(parameters).
 
1369
    """
 
1370
 
 
1371
    _optimisers = []
 
1372
    """The available optimised InterRepository types."""
 
1373
 
 
1374
    def copy_content(self, revision_id=None):
 
1375
        raise NotImplementedError(self.copy_content)
 
1376
 
 
1377
    def fetch(self, revision_id=None, pb=None):
 
1378
        """Fetch the content required to construct revision_id.
 
1379
 
 
1380
        The content is copied from self.source to self.target.
 
1381
 
 
1382
        :param revision_id: if None all content is copied, if NULL_REVISION no
 
1383
                            content is copied.
 
1384
        :param pb: optional progress bar to use for progress reports. If not
 
1385
                   provided a default one will be created.
 
1386
 
 
1387
        Returns the copied revision count and the failed revisions in a tuple:
 
1388
        (copied, failures).
 
1389
        """
 
1390
        raise NotImplementedError(self.fetch)
 
1391
   
 
1392
    @needs_read_lock
 
1393
    def missing_revision_ids(self, revision_id=None):
 
1394
        """Return the revision ids that source has that target does not.
 
1395
        
 
1396
        These are returned in topological order.
 
1397
 
 
1398
        :param revision_id: only return revision ids included by this
 
1399
                            revision_id.
 
1400
        """
 
1401
        # generic, possibly worst case, slow code path.
 
1402
        target_ids = set(self.target.all_revision_ids())
 
1403
        if revision_id is not None:
 
1404
            # TODO: jam 20070210 InterRepository is internal enough that it
 
1405
            #       should assume revision_ids are already utf-8
 
1406
            revision_id = osutils.safe_revision_id(revision_id)
 
1407
            source_ids = self.source.get_ancestry(revision_id)
 
1408
            assert source_ids[0] is None
 
1409
            source_ids.pop(0)
 
1410
        else:
 
1411
            source_ids = self.source.all_revision_ids()
 
1412
        result_set = set(source_ids).difference(target_ids)
 
1413
        # this may look like a no-op: its not. It preserves the ordering
 
1414
        # other_ids had while only returning the members from other_ids
 
1415
        # that we've decided we need.
 
1416
        return [rev_id for rev_id in source_ids if rev_id in result_set]
 
1417
 
 
1418
 
 
1419
class InterSameDataRepository(InterRepository):
 
1420
    """Code for converting between repositories that represent the same data.
 
1421
    
 
1422
    Data format and model must match for this to work.
 
1423
    """
 
1424
 
 
1425
    @classmethod
 
1426
    def _get_repo_format_to_test(self):
 
1427
        """Repository format for testing with."""
 
1428
        return RepositoryFormat.get_default_format()
 
1429
 
 
1430
    @staticmethod
 
1431
    def is_compatible(source, target):
 
1432
        if source.supports_rich_root() != target.supports_rich_root():
 
1433
            return False
 
1434
        if source._serializer != target._serializer:
 
1435
            return False
 
1436
        return True
 
1437
 
 
1438
    @needs_write_lock
 
1439
    def copy_content(self, revision_id=None):
 
1440
        """Make a complete copy of the content in self into destination.
 
1441
 
 
1442
        This copies both the repository's revision data, and configuration information
 
1443
        such as the make_working_trees setting.
 
1444
        
 
1445
        This is a destructive operation! Do not use it on existing 
 
1446
        repositories.
 
1447
 
 
1448
        :param revision_id: Only copy the content needed to construct
 
1449
                            revision_id and its parents.
 
1450
        """
 
1451
        try:
 
1452
            self.target.set_make_working_trees(self.source.make_working_trees())
 
1453
        except NotImplementedError:
 
1454
            pass
 
1455
        # TODO: jam 20070210 This is fairly internal, so we should probably
 
1456
        #       just assert that revision_id is not unicode.
 
1457
        revision_id = osutils.safe_revision_id(revision_id)
 
1458
        # but don't bother fetching if we have the needed data now.
 
1459
        if (revision_id not in (None, _mod_revision.NULL_REVISION) and 
 
1460
            self.target.has_revision(revision_id)):
 
1461
            return
 
1462
        self.target.fetch(self.source, revision_id=revision_id)
 
1463
 
 
1464
    @needs_write_lock
 
1465
    def fetch(self, revision_id=None, pb=None):
 
1466
        """See InterRepository.fetch()."""
 
1467
        from bzrlib.fetch import GenericRepoFetcher
 
1468
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
 
1469
               self.source, self.source._format, self.target, 
 
1470
               self.target._format)
 
1471
        # TODO: jam 20070210 This should be an assert, not a translate
 
1472
        revision_id = osutils.safe_revision_id(revision_id)
 
1473
        f = GenericRepoFetcher(to_repository=self.target,
 
1474
                               from_repository=self.source,
 
1475
                               last_revision=revision_id,
 
1476
                               pb=pb)
 
1477
        return f.count_copied, f.failed_revisions
 
1478
 
 
1479
 
 
1480
class InterWeaveRepo(InterSameDataRepository):
 
1481
    """Optimised code paths between Weave based repositories."""
 
1482
 
 
1483
    @classmethod
 
1484
    def _get_repo_format_to_test(self):
 
1485
        from bzrlib.repofmt import weaverepo
 
1486
        return weaverepo.RepositoryFormat7()
 
1487
 
 
1488
    @staticmethod
 
1489
    def is_compatible(source, target):
 
1490
        """Be compatible with known Weave formats.
 
1491
        
 
1492
        We don't test for the stores being of specific types because that
 
1493
        could lead to confusing results, and there is no need to be 
 
1494
        overly general.
 
1495
        """
 
1496
        from bzrlib.repofmt.weaverepo import (
 
1497
                RepositoryFormat5,
 
1498
                RepositoryFormat6,
 
1499
                RepositoryFormat7,
 
1500
                )
 
1501
        try:
 
1502
            return (isinstance(source._format, (RepositoryFormat5,
 
1503
                                                RepositoryFormat6,
 
1504
                                                RepositoryFormat7)) and
 
1505
                    isinstance(target._format, (RepositoryFormat5,
 
1506
                                                RepositoryFormat6,
 
1507
                                                RepositoryFormat7)))
 
1508
        except AttributeError:
 
1509
            return False
 
1510
    
 
1511
    @needs_write_lock
 
1512
    def copy_content(self, revision_id=None):
 
1513
        """See InterRepository.copy_content()."""
 
1514
        # weave specific optimised path:
 
1515
        # TODO: jam 20070210 Internal, should be an assert, not translate
 
1516
        revision_id = osutils.safe_revision_id(revision_id)
 
1517
        try:
 
1518
            self.target.set_make_working_trees(self.source.make_working_trees())
 
1519
        except NotImplementedError:
 
1520
            pass
 
1521
        # FIXME do not peek!
 
1522
        if self.source.control_files._transport.listable():
 
1523
            pb = ui.ui_factory.nested_progress_bar()
 
1524
            try:
 
1525
                self.target.weave_store.copy_all_ids(
 
1526
                    self.source.weave_store,
 
1527
                    pb=pb,
 
1528
                    from_transaction=self.source.get_transaction(),
 
1529
                    to_transaction=self.target.get_transaction())
 
1530
                pb.update('copying inventory', 0, 1)
 
1531
                self.target.control_weaves.copy_multi(
 
1532
                    self.source.control_weaves, ['inventory'],
 
1533
                    from_transaction=self.source.get_transaction(),
 
1534
                    to_transaction=self.target.get_transaction())
 
1535
                self.target._revision_store.text_store.copy_all_ids(
 
1536
                    self.source._revision_store.text_store,
 
1537
                    pb=pb)
 
1538
            finally:
 
1539
                pb.finished()
 
1540
        else:
 
1541
            self.target.fetch(self.source, revision_id=revision_id)
 
1542
 
 
1543
    @needs_write_lock
 
1544
    def fetch(self, revision_id=None, pb=None):
 
1545
        """See InterRepository.fetch()."""
 
1546
        from bzrlib.fetch import GenericRepoFetcher
 
1547
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
 
1548
               self.source, self.source._format, self.target, self.target._format)
 
1549
        # TODO: jam 20070210 This should be an assert, not a translate
 
1550
        revision_id = osutils.safe_revision_id(revision_id)
 
1551
        f = GenericRepoFetcher(to_repository=self.target,
 
1552
                               from_repository=self.source,
 
1553
                               last_revision=revision_id,
 
1554
                               pb=pb)
 
1555
        return f.count_copied, f.failed_revisions
 
1556
 
 
1557
    @needs_read_lock
 
1558
    def missing_revision_ids(self, revision_id=None):
 
1559
        """See InterRepository.missing_revision_ids()."""
 
1560
        # we want all revisions to satisfy revision_id in source.
 
1561
        # but we don't want to stat every file here and there.
 
1562
        # we want then, all revisions other needs to satisfy revision_id 
 
1563
        # checked, but not those that we have locally.
 
1564
        # so the first thing is to get a subset of the revisions to 
 
1565
        # satisfy revision_id in source, and then eliminate those that
 
1566
        # we do already have. 
 
1567
        # this is slow on high latency connection to self, but as as this
 
1568
        # disk format scales terribly for push anyway due to rewriting 
 
1569
        # inventory.weave, this is considered acceptable.
 
1570
        # - RBC 20060209
 
1571
        if revision_id is not None:
 
1572
            source_ids = self.source.get_ancestry(revision_id)
 
1573
            assert source_ids[0] is None
 
1574
            source_ids.pop(0)
 
1575
        else:
 
1576
            source_ids = self.source._all_possible_ids()
 
1577
        source_ids_set = set(source_ids)
 
1578
        # source_ids is the worst possible case we may need to pull.
 
1579
        # now we want to filter source_ids against what we actually
 
1580
        # have in target, but don't try to check for existence where we know
 
1581
        # we do not have a revision as that would be pointless.
 
1582
        target_ids = set(self.target._all_possible_ids())
 
1583
        possibly_present_revisions = target_ids.intersection(source_ids_set)
 
1584
        actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
 
1585
        required_revisions = source_ids_set.difference(actually_present_revisions)
 
1586
        required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
 
1587
        if revision_id is not None:
 
1588
            # we used get_ancestry to determine source_ids then we are assured all
 
1589
            # revisions referenced are present as they are installed in topological order.
 
1590
            # and the tip revision was validated by get_ancestry.
 
1591
            return required_topo_revisions
 
1592
        else:
 
1593
            # if we just grabbed the possibly available ids, then 
 
1594
            # we only have an estimate of whats available and need to validate
 
1595
            # that against the revision records.
 
1596
            return self.source._eliminate_revisions_not_present(required_topo_revisions)
 
1597
 
 
1598
 
 
1599
class InterKnitRepo(InterSameDataRepository):
 
1600
    """Optimised code paths between Knit based repositories."""
 
1601
 
 
1602
    @classmethod
 
1603
    def _get_repo_format_to_test(self):
 
1604
        from bzrlib.repofmt import knitrepo
 
1605
        return knitrepo.RepositoryFormatKnit1()
 
1606
 
 
1607
    @staticmethod
 
1608
    def is_compatible(source, target):
 
1609
        """Be compatible with known Knit formats.
 
1610
        
 
1611
        We don't test for the stores being of specific types because that
 
1612
        could lead to confusing results, and there is no need to be 
 
1613
        overly general.
 
1614
        """
 
1615
        from bzrlib.repofmt.knitrepo import RepositoryFormatKnit1
 
1616
        try:
 
1617
            return (isinstance(source._format, (RepositoryFormatKnit1)) and
 
1618
                    isinstance(target._format, (RepositoryFormatKnit1)))
 
1619
        except AttributeError:
 
1620
            return False
 
1621
 
 
1622
    @needs_write_lock
 
1623
    def fetch(self, revision_id=None, pb=None):
 
1624
        """See InterRepository.fetch()."""
 
1625
        from bzrlib.fetch import KnitRepoFetcher
 
1626
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
 
1627
               self.source, self.source._format, self.target, self.target._format)
 
1628
        # TODO: jam 20070210 This should be an assert, not a translate
 
1629
        revision_id = osutils.safe_revision_id(revision_id)
 
1630
        f = KnitRepoFetcher(to_repository=self.target,
 
1631
                            from_repository=self.source,
 
1632
                            last_revision=revision_id,
 
1633
                            pb=pb)
 
1634
        return f.count_copied, f.failed_revisions
 
1635
 
 
1636
    @needs_read_lock
 
1637
    def missing_revision_ids(self, revision_id=None):
 
1638
        """See InterRepository.missing_revision_ids()."""
 
1639
        if revision_id is not None:
 
1640
            source_ids = self.source.get_ancestry(revision_id)
 
1641
            assert source_ids[0] is None
 
1642
            source_ids.pop(0)
 
1643
        else:
 
1644
            source_ids = self.source._all_possible_ids()
 
1645
        source_ids_set = set(source_ids)
 
1646
        # source_ids is the worst possible case we may need to pull.
 
1647
        # now we want to filter source_ids against what we actually
 
1648
        # have in target, but don't try to check for existence where we know
 
1649
        # we do not have a revision as that would be pointless.
 
1650
        target_ids = set(self.target._all_possible_ids())
 
1651
        possibly_present_revisions = target_ids.intersection(source_ids_set)
 
1652
        actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
 
1653
        required_revisions = source_ids_set.difference(actually_present_revisions)
 
1654
        required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
 
1655
        if revision_id is not None:
 
1656
            # we used get_ancestry to determine source_ids then we are assured all
 
1657
            # revisions referenced are present as they are installed in topological order.
 
1658
            # and the tip revision was validated by get_ancestry.
 
1659
            return required_topo_revisions
 
1660
        else:
 
1661
            # if we just grabbed the possibly available ids, then 
 
1662
            # we only have an estimate of whats available and need to validate
 
1663
            # that against the revision records.
 
1664
            return self.source._eliminate_revisions_not_present(required_topo_revisions)
 
1665
 
 
1666
 
 
1667
class InterModel1and2(InterRepository):
 
1668
 
 
1669
    @classmethod
 
1670
    def _get_repo_format_to_test(self):
 
1671
        return None
 
1672
 
 
1673
    @staticmethod
 
1674
    def is_compatible(source, target):
 
1675
        if not source.supports_rich_root() and target.supports_rich_root():
 
1676
            return True
 
1677
        else:
 
1678
            return False
 
1679
 
 
1680
    @needs_write_lock
 
1681
    def fetch(self, revision_id=None, pb=None):
 
1682
        """See InterRepository.fetch()."""
 
1683
        from bzrlib.fetch import Model1toKnit2Fetcher
 
1684
        # TODO: jam 20070210 This should be an assert, not a translate
 
1685
        revision_id = osutils.safe_revision_id(revision_id)
 
1686
        f = Model1toKnit2Fetcher(to_repository=self.target,
 
1687
                                 from_repository=self.source,
 
1688
                                 last_revision=revision_id,
 
1689
                                 pb=pb)
 
1690
        return f.count_copied, f.failed_revisions
 
1691
 
 
1692
    @needs_write_lock
 
1693
    def copy_content(self, revision_id=None):
 
1694
        """Make a complete copy of the content in self into destination.
 
1695
        
 
1696
        This is a destructive operation! Do not use it on existing 
 
1697
        repositories.
 
1698
 
 
1699
        :param revision_id: Only copy the content needed to construct
 
1700
                            revision_id and its parents.
 
1701
        """
 
1702
        try:
 
1703
            self.target.set_make_working_trees(self.source.make_working_trees())
 
1704
        except NotImplementedError:
 
1705
            pass
 
1706
        # TODO: jam 20070210 Internal, assert, don't translate
 
1707
        revision_id = osutils.safe_revision_id(revision_id)
 
1708
        # but don't bother fetching if we have the needed data now.
 
1709
        if (revision_id not in (None, _mod_revision.NULL_REVISION) and 
 
1710
            self.target.has_revision(revision_id)):
 
1711
            return
 
1712
        self.target.fetch(self.source, revision_id=revision_id)
 
1713
 
 
1714
 
 
1715
class InterKnit1and2(InterKnitRepo):
 
1716
 
 
1717
    @classmethod
 
1718
    def _get_repo_format_to_test(self):
 
1719
        return None
 
1720
 
 
1721
    @staticmethod
 
1722
    def is_compatible(source, target):
 
1723
        """Be compatible with Knit1 source and Knit3 target"""
 
1724
        from bzrlib.repofmt.knitrepo import RepositoryFormatKnit3
 
1725
        try:
 
1726
            from bzrlib.repofmt.knitrepo import RepositoryFormatKnit1, \
 
1727
                    RepositoryFormatKnit3
 
1728
            return (isinstance(source._format, (RepositoryFormatKnit1)) and
 
1729
                    isinstance(target._format, (RepositoryFormatKnit3)))
 
1730
        except AttributeError:
 
1731
            return False
 
1732
 
 
1733
    @needs_write_lock
 
1734
    def fetch(self, revision_id=None, pb=None):
 
1735
        """See InterRepository.fetch()."""
 
1736
        from bzrlib.fetch import Knit1to2Fetcher
 
1737
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
 
1738
               self.source, self.source._format, self.target, 
 
1739
               self.target._format)
 
1740
        # TODO: jam 20070210 This should be an assert, not a translate
 
1741
        revision_id = osutils.safe_revision_id(revision_id)
 
1742
        f = Knit1to2Fetcher(to_repository=self.target,
 
1743
                            from_repository=self.source,
 
1744
                            last_revision=revision_id,
 
1745
                            pb=pb)
 
1746
        return f.count_copied, f.failed_revisions
 
1747
 
 
1748
 
 
1749
class InterRemoteRepository(InterRepository):
 
1750
    """Code for converting between RemoteRepository objects.
 
1751
 
 
1752
    This just gets an non-remote repository from the RemoteRepository, and calls
 
1753
    InterRepository.get again.
 
1754
    """
 
1755
 
 
1756
    def __init__(self, source, target):
 
1757
        if isinstance(source, remote.RemoteRepository):
 
1758
            source._ensure_real()
 
1759
            real_source = source._real_repository
 
1760
        else:
 
1761
            real_source = source
 
1762
        if isinstance(target, remote.RemoteRepository):
 
1763
            target._ensure_real()
 
1764
            real_target = target._real_repository
 
1765
        else:
 
1766
            real_target = target
 
1767
        self.real_inter = InterRepository.get(real_source, real_target)
 
1768
 
 
1769
    @staticmethod
 
1770
    def is_compatible(source, target):
 
1771
        if isinstance(source, remote.RemoteRepository):
 
1772
            return True
 
1773
        if isinstance(target, remote.RemoteRepository):
 
1774
            return True
 
1775
        return False
 
1776
 
 
1777
    def copy_content(self, revision_id=None):
 
1778
        self.real_inter.copy_content(revision_id=revision_id)
 
1779
 
 
1780
    def fetch(self, revision_id=None, pb=None):
 
1781
        self.real_inter.fetch(revision_id=revision_id, pb=pb)
 
1782
 
 
1783
    @classmethod
 
1784
    def _get_repo_format_to_test(self):
 
1785
        return None
 
1786
 
 
1787
 
 
1788
InterRepository.register_optimiser(InterSameDataRepository)
 
1789
InterRepository.register_optimiser(InterWeaveRepo)
 
1790
InterRepository.register_optimiser(InterKnitRepo)
 
1791
InterRepository.register_optimiser(InterModel1and2)
 
1792
InterRepository.register_optimiser(InterKnit1and2)
 
1793
InterRepository.register_optimiser(InterRemoteRepository)
 
1794
 
 
1795
 
 
1796
class RepositoryTestProviderAdapter(object):
 
1797
    """A tool to generate a suite testing multiple repository formats at once.
 
1798
 
 
1799
    This is done by copying the test once for each transport and injecting
 
1800
    the transport_server, transport_readonly_server, and bzrdir_format and
 
1801
    repository_format classes into each copy. Each copy is also given a new id()
 
1802
    to make it easy to identify.
 
1803
    """
 
1804
 
 
1805
    def __init__(self, transport_server, transport_readonly_server, formats,
 
1806
                 vfs_transport_factory=None):
 
1807
        self._transport_server = transport_server
 
1808
        self._transport_readonly_server = transport_readonly_server
 
1809
        self._vfs_transport_factory = vfs_transport_factory
 
1810
        self._formats = formats
 
1811
    
 
1812
    def adapt(self, test):
 
1813
        result = unittest.TestSuite()
 
1814
        for repository_format, bzrdir_format in self._formats:
 
1815
            from copy import deepcopy
 
1816
            new_test = deepcopy(test)
 
1817
            new_test.transport_server = self._transport_server
 
1818
            new_test.transport_readonly_server = self._transport_readonly_server
 
1819
            # Only override the test's vfs_transport_factory if one was
 
1820
            # specified, otherwise just leave the default in place.
 
1821
            if self._vfs_transport_factory:
 
1822
                new_test.vfs_transport_factory = self._vfs_transport_factory
 
1823
            new_test.bzrdir_format = bzrdir_format
 
1824
            new_test.repository_format = repository_format
 
1825
            def make_new_test_id():
 
1826
                new_id = "%s(%s)" % (new_test.id(), repository_format.__class__.__name__)
 
1827
                return lambda: new_id
 
1828
            new_test.id = make_new_test_id()
 
1829
            result.addTest(new_test)
 
1830
        return result
 
1831
 
 
1832
 
 
1833
class InterRepositoryTestProviderAdapter(object):
 
1834
    """A tool to generate a suite testing multiple inter repository formats.
 
1835
 
 
1836
    This is done by copying the test once for each interrepo provider and injecting
 
1837
    the transport_server, transport_readonly_server, repository_format and 
 
1838
    repository_to_format classes into each copy.
 
1839
    Each copy is also given a new id() to make it easy to identify.
 
1840
    """
 
1841
 
 
1842
    def __init__(self, transport_server, transport_readonly_server, formats):
 
1843
        self._transport_server = transport_server
 
1844
        self._transport_readonly_server = transport_readonly_server
 
1845
        self._formats = formats
 
1846
    
 
1847
    def adapt(self, test):
 
1848
        result = unittest.TestSuite()
 
1849
        for interrepo_class, repository_format, repository_format_to in self._formats:
 
1850
            from copy import deepcopy
 
1851
            new_test = deepcopy(test)
 
1852
            new_test.transport_server = self._transport_server
 
1853
            new_test.transport_readonly_server = self._transport_readonly_server
 
1854
            new_test.interrepo_class = interrepo_class
 
1855
            new_test.repository_format = repository_format
 
1856
            new_test.repository_format_to = repository_format_to
 
1857
            def make_new_test_id():
 
1858
                new_id = "%s(%s)" % (new_test.id(), interrepo_class.__name__)
 
1859
                return lambda: new_id
 
1860
            new_test.id = make_new_test_id()
 
1861
            result.addTest(new_test)
 
1862
        return result
 
1863
 
 
1864
    @staticmethod
 
1865
    def default_test_list():
 
1866
        """Generate the default list of interrepo permutations to test."""
 
1867
        from bzrlib.repofmt import knitrepo, weaverepo
 
1868
        result = []
 
1869
        # test the default InterRepository between format 6 and the current 
 
1870
        # default format.
 
1871
        # XXX: robertc 20060220 reinstate this when there are two supported
 
1872
        # formats which do not have an optimal code path between them.
 
1873
        #result.append((InterRepository,
 
1874
        #               RepositoryFormat6(),
 
1875
        #               RepositoryFormatKnit1()))
 
1876
        for optimiser_class in InterRepository._optimisers:
 
1877
            format_to_test = optimiser_class._get_repo_format_to_test()
 
1878
            if format_to_test is not None:
 
1879
                result.append((optimiser_class,
 
1880
                               format_to_test, format_to_test))
 
1881
        # if there are specific combinations we want to use, we can add them 
 
1882
        # here.
 
1883
        result.append((InterModel1and2,
 
1884
                       weaverepo.RepositoryFormat5(),
 
1885
                       knitrepo.RepositoryFormatKnit3()))
 
1886
        result.append((InterKnit1and2,
 
1887
                       knitrepo.RepositoryFormatKnit1(),
 
1888
                       knitrepo.RepositoryFormatKnit3()))
 
1889
        return result
 
1890
 
 
1891
 
 
1892
class CopyConverter(object):
 
1893
    """A repository conversion tool which just performs a copy of the content.
 
1894
    
 
1895
    This is slow but quite reliable.
 
1896
    """
 
1897
 
 
1898
    def __init__(self, target_format):
 
1899
        """Create a CopyConverter.
 
1900
 
 
1901
        :param target_format: The format the resulting repository should be.
 
1902
        """
 
1903
        self.target_format = target_format
 
1904
        
 
1905
    def convert(self, repo, pb):
 
1906
        """Perform the conversion of to_convert, giving feedback via pb.
 
1907
 
 
1908
        :param to_convert: The disk object to convert.
 
1909
        :param pb: a progress bar to use for progress information.
 
1910
        """
 
1911
        self.pb = pb
 
1912
        self.count = 0
 
1913
        self.total = 4
 
1914
        # this is only useful with metadir layouts - separated repo content.
 
1915
        # trigger an assertion if not such
 
1916
        repo._format.get_format_string()
 
1917
        self.repo_dir = repo.bzrdir
 
1918
        self.step('Moving repository to repository.backup')
 
1919
        self.repo_dir.transport.move('repository', 'repository.backup')
 
1920
        backup_transport =  self.repo_dir.transport.clone('repository.backup')
 
1921
        repo._format.check_conversion_target(self.target_format)
 
1922
        self.source_repo = repo._format.open(self.repo_dir,
 
1923
            _found=True,
 
1924
            _override_transport=backup_transport)
 
1925
        self.step('Creating new repository')
 
1926
        converted = self.target_format.initialize(self.repo_dir,
 
1927
                                                  self.source_repo.is_shared())
 
1928
        converted.lock_write()
 
1929
        try:
 
1930
            self.step('Copying content into repository.')
 
1931
            self.source_repo.copy_content_into(converted)
 
1932
        finally:
 
1933
            converted.unlock()
 
1934
        self.step('Deleting old repository content.')
 
1935
        self.repo_dir.transport.delete_tree('repository.backup')
 
1936
        self.pb.note('repository converted')
 
1937
 
 
1938
    def step(self, message):
 
1939
        """Update the pb by a step."""
 
1940
        self.count +=1
 
1941
        self.pb.update(message, self.count, self.total)
 
1942
 
 
1943
 
 
1944
class CommitBuilder(object):
 
1945
    """Provides an interface to build up a commit.
 
1946
 
 
1947
    This allows describing a tree to be committed without needing to 
 
1948
    know the internals of the format of the repository.
 
1949
    """
 
1950
    
 
1951
    record_root_entry = False
 
1952
    def __init__(self, repository, parents, config, timestamp=None, 
 
1953
                 timezone=None, committer=None, revprops=None, 
 
1954
                 revision_id=None):
 
1955
        """Initiate a CommitBuilder.
 
1956
 
 
1957
        :param repository: Repository to commit to.
 
1958
        :param parents: Revision ids of the parents of the new revision.
 
1959
        :param config: Configuration to use.
 
1960
        :param timestamp: Optional timestamp recorded for commit.
 
1961
        :param timezone: Optional timezone for timestamp.
 
1962
        :param committer: Optional committer to set for commit.
 
1963
        :param revprops: Optional dictionary of revision properties.
 
1964
        :param revision_id: Optional revision id.
 
1965
        """
 
1966
        self._config = config
 
1967
 
 
1968
        if committer is None:
 
1969
            self._committer = self._config.username()
 
1970
        else:
 
1971
            assert isinstance(committer, basestring), type(committer)
 
1972
            self._committer = committer
 
1973
 
 
1974
        self.new_inventory = Inventory(None)
 
1975
        self._new_revision_id = osutils.safe_revision_id(revision_id)
 
1976
        self.parents = parents
 
1977
        self.repository = repository
 
1978
 
 
1979
        self._revprops = {}
 
1980
        if revprops is not None:
 
1981
            self._revprops.update(revprops)
 
1982
 
 
1983
        if timestamp is None:
 
1984
            timestamp = time.time()
 
1985
        # Restrict resolution to 1ms
 
1986
        self._timestamp = round(timestamp, 3)
 
1987
 
 
1988
        if timezone is None:
 
1989
            self._timezone = osutils.local_time_offset()
 
1990
        else:
 
1991
            self._timezone = int(timezone)
 
1992
 
 
1993
        self._generate_revision_if_needed()
 
1994
 
 
1995
    def commit(self, message):
 
1996
        """Make the actual commit.
 
1997
 
 
1998
        :return: The revision id of the recorded revision.
 
1999
        """
 
2000
        rev = _mod_revision.Revision(
 
2001
                       timestamp=self._timestamp,
 
2002
                       timezone=self._timezone,
 
2003
                       committer=self._committer,
 
2004
                       message=message,
 
2005
                       inventory_sha1=self.inv_sha1,
 
2006
                       revision_id=self._new_revision_id,
 
2007
                       properties=self._revprops)
 
2008
        rev.parent_ids = self.parents
 
2009
        self.repository.add_revision(self._new_revision_id, rev, 
 
2010
            self.new_inventory, self._config)
 
2011
        return self._new_revision_id
 
2012
 
 
2013
    def revision_tree(self):
 
2014
        """Return the tree that was just committed.
 
2015
 
 
2016
        After calling commit() this can be called to get a RevisionTree
 
2017
        representing the newly committed tree. This is preferred to
 
2018
        calling Repository.revision_tree() because that may require
 
2019
        deserializing the inventory, while we already have a copy in
 
2020
        memory.
 
2021
        """
 
2022
        return RevisionTree(self.repository, self.new_inventory,
 
2023
                            self._new_revision_id)
 
2024
 
 
2025
    def finish_inventory(self):
 
2026
        """Tell the builder that the inventory is finished."""
 
2027
        if self.new_inventory.root is None:
 
2028
            symbol_versioning.warn('Root entry should be supplied to'
 
2029
                ' record_entry_contents, as of bzr 0.10.',
 
2030
                 DeprecationWarning, stacklevel=2)
 
2031
            self.new_inventory.add(InventoryDirectory(ROOT_ID, '', None))
 
2032
        self.new_inventory.revision_id = self._new_revision_id
 
2033
        self.inv_sha1 = self.repository.add_inventory(
 
2034
            self._new_revision_id,
 
2035
            self.new_inventory,
 
2036
            self.parents
 
2037
            )
 
2038
 
 
2039
    def _gen_revision_id(self):
 
2040
        """Return new revision-id."""
 
2041
        return generate_ids.gen_revision_id(self._config.username(),
 
2042
                                            self._timestamp)
 
2043
 
 
2044
    def _generate_revision_if_needed(self):
 
2045
        """Create a revision id if None was supplied.
 
2046
        
 
2047
        If the repository can not support user-specified revision ids
 
2048
        they should override this function and raise CannotSetRevisionId
 
2049
        if _new_revision_id is not None.
 
2050
 
 
2051
        :raises: CannotSetRevisionId
 
2052
        """
 
2053
        if self._new_revision_id is None:
 
2054
            self._new_revision_id = self._gen_revision_id()
 
2055
 
 
2056
    def record_entry_contents(self, ie, parent_invs, path, tree):
 
2057
        """Record the content of ie from tree into the commit if needed.
 
2058
 
 
2059
        Side effect: sets ie.revision when unchanged
 
2060
 
 
2061
        :param ie: An inventory entry present in the commit.
 
2062
        :param parent_invs: The inventories of the parent revisions of the
 
2063
            commit.
 
2064
        :param path: The path the entry is at in the tree.
 
2065
        :param tree: The tree which contains this entry and should be used to 
 
2066
        obtain content.
 
2067
        """
 
2068
        if self.new_inventory.root is None and ie.parent_id is not None:
 
2069
            symbol_versioning.warn('Root entry should be supplied to'
 
2070
                ' record_entry_contents, as of bzr 0.10.',
 
2071
                 DeprecationWarning, stacklevel=2)
 
2072
            self.record_entry_contents(tree.inventory.root.copy(), parent_invs,
 
2073
                                       '', tree)
 
2074
        self.new_inventory.add(ie)
 
2075
 
 
2076
        # ie.revision is always None if the InventoryEntry is considered
 
2077
        # for committing. ie.snapshot will record the correct revision 
 
2078
        # which may be the sole parent if it is untouched.
 
2079
        if ie.revision is not None:
 
2080
            return
 
2081
 
 
2082
        # In this revision format, root entries have no knit or weave
 
2083
        if ie is self.new_inventory.root:
 
2084
            # When serializing out to disk and back in
 
2085
            # root.revision is always _new_revision_id
 
2086
            ie.revision = self._new_revision_id
 
2087
            return
 
2088
        previous_entries = ie.find_previous_heads(
 
2089
            parent_invs,
 
2090
            self.repository.weave_store,
 
2091
            self.repository.get_transaction())
 
2092
        # we are creating a new revision for ie in the history store
 
2093
        # and inventory.
 
2094
        ie.snapshot(self._new_revision_id, path, previous_entries, tree, self)
 
2095
 
 
2096
    def modified_directory(self, file_id, file_parents):
 
2097
        """Record the presence of a symbolic link.
 
2098
 
 
2099
        :param file_id: The file_id of the link to record.
 
2100
        :param file_parents: The per-file parent revision ids.
 
2101
        """
 
2102
        self._add_text_to_weave(file_id, [], file_parents.keys())
 
2103
 
 
2104
    def modified_reference(self, file_id, file_parents):
 
2105
        """Record the modification of a reference.
 
2106
 
 
2107
        :param file_id: The file_id of the link to record.
 
2108
        :param file_parents: The per-file parent revision ids.
 
2109
        """
 
2110
        self._add_text_to_weave(file_id, [], file_parents.keys())
 
2111
    
 
2112
    def modified_file_text(self, file_id, file_parents,
 
2113
                           get_content_byte_lines, text_sha1=None,
 
2114
                           text_size=None):
 
2115
        """Record the text of file file_id
 
2116
 
 
2117
        :param file_id: The file_id of the file to record the text of.
 
2118
        :param file_parents: The per-file parent revision ids.
 
2119
        :param get_content_byte_lines: A callable which will return the byte
 
2120
            lines for the file.
 
2121
        :param text_sha1: Optional SHA1 of the file contents.
 
2122
        :param text_size: Optional size of the file contents.
 
2123
        """
 
2124
        # mutter('storing text of file {%s} in revision {%s} into %r',
 
2125
        #        file_id, self._new_revision_id, self.repository.weave_store)
 
2126
        # special case to avoid diffing on renames or 
 
2127
        # reparenting
 
2128
        if (len(file_parents) == 1
 
2129
            and text_sha1 == file_parents.values()[0].text_sha1
 
2130
            and text_size == file_parents.values()[0].text_size):
 
2131
            previous_ie = file_parents.values()[0]
 
2132
            versionedfile = self.repository.weave_store.get_weave(file_id, 
 
2133
                self.repository.get_transaction())
 
2134
            versionedfile.clone_text(self._new_revision_id, 
 
2135
                previous_ie.revision, file_parents.keys())
 
2136
            return text_sha1, text_size
 
2137
        else:
 
2138
            new_lines = get_content_byte_lines()
 
2139
            # TODO: Rather than invoking sha_strings here, _add_text_to_weave
 
2140
            # should return the SHA1 and size
 
2141
            self._add_text_to_weave(file_id, new_lines, file_parents.keys())
 
2142
            return osutils.sha_strings(new_lines), \
 
2143
                sum(map(len, new_lines))
 
2144
 
 
2145
    def modified_link(self, file_id, file_parents, link_target):
 
2146
        """Record the presence of a symbolic link.
 
2147
 
 
2148
        :param file_id: The file_id of the link to record.
 
2149
        :param file_parents: The per-file parent revision ids.
 
2150
        :param link_target: Target location of this link.
 
2151
        """
 
2152
        self._add_text_to_weave(file_id, [], file_parents.keys())
 
2153
 
 
2154
    def _add_text_to_weave(self, file_id, new_lines, parents):
 
2155
        versionedfile = self.repository.weave_store.get_weave_or_empty(
 
2156
            file_id, self.repository.get_transaction())
 
2157
        versionedfile.add_lines(self._new_revision_id, parents, new_lines)
 
2158
        versionedfile.clear_cache()
 
2159
 
 
2160
 
 
2161
class _CommitBuilder(CommitBuilder):
 
2162
    """Temporary class so old CommitBuilders are detected properly
 
2163
    
 
2164
    Note: CommitBuilder works whether or not root entry is recorded.
 
2165
    """
 
2166
 
 
2167
    record_root_entry = True
 
2168
 
 
2169
 
 
2170
class RootCommitBuilder(CommitBuilder):
 
2171
    """This commitbuilder actually records the root id"""
 
2172
    
 
2173
    record_root_entry = True
 
2174
 
 
2175
    def record_entry_contents(self, ie, parent_invs, path, tree):
 
2176
        """Record the content of ie from tree into the commit if needed.
 
2177
 
 
2178
        Side effect: sets ie.revision when unchanged
 
2179
 
 
2180
        :param ie: An inventory entry present in the commit.
 
2181
        :param parent_invs: The inventories of the parent revisions of the
 
2182
            commit.
 
2183
        :param path: The path the entry is at in the tree.
 
2184
        :param tree: The tree which contains this entry and should be used to 
 
2185
        obtain content.
 
2186
        """
 
2187
        assert self.new_inventory.root is not None or ie.parent_id is None
 
2188
        self.new_inventory.add(ie)
 
2189
 
 
2190
        # ie.revision is always None if the InventoryEntry is considered
 
2191
        # for committing. ie.snapshot will record the correct revision 
 
2192
        # which may be the sole parent if it is untouched.
 
2193
        if ie.revision is not None:
 
2194
            return
 
2195
 
 
2196
        previous_entries = ie.find_previous_heads(
 
2197
            parent_invs,
 
2198
            self.repository.weave_store,
 
2199
            self.repository.get_transaction())
 
2200
        # we are creating a new revision for ie in the history store
 
2201
        # and inventory.
 
2202
        ie.snapshot(self._new_revision_id, path, previous_entries, tree, self)
 
2203
 
 
2204
 
 
2205
_unescape_map = {
 
2206
    'apos':"'",
 
2207
    'quot':'"',
 
2208
    'amp':'&',
 
2209
    'lt':'<',
 
2210
    'gt':'>'
 
2211
}
 
2212
 
 
2213
 
 
2214
def _unescaper(match, _map=_unescape_map):
 
2215
    code = match.group(1)
 
2216
    try:
 
2217
        return _map[code]
 
2218
    except KeyError:
 
2219
        if not code.startswith('#'):
 
2220
            raise
 
2221
        return unichr(int(code[1:])).encode('utf8')
 
2222
 
 
2223
 
 
2224
_unescape_re = None
 
2225
 
 
2226
 
 
2227
def _unescape_xml(data):
 
2228
    """Unescape predefined XML entities in a string of data."""
 
2229
    global _unescape_re
 
2230
    if _unescape_re is None:
 
2231
        _unescape_re = re.compile('\&([^;]*);')
 
2232
    return _unescape_re.sub(_unescaper, data)