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