/brz/remove-bazaar

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