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