/brz/remove-bazaar

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