~bzr-pqm/bzr/bzr.dev

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