/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-20 02:27:13 UTC
  • mfrom: (2634 +trunk)
  • mto: (2592.3.48 repository)
  • mto: This revision was merged to the branch mainline in revision 2682.
  • Revision ID: robertc@robertcollins.net-20070720022713-z6x6cns4dy1mzhpk
Merge bzr.dev.

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