/brz/remove-bazaar

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