/brz/remove-bazaar

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