~bzr-pqm/bzr/bzr.dev

1553.5.56 by Martin Pool
Format 7 repo now uses LockDir!
1
# Copyright (C) 2005, 2006 Canonical Ltd
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
2
#
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
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.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
7
#
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
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.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
12
#
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
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
1185.65.10 by Robert Collins
Rename Controlfiles to LockableFiles.
16
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
17
from cStringIO import StringIO
18
19
from bzrlib.lazy_import import lazy_import
20
lazy_import(globals(), """
1740.3.7 by Jelmer Vernooij
Move committer, log, revprops, timestamp and timezone to CommitBuilder.
21
from binascii import hexlify
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
22
from copy import deepcopy
1740.3.7 by Jelmer Vernooij
Move committer, log, revprops, timestamp and timezone to CommitBuilder.
23
import re
24
import time
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
25
import unittest
26
1910.2.22 by Aaron Bentley
Make commits preserve root entry data
27
from bzrlib import (
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
28
    bzrdir,
29
    check,
30
    delta,
31
    errors,
2116.4.1 by John Arbash Meinel
Update file and revision id generators.
32
    generate_ids,
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
33
    gpg,
34
    graph,
1996.3.5 by John Arbash Meinel
Cleanup, deprecated, and get the tests passing again.
35
    knit,
2163.2.1 by John Arbash Meinel
Speed up the fileids_altered_by_revision_ids processing
36
    lazy_regex,
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
37
    lockable_files,
38
    lockdir,
1910.2.22 by Aaron Bentley
Make commits preserve root entry data
39
    osutils,
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
40
    revision as _mod_revision,
41
    symbol_versioning,
1910.2.22 by Aaron Bentley
Make commits preserve root entry data
42
    transactions,
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
43
    ui,
44
    weave,
45
    weavefile,
46
    xml5,
1910.2.22 by Aaron Bentley
Make commits preserve root entry data
47
    xml6,
48
    )
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
49
from bzrlib.osutils import (
50
    rand_bytes,
51
    compact_date, 
52
    local_time_offset,
53
    )
54
from bzrlib.revisiontree import RevisionTree
55
from bzrlib.store.versioned import VersionedFileStore
56
from bzrlib.store.text import TextStore
57
from bzrlib.testament import Testament
58
""")
59
1534.4.28 by Robert Collins
first cut at merge from integration.
60
from bzrlib.decorators import needs_read_lock, needs_write_lock
1563.2.12 by Robert Collins
Checkpointing: created InterObject to factor out common inter object worker code, added InterVersionedFile and tests to allow making join work between any versionedfile.
61
from bzrlib.inter import InterObject
1910.2.3 by Aaron Bentley
All tests pass
62
from bzrlib.inventory import Inventory, InventoryDirectory, ROOT_ID
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
63
from bzrlib.symbol_versioning import (
64
        deprecated_method,
65
        zero_nine,
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
66
        )
1904.2.3 by Martin Pool
Give a warning on access to old repository formats
67
from bzrlib.trace import mutter, note, warning
1185.70.3 by Martin Pool
Various updates to make storage branch mergeable:
68
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
69
1904.2.5 by Martin Pool
Fix format warning inside test suite and add test
70
# Old formats display a warning, but only once
71
_deprecation_warning_done = False
72
73
1185.66.5 by Aaron Bentley
Renamed RevisionStorage to Repository
74
class Repository(object):
1185.70.3 by Martin Pool
Various updates to make storage branch mergeable:
75
    """Repository holding history for one or more branches.
76
77
    The repository holds and retrieves historical information including
78
    revisions and file history.  It's normally accessed only by the Branch,
79
    which views a particular line of development through that history.
80
81
    The Repository builds on top of Stores and a Transport, which respectively 
82
    describe the disk data format and the way of accessing the (possibly 
83
    remote) disk.
84
    """
1185.65.17 by Robert Collins
Merge from integration, mode-changes are broken.
85
2163.2.1 by John Arbash Meinel
Speed up the fileids_altered_by_revision_ids processing
86
    _file_ids_altered_regex = lazy_regex.lazy_compile(
87
        r'file_id="(?P<file_id>[^"]+)"'
88
        r'.*revision="(?P<revision_id>[^"]+)"'
89
        )
90
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
91
    @needs_write_lock
92
    def add_inventory(self, revid, inv, parents):
93
        """Add the inventory inv to the repository as revid.
94
        
95
        :param parents: The revision ids of the parents that revid
96
                        is known to have and are in the repository already.
97
98
        returns the sha1 of the serialized inventory.
99
        """
2229.2.3 by Aaron Bentley
change reserved_id to is_reserved_id, add check_not_reserved for DRY
100
        _mod_revision.check_not_reserved_id(revid)
1740.2.2 by Aaron Bentley
Add test for the basis inventory automatically adding the revision id.
101
        assert inv.revision_id is None or inv.revision_id == revid, \
102
            "Mismatch between inventory revision" \
103
            " id and insertion revid (%r, %r)" % (inv.revision_id, revid)
1910.2.6 by Aaron Bentley
Update for merge review, handle deprecations
104
        assert inv.root is not None
1910.2.22 by Aaron Bentley
Make commits preserve root entry data
105
        inv_text = self.serialise_inventory(inv)
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
106
        inv_sha1 = osutils.sha_string(inv_text)
1563.2.25 by Robert Collins
Merge in upstream.
107
        inv_vf = self.control_weaves.get_weave('inventory',
108
                                               self.get_transaction())
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
109
        self._inventory_add_lines(inv_vf, revid, parents, osutils.split_lines(inv_text))
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
110
        return inv_sha1
111
1740.3.6 by Jelmer Vernooij
Move inventory writing to the commit builder.
112
    def _inventory_add_lines(self, inv_vf, revid, parents, lines):
113
        final_parents = []
114
        for parent in parents:
115
            if parent in inv_vf:
116
                final_parents.append(parent)
117
118
        inv_vf.add_lines(revid, final_parents, lines)
119
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
120
    @needs_write_lock
121
    def add_revision(self, rev_id, rev, inv=None, config=None):
122
        """Add rev to the revision store as rev_id.
123
124
        :param rev_id: the revision id to use.
125
        :param rev: The revision object.
126
        :param inv: The inventory for the revision. if None, it will be looked
127
                    up in the inventory storer
128
        :param config: If None no digital signature will be created.
129
                       If supplied its signature_needed method will be used
130
                       to determine if a signature should be made.
131
        """
2229.2.3 by Aaron Bentley
change reserved_id to is_reserved_id, add check_not_reserved for DRY
132
        _mod_revision.check_not_reserved_id(rev_id)
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
133
        if config is not None and config.signature_needed():
134
            if inv is None:
135
                inv = self.get_inventory(rev_id)
136
            plaintext = Testament(rev, inv).as_short_text()
137
            self.store_revision_signature(
138
                gpg.GPGStrategy(config), plaintext, rev_id)
139
        if not rev_id in self.get_inventory_weave():
140
            if inv is None:
141
                raise errors.WeaveRevisionNotPresent(rev_id,
142
                                                     self.get_inventory_weave())
143
            else:
144
                # yes, this is not suitable for adding with ghosts.
145
                self.add_inventory(rev_id, inv, rev.parent_ids)
1608.2.1 by Martin Pool
[merge] Storage filename escaping
146
        self._revision_store.add_revision(rev, self.get_transaction())
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
147
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
148
    @needs_read_lock
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
149
    def _all_possible_ids(self):
150
        """Return all the possible revisions that we could find."""
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
151
        return self.get_inventory_weave().versions()
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
152
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
153
    def all_revision_ids(self):
154
        """Returns a list of all the revision ids in the repository. 
155
156
        This is deprecated because code should generally work on the graph
157
        reachable from a particular revision, and ignore any other revisions
158
        that might be present.  There is no direct replacement method.
159
        """
160
        return self._all_revision_ids()
161
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
162
    @needs_read_lock
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
163
    def _all_revision_ids(self):
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
164
        """Returns a list of all the revision ids in the repository. 
165
166
        These are in as much topological order as the underlying store can 
167
        present: for weaves ghosts may lead to a lack of correctness until
168
        the reweave updates the parents list.
169
        """
1563.2.29 by Robert Collins
Remove all but fetch references to repository.revision_store.
170
        if self._revision_store.text_store.listable():
171
            return self._revision_store.all_revision_ids(self.get_transaction())
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
172
        result = self._all_possible_ids()
173
        return self._eliminate_revisions_not_present(result)
174
1687.1.7 by Robert Collins
Teach Repository about break_lock.
175
    def break_lock(self):
176
        """Break a lock if one is present from another instance.
177
178
        Uses the ui factory to ask for confirmation if the lock may be from
179
        an active process.
180
        """
181
        self.control_files.break_lock()
182
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
183
    @needs_read_lock
184
    def _eliminate_revisions_not_present(self, revision_ids):
185
        """Check every revision id in revision_ids to see if we have it.
186
187
        Returns a set of the present revisions.
188
        """
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
189
        result = []
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
190
        for id in revision_ids:
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
191
            if self.has_revision(id):
192
               result.append(id)
193
        return result
194
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
195
    @staticmethod
196
    def create(a_bzrdir):
197
        """Construct the current default format repository in a_bzrdir."""
198
        return RepositoryFormat.get_default_format().initialize(a_bzrdir)
199
1563.2.29 by Robert Collins
Remove all but fetch references to repository.revision_store.
200
    def __init__(self, _format, a_bzrdir, control_files, _revision_store, control_store, text_store):
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
201
        """instantiate a Repository.
202
203
        :param _format: The format of the repository on disk.
204
        :param a_bzrdir: The BzrDir of the repository.
205
206
        In the future we will have a single api for all stores for
207
        getting file texts, inventories and revisions, then
208
        this construct will accept instances of those things.
209
        """
1608.2.1 by Martin Pool
[merge] Storage filename escaping
210
        super(Repository, self).__init__()
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
211
        self._format = _format
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
212
        # the following are part of the public API for Repository:
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
213
        self.bzrdir = a_bzrdir
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
214
        self.control_files = control_files
1563.2.29 by Robert Collins
Remove all but fetch references to repository.revision_store.
215
        self._revision_store = _revision_store
1563.2.17 by Robert Collins
Change knits repositories to use a knit versioned file store for file texts.
216
        self.text_store = text_store
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
217
        # backwards compatibility
1563.2.17 by Robert Collins
Change knits repositories to use a knit versioned file store for file texts.
218
        self.weave_store = text_store
1563.2.23 by Robert Collins
Add add_revision and get_revision methods to RevisionStore
219
        # not right yet - should be more semantically clear ? 
220
        # 
221
        self.control_store = control_store
222
        self.control_weaves = control_store
1608.2.1 by Martin Pool
[merge] Storage filename escaping
223
        # TODO: make sure to construct the right store classes, etc, depending
224
        # on whether escaping is required.
1904.2.3 by Martin Pool
Give a warning on access to old repository formats
225
        self._warn_if_deprecated()
1910.2.48 by Aaron Bentley
Update from review comments
226
        self._serializer = xml5.serializer_v5
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
227
1668.1.3 by Martin Pool
[patch] use the correct transaction when committing snapshot (Malone: #43959)
228
    def __repr__(self):
229
        return '%s(%r)' % (self.__class__.__name__, 
230
                           self.bzrdir.transport.base)
231
1694.2.6 by Martin Pool
[merge] bzr.dev
232
    def is_locked(self):
233
        return self.control_files.is_locked()
234
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
235
    def lock_write(self):
236
        self.control_files.lock_write()
237
238
    def lock_read(self):
1553.5.55 by Martin Pool
[revert] broken changes
239
        self.control_files.lock_read()
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
240
1694.2.6 by Martin Pool
[merge] bzr.dev
241
    def get_physical_lock_status(self):
242
        return self.control_files.get_physical_lock_status()
1624.3.36 by Olaf Conradi
Rename is_transport_locked() to get_physical_lock_status() as the
243
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
244
    @needs_read_lock
245
    def missing_revision_ids(self, other, revision_id=None):
246
        """Return the revision ids that other has that this does not.
247
        
248
        These are returned in topological order.
249
250
        revision_id: only return revision ids included by revision_id.
251
        """
1534.1.34 by Robert Collins
Move missing_revision_ids from Repository to InterRepository, and eliminate the now unused Repository._compatible_formats method.
252
        return InterRepository.get(other, self).missing_revision_ids(revision_id)
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
253
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
254
    @staticmethod
255
    def open(base):
256
        """Open the repository rooted at base.
257
258
        For instance, if the repository is at URL/.bzr/repository,
259
        Repository.open(URL) -> a Repository instance.
260
        """
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
261
        control = bzrdir.BzrDir.open(base)
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
262
        return control.open_repository()
263
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
264
    def copy_content_into(self, destination, revision_id=None, basis=None):
1534.6.6 by Robert Collins
Move find_repository to bzrdir, its not quite ideal there but its simpler and until someone chooses to vary the search by branch type its completely sufficient.
265
        """Make a complete copy of the content in self into destination.
266
        
267
        This is a destructive operation! Do not use it on existing 
268
        repositories.
269
        """
1534.1.33 by Robert Collins
Move copy_content_into into InterRepository and InterWeaveRepo, and disable the default codepath test as we have optimised paths for all current combinations.
270
        return InterRepository.get(self, destination).copy_content(revision_id, basis)
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
271
1534.1.31 by Robert Collins
Deprecated fetch.fetch and fetch.greedy_fetch for branch.fetch, and move the Repository.fetch internals to InterRepo and InterWeaveRepo.
272
    def fetch(self, source, revision_id=None, pb=None):
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
273
        """Fetch the content required to construct revision_id from source.
274
275
        If revision_id is None all content is copied.
276
        """
1534.1.31 by Robert Collins
Deprecated fetch.fetch and fetch.greedy_fetch for branch.fetch, and move the Repository.fetch internals to InterRepo and InterWeaveRepo.
277
        return InterRepository.get(source, self).fetch(revision_id=revision_id,
278
                                                       pb=pb)
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
279
1740.3.7 by Jelmer Vernooij
Move committer, log, revprops, timestamp and timezone to CommitBuilder.
280
    def get_commit_builder(self, branch, parents, config, timestamp=None, 
281
                           timezone=None, committer=None, revprops=None, 
282
                           revision_id=None):
283
        """Obtain a CommitBuilder for this repository.
284
        
285
        :param branch: Branch to commit to.
286
        :param parents: Revision ids of the parents of the new revision.
287
        :param config: Configuration to use.
288
        :param timestamp: Optional timestamp recorded for commit.
289
        :param timezone: Optional timezone for timestamp.
290
        :param committer: Optional committer to set for commit.
291
        :param revprops: Optional dictionary of revision properties.
292
        :param revision_id: Optional revision id.
293
        """
1910.2.6 by Aaron Bentley
Update for merge review, handle deprecations
294
        return _CommitBuilder(self, parents, config, timestamp, timezone,
295
                              committer, revprops, revision_id)
1740.3.1 by Jelmer Vernooij
Introduce and use CommitBuilder objects.
296
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
297
    def unlock(self):
298
        self.control_files.unlock()
299
1185.65.27 by Robert Collins
Tweak storage towards mergability.
300
    @needs_read_lock
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
301
    def clone(self, a_bzrdir, revision_id=None, basis=None):
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
302
        """Clone this repository into a_bzrdir using the current format.
303
304
        Currently no check is made that the format of this repository and
305
        the bzrdir format are compatible. FIXME RBC 20060201.
306
        """
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
307
        if not isinstance(a_bzrdir._format, self.bzrdir._format.__class__):
308
            # use target default format.
309
            result = a_bzrdir.create_repository()
310
        # FIXME RBC 20060209 split out the repository type to avoid this check ?
311
        elif isinstance(a_bzrdir._format,
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
312
                      (bzrdir.BzrDirFormat4,
313
                       bzrdir.BzrDirFormat5,
314
                       bzrdir.BzrDirFormat6)):
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
315
            result = a_bzrdir.open_repository()
316
        else:
1534.6.5 by Robert Collins
Cloning of repos preserves shared and make-working-tree attributes.
317
            result = self._format.initialize(a_bzrdir, shared=self.is_shared())
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
318
        self.copy_content_into(result, revision_id, basis)
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
319
        return result
320
1563.2.22 by Robert Collins
Move responsibility for repository.has_revision into RevisionStore
321
    @needs_read_lock
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
322
    def has_revision(self, revision_id):
1563.2.22 by Robert Collins
Move responsibility for repository.has_revision into RevisionStore
323
        """True if this repository has a copy of the revision."""
324
        return self._revision_store.has_revision_id(revision_id,
325
                                                    self.get_transaction())
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
326
1185.65.27 by Robert Collins
Tweak storage towards mergability.
327
    @needs_read_lock
1570.1.13 by Robert Collins
Check for incorrect revision parentage in the weave during revision access.
328
    def get_revision_reconcile(self, revision_id):
329
        """'reconcile' helper routine that allows access to a revision always.
330
        
331
        This variant of get_revision does not cross check the weave graph
332
        against the revision one as get_revision does: but it should only
333
        be used by reconcile, or reconcile-alike commands that are correcting
334
        or testing the revision graph.
335
        """
1563.2.25 by Robert Collins
Merge in upstream.
336
        if not revision_id or not isinstance(revision_id, basestring):
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
337
            raise errors.InvalidRevisionId(revision_id=revision_id,
338
                                           branch=self)
1756.1.2 by Aaron Bentley
Show logs using get_revisions
339
        return self._revision_store.get_revisions([revision_id],
340
                                                  self.get_transaction())[0]
341
    @needs_read_lock
342
    def get_revisions(self, revision_ids):
343
        return self._revision_store.get_revisions(revision_ids,
344
                                                  self.get_transaction())
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
345
1185.65.27 by Robert Collins
Tweak storage towards mergability.
346
    @needs_read_lock
1563.2.29 by Robert Collins
Remove all but fetch references to repository.revision_store.
347
    def get_revision_xml(self, revision_id):
348
        rev = self.get_revision(revision_id) 
349
        rev_tmp = StringIO()
350
        # the current serializer..
351
        self._revision_store._serializer.write_revision(rev, rev_tmp)
352
        rev_tmp.seek(0)
353
        return rev_tmp.getvalue()
354
355
    @needs_read_lock
1570.1.13 by Robert Collins
Check for incorrect revision parentage in the weave during revision access.
356
    def get_revision(self, revision_id):
357
        """Return the Revision object for a named revision"""
358
        r = self.get_revision_reconcile(revision_id)
359
        # weave corruption can lead to absent revision markers that should be
360
        # present.
361
        # the following test is reasonably cheap (it needs a single weave read)
362
        # and the weave is cached in read transactions. In write transactions
363
        # it is not cached but typically we only read a small number of
364
        # revisions. For knits when they are introduced we will probably want
365
        # to ensure that caching write transactions are in use.
366
        inv = self.get_inventory_weave()
1570.1.14 by Robert Collins
Enforce repository consistency during 'fetch' operations.
367
        self._check_revision_parents(r, inv)
368
        return r
369
1756.3.19 by Aaron Bentley
Documentation and cleanups
370
    @needs_read_lock
1756.3.22 by Aaron Bentley
Tweaks from review
371
    def get_deltas_for_revisions(self, revisions):
1756.3.19 by Aaron Bentley
Documentation and cleanups
372
        """Produce a generator of revision deltas.
373
        
374
        Note that the input is a sequence of REVISIONS, not revision_ids.
375
        Trees will be held in memory until the generator exits.
376
        Each delta is relative to the revision's lefthand predecessor.
377
        """
1756.3.3 by Aaron Bentley
More refactoring, introduce revision_trees.
378
        required_trees = set()
379
        for revision in revisions:
380
            required_trees.add(revision.revision_id)
381
            required_trees.update(revision.parent_ids[:1])
382
        trees = dict((t.get_revision_id(), t) for 
383
                     t in self.revision_trees(required_trees))
384
        for revision in revisions:
385
            if not revision.parent_ids:
1852.5.1 by Robert Collins
Deprecate EmptyTree in favour of using Repository.revision_tree.
386
                old_tree = self.revision_tree(None)
1756.3.3 by Aaron Bentley
More refactoring, introduce revision_trees.
387
            else:
388
                old_tree = trees[revision.parent_ids[0]]
1852.10.3 by Robert Collins
Remove all uses of compare_trees and replace with Tree.changes_from throughout bzrlib.
389
            yield trees[revision.revision_id].changes_from(old_tree)
1756.3.3 by Aaron Bentley
More refactoring, introduce revision_trees.
390
1756.3.19 by Aaron Bentley
Documentation and cleanups
391
    @needs_read_lock
1744.2.2 by Johan Rydberg
Add get_revision_delta to Repository; and make Branch.get_revision_delta use it.
392
    def get_revision_delta(self, revision_id):
393
        """Return the delta for one revision.
394
395
        The delta is relative to the left-hand predecessor of the
396
        revision.
397
        """
1756.3.3 by Aaron Bentley
More refactoring, introduce revision_trees.
398
        r = self.get_revision(revision_id)
1756.3.22 by Aaron Bentley
Tweaks from review
399
        return list(self.get_deltas_for_revisions([r]))[0]
1744.2.2 by Johan Rydberg
Add get_revision_delta to Repository; and make Branch.get_revision_delta use it.
400
1570.1.14 by Robert Collins
Enforce repository consistency during 'fetch' operations.
401
    def _check_revision_parents(self, revision, inventory):
402
        """Private to Repository and Fetch.
403
        
404
        This checks the parentage of revision in an inventory weave for 
405
        consistency and is only applicable to inventory-weave-for-ancestry
406
        using repository formats & fetchers.
407
        """
1563.2.25 by Robert Collins
Merge in upstream.
408
        weave_parents = inventory.get_parents(revision.revision_id)
409
        weave_names = inventory.versions()
1570.1.14 by Robert Collins
Enforce repository consistency during 'fetch' operations.
410
        for parent_id in revision.parent_ids:
1570.1.13 by Robert Collins
Check for incorrect revision parentage in the weave during revision access.
411
            if parent_id in weave_names:
412
                # this parent must not be a ghost.
413
                if not parent_id in weave_parents:
414
                    # but it is a ghost
415
                    raise errors.CorruptRepository(self)
416
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
417
    @needs_write_lock
418
    def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
1563.2.29 by Robert Collins
Remove all but fetch references to repository.revision_store.
419
        signature = gpg_strategy.sign(plaintext)
420
        self._revision_store.add_revision_signature_text(revision_id,
421
                                                         signature,
422
                                                         self.get_transaction())
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
423
1694.2.6 by Martin Pool
[merge] bzr.dev
424
    def fileids_altered_by_revision_ids(self, revision_ids):
425
        """Find the file ids and versions affected by revisions.
426
427
        :param revisions: an iterable containing revision ids.
428
        :return: a dictionary mapping altered file-ids to an iterable of
429
        revision_ids. Each altered file-ids has the exact revision_ids that
430
        altered it listed explicitly.
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
431
        """
1910.2.48 by Aaron Bentley
Update from review comments
432
        assert self._serializer.support_altered_by_hack, \
1732.2.1 by Martin Pool
Remove obsolete fileid_involved from KnitRepository, fix error message.
433
            ("fileids_altered_by_revision_ids only supported for branches " 
434
             "which store inventory as unnested xml, not on %r" % self)
1694.2.6 by Martin Pool
[merge] bzr.dev
435
        selected_revision_ids = set(revision_ids)
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
436
        w = self.get_inventory_weave()
1694.2.6 by Martin Pool
[merge] bzr.dev
437
        result = {}
1563.2.35 by Robert Collins
cleanup deprecation warnings and finish conversion so the inventory is knit based too.
438
1694.2.6 by Martin Pool
[merge] bzr.dev
439
        # this code needs to read every new line in every inventory for the
440
        # inventories [revision_ids]. Seeing a line twice is ok. Seeing a line
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
441
        # not present in one of those inventories is unnecessary but not 
1594.2.6 by Robert Collins
Introduce a api specifically for looking at lines in some versions of the inventory, for fileid_involved.
442
        # harmful because we are filtering by the revision id marker in the
1694.2.6 by Martin Pool
[merge] bzr.dev
443
        # inventory lines : we only select file ids altered in one of those  
1759.2.2 by Jelmer Vernooij
Revert some of my spelling fixes and fix some typos after review by Aaron.
444
        # revisions. We don't need to see all lines in the inventory because
1594.2.6 by Robert Collins
Introduce a api specifically for looking at lines in some versions of the inventory, for fileid_involved.
445
        # only those added in an inventory in rev X can contain a revision=X
446
        # line.
2163.2.3 by John Arbash Meinel
Change to local variables to save another 300ms
447
        unescape_revid_cache = {}
448
        unescape_fileid_cache = {}
449
2163.2.5 by John Arbash Meinel
Inline the cache lookup, and explain why
450
        # jam 20061218 In a big fetch, this handles hundreds of thousands
451
        # of lines, so it has had a lot of inlining and optimizing done.
452
        # Sorry that it is a little bit messy.
2163.2.3 by John Arbash Meinel
Change to local variables to save another 300ms
453
        # Move several functions to be local variables, since this is a long
454
        # running loop.
455
        search = self._file_ids_altered_regex.search
2163.2.5 by John Arbash Meinel
Inline the cache lookup, and explain why
456
        unescape = _unescape_xml
2163.2.3 by John Arbash Meinel
Change to local variables to save another 300ms
457
        setdefault = result.setdefault
2039.1.1 by Aaron Bentley
Clean up progress properly when interrupted during fetch (#54000)
458
        pb = ui.ui_factory.nested_progress_bar()
459
        try:
460
            for line in w.iter_lines_added_or_present_in_versions(
2163.2.3 by John Arbash Meinel
Change to local variables to save another 300ms
461
                                        selected_revision_ids, pb=pb):
462
                match = search(line)
2163.2.1 by John Arbash Meinel
Speed up the fileids_altered_by_revision_ids processing
463
                if match is None:
464
                    continue
2163.2.5 by John Arbash Meinel
Inline the cache lookup, and explain why
465
                # One call to match.group() returning multiple items is quite a
466
                # bit faster than 2 calls to match.group() each returning 1
2163.2.1 by John Arbash Meinel
Speed up the fileids_altered_by_revision_ids processing
467
                file_id, revision_id = match.group('file_id', 'revision_id')
2163.2.5 by John Arbash Meinel
Inline the cache lookup, and explain why
468
469
                # Inlining the cache lookups helps a lot when you make 170,000
470
                # lines and 350k ids, versus 8.4 unique ids.
471
                # Using a cache helps in 2 ways:
472
                #   1) Avoids unnecessary decoding calls
473
                #   2) Re-uses cached strings, which helps in future set and
474
                #      equality checks.
475
                # (2) is enough that removing encoding entirely along with
476
                # the cache (so we are using plain strings) results in no
477
                # performance improvement.
478
                try:
479
                    revision_id = unescape_revid_cache[revision_id]
480
                except KeyError:
481
                    unescaped = unescape(revision_id)
482
                    unescape_revid_cache[revision_id] = unescaped
483
                    revision_id = unescaped
484
2039.1.1 by Aaron Bentley
Clean up progress properly when interrupted during fetch (#54000)
485
                if revision_id in selected_revision_ids:
2163.2.5 by John Arbash Meinel
Inline the cache lookup, and explain why
486
                    try:
487
                        file_id = unescape_fileid_cache[file_id]
488
                    except KeyError:
489
                        unescaped = unescape(file_id)
490
                        unescape_fileid_cache[file_id] = unescaped
491
                        file_id = unescaped
2163.2.3 by John Arbash Meinel
Change to local variables to save another 300ms
492
                    setdefault(file_id, set()).add(revision_id)
2039.1.1 by Aaron Bentley
Clean up progress properly when interrupted during fetch (#54000)
493
        finally:
494
            pb.finished()
1694.2.6 by Martin Pool
[merge] bzr.dev
495
        return result
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
496
1185.65.27 by Robert Collins
Tweak storage towards mergability.
497
    @needs_read_lock
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
498
    def get_inventory_weave(self):
499
        return self.control_weaves.get_weave('inventory',
500
            self.get_transaction())
501
1185.65.27 by Robert Collins
Tweak storage towards mergability.
502
    @needs_read_lock
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
503
    def get_inventory(self, revision_id):
504
        """Get Inventory object by hash."""
1740.2.3 by Aaron Bentley
Only reserialize the working tree basis inventory when needed.
505
        return self.deserialise_inventory(
506
            revision_id, self.get_inventory_xml(revision_id))
507
508
    def deserialise_inventory(self, revision_id, xml):
509
        """Transform the xml into an inventory object. 
510
511
        :param revision_id: The expected revision id of the inventory.
512
        :param xml: A serialised inventory.
513
        """
1910.2.48 by Aaron Bentley
Update from review comments
514
        result = self._serializer.read_inventory_from_string(xml)
1910.2.1 by Aaron Bentley
Ensure root entry always has a revision
515
        result.root.revision = revision_id
516
        return result
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
517
1910.2.22 by Aaron Bentley
Make commits preserve root entry data
518
    def serialise_inventory(self, inv):
1910.2.48 by Aaron Bentley
Update from review comments
519
        return self._serializer.write_inventory_to_string(inv)
1910.2.22 by Aaron Bentley
Make commits preserve root entry data
520
1185.65.27 by Robert Collins
Tweak storage towards mergability.
521
    @needs_read_lock
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
522
    def get_inventory_xml(self, revision_id):
523
        """Get inventory XML as a file object."""
524
        try:
525
            assert isinstance(revision_id, basestring), type(revision_id)
526
            iw = self.get_inventory_weave()
1563.2.18 by Robert Collins
get knit repositories really using knits for text storage.
527
            return iw.get_text(revision_id)
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
528
        except IndexError:
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
529
            raise errors.HistoryMissing(self, 'inventory', revision_id)
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
530
1185.65.27 by Robert Collins
Tweak storage towards mergability.
531
    @needs_read_lock
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
532
    def get_inventory_sha1(self, revision_id):
533
        """Return the sha1 hash of the inventory entry
534
        """
535
        return self.get_revision(revision_id).inventory_sha1
536
1185.65.27 by Robert Collins
Tweak storage towards mergability.
537
    @needs_read_lock
1590.1.1 by Robert Collins
Improve common_ancestor performance.
538
    def get_revision_graph(self, revision_id=None):
539
        """Return a dictionary containing the revision graph.
540
        
1836.3.1 by Robert Collins
(robertc) Teach repository.get_revision_graph, and revision.common_ancestor, about NULL_REVISION.
541
        :param revision_id: The revision_id to get a graph from. If None, then
542
        the entire revision graph is returned. This is a deprecated mode of
543
        operation and will be removed in the future.
1590.1.1 by Robert Collins
Improve common_ancestor performance.
544
        :return: a dictionary of revision_id->revision_parents_list.
545
        """
1836.3.1 by Robert Collins
(robertc) Teach repository.get_revision_graph, and revision.common_ancestor, about NULL_REVISION.
546
        # special case NULL_REVISION
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
547
        if revision_id == _mod_revision.NULL_REVISION:
1836.3.1 by Robert Collins
(robertc) Teach repository.get_revision_graph, and revision.common_ancestor, about NULL_REVISION.
548
            return {}
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
549
        a_weave = self.get_inventory_weave()
550
        all_revisions = self._eliminate_revisions_not_present(
551
                                a_weave.versions())
552
        entire_graph = dict([(node, a_weave.get_parents(node)) for 
1590.1.1 by Robert Collins
Improve common_ancestor performance.
553
                             node in all_revisions])
554
        if revision_id is None:
555
            return entire_graph
556
        elif revision_id not in entire_graph:
557
            raise errors.NoSuchRevision(self, revision_id)
558
        else:
559
            # add what can be reached from revision_id
560
            result = {}
561
            pending = set([revision_id])
562
            while len(pending) > 0:
563
                node = pending.pop()
564
                result[node] = entire_graph[node]
565
                for revision_id in result[node]:
566
                    if revision_id not in result:
567
                        pending.add(revision_id)
568
            return result
569
570
    @needs_read_lock
1594.2.3 by Robert Collins
bugfix revision.MultipleRevisionSources.get_revision_graph to integrate ghosts between sources. [slow on weaves, fast on knits.
571
    def get_revision_graph_with_ghosts(self, revision_ids=None):
572
        """Return a graph of the revisions with ghosts marked as applicable.
573
574
        :param revision_ids: an iterable of revisions to graph or None for all.
575
        :return: a Graph object with the graph reachable from revision_ids.
576
        """
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
577
        result = graph.Graph()
1594.2.3 by Robert Collins
bugfix revision.MultipleRevisionSources.get_revision_graph to integrate ghosts between sources. [slow on weaves, fast on knits.
578
        if not revision_ids:
1773.4.2 by Martin Pool
Cleanup of imports; undeprecate all_revision_ids()
579
            pending = set(self.all_revision_ids())
1594.2.3 by Robert Collins
bugfix revision.MultipleRevisionSources.get_revision_graph to integrate ghosts between sources. [slow on weaves, fast on knits.
580
            required = set([])
581
        else:
582
            pending = set(revision_ids)
1836.3.1 by Robert Collins
(robertc) Teach repository.get_revision_graph, and revision.common_ancestor, about NULL_REVISION.
583
            # special case NULL_REVISION
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
584
            if _mod_revision.NULL_REVISION in pending:
585
                pending.remove(_mod_revision.NULL_REVISION)
1836.3.1 by Robert Collins
(robertc) Teach repository.get_revision_graph, and revision.common_ancestor, about NULL_REVISION.
586
            required = set(pending)
1594.2.3 by Robert Collins
bugfix revision.MultipleRevisionSources.get_revision_graph to integrate ghosts between sources. [slow on weaves, fast on knits.
587
        done = set([])
588
        while len(pending):
589
            revision_id = pending.pop()
590
            try:
591
                rev = self.get_revision(revision_id)
592
            except errors.NoSuchRevision:
593
                if revision_id in required:
594
                    raise
595
                # a ghost
596
                result.add_ghost(revision_id)
597
                continue
598
            for parent_id in rev.parent_ids:
599
                # is this queued or done ?
600
                if (parent_id not in pending and
601
                    parent_id not in done):
602
                    # no, queue it.
603
                    pending.add(parent_id)
604
            result.add_node(revision_id, rev.parent_ids)
1594.2.15 by Robert Collins
Unfuck performance.
605
            done.add(revision_id)
1594.2.3 by Robert Collins
bugfix revision.MultipleRevisionSources.get_revision_graph to integrate ghosts between sources. [slow on weaves, fast on knits.
606
        return result
607
608
    @needs_read_lock
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
609
    def get_revision_inventory(self, revision_id):
610
        """Return inventory of a past revision."""
611
        # TODO: Unify this with get_inventory()
612
        # bzr 0.0.6 and later imposes the constraint that the inventory_id
613
        # must be the same as its revision, so this is trivial.
1534.4.28 by Robert Collins
first cut at merge from integration.
614
        if revision_id is None:
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
615
            # This does not make sense: if there is no revision,
616
            # then it is the current tree inventory surely ?!
617
            # and thus get_root_id() is something that looks at the last
618
            # commit on the branch, and the get_root_id is an inventory check.
619
            raise NotImplementedError
620
            # return Inventory(self.get_root_id())
621
        else:
622
            return self.get_inventory(revision_id)
623
1185.65.27 by Robert Collins
Tweak storage towards mergability.
624
    @needs_read_lock
1534.6.3 by Robert Collins
find_repository sufficiently robust.
625
    def is_shared(self):
626
        """Return True if this repository is flagged as a shared repository."""
1596.2.12 by Robert Collins
Merge and make Knit Repository use the revision store for all possible queries.
627
        raise NotImplementedError(self.is_shared)
1534.6.3 by Robert Collins
find_repository sufficiently robust.
628
1594.2.7 by Robert Collins
Add versionedfile.fix_parents api for correcting data post hoc.
629
    @needs_write_lock
1692.1.1 by Robert Collins
* Repository.reconcile now takes a thorough keyword parameter to allow
630
    def reconcile(self, other=None, thorough=False):
1594.2.7 by Robert Collins
Add versionedfile.fix_parents api for correcting data post hoc.
631
        """Reconcile this repository."""
632
        from bzrlib.reconcile import RepoReconciler
1692.1.1 by Robert Collins
* Repository.reconcile now takes a thorough keyword parameter to allow
633
        reconciler = RepoReconciler(self, thorough=thorough)
1594.2.7 by Robert Collins
Add versionedfile.fix_parents api for correcting data post hoc.
634
        reconciler.reconcile()
635
        return reconciler
636
    
1534.6.3 by Robert Collins
find_repository sufficiently robust.
637
    @needs_read_lock
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
638
    def revision_tree(self, revision_id):
639
        """Return Tree for a revision on this branch.
640
1852.5.1 by Robert Collins
Deprecate EmptyTree in favour of using Repository.revision_tree.
641
        `revision_id` may be None for the empty tree revision.
642
        """
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
643
        # TODO: refactor this to use an existing revision object
644
        # so we don't need to read it in twice.
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
645
        if revision_id is None or revision_id == _mod_revision.NULL_REVISION:
1731.1.61 by Aaron Bentley
Merge bzr.dev
646
            return RevisionTree(self, Inventory(root_id=None), 
647
                                _mod_revision.NULL_REVISION)
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
648
        else:
649
            inv = self.get_revision_inventory(revision_id)
1185.65.17 by Robert Collins
Merge from integration, mode-changes are broken.
650
            return RevisionTree(self, inv, revision_id)
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
651
1185.65.27 by Robert Collins
Tweak storage towards mergability.
652
    @needs_read_lock
1756.3.3 by Aaron Bentley
More refactoring, introduce revision_trees.
653
    def revision_trees(self, revision_ids):
654
        """Return Tree for a revision on this branch.
655
1756.3.19 by Aaron Bentley
Documentation and cleanups
656
        `revision_id` may not be None or 'null:'"""
1756.3.3 by Aaron Bentley
More refactoring, introduce revision_trees.
657
        assert None not in revision_ids
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
658
        assert _mod_revision.NULL_REVISION not in revision_ids
1756.3.5 by Aaron Bentley
Switch to get_texts, optimize get_texts
659
        texts = self.get_inventory_weave().get_texts(revision_ids)
1756.3.3 by Aaron Bentley
More refactoring, introduce revision_trees.
660
        for text, revision_id in zip(texts, revision_ids):
661
            inv = self.deserialise_inventory(revision_id, text)
662
            yield RevisionTree(self, inv, revision_id)
663
664
    @needs_read_lock
1185.66.2 by Aaron Bentley
Moved get_ancestry to RevisionStorage
665
    def get_ancestry(self, revision_id):
666
        """Return a list of revision-ids integrated by a revision.
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
667
668
        The first element of the list is always None, indicating the origin 
669
        revision.  This might change when we have history horizons, or 
670
        perhaps we should have a new API.
1185.66.2 by Aaron Bentley
Moved get_ancestry to RevisionStorage
671
        
672
        This is topologically sorted.
673
        """
674
        if revision_id is None:
675
            return [None]
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
676
        if not self.has_revision(revision_id):
677
            raise errors.NoSuchRevision(self, revision_id)
1185.66.2 by Aaron Bentley
Moved get_ancestry to RevisionStorage
678
        w = self.get_inventory_weave()
1594.2.9 by Robert Collins
Teach Knit repositories how to handle ghosts without corrupting at all.
679
        candidates = w.get_ancestry(revision_id)
680
        return [None] + candidates # self._eliminate_revisions_not_present(candidates)
1185.66.2 by Aaron Bentley
Moved get_ancestry to RevisionStorage
681
1185.65.4 by Aaron Bentley
Fixed cat command
682
    @needs_read_lock
683
    def print_file(self, file, revision_id):
1185.65.29 by Robert Collins
Implement final review suggestions.
684
        """Print `file` to stdout.
685
        
686
        FIXME RBC 20060125 as John Meinel points out this is a bad api
687
        - it writes to stdout, it assumes that that is valid etc. Fix
688
        by creating a new more flexible convenience function.
689
        """
1185.65.4 by Aaron Bentley
Fixed cat command
690
        tree = self.revision_tree(revision_id)
691
        # use inventory as it was in that revision
692
        file_id = tree.inventory.path2id(file)
693
        if not file_id:
1685.1.26 by John Arbash Meinel
Repository had a bug with what exception was raised when a file was missing
694
            # TODO: jam 20060427 Write a test for this code path
695
            #       it had a bug in it, and was raising the wrong
696
            #       exception.
697
            raise errors.BzrError("%r is not present in revision %s" % (file, revision_id))
1185.65.4 by Aaron Bentley
Fixed cat command
698
        tree.print_file(file_id)
699
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
700
    def get_transaction(self):
701
        return self.control_files.get_transaction()
702
1590.1.1 by Robert Collins
Improve common_ancestor performance.
703
    def revision_parents(self, revid):
704
        return self.get_inventory_weave().parent_names(revid)
705
1185.65.27 by Robert Collins
Tweak storage towards mergability.
706
    @needs_write_lock
1534.6.5 by Robert Collins
Cloning of repos preserves shared and make-working-tree attributes.
707
    def set_make_working_trees(self, new_value):
708
        """Set the policy flag for making working trees when creating branches.
709
710
        This only applies to branches that use this repository.
711
712
        The default is 'True'.
713
        :param new_value: True to restore the default, False to disable making
714
                          working trees.
715
        """
1596.2.12 by Robert Collins
Merge and make Knit Repository use the revision store for all possible queries.
716
        raise NotImplementedError(self.set_make_working_trees)
1534.6.5 by Robert Collins
Cloning of repos preserves shared and make-working-tree attributes.
717
    
718
    def make_working_trees(self):
719
        """Returns the policy for making working trees on new branches."""
1596.2.12 by Robert Collins
Merge and make Knit Repository use the revision store for all possible queries.
720
        raise NotImplementedError(self.make_working_trees)
1534.6.5 by Robert Collins
Cloning of repos preserves shared and make-working-tree attributes.
721
722
    @needs_write_lock
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
723
    def sign_revision(self, revision_id, gpg_strategy):
724
        plaintext = Testament.from_revision(self, revision_id).as_short_text()
725
        self.store_revision_signature(gpg_strategy, plaintext, revision_id)
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
726
1563.2.29 by Robert Collins
Remove all but fetch references to repository.revision_store.
727
    @needs_read_lock
728
    def has_signature_for_revision_id(self, revision_id):
729
        """Query for a revision signature for revision_id in the repository."""
730
        return self._revision_store.has_signature(revision_id,
731
                                                  self.get_transaction())
732
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
733
    @needs_read_lock
734
    def get_signature_text(self, revision_id):
735
        """Return the text for a signature."""
736
        return self._revision_store.get_signature_text(revision_id,
737
                                                       self.get_transaction())
738
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
739
    @needs_read_lock
740
    def check(self, revision_ids):
741
        """Check consistency of all history of given revision_ids.
742
743
        Different repository implementations should override _check().
744
745
        :param revision_ids: A non-empty list of revision_ids whose ancestry
746
             will be checked.  Typically the last revision_id of a branch.
747
        """
748
        if not revision_ids:
749
            raise ValueError("revision_ids must be non-empty in %s.check" 
750
                    % (self,))
751
        return self._check(revision_ids)
752
753
    def _check(self, revision_ids):
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
754
        result = check.Check(self)
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
755
        result.check()
756
        return result
757
1904.2.3 by Martin Pool
Give a warning on access to old repository formats
758
    def _warn_if_deprecated(self):
1904.2.5 by Martin Pool
Fix format warning inside test suite and add test
759
        global _deprecation_warning_done
760
        if _deprecation_warning_done:
761
            return
762
        _deprecation_warning_done = True
1904.2.3 by Martin Pool
Give a warning on access to old repository formats
763
        warning("Format %s for %s is deprecated - please use 'bzr upgrade' to get better performance"
764
                % (self._format, self.bzrdir.transport.base))
765
1910.2.63 by Aaron Bentley
Add supports_rich_root member to repository
766
    def supports_rich_root(self):
767
        return self._format.rich_root_data
768
2150.2.2 by Robert Collins
Change the commit builder selected-revision-id test to use a unicode revision id where possible, leading to stricter testing of the hypothetical unicode revision id support in bzr.
769
    def _check_ascii_revisionid(self, revision_id, method):
770
        """Private helper for ascii-only repositories."""
771
        # weave repositories refuse to store revisionids that are non-ascii.
772
        if revision_id is not None:
773
            # weaves require ascii revision ids.
774
            if isinstance(revision_id, unicode):
775
                try:
776
                    revision_id.encode('ascii')
777
                except UnicodeEncodeError:
778
                    raise errors.NonAsciiRevisionId(method, self)
779
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
780
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
781
class AllInOneRepository(Repository):
782
    """Legacy support - the repository behaviour for all-in-one branches."""
783
1563.2.29 by Robert Collins
Remove all but fetch references to repository.revision_store.
784
    def __init__(self, _format, a_bzrdir, _revision_store, control_store, text_store):
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
785
        # we reuse one control files instance.
786
        dir_mode = a_bzrdir._control_files._dir_mode
787
        file_mode = a_bzrdir._control_files._file_mode
788
789
        def get_store(name, compressed=True, prefixed=False):
790
            # FIXME: This approach of assuming stores are all entirely compressed
791
            # or entirely uncompressed is tidy, but breaks upgrade from 
792
            # some existing branches where there's a mixture; we probably 
793
            # still want the option to look for both.
794
            relpath = a_bzrdir._control_files._escape(name)
795
            store = TextStore(a_bzrdir._control_files._transport.clone(relpath),
796
                              prefixed=prefixed, compressed=compressed,
797
                              dir_mode=dir_mode,
798
                              file_mode=file_mode)
799
            #if self._transport.should_cache():
800
            #    cache_path = os.path.join(self.cache_root, name)
801
            #    os.mkdir(cache_path)
802
            #    store = bzrlib.store.CachedStore(store, cache_path)
803
            return store
804
805
        # not broken out yet because the controlweaves|inventory_store
806
        # and text_store | weave_store bits are still different.
807
        if isinstance(_format, RepositoryFormat4):
1563.2.23 by Robert Collins
Add add_revision and get_revision methods to RevisionStore
808
            # cannot remove these - there is still no consistent api 
809
            # which allows access to this old info.
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
810
            self.inventory_store = get_store('inventory-store')
1563.2.18 by Robert Collins
get knit repositories really using knits for text storage.
811
            text_store = get_store('text-store')
1563.2.29 by Robert Collins
Remove all but fetch references to repository.revision_store.
812
        super(AllInOneRepository, self).__init__(_format, a_bzrdir, a_bzrdir._control_files, _revision_store, control_store, text_store)
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
813
2150.2.2 by Robert Collins
Change the commit builder selected-revision-id test to use a unicode revision id where possible, leading to stricter testing of the hypothetical unicode revision id support in bzr.
814
    def get_commit_builder(self, branch, parents, config, timestamp=None,
815
                           timezone=None, committer=None, revprops=None,
816
                           revision_id=None):
817
        self._check_ascii_revisionid(revision_id, self.get_commit_builder)
818
        return Repository.get_commit_builder(self, branch, parents, config,
819
            timestamp, timezone, committer, revprops, revision_id)
820
1596.2.12 by Robert Collins
Merge and make Knit Repository use the revision store for all possible queries.
821
    @needs_read_lock
822
    def is_shared(self):
823
        """AllInOne repositories cannot be shared."""
824
        return False
825
826
    @needs_write_lock
827
    def set_make_working_trees(self, new_value):
828
        """Set the policy flag for making working trees when creating branches.
829
830
        This only applies to branches that use this repository.
831
832
        The default is 'True'.
833
        :param new_value: True to restore the default, False to disable making
834
                          working trees.
835
        """
836
        raise NotImplementedError(self.set_make_working_trees)
837
    
838
    def make_working_trees(self):
839
        """Returns the policy for making working trees on new branches."""
840
        return True
841
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
842
1185.82.84 by Aaron Bentley
Moved stuff around
843
def install_revision(repository, rev, revision_tree):
844
    """Install all revision data into a repository."""
845
    present_parents = []
846
    parent_trees = {}
847
    for p_id in rev.parent_ids:
848
        if repository.has_revision(p_id):
849
            present_parents.append(p_id)
850
            parent_trees[p_id] = repository.revision_tree(p_id)
851
        else:
1852.5.1 by Robert Collins
Deprecate EmptyTree in favour of using Repository.revision_tree.
852
            parent_trees[p_id] = repository.revision_tree(None)
1185.82.84 by Aaron Bentley
Moved stuff around
853
854
    inv = revision_tree.inventory
1910.2.51 by Aaron Bentley
Bundles now corrupt repositories
855
    entries = inv.iter_entries()
1852.6.3 by Robert Collins
Make iter(Tree) consistent for all tree types.
856
    # backwards compatability hack: skip the root id.
1910.2.63 by Aaron Bentley
Add supports_rich_root member to repository
857
    if not repository.supports_rich_root():
1910.2.60 by Aaron Bentley
Ensure that new-model revisions aren't installed into old-model repos
858
        path, root = entries.next()
859
        if root.revision != rev.revision_id:
1910.2.63 by Aaron Bentley
Add supports_rich_root member to repository
860
            raise errors.IncompatibleRevision(repr(repository))
1185.82.84 by Aaron Bentley
Moved stuff around
861
    # Add the texts that are not already present
1852.6.3 by Robert Collins
Make iter(Tree) consistent for all tree types.
862
    for path, ie in entries:
1185.82.84 by Aaron Bentley
Moved stuff around
863
        w = repository.weave_store.get_weave_or_empty(ie.file_id,
864
                repository.get_transaction())
865
        if ie.revision not in w:
866
            text_parents = []
1740.2.2 by Aaron Bentley
Add test for the basis inventory automatically adding the revision id.
867
            # FIXME: TODO: The following loop *may* be overlapping/duplicate
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
868
            # with InventoryEntry.find_previous_heads(). if it is, then there
1740.2.2 by Aaron Bentley
Add test for the basis inventory automatically adding the revision id.
869
            # is a latent bug here where the parents may have ancestors of each
870
            # other. RBC, AB
1185.82.84 by Aaron Bentley
Moved stuff around
871
            for revision, tree in parent_trees.iteritems():
872
                if ie.file_id not in tree:
873
                    continue
874
                parent_id = tree.inventory[ie.file_id].revision
875
                if parent_id in text_parents:
876
                    continue
877
                text_parents.append(parent_id)
878
                    
879
            vfile = repository.weave_store.get_weave_or_empty(ie.file_id, 
880
                repository.get_transaction())
881
            lines = revision_tree.get_file(ie.file_id).readlines()
882
            vfile.add_lines(rev.revision_id, text_parents, lines)
883
    try:
884
        # install the inventory
885
        repository.add_inventory(rev.revision_id, inv, present_parents)
886
    except errors.RevisionAlreadyPresent:
887
        pass
888
    repository.add_revision(rev.revision_id, rev, inv)
889
890
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
891
class MetaDirRepository(Repository):
892
    """Repositories in the new meta-dir layout."""
893
1563.2.29 by Robert Collins
Remove all but fetch references to repository.revision_store.
894
    def __init__(self, _format, a_bzrdir, control_files, _revision_store, control_store, text_store):
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
895
        super(MetaDirRepository, self).__init__(_format,
896
                                                a_bzrdir,
897
                                                control_files,
1563.2.29 by Robert Collins
Remove all but fetch references to repository.revision_store.
898
                                                _revision_store,
1563.2.23 by Robert Collins
Add add_revision and get_revision methods to RevisionStore
899
                                                control_store,
1563.2.17 by Robert Collins
Change knits repositories to use a knit versioned file store for file texts.
900
                                                text_store)
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
901
        dir_mode = self.control_files._dir_mode
902
        file_mode = self.control_files._file_mode
903
1596.2.12 by Robert Collins
Merge and make Knit Repository use the revision store for all possible queries.
904
    @needs_read_lock
905
    def is_shared(self):
906
        """Return True if this repository is flagged as a shared repository."""
907
        return self.control_files._transport.has('shared-storage')
908
909
    @needs_write_lock
910
    def set_make_working_trees(self, new_value):
911
        """Set the policy flag for making working trees when creating branches.
912
913
        This only applies to branches that use this repository.
914
915
        The default is 'True'.
916
        :param new_value: True to restore the default, False to disable making
917
                          working trees.
918
        """
919
        if new_value:
920
            try:
921
                self.control_files._transport.delete('no-working-trees')
922
            except errors.NoSuchFile:
923
                pass
924
        else:
925
            self.control_files.put_utf8('no-working-trees', '')
926
    
927
    def make_working_trees(self):
928
        """Returns the policy for making working trees on new branches."""
929
        return not self.control_files._transport.has('no-working-trees')
930
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
931
2150.2.2 by Robert Collins
Change the commit builder selected-revision-id test to use a unicode revision id where possible, leading to stricter testing of the hypothetical unicode revision id support in bzr.
932
class WeaveMetaDirRepository(MetaDirRepository):
933
    """A subclass of MetaDirRepository to set weave specific policy."""
934
935
    def get_commit_builder(self, branch, parents, config, timestamp=None,
936
                           timezone=None, committer=None, revprops=None,
937
                           revision_id=None):
938
        self._check_ascii_revisionid(revision_id, self.get_commit_builder)
939
        return MetaDirRepository.get_commit_builder(self, branch, parents,
940
            config, timestamp, timezone, committer, revprops, revision_id)
941
942
1563.2.29 by Robert Collins
Remove all but fetch references to repository.revision_store.
943
class KnitRepository(MetaDirRepository):
944
    """Knit format repository."""
945
1904.2.3 by Martin Pool
Give a warning on access to old repository formats
946
    def _warn_if_deprecated(self):
947
        # This class isn't deprecated
948
        pass
949
1740.3.6 by Jelmer Vernooij
Move inventory writing to the commit builder.
950
    def _inventory_add_lines(self, inv_vf, revid, parents, lines):
951
        inv_vf.add_lines_with_ghosts(revid, parents, lines)
952
1563.2.29 by Robert Collins
Remove all but fetch references to repository.revision_store.
953
    @needs_read_lock
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
954
    def _all_revision_ids(self):
1563.2.29 by Robert Collins
Remove all but fetch references to repository.revision_store.
955
        """See Repository.all_revision_ids()."""
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
956
        # Knits get the revision graph from the index of the revision knit, so
957
        # it's always possible even if they're on an unlistable transport.
1563.2.29 by Robert Collins
Remove all but fetch references to repository.revision_store.
958
        return self._revision_store.all_revision_ids(self.get_transaction())
959
1732.2.6 by Martin Pool
Restore removed fileid_involved* methods
960
    def fileid_involved_between_revs(self, from_revid, to_revid):
961
        """Find file_id(s) which are involved in the changes between revisions.
962
963
        This determines the set of revisions which are involved, and then
964
        finds all file ids affected by those revisions.
965
        """
966
        vf = self._get_revision_vf()
967
        from_set = set(vf.get_ancestry(from_revid))
968
        to_set = set(vf.get_ancestry(to_revid))
969
        changed = to_set.difference(from_set)
970
        return self._fileid_involved_by_set(changed)
971
972
    def fileid_involved(self, last_revid=None):
973
        """Find all file_ids modified in the ancestry of last_revid.
974
975
        :param last_revid: If None, last_revision() will be used.
976
        """
977
        if not last_revid:
978
            changed = set(self.all_revision_ids())
979
        else:
980
            changed = set(self.get_ancestry(last_revid))
981
        if None in changed:
982
            changed.remove(None)
983
        return self._fileid_involved_by_set(changed)
984
1594.2.7 by Robert Collins
Add versionedfile.fix_parents api for correcting data post hoc.
985
    @needs_read_lock
986
    def get_ancestry(self, revision_id):
987
        """Return a list of revision-ids integrated by a revision.
988
        
989
        This is topologically sorted.
990
        """
991
        if revision_id is None:
992
            return [None]
1596.2.12 by Robert Collins
Merge and make Knit Repository use the revision store for all possible queries.
993
        vf = self._get_revision_vf()
1594.2.9 by Robert Collins
Teach Knit repositories how to handle ghosts without corrupting at all.
994
        try:
995
            return [None] + vf.get_ancestry(revision_id)
996
        except errors.RevisionNotPresent:
997
            raise errors.NoSuchRevision(self, revision_id)
998
999
    @needs_read_lock
1594.2.10 by Robert Collins
Teach knit fetching and branching to only duplicate relevant data avoiding unnecessary reconciles.
1000
    def get_revision(self, revision_id):
1001
        """Return the Revision object for a named revision"""
1002
        return self.get_revision_reconcile(revision_id)
1003
1004
    @needs_read_lock
1596.2.12 by Robert Collins
Merge and make Knit Repository use the revision store for all possible queries.
1005
    def get_revision_graph(self, revision_id=None):
1006
        """Return a dictionary containing the revision graph.
1836.3.1 by Robert Collins
(robertc) Teach repository.get_revision_graph, and revision.common_ancestor, about NULL_REVISION.
1007
1008
        :param revision_id: The revision_id to get a graph from. If None, then
1009
        the entire revision graph is returned. This is a deprecated mode of
1010
        operation and will be removed in the future.
1596.2.12 by Robert Collins
Merge and make Knit Repository use the revision store for all possible queries.
1011
        :return: a dictionary of revision_id->revision_parents_list.
1012
        """
1836.3.1 by Robert Collins
(robertc) Teach repository.get_revision_graph, and revision.common_ancestor, about NULL_REVISION.
1013
        # special case NULL_REVISION
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
1014
        if revision_id == _mod_revision.NULL_REVISION:
1836.3.1 by Robert Collins
(robertc) Teach repository.get_revision_graph, and revision.common_ancestor, about NULL_REVISION.
1015
            return {}
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
1016
        a_weave = self._get_revision_vf()
1017
        entire_graph = a_weave.get_graph()
1596.2.12 by Robert Collins
Merge and make Knit Repository use the revision store for all possible queries.
1018
        if revision_id is None:
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
1019
            return a_weave.get_graph()
1020
        elif revision_id not in a_weave:
1596.2.12 by Robert Collins
Merge and make Knit Repository use the revision store for all possible queries.
1021
            raise errors.NoSuchRevision(self, revision_id)
1022
        else:
1023
            # add what can be reached from revision_id
1024
            result = {}
1025
            pending = set([revision_id])
1026
            while len(pending) > 0:
1027
                node = pending.pop()
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
1028
                result[node] = a_weave.get_parents(node)
1596.2.12 by Robert Collins
Merge and make Knit Repository use the revision store for all possible queries.
1029
                for revision_id in result[node]:
1030
                    if revision_id not in result:
1031
                        pending.add(revision_id)
1032
            return result
1033
1034
    @needs_read_lock
1594.2.9 by Robert Collins
Teach Knit repositories how to handle ghosts without corrupting at all.
1035
    def get_revision_graph_with_ghosts(self, revision_ids=None):
1036
        """Return a graph of the revisions with ghosts marked as applicable.
1037
1038
        :param revision_ids: an iterable of revisions to graph or None for all.
1039
        :return: a Graph object with the graph reachable from revision_ids.
1040
        """
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
1041
        result = graph.Graph()
1596.2.12 by Robert Collins
Merge and make Knit Repository use the revision store for all possible queries.
1042
        vf = self._get_revision_vf()
1628.1.7 by Robert Collins
Tune get_revision_graph_with_ghosts for Knit repositories.
1043
        versions = set(vf.versions())
1594.2.9 by Robert Collins
Teach Knit repositories how to handle ghosts without corrupting at all.
1044
        if not revision_ids:
1773.4.2 by Martin Pool
Cleanup of imports; undeprecate all_revision_ids()
1045
            pending = set(self.all_revision_ids())
1594.2.9 by Robert Collins
Teach Knit repositories how to handle ghosts without corrupting at all.
1046
            required = set([])
1047
        else:
1048
            pending = set(revision_ids)
1836.3.1 by Robert Collins
(robertc) Teach repository.get_revision_graph, and revision.common_ancestor, about NULL_REVISION.
1049
            # special case NULL_REVISION
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
1050
            if _mod_revision.NULL_REVISION in pending:
1051
                pending.remove(_mod_revision.NULL_REVISION)
1836.3.1 by Robert Collins
(robertc) Teach repository.get_revision_graph, and revision.common_ancestor, about NULL_REVISION.
1052
            required = set(pending)
1594.2.9 by Robert Collins
Teach Knit repositories how to handle ghosts without corrupting at all.
1053
        done = set([])
1054
        while len(pending):
1055
            revision_id = pending.pop()
1056
            if not revision_id in versions:
1057
                if revision_id in required:
1058
                    raise errors.NoSuchRevision(self, revision_id)
1059
                # a ghost
1060
                result.add_ghost(revision_id)
1759.2.2 by Jelmer Vernooij
Revert some of my spelling fixes and fix some typos after review by Aaron.
1061
                # mark it as done so we don't try for it again.
1628.1.7 by Robert Collins
Tune get_revision_graph_with_ghosts for Knit repositories.
1062
                done.add(revision_id)
1594.2.9 by Robert Collins
Teach Knit repositories how to handle ghosts without corrupting at all.
1063
                continue
1064
            parent_ids = vf.get_parents_with_ghosts(revision_id)
1065
            for parent_id in parent_ids:
1066
                # is this queued or done ?
1067
                if (parent_id not in pending and
1068
                    parent_id not in done):
1069
                    # no, queue it.
1070
                    pending.add(parent_id)
1071
            result.add_node(revision_id, parent_ids)
1628.1.7 by Robert Collins
Tune get_revision_graph_with_ghosts for Knit repositories.
1072
            done.add(revision_id)
1594.2.9 by Robert Collins
Teach Knit repositories how to handle ghosts without corrupting at all.
1073
        return result
1594.2.7 by Robert Collins
Add versionedfile.fix_parents api for correcting data post hoc.
1074
1596.2.12 by Robert Collins
Merge and make Knit Repository use the revision store for all possible queries.
1075
    def _get_revision_vf(self):
1607.1.2 by Robert Collins
Merge in knit-using-revision-versioned-file-graph tuning work.
1076
        """:return: a versioned file containing the revisions."""
1596.2.12 by Robert Collins
Merge and make Knit Repository use the revision store for all possible queries.
1077
        vf = self._revision_store.get_revision_file(self.get_transaction())
1078
        return vf
1079
1594.2.7 by Robert Collins
Add versionedfile.fix_parents api for correcting data post hoc.
1080
    @needs_write_lock
1692.1.1 by Robert Collins
* Repository.reconcile now takes a thorough keyword parameter to allow
1081
    def reconcile(self, other=None, thorough=False):
1594.2.7 by Robert Collins
Add versionedfile.fix_parents api for correcting data post hoc.
1082
        """Reconcile this repository."""
1083
        from bzrlib.reconcile import KnitReconciler
1692.1.1 by Robert Collins
* Repository.reconcile now takes a thorough keyword parameter to allow
1084
        reconciler = KnitReconciler(self, thorough=thorough)
1594.2.7 by Robert Collins
Add versionedfile.fix_parents api for correcting data post hoc.
1085
        reconciler.reconcile()
1086
        return reconciler
1087
    
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
1088
    def revision_parents(self, revision_id):
1089
        return self._get_revision_vf().get_parents(revision_id)
1090
1563.2.29 by Robert Collins
Remove all but fetch references to repository.revision_store.
1091
1910.2.22 by Aaron Bentley
Make commits preserve root entry data
1092
class KnitRepository2(KnitRepository):
1093
    """"""
1910.2.48 by Aaron Bentley
Update from review comments
1094
    def __init__(self, _format, a_bzrdir, control_files, _revision_store,
1095
                 control_store, text_store):
1096
        KnitRepository.__init__(self, _format, a_bzrdir, control_files,
1097
                              _revision_store, control_store, text_store)
1098
        self._serializer = xml6.serializer_v6
1910.2.22 by Aaron Bentley
Make commits preserve root entry data
1099
1100
    def deserialise_inventory(self, revision_id, xml):
1101
        """Transform the xml into an inventory object. 
1102
1103
        :param revision_id: The expected revision id of the inventory.
1104
        :param xml: A serialised inventory.
1105
        """
1910.2.48 by Aaron Bentley
Update from review comments
1106
        result = self._serializer.read_inventory_from_string(xml)
1910.2.22 by Aaron Bentley
Make commits preserve root entry data
1107
        assert result.root.revision is not None
1108
        return result
1109
1110
    def serialise_inventory(self, inv):
1111
        """Transform the inventory object into XML text.
1112
1113
        :param revision_id: The expected revision id of the inventory.
1114
        :param xml: A serialised inventory.
1115
        """
1910.2.23 by Aaron Bentley
Fix up test cases that manually construct inventories
1116
        assert inv.revision_id is not None
1910.2.22 by Aaron Bentley
Make commits preserve root entry data
1117
        assert inv.root.revision is not None
1910.2.48 by Aaron Bentley
Update from review comments
1118
        return KnitRepository.serialise_inventory(self, inv)
1910.2.22 by Aaron Bentley
Make commits preserve root entry data
1119
1120
    def get_commit_builder(self, branch, parents, config, timestamp=None, 
1121
                           timezone=None, committer=None, revprops=None, 
1122
                           revision_id=None):
1123
        """Obtain a CommitBuilder for this repository.
1124
        
1125
        :param branch: Branch to commit to.
1126
        :param parents: Revision ids of the parents of the new revision.
1127
        :param config: Configuration to use.
1128
        :param timestamp: Optional timestamp recorded for commit.
1129
        :param timezone: Optional timezone for timestamp.
1130
        :param committer: Optional committer to set for commit.
1131
        :param revprops: Optional dictionary of revision properties.
1132
        :param revision_id: Optional revision id.
1133
        """
1134
        return RootCommitBuilder(self, parents, config, timestamp, timezone,
1135
                                 committer, revprops, revision_id)
1136
1910.2.46 by Aaron Bentley
Whitespace fix
1137
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1138
class RepositoryFormat(object):
1139
    """A repository format.
1140
1141
    Formats provide three things:
1142
     * An initialization routine to construct repository data on disk.
1143
     * a format string which is used when the BzrDir supports versioned
1144
       children.
1145
     * an open routine which returns a Repository instance.
1146
1147
    Formats are placed in an dict by their format string for reference 
1148
    during opening. These should be subclasses of RepositoryFormat
1149
    for consistency.
1150
1151
    Once a format is deprecated, just deprecate the initialize and open
1152
    methods on the format class. Do not deprecate the object, as the 
1153
    object will be created every system load.
1154
1155
    Common instance attributes:
1156
    _matchingbzrdir - the bzrdir format that the repository format was
1157
    originally written to work with. This can be used if manually
1158
    constructing a bzrdir and repository, or more commonly for test suite
1159
    parameterisation.
1160
    """
1161
1162
    _default_format = None
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1163
    """The default format used for new repositories."""
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1164
1165
    _formats = {}
1166
    """The known formats."""
1167
1904.2.3 by Martin Pool
Give a warning on access to old repository formats
1168
    def __str__(self):
1169
        return "<%s>" % self.__class__.__name__
1170
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1171
    @classmethod
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
1172
    def find_format(klass, a_bzrdir):
1173
        """Return the format for the repository object in a_bzrdir."""
1174
        try:
1175
            transport = a_bzrdir.get_repository_transport(None)
1176
            format_string = transport.get("format").read()
1177
            return klass._formats[format_string]
1178
        except errors.NoSuchFile:
1179
            raise errors.NoRepositoryPresent(a_bzrdir)
1180
        except KeyError:
1740.5.6 by Martin Pool
Clean up many exception classes.
1181
            raise errors.UnknownFormatError(format=format_string)
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
1182
1563.2.23 by Robert Collins
Add add_revision and get_revision methods to RevisionStore
1183
    def _get_control_store(self, repo_transport, control_files):
1184
        """Return the control store for this repository."""
1185
        raise NotImplementedError(self._get_control_store)
1186
    
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
1187
    @classmethod
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1188
    def get_default_format(klass):
1189
        """Return the current default format."""
1190
        return klass._default_format
1191
1192
    def get_format_string(self):
1193
        """Return the ASCII format string that identifies this format.
1194
        
1195
        Note that in pre format ?? repositories the format string is 
1196
        not permitted nor written to disk.
1197
        """
1198
        raise NotImplementedError(self.get_format_string)
1199
1624.3.19 by Olaf Conradi
New call get_format_description to give a user-friendly description of a
1200
    def get_format_description(self):
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
1201
        """Return the short description for this format."""
1624.3.19 by Olaf Conradi
New call get_format_description to give a user-friendly description of a
1202
        raise NotImplementedError(self.get_format_description)
1203
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
1204
    def _get_revision_store(self, repo_transport, control_files):
1205
        """Return the revision store object for this a_bzrdir."""
1556.1.5 by Robert Collins
Review feedback.
1206
        raise NotImplementedError(self._get_revision_store)
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
1207
1563.2.22 by Robert Collins
Move responsibility for repository.has_revision into RevisionStore
1208
    def _get_text_rev_store(self,
1209
                            transport,
1210
                            control_files,
1211
                            name,
1212
                            compressed=True,
1563.2.28 by Robert Collins
Add total_size to the revision_store api.
1213
                            prefixed=False,
1214
                            serializer=None):
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
1215
        """Common logic for getting a revision store for a repository.
1216
        
1563.2.17 by Robert Collins
Change knits repositories to use a knit versioned file store for file texts.
1217
        see self._get_revision_store for the subclass-overridable method to 
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
1218
        get the store for a repository.
1219
        """
1563.2.22 by Robert Collins
Move responsibility for repository.has_revision into RevisionStore
1220
        from bzrlib.store.revision.text import TextRevisionStore
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
1221
        dir_mode = control_files._dir_mode
1222
        file_mode = control_files._file_mode
1563.2.22 by Robert Collins
Move responsibility for repository.has_revision into RevisionStore
1223
        text_store =TextStore(transport.clone(name),
1224
                              prefixed=prefixed,
1225
                              compressed=compressed,
1226
                              dir_mode=dir_mode,
1227
                              file_mode=file_mode)
1563.2.29 by Robert Collins
Remove all but fetch references to repository.revision_store.
1228
        _revision_store = TextRevisionStore(text_store, serializer)
1229
        return _revision_store
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
1230
1563.2.17 by Robert Collins
Change knits repositories to use a knit versioned file store for file texts.
1231
    def _get_versioned_file_store(self,
1232
                                  name,
1233
                                  transport,
1234
                                  control_files,
1235
                                  prefixed=True,
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
1236
                                  versionedfile_class=weave.WeaveFile,
1946.2.5 by John Arbash Meinel
Make knit stores delay creation, but not control stores
1237
                                  versionedfile_kwargs={},
1608.2.12 by Martin Pool
Store-escaping must quote uppercase characters too, so that they're safely
1238
                                  escaped=False):
1563.2.17 by Robert Collins
Change knits repositories to use a knit versioned file store for file texts.
1239
        weave_transport = control_files._transport.clone(name)
1240
        dir_mode = control_files._dir_mode
1241
        file_mode = control_files._file_mode
1242
        return VersionedFileStore(weave_transport, prefixed=prefixed,
1608.2.12 by Martin Pool
Store-escaping must quote uppercase characters too, so that they're safely
1243
                                  dir_mode=dir_mode,
1244
                                  file_mode=file_mode,
1245
                                  versionedfile_class=versionedfile_class,
1946.2.5 by John Arbash Meinel
Make knit stores delay creation, but not control stores
1246
                                  versionedfile_kwargs=versionedfile_kwargs,
1608.2.12 by Martin Pool
Store-escaping must quote uppercase characters too, so that they're safely
1247
                                  escaped=escaped)
1563.2.17 by Robert Collins
Change knits repositories to use a knit versioned file store for file texts.
1248
1534.6.1 by Robert Collins
allow API creation of shared repositories
1249
    def initialize(self, a_bzrdir, shared=False):
1250
        """Initialize a repository of this format in a_bzrdir.
1251
1252
        :param a_bzrdir: The bzrdir to put the new repository in it.
1253
        :param shared: The repository should be initialized as a sharable one.
1254
1255
        This may raise UninitializableFormat if shared repository are not
1256
        compatible the a_bzrdir.
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1257
        """
1258
1259
    def is_supported(self):
1260
        """Is this format supported?
1261
1262
        Supported formats must be initializable and openable.
1263
        Unsupported formats may not support initialization or committing or 
1264
        some other features depending on the reason for not being supported.
1265
        """
1266
        return True
1267
1910.2.12 by Aaron Bentley
Implement knit repo format 2
1268
    def check_conversion_target(self, target_format):
1269
        raise NotImplementedError(self.check_conversion_target)
1270
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1271
    def open(self, a_bzrdir, _found=False):
1272
        """Return an instance of this format for the bzrdir a_bzrdir.
1273
        
1274
        _found is a private parameter, do not use it.
1275
        """
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
1276
        raise NotImplementedError(self.open)
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1277
1278
    @classmethod
1279
    def register_format(klass, format):
1280
        klass._formats[format.get_format_string()] = format
1281
1282
    @classmethod
2204.4.11 by Aaron Bentley
deprecate Repository.set_default_format, update upgrade tests
1283
    @deprecated_method(symbol_versioning.zero_fourteen)
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1284
    def set_default_format(klass, format):
2204.4.11 by Aaron Bentley
deprecate Repository.set_default_format, update upgrade tests
1285
        klass._set_default_format(format)
1286
1287
    @classmethod
1288
    def _set_default_format(klass, format):
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1289
        klass._default_format = format
1290
1291
    @classmethod
1292
    def unregister_format(klass, format):
1293
        assert klass._formats[format.get_format_string()] is format
1294
        del klass._formats[format.get_format_string()]
1295
1296
1534.6.1 by Robert Collins
allow API creation of shared repositories
1297
class PreSplitOutRepositoryFormat(RepositoryFormat):
1298
    """Base class for the pre split out repository formats."""
1299
1910.2.14 by Aaron Bentley
Fail when trying to use interrepository on Knit2 and Knit1
1300
    rich_root_data = False
1301
1534.6.1 by Robert Collins
allow API creation of shared repositories
1302
    def initialize(self, a_bzrdir, shared=False, _internal=False):
1303
        """Create a weave repository.
1304
        
1305
        TODO: when creating split out bzr branch formats, move this to a common
1306
        base for Format5, Format6. or something like that.
1307
        """
1308
        if shared:
1309
            raise errors.IncompatibleFormat(self, a_bzrdir._format)
1310
1311
        if not _internal:
1312
            # always initialized when the bzrdir is.
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
1313
            return self.open(a_bzrdir, _found=True)
1534.6.1 by Robert Collins
allow API creation of shared repositories
1314
        
1315
        # Create an empty weave
1316
        sio = StringIO()
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
1317
        weavefile.write_weave_v5(weave.Weave(), sio)
1534.6.1 by Robert Collins
allow API creation of shared repositories
1318
        empty_weave = sio.getvalue()
1319
1320
        mutter('creating repository in %s.', a_bzrdir.transport.base)
1321
        dirs = ['revision-store', 'weaves']
1553.5.56 by Martin Pool
Format 7 repo now uses LockDir!
1322
        files = [('inventory.weave', StringIO(empty_weave)),
1534.6.1 by Robert Collins
allow API creation of shared repositories
1323
                 ]
1324
        
1759.2.2 by Jelmer Vernooij
Revert some of my spelling fixes and fix some typos after review by Aaron.
1325
        # FIXME: RBC 20060125 don't peek under the covers
1534.6.1 by Robert Collins
allow API creation of shared repositories
1326
        # NB: no need to escape relative paths that are url safe.
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
1327
        control_files = lockable_files.LockableFiles(a_bzrdir.transport,
1328
                                'branch-lock', lockable_files.TransportLock)
1553.5.63 by Martin Pool
Lock type is now mandatory for LockableFiles constructor
1329
        control_files.create_lock()
1534.6.1 by Robert Collins
allow API creation of shared repositories
1330
        control_files.lock_write()
1331
        control_files._transport.mkdir_multi(dirs,
1332
                mode=control_files._dir_mode)
1333
        try:
1334
            for file, content in files:
1335
                control_files.put(file, content)
1336
        finally:
1337
            control_files.unlock()
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
1338
        return self.open(a_bzrdir, _found=True)
1339
1563.2.23 by Robert Collins
Add add_revision and get_revision methods to RevisionStore
1340
    def _get_control_store(self, repo_transport, control_files):
1341
        """Return the control store for this repository."""
1342
        return self._get_versioned_file_store('',
1343
                                              repo_transport,
1344
                                              control_files,
1345
                                              prefixed=False)
1346
1563.2.17 by Robert Collins
Change knits repositories to use a knit versioned file store for file texts.
1347
    def _get_text_store(self, transport, control_files):
1348
        """Get a store for file texts for this format."""
1349
        raise NotImplementedError(self._get_text_store)
1350
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
1351
    def open(self, a_bzrdir, _found=False):
1352
        """See RepositoryFormat.open()."""
1353
        if not _found:
1354
            # we are being called directly and must probe.
1355
            raise NotImplementedError
1356
1357
        repo_transport = a_bzrdir.get_repository_transport(None)
1358
        control_files = a_bzrdir._control_files
1563.2.23 by Robert Collins
Add add_revision and get_revision methods to RevisionStore
1359
        text_store = self._get_text_store(repo_transport, control_files)
1360
        control_store = self._get_control_store(repo_transport, control_files)
1563.2.29 by Robert Collins
Remove all but fetch references to repository.revision_store.
1361
        _revision_store = self._get_revision_store(repo_transport, control_files)
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
1362
        return AllInOneRepository(_format=self,
1363
                                  a_bzrdir=a_bzrdir,
1563.2.29 by Robert Collins
Remove all but fetch references to repository.revision_store.
1364
                                  _revision_store=_revision_store,
1563.2.23 by Robert Collins
Add add_revision and get_revision methods to RevisionStore
1365
                                  control_store=control_store,
1563.2.17 by Robert Collins
Change knits repositories to use a knit versioned file store for file texts.
1366
                                  text_store=text_store)
1534.6.1 by Robert Collins
allow API creation of shared repositories
1367
1910.2.12 by Aaron Bentley
Implement knit repo format 2
1368
    def check_conversion_target(self, target_format):
1369
        pass
1370
1534.6.1 by Robert Collins
allow API creation of shared repositories
1371
1372
class RepositoryFormat4(PreSplitOutRepositoryFormat):
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1373
    """Bzr repository format 4.
1374
1375
    This repository format has:
1376
     - flat stores
1377
     - TextStores for texts, inventories,revisions.
1378
1379
    This format is deprecated: it indexes texts using a text id which is
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
1380
    removed in format 5; initialization and write support for this format
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1381
    has been removed.
1382
    """
1383
1384
    def __init__(self):
1385
        super(RepositoryFormat4, self).__init__()
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
1386
        self._matchingbzrdir = bzrdir.BzrDirFormat4()
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1387
1624.3.19 by Olaf Conradi
New call get_format_description to give a user-friendly description of a
1388
    def get_format_description(self):
1389
        """See RepositoryFormat.get_format_description()."""
1390
        return "Repository format 4"
1391
1534.6.1 by Robert Collins
allow API creation of shared repositories
1392
    def initialize(self, url, shared=False, _internal=False):
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1393
        """Format 4 branches cannot be created."""
1394
        raise errors.UninitializableFormat(self)
1395
1396
    def is_supported(self):
1397
        """Format 4 is not supported.
1398
1399
        It is not supported because the model changed from 4 to 5 and the
1400
        conversion logic is expensive - so doing it on the fly was not 
1401
        feasible.
1402
        """
1403
        return False
1404
1563.2.23 by Robert Collins
Add add_revision and get_revision methods to RevisionStore
1405
    def _get_control_store(self, repo_transport, control_files):
1406
        """Format 4 repositories have no formal control store at this point.
1407
        
1408
        This will cause any control-file-needing apis to fail - this is desired.
1409
        """
1410
        return None
1411
    
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
1412
    def _get_revision_store(self, repo_transport, control_files):
1413
        """See RepositoryFormat._get_revision_store()."""
1563.2.28 by Robert Collins
Add total_size to the revision_store api.
1414
        from bzrlib.xml4 import serializer_v4
1563.2.22 by Robert Collins
Move responsibility for repository.has_revision into RevisionStore
1415
        return self._get_text_rev_store(repo_transport,
1416
                                        control_files,
1563.2.28 by Robert Collins
Add total_size to the revision_store api.
1417
                                        'revision-store',
1418
                                        serializer=serializer_v4)
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
1419
1563.2.17 by Robert Collins
Change knits repositories to use a knit versioned file store for file texts.
1420
    def _get_text_store(self, transport, control_files):
1421
        """See RepositoryFormat._get_text_store()."""
1422
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1423
1534.6.1 by Robert Collins
allow API creation of shared repositories
1424
class RepositoryFormat5(PreSplitOutRepositoryFormat):
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1425
    """Bzr control format 5.
1426
1427
    This repository format has:
1428
     - weaves for file texts and inventory
1429
     - flat stores
1430
     - TextStores for revisions and signatures.
1431
    """
1432
1433
    def __init__(self):
1434
        super(RepositoryFormat5, self).__init__()
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
1435
        self._matchingbzrdir = bzrdir.BzrDirFormat5()
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1436
1624.3.19 by Olaf Conradi
New call get_format_description to give a user-friendly description of a
1437
    def get_format_description(self):
1438
        """See RepositoryFormat.get_format_description()."""
1439
        return "Weave repository format 5"
1440
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
1441
    def _get_revision_store(self, repo_transport, control_files):
1442
        """See RepositoryFormat._get_revision_store()."""
1443
        """Return the revision store object for this a_bzrdir."""
1563.2.22 by Robert Collins
Move responsibility for repository.has_revision into RevisionStore
1444
        return self._get_text_rev_store(repo_transport,
1445
                                        control_files,
1446
                                        'revision-store',
1447
                                        compressed=False)
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
1448
1563.2.17 by Robert Collins
Change knits repositories to use a knit versioned file store for file texts.
1449
    def _get_text_store(self, transport, control_files):
1450
        """See RepositoryFormat._get_text_store()."""
1451
        return self._get_versioned_file_store('weaves', transport, control_files, prefixed=False)
1452
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1453
1534.6.1 by Robert Collins
allow API creation of shared repositories
1454
class RepositoryFormat6(PreSplitOutRepositoryFormat):
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1455
    """Bzr control format 6.
1456
1457
    This repository format has:
1458
     - weaves for file texts and inventory
1459
     - hash subdirectory based stores.
1460
     - TextStores for revisions and signatures.
1461
    """
1462
1463
    def __init__(self):
1464
        super(RepositoryFormat6, self).__init__()
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
1465
        self._matchingbzrdir = bzrdir.BzrDirFormat6()
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1466
1624.3.19 by Olaf Conradi
New call get_format_description to give a user-friendly description of a
1467
    def get_format_description(self):
1468
        """See RepositoryFormat.get_format_description()."""
1469
        return "Weave repository format 6"
1470
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
1471
    def _get_revision_store(self, repo_transport, control_files):
1472
        """See RepositoryFormat._get_revision_store()."""
1563.2.22 by Robert Collins
Move responsibility for repository.has_revision into RevisionStore
1473
        return self._get_text_rev_store(repo_transport,
1474
                                        control_files,
1475
                                        'revision-store',
1476
                                        compressed=False,
1477
                                        prefixed=True)
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
1478
1563.2.17 by Robert Collins
Change knits repositories to use a knit versioned file store for file texts.
1479
    def _get_text_store(self, transport, control_files):
1480
        """See RepositoryFormat._get_text_store()."""
1481
        return self._get_versioned_file_store('weaves', transport, control_files)
1482
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
1483
1484
class MetaDirRepositoryFormat(RepositoryFormat):
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
1485
    """Common base class for the new repositories using the metadir layout."""
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
1486
1910.2.14 by Aaron Bentley
Fail when trying to use interrepository on Knit2 and Knit1
1487
    rich_root_data = False
1488
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
1489
    def __init__(self):
1490
        super(MetaDirRepositoryFormat, self).__init__()
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
1491
        self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
1492
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
1493
    def _create_control_files(self, a_bzrdir):
1494
        """Create the required files and the initial control_files object."""
1759.2.2 by Jelmer Vernooij
Revert some of my spelling fixes and fix some typos after review by Aaron.
1495
        # FIXME: RBC 20060125 don't peek under the covers
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
1496
        # NB: no need to escape relative paths that are url safe.
1497
        repository_transport = a_bzrdir.get_repository_transport(self)
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
1498
        control_files = lockable_files.LockableFiles(repository_transport,
1499
                                'lock', lockdir.LockDir)
1553.5.61 by Martin Pool
Locks protecting LockableFiles must now be explicitly created before use.
1500
        control_files.create_lock()
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
1501
        return control_files
1502
1503
    def _upload_blank_content(self, a_bzrdir, dirs, files, utf8_files, shared):
1504
        """Upload the initial blank content."""
1505
        control_files = self._create_control_files(a_bzrdir)
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
1506
        control_files.lock_write()
1507
        try:
1553.5.49 by Martin Pool
Use LockDirs for repo format 7
1508
            control_files._transport.mkdir_multi(dirs,
1509
                    mode=control_files._dir_mode)
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
1510
            for file, content in files:
1511
                control_files.put(file, content)
1512
            for file, content in utf8_files:
1513
                control_files.put_utf8(file, content)
1534.6.1 by Robert Collins
allow API creation of shared repositories
1514
            if shared == True:
1515
                control_files.put_utf8('shared-storage', '')
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
1516
        finally:
1517
            control_files.unlock()
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
1518
1519
1520
class RepositoryFormat7(MetaDirRepositoryFormat):
1521
    """Bzr repository 7.
1522
1523
    This repository format has:
1524
     - weaves for file texts and inventory
1525
     - hash subdirectory based stores.
1526
     - TextStores for revisions and signatures.
1527
     - a format marker of its own
1528
     - an optional 'shared-storage' flag
1529
     - an optional 'no-working-trees' flag
1530
    """
1531
1563.2.35 by Robert Collins
cleanup deprecation warnings and finish conversion so the inventory is knit based too.
1532
    def _get_control_store(self, repo_transport, control_files):
1533
        """Return the control store for this repository."""
1534
        return self._get_versioned_file_store('',
1535
                                              repo_transport,
1536
                                              control_files,
1537
                                              prefixed=False)
1538
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
1539
    def get_format_string(self):
1540
        """See RepositoryFormat.get_format_string()."""
1541
        return "Bazaar-NG Repository format 7"
1542
1624.3.19 by Olaf Conradi
New call get_format_description to give a user-friendly description of a
1543
    def get_format_description(self):
1544
        """See RepositoryFormat.get_format_description()."""
1545
        return "Weave repository format 7"
1546
1910.2.12 by Aaron Bentley
Implement knit repo format 2
1547
    def check_conversion_target(self, target_format):
1548
        pass
1549
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
1550
    def _get_revision_store(self, repo_transport, control_files):
1551
        """See RepositoryFormat._get_revision_store()."""
1552
        return self._get_text_rev_store(repo_transport,
1553
                                        control_files,
1554
                                        'revision-store',
1555
                                        compressed=False,
1556
                                        prefixed=True,
1557
                                        )
1558
1563.2.17 by Robert Collins
Change knits repositories to use a knit versioned file store for file texts.
1559
    def _get_text_store(self, transport, control_files):
1560
        """See RepositoryFormat._get_text_store()."""
1561
        return self._get_versioned_file_store('weaves',
1562
                                              transport,
1563
                                              control_files)
1564
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
1565
    def initialize(self, a_bzrdir, shared=False):
1566
        """Create a weave repository.
1567
1568
        :param shared: If true the repository will be initialized as a shared
1569
                       repository.
1570
        """
1571
        # Create an empty weave
1572
        sio = StringIO()
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
1573
        weavefile.write_weave_v5(weave.Weave(), sio)
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
1574
        empty_weave = sio.getvalue()
1575
1576
        mutter('creating repository in %s.', a_bzrdir.transport.base)
1577
        dirs = ['revision-store', 'weaves']
1578
        files = [('inventory.weave', StringIO(empty_weave)), 
1579
                 ]
1580
        utf8_files = [('format', self.get_format_string())]
1581
 
1582
        self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
1583
        return self.open(a_bzrdir=a_bzrdir, _found=True)
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
1584
1563.2.29 by Robert Collins
Remove all but fetch references to repository.revision_store.
1585
    def open(self, a_bzrdir, _found=False, _override_transport=None):
1586
        """See RepositoryFormat.open().
1587
        
1588
        :param _override_transport: INTERNAL USE ONLY. Allows opening the
1589
                                    repository at a slightly different url
1590
                                    than normal. I.e. during 'upgrade'.
1591
        """
1592
        if not _found:
1593
            format = RepositoryFormat.find_format(a_bzrdir)
1594
            assert format.__class__ ==  self.__class__
1595
        if _override_transport is not None:
1596
            repo_transport = _override_transport
1597
        else:
1598
            repo_transport = a_bzrdir.get_repository_transport(None)
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
1599
        control_files = lockable_files.LockableFiles(repo_transport,
1600
                                'lock', lockdir.LockDir)
1563.2.29 by Robert Collins
Remove all but fetch references to repository.revision_store.
1601
        text_store = self._get_text_store(repo_transport, control_files)
1602
        control_store = self._get_control_store(repo_transport, control_files)
1603
        _revision_store = self._get_revision_store(repo_transport, control_files)
2150.2.2 by Robert Collins
Change the commit builder selected-revision-id test to use a unicode revision id where possible, leading to stricter testing of the hypothetical unicode revision id support in bzr.
1604
        return WeaveMetaDirRepository(_format=self,
1605
            a_bzrdir=a_bzrdir,
1606
            control_files=control_files,
1607
            _revision_store=_revision_store,
1608
            control_store=control_store,
1609
            text_store=text_store)
1563.2.29 by Robert Collins
Remove all but fetch references to repository.revision_store.
1610
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
1611
1910.2.11 by Aaron Bentley
Start work on Knit format 2
1612
class RepositoryFormatKnit(MetaDirRepositoryFormat):
1613
    """Bzr repository knit format (generalized). 
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
1614
1615
    This repository format has:
1616
     - knits for file texts and inventory
1617
     - hash subdirectory based stores.
1618
     - knits for revisions and signatures
1619
     - TextStores for revisions and signatures.
1620
     - a format marker of its own
1621
     - an optional 'shared-storage' flag
1622
     - an optional 'no-working-trees' flag
1553.5.62 by Martin Pool
Add tests that MetaDir repositories use LockDirs
1623
     - a LockDir lock
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
1624
    """
1625
1563.2.35 by Robert Collins
cleanup deprecation warnings and finish conversion so the inventory is knit based too.
1626
    def _get_control_store(self, repo_transport, control_files):
1627
        """Return the control store for this repository."""
1628.1.5 by Robert Collins
Make inventory knits not annotated, only delta compressed.
1628
        return VersionedFileStore(
1629
            repo_transport,
1630
            prefixed=False,
1631
            file_mode=control_files._file_mode,
1996.3.5 by John Arbash Meinel
Cleanup, deprecated, and get the tests passing again.
1632
            versionedfile_class=knit.KnitVersionedFile,
1633
            versionedfile_kwargs={'factory':knit.KnitPlainFactory()},
1628.1.5 by Robert Collins
Make inventory knits not annotated, only delta compressed.
1634
            )
1563.2.35 by Robert Collins
cleanup deprecation warnings and finish conversion so the inventory is knit based too.
1635
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
1636
    def _get_revision_store(self, repo_transport, control_files):
1637
        """See RepositoryFormat._get_revision_store()."""
1638
        from bzrlib.store.revision.knit import KnitRevisionStore
1639
        versioned_file_store = VersionedFileStore(
1563.2.35 by Robert Collins
cleanup deprecation warnings and finish conversion so the inventory is knit based too.
1640
            repo_transport,
1651.1.1 by Martin Pool
[merge][wip] Storage escaping
1641
            file_mode=control_files._file_mode,
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
1642
            prefixed=False,
1563.2.34 by Robert Collins
Remove the commit and rollback transaction methods as misleading, and implement a WriteTransaction
1643
            precious=True,
1996.3.5 by John Arbash Meinel
Cleanup, deprecated, and get the tests passing again.
1644
            versionedfile_class=knit.KnitVersionedFile,
1645
            versionedfile_kwargs={'delta':False,
1646
                                  'factory':knit.KnitPlainFactory(),
1647
                                 },
1608.2.12 by Martin Pool
Store-escaping must quote uppercase characters too, so that they're safely
1648
            escaped=True,
1651.1.1 by Martin Pool
[merge][wip] Storage escaping
1649
            )
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
1650
        return KnitRevisionStore(versioned_file_store)
1651
1563.2.17 by Robert Collins
Change knits repositories to use a knit versioned file store for file texts.
1652
    def _get_text_store(self, transport, control_files):
1653
        """See RepositoryFormat._get_text_store()."""
1654
        return self._get_versioned_file_store('knits',
1996.3.5 by John Arbash Meinel
Cleanup, deprecated, and get the tests passing again.
1655
                                  transport,
1656
                                  control_files,
1657
                                  versionedfile_class=knit.KnitVersionedFile,
1658
                                  versionedfile_kwargs={
1659
                                      'create_parent_dir':True,
1660
                                      'delay_create':True,
1661
                                      'dir_mode':control_files._dir_mode,
1662
                                  },
1663
                                  escaped=True)
1563.2.17 by Robert Collins
Change knits repositories to use a knit versioned file store for file texts.
1664
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
1665
    def initialize(self, a_bzrdir, shared=False):
1666
        """Create a knit format 1 repository.
1667
1658.1.7 by Martin Pool
(RepositoryFormatKnit1.initialize) remove dead code that constructs weaves
1668
        :param a_bzrdir: bzrdir to contain the new repository; must already
1669
            be initialized.
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
1670
        :param shared: If true the repository will be initialized as a shared
1671
                       repository.
1672
        """
1673
        mutter('creating repository in %s.', a_bzrdir.transport.base)
1707.3.29 by John Arbash Meinel
reverting 1734
1674
        dirs = ['revision-store', 'knits']
1658.1.7 by Martin Pool
(RepositoryFormatKnit1.initialize) remove dead code that constructs weaves
1675
        files = []
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
1676
        utf8_files = [('format', self.get_format_string())]
1677
        
1678
        self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
1563.2.25 by Robert Collins
Merge in upstream.
1679
        repo_transport = a_bzrdir.get_repository_transport(None)
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
1680
        control_files = lockable_files.LockableFiles(repo_transport,
1681
                                'lock', lockdir.LockDir)
1563.2.25 by Robert Collins
Merge in upstream.
1682
        control_store = self._get_control_store(repo_transport, control_files)
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
1683
        transaction = transactions.WriteTransaction()
1563.2.34 by Robert Collins
Remove the commit and rollback transaction methods as misleading, and implement a WriteTransaction
1684
        # trigger a write of the inventory store.
1563.2.35 by Robert Collins
cleanup deprecation warnings and finish conversion so the inventory is knit based too.
1685
        control_store.get_weave_or_empty('inventory', transaction)
1686
        _revision_store = self._get_revision_store(repo_transport, control_files)
2150.2.2 by Robert Collins
Change the commit builder selected-revision-id test to use a unicode revision id where possible, leading to stricter testing of the hypothetical unicode revision id support in bzr.
1687
        # the revision id here is irrelevant: it will not be stored, and cannot
1688
        # already exist.
1563.2.35 by Robert Collins
cleanup deprecation warnings and finish conversion so the inventory is knit based too.
1689
        _revision_store.has_revision_id('A', transaction)
1690
        _revision_store.get_signature_file(transaction)
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
1691
        return self.open(a_bzrdir=a_bzrdir, _found=True)
1692
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
1693
    def open(self, a_bzrdir, _found=False, _override_transport=None):
1694
        """See RepositoryFormat.open().
1695
        
1696
        :param _override_transport: INTERNAL USE ONLY. Allows opening the
1697
                                    repository at a slightly different url
1698
                                    than normal. I.e. during 'upgrade'.
1699
        """
1700
        if not _found:
1701
            format = RepositoryFormat.find_format(a_bzrdir)
1702
            assert format.__class__ ==  self.__class__
1703
        if _override_transport is not None:
1704
            repo_transport = _override_transport
1705
        else:
1706
            repo_transport = a_bzrdir.get_repository_transport(None)
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
1707
        control_files = lockable_files.LockableFiles(repo_transport,
1708
                                'lock', lockdir.LockDir)
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
1709
        text_store = self._get_text_store(repo_transport, control_files)
1710
        control_store = self._get_control_store(repo_transport, control_files)
1711
        _revision_store = self._get_revision_store(repo_transport, control_files)
1712
        return KnitRepository(_format=self,
1713
                              a_bzrdir=a_bzrdir,
1714
                              control_files=control_files,
1715
                              _revision_store=_revision_store,
1716
                              control_store=control_store,
1717
                              text_store=text_store)
1718
1910.2.12 by Aaron Bentley
Implement knit repo format 2
1719
1910.2.11 by Aaron Bentley
Start work on Knit format 2
1720
class RepositoryFormatKnit1(RepositoryFormatKnit):
1721
    """Bzr repository knit format 1.
1722
1723
    This repository format has:
1724
     - knits for file texts and inventory
1725
     - hash subdirectory based stores.
1726
     - knits for revisions and signatures
1727
     - TextStores for revisions and signatures.
1728
     - a format marker of its own
1729
     - an optional 'shared-storage' flag
1730
     - an optional 'no-working-trees' flag
1731
     - a LockDir lock
1732
1733
    This format was introduced in bzr 0.8.
1734
    """
1735
    def get_format_string(self):
1736
        """See RepositoryFormat.get_format_string()."""
1737
        return "Bazaar-NG Knit Repository Format 1"
1738
1739
    def get_format_description(self):
1740
        """See RepositoryFormat.get_format_description()."""
1741
        return "Knit repository format 1"
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
1742
1910.2.12 by Aaron Bentley
Implement knit repo format 2
1743
    def check_conversion_target(self, target_format):
1744
        pass
1745
1746
1747
class RepositoryFormatKnit2(RepositoryFormatKnit):
1748
    """Bzr repository knit format 2.
1749
1750
    THIS FORMAT IS EXPERIMENTAL
1751
    This repository format has:
1752
     - knits for file texts and inventory
1753
     - hash subdirectory based stores.
1754
     - knits for revisions and signatures
1755
     - TextStores for revisions and signatures.
1756
     - a format marker of its own
1757
     - an optional 'shared-storage' flag
1758
     - an optional 'no-working-trees' flag
1759
     - a LockDir lock
1760
     - Support for recording full info about the tree root
1761
1762
    """
1910.2.14 by Aaron Bentley
Fail when trying to use interrepository on Knit2 and Knit1
1763
    
1764
    rich_root_data = True
1765
1910.2.12 by Aaron Bentley
Implement knit repo format 2
1766
    def get_format_string(self):
1767
        """See RepositoryFormat.get_format_string()."""
1910.2.48 by Aaron Bentley
Update from review comments
1768
        return "Bazaar Knit Repository Format 2\n"
1910.2.12 by Aaron Bentley
Implement knit repo format 2
1769
1770
    def get_format_description(self):
1771
        """See RepositoryFormat.get_format_description()."""
1772
        return "Knit repository format 2"
1773
1774
    def check_conversion_target(self, target_format):
1910.2.14 by Aaron Bentley
Fail when trying to use interrepository on Knit2 and Knit1
1775
        if not target_format.rich_root_data:
1910.2.12 by Aaron Bentley
Implement knit repo format 2
1776
            raise errors.BadConversionTarget(
1777
                'Does not support rich root data.', target_format)
1778
1910.2.22 by Aaron Bentley
Make commits preserve root entry data
1779
    def open(self, a_bzrdir, _found=False, _override_transport=None):
1780
        """See RepositoryFormat.open().
1781
        
1782
        :param _override_transport: INTERNAL USE ONLY. Allows opening the
1783
                                    repository at a slightly different url
1784
                                    than normal. I.e. during 'upgrade'.
1785
        """
1786
        if not _found:
1787
            format = RepositoryFormat.find_format(a_bzrdir)
1788
            assert format.__class__ ==  self.__class__
1789
        if _override_transport is not None:
1790
            repo_transport = _override_transport
1791
        else:
1792
            repo_transport = a_bzrdir.get_repository_transport(None)
1996.3.20 by John Arbash Meinel
[merge] bzr.dev 2063
1793
        control_files = lockable_files.LockableFiles(repo_transport, 'lock',
1794
                                                     lockdir.LockDir)
1910.2.22 by Aaron Bentley
Make commits preserve root entry data
1795
        text_store = self._get_text_store(repo_transport, control_files)
1796
        control_store = self._get_control_store(repo_transport, control_files)
1797
        _revision_store = self._get_revision_store(repo_transport, control_files)
1798
        return KnitRepository2(_format=self,
1799
                               a_bzrdir=a_bzrdir,
1800
                               control_files=control_files,
1801
                               _revision_store=_revision_store,
1802
                               control_store=control_store,
1803
                               text_store=text_store)
1804
1805
1910.2.12 by Aaron Bentley
Implement knit repo format 2
1806
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1807
# formats which have no format string are not discoverable
1808
# and not independently creatable, so are not registered.
1666.1.6 by Robert Collins
Make knit the default format.
1809
RepositoryFormat.register_format(RepositoryFormat7())
2204.4.6 by Aaron Bentley
Fix default to work with RepositoryFormat.set_default_format
1810
# KEEP in sync with bzrdir.format_registry default
1910.2.42 by Aaron Bentley
Restore RepositoryFormatKnit1 as the default
1811
_default_format = RepositoryFormatKnit1()
1534.1.33 by Robert Collins
Move copy_content_into into InterRepository and InterWeaveRepo, and disable the default codepath test as we have optimised paths for all current combinations.
1812
RepositoryFormat.register_format(_default_format)
1910.2.42 by Aaron Bentley
Restore RepositoryFormatKnit1 as the default
1813
RepositoryFormat.register_format(RepositoryFormatKnit2())
2204.4.11 by Aaron Bentley
deprecate Repository.set_default_format, update upgrade tests
1814
RepositoryFormat._set_default_format(_default_format)
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1815
_legacy_formats = [RepositoryFormat4(),
1816
                   RepositoryFormat5(),
1817
                   RepositoryFormat6()]
1818
1819
1563.2.12 by Robert Collins
Checkpointing: created InterObject to factor out common inter object worker code, added InterVersionedFile and tests to allow making join work between any versionedfile.
1820
class InterRepository(InterObject):
1534.1.27 by Robert Collins
Start InterRepository with InterRepository.get.
1821
    """This class represents operations taking place between two repositories.
1822
1534.1.33 by Robert Collins
Move copy_content_into into InterRepository and InterWeaveRepo, and disable the default codepath test as we have optimised paths for all current combinations.
1823
    Its instances have methods like copy_content and fetch, and contain
1534.1.27 by Robert Collins
Start InterRepository with InterRepository.get.
1824
    references to the source and target repositories these operations can be 
1825
    carried out on.
1826
1827
    Often we will provide convenience methods on 'repository' which carry out
1828
    operations with another repository - they will always forward to
1829
    InterRepository.get(other).method_name(parameters).
1830
    """
1831
1910.2.15 by Aaron Bentley
Back out inter.get changes, make optimizers an ordered list
1832
    _optimisers = []
1534.1.28 by Robert Collins
Allow for optimised InterRepository selection.
1833
    """The available optimised InterRepository types."""
1834
1910.2.15 by Aaron Bentley
Back out inter.get changes, make optimizers an ordered list
1835
    def copy_content(self, revision_id=None, basis=None):
1836
        raise NotImplementedError(self.copy_content)
1837
1838
    def fetch(self, revision_id=None, pb=None):
1534.1.31 by Robert Collins
Deprecated fetch.fetch and fetch.greedy_fetch for branch.fetch, and move the Repository.fetch internals to InterRepo and InterWeaveRepo.
1839
        """Fetch the content required to construct revision_id.
1840
1910.7.17 by Andrew Bennetts
Various cosmetic changes.
1841
        The content is copied from self.source to self.target.
1534.1.31 by Robert Collins
Deprecated fetch.fetch and fetch.greedy_fetch for branch.fetch, and move the Repository.fetch internals to InterRepo and InterWeaveRepo.
1842
1843
        :param revision_id: if None all content is copied, if NULL_REVISION no
1844
                            content is copied.
1845
        :param pb: optional progress bar to use for progress reports. If not
1846
                   provided a default one will be created.
1847
1848
        Returns the copied revision count and the failed revisions in a tuple:
1849
        (copied, failures).
1850
        """
1910.2.15 by Aaron Bentley
Back out inter.get changes, make optimizers an ordered list
1851
        raise NotImplementedError(self.fetch)
1852
   
1853
    @needs_read_lock
1854
    def missing_revision_ids(self, revision_id=None):
1855
        """Return the revision ids that source has that target does not.
1856
        
1857
        These are returned in topological order.
1858
1859
        :param revision_id: only return revision ids included by this
1860
                            revision_id.
1861
        """
1862
        # generic, possibly worst case, slow code path.
1863
        target_ids = set(self.target.all_revision_ids())
1864
        if revision_id is not None:
1865
            source_ids = self.source.get_ancestry(revision_id)
1963.2.6 by Robey Pointer
pychecker is on crack; go back to using 'is None'.
1866
            assert source_ids[0] is None
1910.2.15 by Aaron Bentley
Back out inter.get changes, make optimizers an ordered list
1867
            source_ids.pop(0)
1868
        else:
1869
            source_ids = self.source.all_revision_ids()
1870
        result_set = set(source_ids).difference(target_ids)
1871
        # this may look like a no-op: its not. It preserves the ordering
1872
        # other_ids had while only returning the members from other_ids
1873
        # that we've decided we need.
1874
        return [rev_id for rev_id in source_ids if rev_id in result_set]
1875
1876
1877
class InterSameDataRepository(InterRepository):
1878
    """Code for converting between repositories that represent the same data.
1879
    
1880
    Data format and model must match for this to work.
1881
    """
1882
1883
    _matching_repo_format = RepositoryFormat4()
1884
    """Repository format for testing with."""
1885
1910.2.14 by Aaron Bentley
Fail when trying to use interrepository on Knit2 and Knit1
1886
    @staticmethod
1887
    def is_compatible(source, target):
1910.2.15 by Aaron Bentley
Back out inter.get changes, make optimizers an ordered list
1888
        if not isinstance(source, Repository):
1889
            return False
1890
        if not isinstance(target, Repository):
1891
            return False
1910.2.14 by Aaron Bentley
Fail when trying to use interrepository on Knit2 and Knit1
1892
        if source._format.rich_root_data == target._format.rich_root_data:
1893
            return True
1894
        else:
1895
            return False
1896
1534.1.33 by Robert Collins
Move copy_content_into into InterRepository and InterWeaveRepo, and disable the default codepath test as we have optimised paths for all current combinations.
1897
    @needs_write_lock
1898
    def copy_content(self, revision_id=None, basis=None):
1899
        """Make a complete copy of the content in self into destination.
1900
        
1901
        This is a destructive operation! Do not use it on existing 
1902
        repositories.
1903
1904
        :param revision_id: Only copy the content needed to construct
1905
                            revision_id and its parents.
1906
        :param basis: Copy the needed data preferentially from basis.
1907
        """
1908
        try:
1909
            self.target.set_make_working_trees(self.source.make_working_trees())
1910
        except NotImplementedError:
1911
            pass
1912
        # grab the basis available data
1913
        if basis is not None:
1914
            self.target.fetch(basis, revision_id=revision_id)
1759.2.2 by Jelmer Vernooij
Revert some of my spelling fixes and fix some typos after review by Aaron.
1915
        # but don't bother fetching if we have the needed data now.
1996.3.20 by John Arbash Meinel
[merge] bzr.dev 2063
1916
        if (revision_id not in (None, _mod_revision.NULL_REVISION) and 
1534.1.33 by Robert Collins
Move copy_content_into into InterRepository and InterWeaveRepo, and disable the default codepath test as we have optimised paths for all current combinations.
1917
            self.target.has_revision(revision_id)):
1918
            return
1919
        self.target.fetch(self.source, revision_id=revision_id)
1920
1921
    @needs_write_lock
1534.1.31 by Robert Collins
Deprecated fetch.fetch and fetch.greedy_fetch for branch.fetch, and move the Repository.fetch internals to InterRepo and InterWeaveRepo.
1922
    def fetch(self, revision_id=None, pb=None):
1910.7.20 by Andrew Bennetts
Merge from bzr.dev
1923
        """See InterRepository.fetch()."""
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
1924
        from bzrlib.fetch import GenericRepoFetcher
1534.1.31 by Robert Collins
Deprecated fetch.fetch and fetch.greedy_fetch for branch.fetch, and move the Repository.fetch internals to InterRepo and InterWeaveRepo.
1925
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1910.2.15 by Aaron Bentley
Back out inter.get changes, make optimizers an ordered list
1926
               self.source, self.source._format, self.target, 
1927
               self.target._format)
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
1928
        f = GenericRepoFetcher(to_repository=self.target,
1929
                               from_repository=self.source,
1930
                               last_revision=revision_id,
1931
                               pb=pb)
1534.1.33 by Robert Collins
Move copy_content_into into InterRepository and InterWeaveRepo, and disable the default codepath test as we have optimised paths for all current combinations.
1932
        return f.count_copied, f.failed_revisions
1534.1.31 by Robert Collins
Deprecated fetch.fetch and fetch.greedy_fetch for branch.fetch, and move the Repository.fetch internals to InterRepo and InterWeaveRepo.
1933
1910.2.15 by Aaron Bentley
Back out inter.get changes, make optimizers an ordered list
1934
1935
class InterWeaveRepo(InterSameDataRepository):
1534.1.31 by Robert Collins
Deprecated fetch.fetch and fetch.greedy_fetch for branch.fetch, and move the Repository.fetch internals to InterRepo and InterWeaveRepo.
1936
    """Optimised code paths between Weave based repositories."""
1937
1666.1.6 by Robert Collins
Make knit the default format.
1938
    _matching_repo_format = RepositoryFormat7()
1534.1.33 by Robert Collins
Move copy_content_into into InterRepository and InterWeaveRepo, and disable the default codepath test as we have optimised paths for all current combinations.
1939
    """Repository format for testing with."""
1940
1534.1.31 by Robert Collins
Deprecated fetch.fetch and fetch.greedy_fetch for branch.fetch, and move the Repository.fetch internals to InterRepo and InterWeaveRepo.
1941
    @staticmethod
1942
    def is_compatible(source, target):
1943
        """Be compatible with known Weave formats.
1944
        
1759.2.2 by Jelmer Vernooij
Revert some of my spelling fixes and fix some typos after review by Aaron.
1945
        We don't test for the stores being of specific types because that
1534.1.31 by Robert Collins
Deprecated fetch.fetch and fetch.greedy_fetch for branch.fetch, and move the Repository.fetch internals to InterRepo and InterWeaveRepo.
1946
        could lead to confusing results, and there is no need to be 
1947
        overly general.
1948
        """
1534.1.33 by Robert Collins
Move copy_content_into into InterRepository and InterWeaveRepo, and disable the default codepath test as we have optimised paths for all current combinations.
1949
        try:
1950
            return (isinstance(source._format, (RepositoryFormat5,
1951
                                                RepositoryFormat6,
1952
                                                RepositoryFormat7)) and
1953
                    isinstance(target._format, (RepositoryFormat5,
1954
                                                RepositoryFormat6,
1955
                                                RepositoryFormat7)))
1956
        except AttributeError:
1957
            return False
1958
    
1959
    @needs_write_lock
1960
    def copy_content(self, revision_id=None, basis=None):
1961
        """See InterRepository.copy_content()."""
1962
        # weave specific optimised path:
1963
        if basis is not None:
1964
            # copy the basis in, then fetch remaining data.
1965
            basis.copy_content_into(self.target, revision_id)
1759.2.2 by Jelmer Vernooij
Revert some of my spelling fixes and fix some typos after review by Aaron.
1966
            # the basis copy_content_into could miss-set this.
1534.1.33 by Robert Collins
Move copy_content_into into InterRepository and InterWeaveRepo, and disable the default codepath test as we have optimised paths for all current combinations.
1967
            try:
1968
                self.target.set_make_working_trees(self.source.make_working_trees())
1969
            except NotImplementedError:
1970
                pass
1971
            self.target.fetch(self.source, revision_id=revision_id)
1972
        else:
1973
            try:
1974
                self.target.set_make_working_trees(self.source.make_working_trees())
1975
            except NotImplementedError:
1976
                pass
1977
            # FIXME do not peek!
1978
            if self.source.control_files._transport.listable():
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
1979
                pb = ui.ui_factory.nested_progress_bar()
1594.1.3 by Robert Collins
Fixup pb usage to use nested_progress_bar.
1980
                try:
1563.2.37 by Robert Collins
Merge in nested progress bars
1981
                    self.target.weave_store.copy_all_ids(
1982
                        self.source.weave_store,
1983
                        pb=pb,
1984
                        from_transaction=self.source.get_transaction(),
1985
                        to_transaction=self.target.get_transaction())
1594.1.3 by Robert Collins
Fixup pb usage to use nested_progress_bar.
1986
                    pb.update('copying inventory', 0, 1)
1987
                    self.target.control_weaves.copy_multi(
1563.2.37 by Robert Collins
Merge in nested progress bars
1988
                        self.source.control_weaves, ['inventory'],
1989
                        from_transaction=self.source.get_transaction(),
1990
                        to_transaction=self.target.get_transaction())
1991
                    self.target._revision_store.text_store.copy_all_ids(
1992
                        self.source._revision_store.text_store,
1993
                        pb=pb)
1594.1.3 by Robert Collins
Fixup pb usage to use nested_progress_bar.
1994
                finally:
1995
                    pb.finished()
1534.1.33 by Robert Collins
Move copy_content_into into InterRepository and InterWeaveRepo, and disable the default codepath test as we have optimised paths for all current combinations.
1996
            else:
1997
                self.target.fetch(self.source, revision_id=revision_id)
1534.1.31 by Robert Collins
Deprecated fetch.fetch and fetch.greedy_fetch for branch.fetch, and move the Repository.fetch internals to InterRepo and InterWeaveRepo.
1998
1534.1.33 by Robert Collins
Move copy_content_into into InterRepository and InterWeaveRepo, and disable the default codepath test as we have optimised paths for all current combinations.
1999
    @needs_write_lock
1534.1.31 by Robert Collins
Deprecated fetch.fetch and fetch.greedy_fetch for branch.fetch, and move the Repository.fetch internals to InterRepo and InterWeaveRepo.
2000
    def fetch(self, revision_id=None, pb=None):
2001
        """See InterRepository.fetch()."""
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
2002
        from bzrlib.fetch import GenericRepoFetcher
1534.1.31 by Robert Collins
Deprecated fetch.fetch and fetch.greedy_fetch for branch.fetch, and move the Repository.fetch internals to InterRepo and InterWeaveRepo.
2003
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
2004
               self.source, self.source._format, self.target, self.target._format)
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
2005
        f = GenericRepoFetcher(to_repository=self.target,
2006
                               from_repository=self.source,
2007
                               last_revision=revision_id,
2008
                               pb=pb)
1534.1.33 by Robert Collins
Move copy_content_into into InterRepository and InterWeaveRepo, and disable the default codepath test as we have optimised paths for all current combinations.
2009
        return f.count_copied, f.failed_revisions
2010
1534.1.34 by Robert Collins
Move missing_revision_ids from Repository to InterRepository, and eliminate the now unused Repository._compatible_formats method.
2011
    @needs_read_lock
2012
    def missing_revision_ids(self, revision_id=None):
2013
        """See InterRepository.missing_revision_ids()."""
2014
        # we want all revisions to satisfy revision_id in source.
1759.2.2 by Jelmer Vernooij
Revert some of my spelling fixes and fix some typos after review by Aaron.
2015
        # but we don't want to stat every file here and there.
1534.1.34 by Robert Collins
Move missing_revision_ids from Repository to InterRepository, and eliminate the now unused Repository._compatible_formats method.
2016
        # we want then, all revisions other needs to satisfy revision_id 
2017
        # checked, but not those that we have locally.
2018
        # so the first thing is to get a subset of the revisions to 
2019
        # satisfy revision_id in source, and then eliminate those that
2020
        # we do already have. 
2021
        # this is slow on high latency connection to self, but as as this
2022
        # disk format scales terribly for push anyway due to rewriting 
2023
        # inventory.weave, this is considered acceptable.
2024
        # - RBC 20060209
2025
        if revision_id is not None:
2026
            source_ids = self.source.get_ancestry(revision_id)
1963.2.6 by Robey Pointer
pychecker is on crack; go back to using 'is None'.
2027
            assert source_ids[0] is None
1668.1.14 by Martin Pool
merge olaf - InvalidRevisionId fixes
2028
            source_ids.pop(0)
1534.1.34 by Robert Collins
Move missing_revision_ids from Repository to InterRepository, and eliminate the now unused Repository._compatible_formats method.
2029
        else:
2030
            source_ids = self.source._all_possible_ids()
2031
        source_ids_set = set(source_ids)
2032
        # source_ids is the worst possible case we may need to pull.
2033
        # now we want to filter source_ids against what we actually
1759.2.2 by Jelmer Vernooij
Revert some of my spelling fixes and fix some typos after review by Aaron.
2034
        # have in target, but don't try to check for existence where we know
1534.1.34 by Robert Collins
Move missing_revision_ids from Repository to InterRepository, and eliminate the now unused Repository._compatible_formats method.
2035
        # we do not have a revision as that would be pointless.
2036
        target_ids = set(self.target._all_possible_ids())
2037
        possibly_present_revisions = target_ids.intersection(source_ids_set)
2038
        actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
2039
        required_revisions = source_ids_set.difference(actually_present_revisions)
2040
        required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
2041
        if revision_id is not None:
2042
            # we used get_ancestry to determine source_ids then we are assured all
2043
            # revisions referenced are present as they are installed in topological order.
2044
            # and the tip revision was validated by get_ancestry.
2045
            return required_topo_revisions
2046
        else:
2047
            # if we just grabbed the possibly available ids, then 
2048
            # we only have an estimate of whats available and need to validate
2049
            # that against the revision records.
2050
            return self.source._eliminate_revisions_not_present(required_topo_revisions)
2051
1534.1.33 by Robert Collins
Move copy_content_into into InterRepository and InterWeaveRepo, and disable the default codepath test as we have optimised paths for all current combinations.
2052
1910.2.15 by Aaron Bentley
Back out inter.get changes, make optimizers an ordered list
2053
class InterKnitRepo(InterSameDataRepository):
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
2054
    """Optimised code paths between Knit based repositories."""
2055
2056
    _matching_repo_format = RepositoryFormatKnit1()
2057
    """Repository format for testing with."""
2058
2059
    @staticmethod
2060
    def is_compatible(source, target):
2061
        """Be compatible with known Knit formats.
2062
        
1759.2.2 by Jelmer Vernooij
Revert some of my spelling fixes and fix some typos after review by Aaron.
2063
        We don't test for the stores being of specific types because that
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
2064
        could lead to confusing results, and there is no need to be 
2065
        overly general.
2066
        """
2067
        try:
2068
            return (isinstance(source._format, (RepositoryFormatKnit1)) and
2069
                    isinstance(target._format, (RepositoryFormatKnit1)))
2070
        except AttributeError:
2071
            return False
2072
2073
    @needs_write_lock
2074
    def fetch(self, revision_id=None, pb=None):
2075
        """See InterRepository.fetch()."""
2076
        from bzrlib.fetch import KnitRepoFetcher
2077
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
2078
               self.source, self.source._format, self.target, self.target._format)
2079
        f = KnitRepoFetcher(to_repository=self.target,
2080
                            from_repository=self.source,
2081
                            last_revision=revision_id,
2082
                            pb=pb)
2083
        return f.count_copied, f.failed_revisions
2084
2085
    @needs_read_lock
2086
    def missing_revision_ids(self, revision_id=None):
2087
        """See InterRepository.missing_revision_ids()."""
2088
        if revision_id is not None:
2089
            source_ids = self.source.get_ancestry(revision_id)
1963.2.6 by Robey Pointer
pychecker is on crack; go back to using 'is None'.
2090
            assert source_ids[0] is None
1668.1.14 by Martin Pool
merge olaf - InvalidRevisionId fixes
2091
            source_ids.pop(0)
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
2092
        else:
2093
            source_ids = self.source._all_possible_ids()
2094
        source_ids_set = set(source_ids)
2095
        # source_ids is the worst possible case we may need to pull.
2096
        # now we want to filter source_ids against what we actually
1759.2.2 by Jelmer Vernooij
Revert some of my spelling fixes and fix some typos after review by Aaron.
2097
        # have in target, but don't try to check for existence where we know
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
2098
        # we do not have a revision as that would be pointless.
2099
        target_ids = set(self.target._all_possible_ids())
2100
        possibly_present_revisions = target_ids.intersection(source_ids_set)
2101
        actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
2102
        required_revisions = source_ids_set.difference(actually_present_revisions)
2103
        required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
2104
        if revision_id is not None:
2105
            # we used get_ancestry to determine source_ids then we are assured all
2106
            # revisions referenced are present as they are installed in topological order.
2107
            # and the tip revision was validated by get_ancestry.
2108
            return required_topo_revisions
2109
        else:
2110
            # if we just grabbed the possibly available ids, then 
2111
            # we only have an estimate of whats available and need to validate
2112
            # that against the revision records.
2113
            return self.source._eliminate_revisions_not_present(required_topo_revisions)
2114
1910.2.17 by Aaron Bentley
Get fetching from 1 to 2 under test
2115
1910.2.24 by Aaron Bentley
Got intra-repository fetch working between model1 and 2 for all types
2116
class InterModel1and2(InterRepository):
2117
2118
    _matching_repo_format = None
2119
2120
    @staticmethod
2121
    def is_compatible(source, target):
2122
        if not isinstance(source, Repository):
2123
            return False
2124
        if not isinstance(target, Repository):
2125
            return False
2126
        if not source._format.rich_root_data and target._format.rich_root_data:
2127
            return True
2128
        else:
2129
            return False
2130
2131
    @needs_write_lock
2132
    def fetch(self, revision_id=None, pb=None):
2133
        """See InterRepository.fetch()."""
2134
        from bzrlib.fetch import Model1toKnit2Fetcher
2135
        f = Model1toKnit2Fetcher(to_repository=self.target,
2136
                                 from_repository=self.source,
2137
                                 last_revision=revision_id,
2138
                                 pb=pb)
2139
        return f.count_copied, f.failed_revisions
2140
1910.2.26 by Aaron Bentley
Fix up some test cases
2141
    @needs_write_lock
2142
    def copy_content(self, revision_id=None, basis=None):
2143
        """Make a complete copy of the content in self into destination.
2144
        
2145
        This is a destructive operation! Do not use it on existing 
2146
        repositories.
2147
2148
        :param revision_id: Only copy the content needed to construct
2149
                            revision_id and its parents.
2150
        :param basis: Copy the needed data preferentially from basis.
2151
        """
2152
        try:
2153
            self.target.set_make_working_trees(self.source.make_working_trees())
2154
        except NotImplementedError:
2155
            pass
2156
        # grab the basis available data
2157
        if basis is not None:
2158
            self.target.fetch(basis, revision_id=revision_id)
2159
        # but don't bother fetching if we have the needed data now.
1996.3.20 by John Arbash Meinel
[merge] bzr.dev 2063
2160
        if (revision_id not in (None, _mod_revision.NULL_REVISION) and 
1910.2.26 by Aaron Bentley
Fix up some test cases
2161
            self.target.has_revision(revision_id)):
2162
            return
2163
        self.target.fetch(self.source, revision_id=revision_id)
2164
1910.2.24 by Aaron Bentley
Got intra-repository fetch working between model1 and 2 for all types
2165
1910.2.17 by Aaron Bentley
Get fetching from 1 to 2 under test
2166
class InterKnit1and2(InterKnitRepo):
2167
1910.2.24 by Aaron Bentley
Got intra-repository fetch working between model1 and 2 for all types
2168
    _matching_repo_format = None
2169
1910.2.17 by Aaron Bentley
Get fetching from 1 to 2 under test
2170
    @staticmethod
2171
    def is_compatible(source, target):
2172
        """Be compatible with Knit1 source and Knit2 target"""
2173
        try:
2174
            return (isinstance(source._format, (RepositoryFormatKnit1)) and
2175
                    isinstance(target._format, (RepositoryFormatKnit2)))
2176
        except AttributeError:
2177
            return False
2178
2179
    @needs_write_lock
2180
    def fetch(self, revision_id=None, pb=None):
2181
        """See InterRepository.fetch()."""
2182
        from bzrlib.fetch import Knit1to2Fetcher
2183
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
2184
               self.source, self.source._format, self.target, 
2185
               self.target._format)
2186
        f = Knit1to2Fetcher(to_repository=self.target,
2187
                            from_repository=self.source,
2188
                            last_revision=revision_id,
2189
                            pb=pb)
2190
        return f.count_copied, f.failed_revisions
2191
2192
1910.2.15 by Aaron Bentley
Back out inter.get changes, make optimizers an ordered list
2193
InterRepository.register_optimiser(InterSameDataRepository)
1534.1.33 by Robert Collins
Move copy_content_into into InterRepository and InterWeaveRepo, and disable the default codepath test as we have optimised paths for all current combinations.
2194
InterRepository.register_optimiser(InterWeaveRepo)
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
2195
InterRepository.register_optimiser(InterKnitRepo)
1910.2.24 by Aaron Bentley
Got intra-repository fetch working between model1 and 2 for all types
2196
InterRepository.register_optimiser(InterModel1and2)
1910.2.17 by Aaron Bentley
Get fetching from 1 to 2 under test
2197
InterRepository.register_optimiser(InterKnit1and2)
1534.1.31 by Robert Collins
Deprecated fetch.fetch and fetch.greedy_fetch for branch.fetch, and move the Repository.fetch internals to InterRepo and InterWeaveRepo.
2198
2199
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
2200
class RepositoryTestProviderAdapter(object):
2201
    """A tool to generate a suite testing multiple repository formats at once.
2202
2203
    This is done by copying the test once for each transport and injecting
2204
    the transport_server, transport_readonly_server, and bzrdir_format and
2205
    repository_format classes into each copy. Each copy is also given a new id()
2206
    to make it easy to identify.
2207
    """
2208
2209
    def __init__(self, transport_server, transport_readonly_server, formats):
2210
        self._transport_server = transport_server
2211
        self._transport_readonly_server = transport_readonly_server
2212
        self._formats = formats
2213
    
2214
    def adapt(self, test):
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
2215
        result = unittest.TestSuite()
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
2216
        for repository_format, bzrdir_format in self._formats:
2217
            new_test = deepcopy(test)
2218
            new_test.transport_server = self._transport_server
2219
            new_test.transport_readonly_server = self._transport_readonly_server
2220
            new_test.bzrdir_format = bzrdir_format
2221
            new_test.repository_format = repository_format
2222
            def make_new_test_id():
2223
                new_id = "%s(%s)" % (new_test.id(), repository_format.__class__.__name__)
2224
                return lambda: new_id
2225
            new_test.id = make_new_test_id()
2226
            result.addTest(new_test)
2227
        return result
1534.1.29 by Robert Collins
Add a test environment for InterRepository objects, and remove the fetch corner case tests from test_repository.
2228
2229
2230
class InterRepositoryTestProviderAdapter(object):
2231
    """A tool to generate a suite testing multiple inter repository formats.
2232
2233
    This is done by copying the test once for each interrepo provider and injecting
2234
    the transport_server, transport_readonly_server, repository_format and 
2235
    repository_to_format classes into each copy.
2236
    Each copy is also given a new id() to make it easy to identify.
2237
    """
2238
2239
    def __init__(self, transport_server, transport_readonly_server, formats):
2240
        self._transport_server = transport_server
2241
        self._transport_readonly_server = transport_readonly_server
2242
        self._formats = formats
2243
    
2244
    def adapt(self, test):
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
2245
        result = unittest.TestSuite()
1534.1.29 by Robert Collins
Add a test environment for InterRepository objects, and remove the fetch corner case tests from test_repository.
2246
        for interrepo_class, repository_format, repository_format_to in self._formats:
2247
            new_test = deepcopy(test)
2248
            new_test.transport_server = self._transport_server
2249
            new_test.transport_readonly_server = self._transport_readonly_server
2250
            new_test.interrepo_class = interrepo_class
2251
            new_test.repository_format = repository_format
2252
            new_test.repository_format_to = repository_format_to
2253
            def make_new_test_id():
2254
                new_id = "%s(%s)" % (new_test.id(), interrepo_class.__name__)
2255
                return lambda: new_id
2256
            new_test.id = make_new_test_id()
2257
            result.addTest(new_test)
2258
        return result
2259
2260
    @staticmethod
2261
    def default_test_list():
2262
        """Generate the default list of interrepo permutations to test."""
2263
        result = []
2264
        # test the default InterRepository between format 6 and the current 
2265
        # default format.
1534.1.33 by Robert Collins
Move copy_content_into into InterRepository and InterWeaveRepo, and disable the default codepath test as we have optimised paths for all current combinations.
2266
        # XXX: robertc 20060220 reinstate this when there are two supported
2267
        # formats which do not have an optimal code path between them.
1910.2.24 by Aaron Bentley
Got intra-repository fetch working between model1 and 2 for all types
2268
        #result.append((InterRepository,
2269
        #               RepositoryFormat6(),
2270
        #               RepositoryFormatKnit1()))
1534.1.29 by Robert Collins
Add a test environment for InterRepository objects, and remove the fetch corner case tests from test_repository.
2271
        for optimiser in InterRepository._optimisers:
1910.2.24 by Aaron Bentley
Got intra-repository fetch working between model1 and 2 for all types
2272
            if optimiser._matching_repo_format is not None:
2273
                result.append((optimiser,
2274
                               optimiser._matching_repo_format,
2275
                               optimiser._matching_repo_format
2276
                               ))
1534.1.29 by Robert Collins
Add a test environment for InterRepository objects, and remove the fetch corner case tests from test_repository.
2277
        # if there are specific combinations we want to use, we can add them 
2278
        # here.
1910.2.24 by Aaron Bentley
Got intra-repository fetch working between model1 and 2 for all types
2279
        result.append((InterModel1and2, RepositoryFormat5(),
2280
                       RepositoryFormatKnit2()))
2281
        result.append((InterKnit1and2, RepositoryFormatKnit1(),
2282
                       RepositoryFormatKnit2()))
1534.1.29 by Robert Collins
Add a test environment for InterRepository objects, and remove the fetch corner case tests from test_repository.
2283
        return result
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
2284
2285
2286
class CopyConverter(object):
2287
    """A repository conversion tool which just performs a copy of the content.
2288
    
2289
    This is slow but quite reliable.
2290
    """
2291
2292
    def __init__(self, target_format):
2293
        """Create a CopyConverter.
2294
2295
        :param target_format: The format the resulting repository should be.
2296
        """
2297
        self.target_format = target_format
2298
        
2299
    def convert(self, repo, pb):
2300
        """Perform the conversion of to_convert, giving feedback via pb.
2301
2302
        :param to_convert: The disk object to convert.
2303
        :param pb: a progress bar to use for progress information.
2304
        """
2305
        self.pb = pb
2306
        self.count = 0
1596.2.22 by Robert Collins
Fetch changes to use new pb.
2307
        self.total = 4
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
2308
        # this is only useful with metadir layouts - separated repo content.
2309
        # trigger an assertion if not such
2310
        repo._format.get_format_string()
2311
        self.repo_dir = repo.bzrdir
2312
        self.step('Moving repository to repository.backup')
2313
        self.repo_dir.transport.move('repository', 'repository.backup')
2314
        backup_transport =  self.repo_dir.transport.clone('repository.backup')
1910.2.12 by Aaron Bentley
Implement knit repo format 2
2315
        repo._format.check_conversion_target(self.target_format)
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
2316
        self.source_repo = repo._format.open(self.repo_dir,
2317
            _found=True,
2318
            _override_transport=backup_transport)
2319
        self.step('Creating new repository')
2320
        converted = self.target_format.initialize(self.repo_dir,
2321
                                                  self.source_repo.is_shared())
2322
        converted.lock_write()
2323
        try:
2324
            self.step('Copying content into repository.')
2325
            self.source_repo.copy_content_into(converted)
2326
        finally:
2327
            converted.unlock()
2328
        self.step('Deleting old repository content.')
2329
        self.repo_dir.transport.delete_tree('repository.backup')
2330
        self.pb.note('repository converted')
2331
2332
    def step(self, message):
2333
        """Update the pb by a step."""
2334
        self.count +=1
2335
        self.pb.update(message, self.count, self.total)
1596.1.1 by Martin Pool
Use simple xml unescaping rather than importing xml.sax
2336
2337
1740.3.1 by Jelmer Vernooij
Introduce and use CommitBuilder objects.
2338
class CommitBuilder(object):
2339
    """Provides an interface to build up a commit.
2340
2341
    This allows describing a tree to be committed without needing to 
2342
    know the internals of the format of the repository.
2343
    """
1910.2.4 by Aaron Bentley
Support old CommitBuilders
2344
    
2345
    record_root_entry = False
1740.3.7 by Jelmer Vernooij
Move committer, log, revprops, timestamp and timezone to CommitBuilder.
2346
    def __init__(self, repository, parents, config, timestamp=None, 
2347
                 timezone=None, committer=None, revprops=None, 
2348
                 revision_id=None):
2349
        """Initiate a CommitBuilder.
2350
2351
        :param repository: Repository to commit to.
2352
        :param parents: Revision ids of the parents of the new revision.
2353
        :param config: Configuration to use.
2354
        :param timestamp: Optional timestamp recorded for commit.
2355
        :param timezone: Optional timezone for timestamp.
2356
        :param committer: Optional committer to set for commit.
2357
        :param revprops: Optional dictionary of revision properties.
2358
        :param revision_id: Optional revision id.
2359
        """
2360
        self._config = config
2361
2362
        if committer is None:
2363
            self._committer = self._config.username()
2364
        else:
2365
            assert isinstance(committer, basestring), type(committer)
2366
            self._committer = committer
2367
1731.1.33 by Aaron Bentley
Revert no-special-root changes
2368
        self.new_inventory = Inventory(None)
1740.3.7 by Jelmer Vernooij
Move committer, log, revprops, timestamp and timezone to CommitBuilder.
2369
        self._new_revision_id = revision_id
1740.3.6 by Jelmer Vernooij
Move inventory writing to the commit builder.
2370
        self.parents = parents
1740.3.1 by Jelmer Vernooij
Introduce and use CommitBuilder objects.
2371
        self.repository = repository
1740.3.6 by Jelmer Vernooij
Move inventory writing to the commit builder.
2372
1740.3.7 by Jelmer Vernooij
Move committer, log, revprops, timestamp and timezone to CommitBuilder.
2373
        self._revprops = {}
2374
        if revprops is not None:
2375
            self._revprops.update(revprops)
2376
2377
        if timestamp is None:
1864.2.1 by John Arbash Meinel
Commit timestamp restricted to 1ms precision.
2378
            timestamp = time.time()
2379
        # Restrict resolution to 1ms
2380
        self._timestamp = round(timestamp, 3)
1740.3.7 by Jelmer Vernooij
Move committer, log, revprops, timestamp and timezone to CommitBuilder.
2381
2382
        if timezone is None:
2383
            self._timezone = local_time_offset()
2384
        else:
2385
            self._timezone = int(timezone)
2386
2387
        self._generate_revision_if_needed()
2388
1740.3.9 by Jelmer Vernooij
Make the commit message the first argument of CommitBuilder.commit().
2389
    def commit(self, message):
1740.3.8 by Jelmer Vernooij
Move make_revision() to commit builder.
2390
        """Make the actual commit.
2391
2392
        :return: The revision id of the recorded revision.
2393
        """
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
2394
        rev = _mod_revision.Revision(
2395
                       timestamp=self._timestamp,
1740.3.8 by Jelmer Vernooij
Move make_revision() to commit builder.
2396
                       timezone=self._timezone,
2397
                       committer=self._committer,
1740.3.9 by Jelmer Vernooij
Make the commit message the first argument of CommitBuilder.commit().
2398
                       message=message,
1740.3.8 by Jelmer Vernooij
Move make_revision() to commit builder.
2399
                       inventory_sha1=self.inv_sha1,
2400
                       revision_id=self._new_revision_id,
2401
                       properties=self._revprops)
2402
        rev.parent_ids = self.parents
2403
        self.repository.add_revision(self._new_revision_id, rev, 
2404
            self.new_inventory, self._config)
2405
        return self._new_revision_id
2406
2041.1.5 by John Arbash Meinel
CommitBuilder.get_tree => CommitBuilder.revision_tree
2407
    def revision_tree(self):
2041.1.1 by John Arbash Meinel
Add a 'get_tree()' call that returns a RevisionTree for the newly committed tree
2408
        """Return the tree that was just committed.
2409
2410
        After calling commit() this can be called to get a RevisionTree
2411
        representing the newly committed tree. This is preferred to
2412
        calling Repository.revision_tree() because that may require
2413
        deserializing the inventory, while we already have a copy in
2414
        memory.
2415
        """
2416
        return RevisionTree(self.repository, self.new_inventory,
2417
                            self._new_revision_id)
2418
1740.3.6 by Jelmer Vernooij
Move inventory writing to the commit builder.
2419
    def finish_inventory(self):
1740.3.9 by Jelmer Vernooij
Make the commit message the first argument of CommitBuilder.commit().
2420
        """Tell the builder that the inventory is finished."""
1910.2.3 by Aaron Bentley
All tests pass
2421
        if self.new_inventory.root is None:
1910.2.9 by Aaron Bentley
Inroduce assertDeprecated, and use it to test old commitbuilder API
2422
            symbol_versioning.warn('Root entry should be supplied to'
2423
                ' record_entry_contents, as of bzr 0.10.',
1910.2.3 by Aaron Bentley
All tests pass
2424
                 DeprecationWarning, stacklevel=2)
2425
            self.new_inventory.add(InventoryDirectory(ROOT_ID, '', None))
1757.1.2 by Robert Collins
Bugfix CommitBuilders recording of the inventory revision id.
2426
        self.new_inventory.revision_id = self._new_revision_id
1740.3.8 by Jelmer Vernooij
Move make_revision() to commit builder.
2427
        self.inv_sha1 = self.repository.add_inventory(
1740.3.6 by Jelmer Vernooij
Move inventory writing to the commit builder.
2428
            self._new_revision_id,
2429
            self.new_inventory,
2430
            self.parents
2431
            )
1740.3.1 by Jelmer Vernooij
Introduce and use CommitBuilder objects.
2432
1740.3.7 by Jelmer Vernooij
Move committer, log, revprops, timestamp and timezone to CommitBuilder.
2433
    def _gen_revision_id(self):
2434
        """Return new revision-id."""
2116.4.1 by John Arbash Meinel
Update file and revision id generators.
2435
        return generate_ids.gen_revision_id(self._config.username(),
2436
                                            self._timestamp)
1740.3.7 by Jelmer Vernooij
Move committer, log, revprops, timestamp and timezone to CommitBuilder.
2437
2438
    def _generate_revision_if_needed(self):
2439
        """Create a revision id if None was supplied.
2440
        
2441
        If the repository can not support user-specified revision ids
2150.2.2 by Robert Collins
Change the commit builder selected-revision-id test to use a unicode revision id where possible, leading to stricter testing of the hypothetical unicode revision id support in bzr.
2442
        they should override this function and raise CannotSetRevisionId
1740.3.7 by Jelmer Vernooij
Move committer, log, revprops, timestamp and timezone to CommitBuilder.
2443
        if _new_revision_id is not None.
2444
2150.2.2 by Robert Collins
Change the commit builder selected-revision-id test to use a unicode revision id where possible, leading to stricter testing of the hypothetical unicode revision id support in bzr.
2445
        :raises: CannotSetRevisionId
1740.3.3 by Jelmer Vernooij
Move storing directories and links to commit builder.
2446
        """
1740.3.7 by Jelmer Vernooij
Move committer, log, revprops, timestamp and timezone to CommitBuilder.
2447
        if self._new_revision_id is None:
2448
            self._new_revision_id = self._gen_revision_id()
1740.3.3 by Jelmer Vernooij
Move storing directories and links to commit builder.
2449
1740.3.7 by Jelmer Vernooij
Move committer, log, revprops, timestamp and timezone to CommitBuilder.
2450
    def record_entry_contents(self, ie, parent_invs, path, tree):
1740.3.1 by Jelmer Vernooij
Introduce and use CommitBuilder objects.
2451
        """Record the content of ie from tree into the commit if needed.
2452
1910.2.3 by Aaron Bentley
All tests pass
2453
        Side effect: sets ie.revision when unchanged
2454
1740.3.1 by Jelmer Vernooij
Introduce and use CommitBuilder objects.
2455
        :param ie: An inventory entry present in the commit.
2456
        :param parent_invs: The inventories of the parent revisions of the
2457
            commit.
2458
        :param path: The path the entry is at in the tree.
2459
        :param tree: The tree which contains this entry and should be used to 
2460
        obtain content.
2461
        """
1910.2.8 by Aaron Bentley
Fix commit_builder when root not passed to record_entry_contents
2462
        if self.new_inventory.root is None and ie.parent_id is not None:
1910.2.9 by Aaron Bentley
Inroduce assertDeprecated, and use it to test old commitbuilder API
2463
            symbol_versioning.warn('Root entry should be supplied to'
2464
                ' record_entry_contents, as of bzr 0.10.',
1910.2.8 by Aaron Bentley
Fix commit_builder when root not passed to record_entry_contents
2465
                 DeprecationWarning, stacklevel=2)
2466
            self.record_entry_contents(tree.inventory.root.copy(), parent_invs,
2467
                                       '', tree)
1907.1.1 by Aaron Bentley
Unshelved all changes except those related to removing RootEntry
2468
        self.new_inventory.add(ie)
1740.3.6 by Jelmer Vernooij
Move inventory writing to the commit builder.
2469
1740.3.4 by Jelmer Vernooij
Move inventory to commit builder.
2470
        # ie.revision is always None if the InventoryEntry is considered
2471
        # for committing. ie.snapshot will record the correct revision 
2472
        # which may be the sole parent if it is untouched.
1740.3.6 by Jelmer Vernooij
Move inventory writing to the commit builder.
2473
        if ie.revision is not None:
2474
            return
1910.2.3 by Aaron Bentley
All tests pass
2475
2476
        # In this revision format, root entries have no knit or weave
2477
        if ie is self.new_inventory.root:
2044.1.1 by Robert Collins
(Robert Collins) Forward merge from 0.11rc2 NEWS and performance-regression fix.
2478
            # When serializing out to disk and back in
2479
            # root.revision is always _new_revision_id
2480
            ie.revision = self._new_revision_id
1910.2.3 by Aaron Bentley
All tests pass
2481
            return
1740.3.1 by Jelmer Vernooij
Introduce and use CommitBuilder objects.
2482
        previous_entries = ie.find_previous_heads(
2483
            parent_invs,
2484
            self.repository.weave_store,
2485
            self.repository.get_transaction())
1740.3.6 by Jelmer Vernooij
Move inventory writing to the commit builder.
2486
        # we are creating a new revision for ie in the history store
2487
        # and inventory.
1740.3.7 by Jelmer Vernooij
Move committer, log, revprops, timestamp and timezone to CommitBuilder.
2488
        ie.snapshot(self._new_revision_id, path, previous_entries, tree, self)
1740.3.3 by Jelmer Vernooij
Move storing directories and links to commit builder.
2489
2490
    def modified_directory(self, file_id, file_parents):
2491
        """Record the presence of a symbolic link.
2492
2493
        :param file_id: The file_id of the link to record.
2494
        :param file_parents: The per-file parent revision ids.
2495
        """
2496
        self._add_text_to_weave(file_id, [], file_parents.keys())
1740.3.2 by Jelmer Vernooij
Move storing file texts to commit builder.
2497
    
1740.3.3 by Jelmer Vernooij
Move storing directories and links to commit builder.
2498
    def modified_file_text(self, file_id, file_parents,
2499
                           get_content_byte_lines, text_sha1=None,
2500
                           text_size=None):
1740.3.2 by Jelmer Vernooij
Move storing file texts to commit builder.
2501
        """Record the text of file file_id
2502
2503
        :param file_id: The file_id of the file to record the text of.
2504
        :param file_parents: The per-file parent revision ids.
2505
        :param get_content_byte_lines: A callable which will return the byte
2506
            lines for the file.
2507
        :param text_sha1: Optional SHA1 of the file contents.
2508
        :param text_size: Optional size of the file contents.
2509
        """
1711.2.101 by John Arbash Meinel
Clean up some unnecessary mutter() calls
2510
        # mutter('storing text of file {%s} in revision {%s} into %r',
2511
        #        file_id, self._new_revision_id, self.repository.weave_store)
1740.3.2 by Jelmer Vernooij
Move storing file texts to commit builder.
2512
        # special case to avoid diffing on renames or 
2513
        # reparenting
2514
        if (len(file_parents) == 1
2515
            and text_sha1 == file_parents.values()[0].text_sha1
2516
            and text_size == file_parents.values()[0].text_size):
2517
            previous_ie = file_parents.values()[0]
2518
            versionedfile = self.repository.weave_store.get_weave(file_id, 
2519
                self.repository.get_transaction())
1740.3.3 by Jelmer Vernooij
Move storing directories and links to commit builder.
2520
            versionedfile.clone_text(self._new_revision_id, 
1740.3.2 by Jelmer Vernooij
Move storing file texts to commit builder.
2521
                previous_ie.revision, file_parents.keys())
2522
            return text_sha1, text_size
2523
        else:
2524
            new_lines = get_content_byte_lines()
2525
            # TODO: Rather than invoking sha_strings here, _add_text_to_weave
2526
            # should return the SHA1 and size
2527
            self._add_text_to_weave(file_id, new_lines, file_parents.keys())
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
2528
            return osutils.sha_strings(new_lines), \
1740.3.2 by Jelmer Vernooij
Move storing file texts to commit builder.
2529
                sum(map(len, new_lines))
2530
1740.3.3 by Jelmer Vernooij
Move storing directories and links to commit builder.
2531
    def modified_link(self, file_id, file_parents, link_target):
2532
        """Record the presence of a symbolic link.
2533
2534
        :param file_id: The file_id of the link to record.
2535
        :param file_parents: The per-file parent revision ids.
2536
        :param link_target: Target location of this link.
2537
        """
2538
        self._add_text_to_weave(file_id, [], file_parents.keys())
2539
1740.3.2 by Jelmer Vernooij
Move storing file texts to commit builder.
2540
    def _add_text_to_weave(self, file_id, new_lines, parents):
2541
        versionedfile = self.repository.weave_store.get_weave_or_empty(
2542
            file_id, self.repository.get_transaction())
1740.3.3 by Jelmer Vernooij
Move storing directories and links to commit builder.
2543
        versionedfile.add_lines(self._new_revision_id, parents, new_lines)
1740.3.2 by Jelmer Vernooij
Move storing file texts to commit builder.
2544
        versionedfile.clear_cache()
1740.3.1 by Jelmer Vernooij
Introduce and use CommitBuilder objects.
2545
2546
1910.2.6 by Aaron Bentley
Update for merge review, handle deprecations
2547
class _CommitBuilder(CommitBuilder):
1910.2.4 by Aaron Bentley
Support old CommitBuilders
2548
    """Temporary class so old CommitBuilders are detected properly
2549
    
2550
    Note: CommitBuilder works whether or not root entry is recorded.
2551
    """
2552
2553
    record_root_entry = True
2554
2555
1910.2.22 by Aaron Bentley
Make commits preserve root entry data
2556
class RootCommitBuilder(CommitBuilder):
2557
    """This commitbuilder actually records the root id"""
2558
    
2559
    record_root_entry = True
2560
2561
    def record_entry_contents(self, ie, parent_invs, path, tree):
2562
        """Record the content of ie from tree into the commit if needed.
2563
2564
        Side effect: sets ie.revision when unchanged
2565
2566
        :param ie: An inventory entry present in the commit.
2567
        :param parent_invs: The inventories of the parent revisions of the
2568
            commit.
2569
        :param path: The path the entry is at in the tree.
2570
        :param tree: The tree which contains this entry and should be used to 
2571
        obtain content.
2572
        """
2573
        assert self.new_inventory.root is not None or ie.parent_id is None
2574
        self.new_inventory.add(ie)
2575
2576
        # ie.revision is always None if the InventoryEntry is considered
2577
        # for committing. ie.snapshot will record the correct revision 
2578
        # which may be the sole parent if it is untouched.
2579
        if ie.revision is not None:
2580
            return
2581
2582
        previous_entries = ie.find_previous_heads(
2583
            parent_invs,
2584
            self.repository.weave_store,
2585
            self.repository.get_transaction())
2586
        # we are creating a new revision for ie in the history store
2587
        # and inventory.
2588
        ie.snapshot(self._new_revision_id, path, previous_entries, tree, self)
2589
2590
1843.2.4 by Aaron Bentley
Switch to John Meinel's _unescape_xml implementation
2591
_unescape_map = {
2592
    'apos':"'",
2593
    'quot':'"',
2594
    'amp':'&',
2595
    'lt':'<',
2596
    'gt':'>'
2597
}
2598
2599
2600
def _unescaper(match, _map=_unescape_map):
2601
    return _map[match.group(1)]
2602
2603
2604
_unescape_re = None
2605
2606
1596.1.1 by Martin Pool
Use simple xml unescaping rather than importing xml.sax
2607
def _unescape_xml(data):
1843.2.4 by Aaron Bentley
Switch to John Meinel's _unescape_xml implementation
2608
    """Unescape predefined XML entities in a string of data."""
2609
    global _unescape_re
2610
    if _unescape_re is None:
2120.2.1 by John Arbash Meinel
Remove tabs from source files, and add a test to keep it that way.
2611
        _unescape_re = re.compile('\&([^;]*);')
1843.2.4 by Aaron Bentley
Switch to John Meinel's _unescape_xml implementation
2612
    return _unescape_re.sub(_unescaper, data)