/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: Martin Pool
  • Date: 2007-09-25 08:14:12 UTC
  • mto: This revision was merged to the branch mainline in revision 2895.
  • Revision ID: mbp@sourcefrog.net-20070925081412-ta60zj5qxfuokev3
Remove most calls to safe_file_id and safe_revision_id.

The deprecation period for passing unicode objects as revision ids is now over.

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