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