~bzr-pqm/bzr/bzr.dev

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