/brz/remove-bazaar

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