/brz/remove-bazaar

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