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