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