/brz/remove-bazaar

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