/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: Robert Collins
  • Date: 2007-07-31 00:53:40 UTC
  • mto: This revision was merged to the branch mainline in revision 2682.
  • Revision ID: robertc@robertcollins.net-20070731005340-g78eko5xn23lhpq3
More review feedback.

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