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