/brz/remove-bazaar

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