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