/brz/remove-bazaar

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