/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
4110.2.1 by Martin Pool
Remove duplicated code from InterRepository implementations.
1
# Copyright (C) 2005, 2006, 2007, 2008, 2009 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
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 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 bzrlib.lazy_import import lazy_import
18
lazy_import(globals(), """
3224.5.25 by Andrew Bennetts
More minor import tidying suggested by pyflakes.
19
import cStringIO
1740.3.7 by Jelmer Vernooij
Move committer, log, revprops, timestamp and timezone to CommitBuilder.
20
import re
21
import time
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
22
1910.2.22 by Aaron Bentley
Make commits preserve root entry data
23
from bzrlib import (
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
24
    bzrdir,
25
    check,
2745.1.1 by Robert Collins
Add a number of -Devil checkpoints.
26
    debug,
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
27
    errors,
3882.6.23 by John Arbash Meinel
Change the XMLSerializer.read_inventory_from_string api.
28
    fifo_cache,
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,
2988.1.5 by Robert Collins
Use a LRU cache when generating the text index to reduce inventory deserialisations.
35
    lru_cache,
1910.2.22 by Aaron Bentley
Make commits preserve root entry data
36
    osutils,
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
37
    revision as _mod_revision,
38
    symbol_versioning,
2988.1.3 by Robert Collins
Add a new repositoy method _generate_text_key_index for use by reconcile/check.
39
    tsort,
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
40
    ui,
3831.2.1 by Andrew Bennetts
Quick hack to do batching in InterDifferingSerializer. Almost halves the HPSS round-trips fetching pack-0.92-subtree to 1.9-rich-root.
41
    versionedfile,
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
42
    )
2520.4.54 by Aaron Bentley
Hang a create_bundle method off repository
43
from bzrlib.bundle import serializer
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
44
from bzrlib.revisiontree import RevisionTree
45
from bzrlib.store.versioned import VersionedFileStore
46
from bzrlib.testament import Testament
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
3775.2.4 by Robert Collins
Start on a CommitBuilder.record_iter_changes method.
51
from bzrlib.inventory import (
52
    Inventory,
53
    InventoryDirectory,
54
    ROOT_ID,
55
    entry_factory,
56
    )
4032.3.1 by Robert Collins
Add a BranchFormat.network_name() method as preparation for creating branches via RPC calls.
57
from bzrlib import registry
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
58
from bzrlib.symbol_versioning import (
59
        deprecated_method,
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
60
        )
3825.4.1 by Andrew Bennetts
Add suppress_errors to abort_write_group.
61
from bzrlib.trace import (
62
    log_exception_quietly, note, mutter, mutter_callsite, warning)
1185.70.3 by Martin Pool
Various updates to make storage branch mergeable:
63
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
64
1904.2.5 by Martin Pool
Fix format warning inside test suite and add test
65
# Old formats display a warning, but only once
66
_deprecation_warning_done = False
67
68
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
69
class CommitBuilder(object):
70
    """Provides an interface to build up a commit.
71
3879.2.3 by John Arbash Meinel
Hide the .basis_delta variable, and require callers to use .get_basis_delta()
72
    This allows describing a tree to be committed without needing to
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
73
    know the internals of the format of the repository.
74
    """
3879.2.3 by John Arbash Meinel
Hide the .basis_delta variable, and require callers to use .get_basis_delta()
75
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
76
    # all clients should supply tree roots.
77
    record_root_entry = True
2825.5.2 by Robert Collins
Review feedback, and fix pointless commits with nested trees to raise PointlessCommit appropriately.
78
    # the default CommitBuilder does not manage trees whose root is versioned.
79
    _versioned_root = False
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
80
2979.2.2 by Robert Collins
Per-file graph heads detection during commit for pack repositories.
81
    def __init__(self, repository, parents, config, timestamp=None,
82
                 timezone=None, committer=None, revprops=None,
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
83
                 revision_id=None):
84
        """Initiate a CommitBuilder.
85
86
        :param repository: Repository to commit to.
87
        :param parents: Revision ids of the parents of the new revision.
88
        :param config: Configuration to use.
89
        :param timestamp: Optional timestamp recorded for commit.
90
        :param timezone: Optional timezone for timestamp.
91
        :param committer: Optional committer to set for commit.
92
        :param revprops: Optional dictionary of revision properties.
93
        :param revision_id: Optional revision id.
94
        """
95
        self._config = config
96
97
        if committer is None:
98
            self._committer = self._config.username()
99
        else:
100
            self._committer = committer
101
102
        self.new_inventory = Inventory(None)
2858.2.1 by Martin Pool
Remove most calls to safe_file_id and safe_revision_id.
103
        self._new_revision_id = revision_id
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
104
        self.parents = parents
105
        self.repository = repository
106
107
        self._revprops = {}
108
        if revprops is not None:
3831.1.1 by John Arbash Meinel
Before allowing commit to succeed, verify the texts will be 'safe'.
109
            self._validate_revprops(revprops)
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
110
            self._revprops.update(revprops)
111
112
        if timestamp is None:
113
            timestamp = time.time()
114
        # Restrict resolution to 1ms
115
        self._timestamp = round(timestamp, 3)
116
117
        if timezone is None:
118
            self._timezone = osutils.local_time_offset()
119
        else:
120
            self._timezone = int(timezone)
121
122
        self._generate_revision_if_needed()
2979.2.5 by Robert Collins
Make CommitBuilder.heads be _heads as its internal to CommitBuilder only.
123
        self.__heads = graph.HeadsCache(repository.get_graph()).heads
3879.2.3 by John Arbash Meinel
Hide the .basis_delta variable, and require callers to use .get_basis_delta()
124
        self._basis_delta = []
125
        # API compatibility, older code that used CommitBuilder did not call
126
        # .record_delete(), which means the delta that is computed would not be
127
        # valid. Callers that will call record_delete() should call
128
        # .will_record_deletes() to indicate that.
3775.2.2 by Robert Collins
Teach CommitBuilder to accumulate inventory deltas.
129
        self._recording_deletes = False
3775.2.7 by Robert Collins
CommitBuilder handles no-change commits to roots properly with record_iter_changes.
130
        # memo'd check for no-op commits.
3775.2.9 by Robert Collins
CommitBuilder handles deletes via record_iter_entries.
131
        self._any_changes = False
3775.2.7 by Robert Collins
CommitBuilder handles no-change commits to roots properly with record_iter_changes.
132
3775.2.9 by Robert Collins
CommitBuilder handles deletes via record_iter_entries.
133
    def any_changes(self):
3775.2.7 by Robert Collins
CommitBuilder handles no-change commits to roots properly with record_iter_changes.
134
        """Return True if any entries were changed.
135
        
136
        This includes merge-only changes. It is the core for the --unchanged
137
        detection in commit.
138
139
        :return: True if any changes have occured.
140
        """
3775.2.9 by Robert Collins
CommitBuilder handles deletes via record_iter_entries.
141
        return self._any_changes
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
142
3831.1.1 by John Arbash Meinel
Before allowing commit to succeed, verify the texts will be 'safe'.
143
    def _validate_unicode_text(self, text, context):
144
        """Verify things like commit messages don't have bogus characters."""
145
        if '\r' in text:
146
            raise ValueError('Invalid value for %s: %r' % (context, text))
147
148
    def _validate_revprops(self, revprops):
149
        for key, value in revprops.iteritems():
150
            # We know that the XML serializers do not round trip '\r'
151
            # correctly, so refuse to accept them
3831.1.5 by John Arbash Meinel
It seems we have some direct tests that don't use strings and expect a value error as well.
152
            if not isinstance(value, basestring):
153
                raise ValueError('revision property (%s) is not a valid'
154
                                 ' (unicode) string: %r' % (key, value))
3831.1.1 by John Arbash Meinel
Before allowing commit to succeed, verify the texts will be 'safe'.
155
            self._validate_unicode_text(value,
156
                                        'revision property (%s)' % (key,))
157
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
158
    def commit(self, message):
159
        """Make the actual commit.
160
161
        :return: The revision id of the recorded revision.
162
        """
3831.1.1 by John Arbash Meinel
Before allowing commit to succeed, verify the texts will be 'safe'.
163
        self._validate_unicode_text(message, 'commit message')
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
164
        rev = _mod_revision.Revision(
165
                       timestamp=self._timestamp,
166
                       timezone=self._timezone,
167
                       committer=self._committer,
168
                       message=message,
169
                       inventory_sha1=self.inv_sha1,
170
                       revision_id=self._new_revision_id,
171
                       properties=self._revprops)
172
        rev.parent_ids = self.parents
173
        self.repository.add_revision(self._new_revision_id, rev,
174
            self.new_inventory, self._config)
175
        self.repository.commit_write_group()
176
        return self._new_revision_id
177
178
    def abort(self):
179
        """Abort the commit that is being built.
180
        """
181
        self.repository.abort_write_group()
182
183
    def revision_tree(self):
184
        """Return the tree that was just committed.
185
186
        After calling commit() this can be called to get a RevisionTree
187
        representing the newly committed tree. This is preferred to
188
        calling Repository.revision_tree() because that may require
189
        deserializing the inventory, while we already have a copy in
190
        memory.
191
        """
3775.2.9 by Robert Collins
CommitBuilder handles deletes via record_iter_entries.
192
        if self.new_inventory is None:
193
            self.new_inventory = self.repository.get_inventory(
194
                self._new_revision_id)
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
195
        return RevisionTree(self.repository, self.new_inventory,
3775.2.9 by Robert Collins
CommitBuilder handles deletes via record_iter_entries.
196
            self._new_revision_id)
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
197
198
    def finish_inventory(self):
3775.2.4 by Robert Collins
Start on a CommitBuilder.record_iter_changes method.
199
        """Tell the builder that the inventory is finished.
200
        
201
        :return: The inventory id in the repository, which can be used with
202
            repository.get_inventory.
203
        """
204
        if self.new_inventory is None:
205
            # an inventory delta was accumulated without creating a new
206
            # inventory.
3775.2.29 by Robert Collins
Updates to the form of add_inventory_by_delta that landed in trunk.
207
            basis_id = self.basis_delta_revision
208
            self.inv_sha1 = self.repository.add_inventory_by_delta(
209
                basis_id, self._basis_delta, self._new_revision_id,
3775.2.9 by Robert Collins
CommitBuilder handles deletes via record_iter_entries.
210
                self.parents)
3775.2.4 by Robert Collins
Start on a CommitBuilder.record_iter_changes method.
211
        else:
212
            if self.new_inventory.root is None:
213
                raise AssertionError('Root entry should be supplied to'
214
                    ' record_entry_contents, as of bzr 0.10.')
215
                self.new_inventory.add(InventoryDirectory(ROOT_ID, '', None))
216
            self.new_inventory.revision_id = self._new_revision_id
217
            self.inv_sha1 = self.repository.add_inventory(
218
                self._new_revision_id,
219
                self.new_inventory,
220
                self.parents
221
                )
222
        return self._new_revision_id
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
223
224
    def _gen_revision_id(self):
225
        """Return new revision-id."""
226
        return generate_ids.gen_revision_id(self._config.username(),
227
                                            self._timestamp)
228
229
    def _generate_revision_if_needed(self):
230
        """Create a revision id if None was supplied.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
231
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
232
        If the repository can not support user-specified revision ids
233
        they should override this function and raise CannotSetRevisionId
234
        if _new_revision_id is not None.
235
236
        :raises: CannotSetRevisionId
237
        """
238
        if self._new_revision_id is None:
239
            self._new_revision_id = self._gen_revision_id()
240
            self.random_revid = True
241
        else:
242
            self.random_revid = False
243
2979.2.5 by Robert Collins
Make CommitBuilder.heads be _heads as its internal to CommitBuilder only.
244
    def _heads(self, file_id, revision_ids):
2979.2.1 by Robert Collins
Make it possible for different commit builders to override heads().
245
        """Calculate the graph heads for revision_ids in the graph of file_id.
246
247
        This can use either a per-file graph or a global revision graph as we
248
        have an identity relationship between the two graphs.
249
        """
2979.2.5 by Robert Collins
Make CommitBuilder.heads be _heads as its internal to CommitBuilder only.
250
        return self.__heads(revision_ids)
2979.2.1 by Robert Collins
Make it possible for different commit builders to override heads().
251
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
252
    def _check_root(self, ie, parent_invs, tree):
253
        """Helper for record_entry_contents.
254
255
        :param ie: An entry being added.
256
        :param parent_invs: The inventories of the parent revisions of the
257
            commit.
258
        :param tree: The tree that is being committed.
259
        """
2871.1.2 by Robert Collins
* ``CommitBuilder.record_entry_contents`` now requires the root entry of a
260
        # In this revision format, root entries have no knit or weave When
261
        # serializing out to disk and back in root.revision is always
262
        # _new_revision_id
263
        ie.revision = self._new_revision_id
2818.3.1 by Robert Collins
Change CommitBuilder factory delegation to allow simple declaration.
264
3775.2.9 by Robert Collins
CommitBuilder handles deletes via record_iter_entries.
265
    def _require_root_change(self, tree):
3775.2.7 by Robert Collins
CommitBuilder handles no-change commits to roots properly with record_iter_changes.
266
        """Enforce an appropriate root object change.
267
268
        This is called once when record_iter_changes is called, if and only if
269
        the root was not in the delta calculated by record_iter_changes.
3775.2.9 by Robert Collins
CommitBuilder handles deletes via record_iter_entries.
270
271
        :param tree: The tree which is being committed.
3775.2.7 by Robert Collins
CommitBuilder handles no-change commits to roots properly with record_iter_changes.
272
        """
273
        # NB: if there are no parents then this method is not called, so no
274
        # need to guard on parents having length.
3775.2.9 by Robert Collins
CommitBuilder handles deletes via record_iter_entries.
275
        entry = entry_factory['directory'](tree.path2id(''), '',
3775.2.7 by Robert Collins
CommitBuilder handles no-change commits to roots properly with record_iter_changes.
276
            None)
277
        entry.revision = self._new_revision_id
3775.2.29 by Robert Collins
Updates to the form of add_inventory_by_delta that landed in trunk.
278
        self._basis_delta.append(('', '', entry.file_id, entry))
3775.2.7 by Robert Collins
CommitBuilder handles no-change commits to roots properly with record_iter_changes.
279
2871.1.4 by Robert Collins
Merge bzr.dev.
280
    def _get_delta(self, ie, basis_inv, path):
281
        """Get a delta against the basis inventory for ie."""
282
        if ie.file_id not in basis_inv:
283
            # add
3775.2.2 by Robert Collins
Teach CommitBuilder to accumulate inventory deltas.
284
            result = (None, path, ie.file_id, ie)
3879.2.3 by John Arbash Meinel
Hide the .basis_delta variable, and require callers to use .get_basis_delta()
285
            self._basis_delta.append(result)
3775.2.2 by Robert Collins
Teach CommitBuilder to accumulate inventory deltas.
286
            return result
2871.1.4 by Robert Collins
Merge bzr.dev.
287
        elif ie != basis_inv[ie.file_id]:
288
            # common but altered
289
            # TODO: avoid tis id2path call.
3775.2.2 by Robert Collins
Teach CommitBuilder to accumulate inventory deltas.
290
            result = (basis_inv.id2path(ie.file_id), path, ie.file_id, ie)
3879.2.3 by John Arbash Meinel
Hide the .basis_delta variable, and require callers to use .get_basis_delta()
291
            self._basis_delta.append(result)
3775.2.2 by Robert Collins
Teach CommitBuilder to accumulate inventory deltas.
292
            return result
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
293
        else:
2871.1.4 by Robert Collins
Merge bzr.dev.
294
            # common, unaltered
295
            return None
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
296
3879.2.3 by John Arbash Meinel
Hide the .basis_delta variable, and require callers to use .get_basis_delta()
297
    def get_basis_delta(self):
298
        """Return the complete inventory delta versus the basis inventory.
299
300
        This has been built up with the calls to record_delete and
301
        record_entry_contents. The client must have already called
302
        will_record_deletes() to indicate that they will be generating a
303
        complete delta.
304
305
        :return: An inventory delta, suitable for use with apply_delta, or
306
            Repository.add_inventory_by_delta, etc.
307
        """
308
        if not self._recording_deletes:
309
            raise AssertionError("recording deletes not activated.")
310
        return self._basis_delta
311
3775.2.2 by Robert Collins
Teach CommitBuilder to accumulate inventory deltas.
312
    def record_delete(self, path, file_id):
313
        """Record that a delete occured against a basis tree.
314
315
        This is an optional API - when used it adds items to the basis_delta
316
        being accumulated by the commit builder. It cannot be called unless the
3879.2.3 by John Arbash Meinel
Hide the .basis_delta variable, and require callers to use .get_basis_delta()
317
        method will_record_deletes() has been called to inform the builder that
318
        a delta is being supplied.
3775.2.2 by Robert Collins
Teach CommitBuilder to accumulate inventory deltas.
319
320
        :param path: The path of the thing deleted.
321
        :param file_id: The file id that was deleted.
322
        """
323
        if not self._recording_deletes:
324
            raise AssertionError("recording deletes not activated.")
3879.2.5 by John Arbash Meinel
Change record_delete() to return the delta.
325
        delta = (path, None, file_id, None)
326
        self._basis_delta.append(delta)
327
        return delta
3775.2.2 by Robert Collins
Teach CommitBuilder to accumulate inventory deltas.
328
3879.2.3 by John Arbash Meinel
Hide the .basis_delta variable, and require callers to use .get_basis_delta()
329
    def will_record_deletes(self):
3775.2.2 by Robert Collins
Teach CommitBuilder to accumulate inventory deltas.
330
        """Tell the commit builder that deletes are being notified.
331
332
        This enables the accumulation of an inventory delta; for the resulting
3879.2.3 by John Arbash Meinel
Hide the .basis_delta variable, and require callers to use .get_basis_delta()
333
        commit to be valid, deletes against the basis MUST be recorded via
3775.2.2 by Robert Collins
Teach CommitBuilder to accumulate inventory deltas.
334
        builder.record_delete().
335
        """
336
        self._recording_deletes = True
3775.2.29 by Robert Collins
Updates to the form of add_inventory_by_delta that landed in trunk.
337
        try:
338
            basis_id = self.parents[0]
339
        except IndexError:
340
            basis_id = _mod_revision.NULL_REVISION
341
        self.basis_delta_revision = basis_id
3775.2.2 by Robert Collins
Teach CommitBuilder to accumulate inventory deltas.
342
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
343
    def record_entry_contents(self, ie, parent_invs, path, tree,
344
        content_summary):
345
        """Record the content of ie from tree into the commit if needed.
346
347
        Side effect: sets ie.revision when unchanged
348
349
        :param ie: An inventory entry present in the commit.
350
        :param parent_invs: The inventories of the parent revisions of the
351
            commit.
352
        :param path: The path the entry is at in the tree.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
353
        :param tree: The tree which contains this entry and should be used to
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
354
            obtain content.
355
        :param content_summary: Summary data from the tree about the paths
356
            content - stat, length, exec, sha/link target. This is only
357
            accessed when the entry has a revision of None - that is when it is
358
            a candidate to commit.
3709.3.1 by Robert Collins
First cut - make it work - at updating the tree stat cache during commit.
359
        :return: A tuple (change_delta, version_recorded, fs_hash).
360
            change_delta is an inventory_delta change for this entry against
361
            the basis tree of the commit, or None if no change occured against
362
            the basis tree.
2871.1.3 by Robert Collins
* The CommitBuilder method ``record_entry_contents`` now returns summary
363
            version_recorded is True if a new version of the entry has been
364
            recorded. For instance, committing a merge where a file was only
365
            changed on the other side will return (delta, False).
3709.3.3 by Robert Collins
NEWS for the record_entry_contents change.
366
            fs_hash is either None, or the hash details for the path (currently
367
            a tuple of the contents sha1 and the statvalue returned by
368
            tree.get_file_with_stat()).
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
369
        """
370
        if self.new_inventory.root is None:
2871.1.2 by Robert Collins
* ``CommitBuilder.record_entry_contents`` now requires the root entry of a
371
            if ie.parent_id is not None:
372
                raise errors.RootMissing()
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
373
            self._check_root(ie, parent_invs, tree)
374
        if ie.revision is None:
375
            kind = content_summary[0]
376
        else:
377
            # ie is carried over from a prior commit
378
            kind = ie.kind
379
        # XXX: repository specific check for nested tree support goes here - if
380
        # the repo doesn't want nested trees we skip it ?
381
        if (kind == 'tree-reference' and
382
            not self.repository._format.supports_tree_reference):
383
            # mismatch between commit builder logic and repository:
384
            # this needs the entry creation pushed down into the builder.
2776.4.18 by Robert Collins
Review feedback.
385
            raise NotImplementedError('Missing repository subtree support.')
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
386
        self.new_inventory.add(ie)
387
2871.1.3 by Robert Collins
* The CommitBuilder method ``record_entry_contents`` now returns summary
388
        # TODO: slow, take it out of the inner loop.
389
        try:
390
            basis_inv = parent_invs[0]
391
        except IndexError:
392
            basis_inv = Inventory(root_id=None)
393
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
394
        # ie.revision is always None if the InventoryEntry is considered
2776.4.13 by Robert Collins
Merge bzr.dev.
395
        # for committing. We may record the previous parents revision if the
396
        # content is actually unchanged against a sole head.
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
397
        if ie.revision is not None:
2903.2.5 by Martin Pool
record_entry_contents should give back deltas for changed roots; clean it up a bit
398
            if not self._versioned_root and path == '':
2871.1.3 by Robert Collins
* The CommitBuilder method ``record_entry_contents`` now returns summary
399
                # repositories that do not version the root set the root's
3775.2.2 by Robert Collins
Teach CommitBuilder to accumulate inventory deltas.
400
                # revision to the new commit even when no change occurs (more
401
                # specifically, they do not record a revision on the root; and
402
                # the rev id is assigned to the root during deserialisation -
403
                # this masks when a change may have occurred against the basis.
404
                # To match this we always issue a delta, because the revision
405
                # of the root will always be changing.
2903.2.5 by Martin Pool
record_entry_contents should give back deltas for changed roots; clean it up a bit
406
                if ie.file_id in basis_inv:
407
                    delta = (basis_inv.id2path(ie.file_id), path,
408
                        ie.file_id, ie)
409
                else:
2871.1.3 by Robert Collins
* The CommitBuilder method ``record_entry_contents`` now returns summary
410
                    # add
411
                    delta = (None, path, ie.file_id, ie)
3879.2.3 by John Arbash Meinel
Hide the .basis_delta variable, and require callers to use .get_basis_delta()
412
                self._basis_delta.append(delta)
3709.3.1 by Robert Collins
First cut - make it work - at updating the tree stat cache during commit.
413
                return delta, False, None
2903.2.5 by Martin Pool
record_entry_contents should give back deltas for changed roots; clean it up a bit
414
            else:
415
                # we don't need to commit this, because the caller already
416
                # determined that an existing revision of this file is
3619.1.1 by Robert Collins
Tighten up the handling of carried-over inventory entries.
417
                # appropriate. If its not being considered for committing then
418
                # it and all its parents to the root must be unaltered so
419
                # no-change against the basis.
420
                if ie.revision == self._new_revision_id:
421
                    raise AssertionError("Impossible situation, a skipped "
3619.1.2 by Robert Collins
Review feedback.
422
                        "inventory entry (%r) claims to be modified in this "
423
                        "commit (%r).", (ie, self._new_revision_id))
3709.3.1 by Robert Collins
First cut - make it work - at updating the tree stat cache during commit.
424
                return None, False, None
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
425
        # XXX: Friction: parent_candidates should return a list not a dict
426
        #      so that we don't have to walk the inventories again.
427
        parent_candiate_entries = ie.parent_candidates(parent_invs)
2979.2.5 by Robert Collins
Make CommitBuilder.heads be _heads as its internal to CommitBuilder only.
428
        head_set = self._heads(ie.file_id, parent_candiate_entries.keys())
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
429
        heads = []
430
        for inv in parent_invs:
431
            if ie.file_id in inv:
432
                old_rev = inv[ie.file_id].revision
433
                if old_rev in head_set:
434
                    heads.append(inv[ie.file_id].revision)
435
                    head_set.remove(inv[ie.file_id].revision)
436
437
        store = False
438
        # now we check to see if we need to write a new record to the
439
        # file-graph.
440
        # We write a new entry unless there is one head to the ancestors, and
441
        # the kind-derived content is unchanged.
442
443
        # Cheapest check first: no ancestors, or more the one head in the
444
        # ancestors, we write a new node.
445
        if len(heads) != 1:
446
            store = True
447
        if not store:
448
            # There is a single head, look it up for comparison
449
            parent_entry = parent_candiate_entries[heads[0]]
450
            # if the non-content specific data has changed, we'll be writing a
451
            # node:
452
            if (parent_entry.parent_id != ie.parent_id or
453
                parent_entry.name != ie.name):
454
                store = True
455
        # now we need to do content specific checks:
456
        if not store:
457
            # if the kind changed the content obviously has
458
            if kind != parent_entry.kind:
459
                store = True
3709.3.2 by Robert Collins
Race-free stat-fingerprint updating during commit via a new method get_file_with_stat.
460
        # Stat cache fingerprint feedback for the caller - None as we usually
461
        # don't generate one.
462
        fingerprint = None
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
463
        if kind == 'file':
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
464
            if content_summary[2] is None:
465
                raise ValueError("Files must not have executable = None")
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
466
            if not store:
467
                if (# if the file length changed we have to store:
468
                    parent_entry.text_size != content_summary[1] or
469
                    # if the exec bit has changed we have to store:
470
                    parent_entry.executable != content_summary[2]):
471
                    store = True
472
                elif parent_entry.text_sha1 == content_summary[3]:
473
                    # all meta and content is unchanged (using a hash cache
474
                    # hit to check the sha)
475
                    ie.revision = parent_entry.revision
476
                    ie.text_size = parent_entry.text_size
477
                    ie.text_sha1 = parent_entry.text_sha1
478
                    ie.executable = parent_entry.executable
3709.3.1 by Robert Collins
First cut - make it work - at updating the tree stat cache during commit.
479
                    return self._get_delta(ie, basis_inv, path), False, None
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
480
                else:
481
                    # Either there is only a hash change(no hash cache entry,
482
                    # or same size content change), or there is no change on
483
                    # this file at all.
2776.4.19 by Robert Collins
Final review tweaks.
484
                    # Provide the parent's hash to the store layer, so that the
485
                    # content is unchanged we will not store a new node.
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
486
                    nostore_sha = parent_entry.text_sha1
487
            if store:
2776.4.18 by Robert Collins
Review feedback.
488
                # We want to record a new node regardless of the presence or
489
                # absence of a content change in the file.
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
490
                nostore_sha = None
2776.4.18 by Robert Collins
Review feedback.
491
            ie.executable = content_summary[2]
3709.3.2 by Robert Collins
Race-free stat-fingerprint updating during commit via a new method get_file_with_stat.
492
            file_obj, stat_value = tree.get_file_with_stat(ie.file_id, path)
493
            try:
494
                lines = file_obj.readlines()
495
            finally:
496
                file_obj.close()
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
497
            try:
498
                ie.text_sha1, ie.text_size = self._add_text_to_weave(
499
                    ie.file_id, lines, heads, nostore_sha)
3709.3.2 by Robert Collins
Race-free stat-fingerprint updating during commit via a new method get_file_with_stat.
500
                # Let the caller know we generated a stat fingerprint.
501
                fingerprint = (ie.text_sha1, stat_value)
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
502
            except errors.ExistingContent:
2776.4.18 by Robert Collins
Review feedback.
503
                # Turns out that the file content was unchanged, and we were
504
                # only going to store a new node if it was changed. Carry over
505
                # the entry.
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
506
                ie.revision = parent_entry.revision
507
                ie.text_size = parent_entry.text_size
508
                ie.text_sha1 = parent_entry.text_sha1
509
                ie.executable = parent_entry.executable
3709.3.1 by Robert Collins
First cut - make it work - at updating the tree stat cache during commit.
510
                return self._get_delta(ie, basis_inv, path), False, None
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
511
        elif kind == 'directory':
512
            if not store:
513
                # all data is meta here, nothing specific to directory, so
514
                # carry over:
515
                ie.revision = parent_entry.revision
3709.3.1 by Robert Collins
First cut - make it work - at updating the tree stat cache during commit.
516
                return self._get_delta(ie, basis_inv, path), False, None
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
517
            lines = []
518
            self._add_text_to_weave(ie.file_id, lines, heads, None)
519
        elif kind == 'symlink':
520
            current_link_target = content_summary[3]
521
            if not store:
2776.4.18 by Robert Collins
Review feedback.
522
                # symlink target is not generic metadata, check if it has
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
523
                # changed.
524
                if current_link_target != parent_entry.symlink_target:
525
                    store = True
526
            if not store:
527
                # unchanged, carry over.
528
                ie.revision = parent_entry.revision
529
                ie.symlink_target = parent_entry.symlink_target
3709.3.1 by Robert Collins
First cut - make it work - at updating the tree stat cache during commit.
530
                return self._get_delta(ie, basis_inv, path), False, None
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
531
            ie.symlink_target = current_link_target
532
            lines = []
533
            self._add_text_to_weave(ie.file_id, lines, heads, None)
534
        elif kind == 'tree-reference':
535
            if not store:
536
                if content_summary[3] != parent_entry.reference_revision:
537
                    store = True
538
            if not store:
539
                # unchanged, carry over.
540
                ie.reference_revision = parent_entry.reference_revision
541
                ie.revision = parent_entry.revision
3709.3.1 by Robert Collins
First cut - make it work - at updating the tree stat cache during commit.
542
                return self._get_delta(ie, basis_inv, path), False, None
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
543
            ie.reference_revision = content_summary[3]
544
            lines = []
545
            self._add_text_to_weave(ie.file_id, lines, heads, None)
546
        else:
547
            raise NotImplementedError('unknown kind')
548
        ie.revision = self._new_revision_id
3775.2.9 by Robert Collins
CommitBuilder handles deletes via record_iter_entries.
549
        self._any_changes = True
3709.3.2 by Robert Collins
Race-free stat-fingerprint updating during commit via a new method get_file_with_stat.
550
        return self._get_delta(ie, basis_inv, path), True, fingerprint
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
551
3775.2.30 by Robert Collins
Remove the basis_tree parameter to record_iter_changes.
552
    def record_iter_changes(self, tree, basis_revision_id, iter_changes,
553
        _entry_factory=entry_factory):
3775.2.4 by Robert Collins
Start on a CommitBuilder.record_iter_changes method.
554
        """Record a new tree via iter_changes.
555
3775.2.9 by Robert Collins
CommitBuilder handles deletes via record_iter_entries.
556
        :param tree: The tree to obtain text contents from for changed objects.
3775.2.4 by Robert Collins
Start on a CommitBuilder.record_iter_changes method.
557
        :param basis_revision_id: The revision id of the tree the iter_changes
3775.2.29 by Robert Collins
Updates to the form of add_inventory_by_delta that landed in trunk.
558
            has been generated against. Currently assumed to be the same
559
            as self.parents[0] - if it is not, errors may occur.
560
        :param iter_changes: An iter_changes iterator with the changes to apply
561
            to basis_revision_id.
3775.2.4 by Robert Collins
Start on a CommitBuilder.record_iter_changes method.
562
        :param _entry_factory: Private method to bind entry_factory locally for
563
            performance.
564
        :return: None
565
        """
566
        # Create an inventory delta based on deltas between all the parents and
567
        # deltas between all the parent inventories. We use inventory delta's 
568
        # between the inventory objects because iter_changes masks
569
        # last-changed-field only changes.
3775.2.29 by Robert Collins
Updates to the form of add_inventory_by_delta that landed in trunk.
570
        # Working data:
3775.2.4 by Robert Collins
Start on a CommitBuilder.record_iter_changes method.
571
        # file_id -> change map, change is fileid, paths, changed, versioneds,
572
        # parents, names, kinds, executables
3775.2.11 by Robert Collins
CommitBuilder handles renamed directory and unmodified entries with single parents, for record_iter_changes.
573
        merged_ids = {}
3775.2.32 by Robert Collins
Trivial review feedback.
574
        # {file_id -> revision_id -> inventory entry, for entries in parent
3775.2.22 by Robert Collins
CommitBuilder.record_iter_changes handles changed-in-branch directories.
575
        # trees that are not parents[0]
576
        parent_entries = {}
3775.2.29 by Robert Collins
Updates to the form of add_inventory_by_delta that landed in trunk.
577
        revtrees = list(self.repository.revision_trees(self.parents))
578
        # The basis inventory from a repository 
579
        if revtrees:
580
            basis_inv = revtrees[0].inventory
581
        else:
582
            basis_inv = self.repository.revision_tree(
583
                _mod_revision.NULL_REVISION).inventory
3775.2.32 by Robert Collins
Trivial review feedback.
584
        if len(self.parents) > 0:
3775.2.29 by Robert Collins
Updates to the form of add_inventory_by_delta that landed in trunk.
585
            if basis_revision_id != self.parents[0]:
586
                raise Exception(
587
                    "arbitrary basis parents not yet supported with merges")
3775.2.11 by Robert Collins
CommitBuilder handles renamed directory and unmodified entries with single parents, for record_iter_changes.
588
            for revtree in revtrees[1:]:
3775.2.32 by Robert Collins
Trivial review feedback.
589
                for change in revtree.inventory._make_delta(basis_inv):
3775.2.11 by Robert Collins
CommitBuilder handles renamed directory and unmodified entries with single parents, for record_iter_changes.
590
                    if change[1] is None:
3775.2.32 by Robert Collins
Trivial review feedback.
591
                        # Not present in this parent.
3775.2.11 by Robert Collins
CommitBuilder handles renamed directory and unmodified entries with single parents, for record_iter_changes.
592
                        continue
593
                    if change[2] not in merged_ids:
594
                        if change[0] is not None:
3775.2.19 by Robert Collins
CommitBuilder.record_iter_changes handles merged directories.
595
                            merged_ids[change[2]] = [
3775.2.32 by Robert Collins
Trivial review feedback.
596
                                basis_inv[change[2]].revision,
3775.2.19 by Robert Collins
CommitBuilder.record_iter_changes handles merged directories.
597
                                change[3].revision]
3775.2.11 by Robert Collins
CommitBuilder handles renamed directory and unmodified entries with single parents, for record_iter_changes.
598
                        else:
3775.2.19 by Robert Collins
CommitBuilder.record_iter_changes handles merged directories.
599
                            merged_ids[change[2]] = [change[3].revision]
3775.2.22 by Robert Collins
CommitBuilder.record_iter_changes handles changed-in-branch directories.
600
                        parent_entries[change[2]] = {change[3].revision:change[3]}
3775.2.11 by Robert Collins
CommitBuilder handles renamed directory and unmodified entries with single parents, for record_iter_changes.
601
                    else:
3775.2.19 by Robert Collins
CommitBuilder.record_iter_changes handles merged directories.
602
                        merged_ids[change[2]].append(change[3].revision)
3775.2.22 by Robert Collins
CommitBuilder.record_iter_changes handles changed-in-branch directories.
603
                        parent_entries[change[2]][change[3].revision] = change[3]
3775.2.11 by Robert Collins
CommitBuilder handles renamed directory and unmodified entries with single parents, for record_iter_changes.
604
        else:
605
            merged_ids = {}
3775.2.29 by Robert Collins
Updates to the form of add_inventory_by_delta that landed in trunk.
606
        # Setup the changes from the tree:
3775.2.32 by Robert Collins
Trivial review feedback.
607
        # changes maps file_id -> (change, [parent revision_ids])
3775.2.4 by Robert Collins
Start on a CommitBuilder.record_iter_changes method.
608
        changes= {}
609
        for change in iter_changes:
3775.2.19 by Robert Collins
CommitBuilder.record_iter_changes handles merged directories.
610
            # This probably looks up in basis_inv way to much.
3775.2.29 by Robert Collins
Updates to the form of add_inventory_by_delta that landed in trunk.
611
            if change[1][0] is not None:
612
                head_candidate = [basis_inv[change[0]].revision]
613
            else:
614
                head_candidate = []
615
            changes[change[0]] = change, merged_ids.get(change[0],
616
                head_candidate)
3775.2.11 by Robert Collins
CommitBuilder handles renamed directory and unmodified entries with single parents, for record_iter_changes.
617
        unchanged_merged = set(merged_ids) - set(changes)
3775.2.29 by Robert Collins
Updates to the form of add_inventory_by_delta that landed in trunk.
618
        # Extend the changes dict with synthetic changes to record merges of
619
        # texts.
3775.2.19 by Robert Collins
CommitBuilder.record_iter_changes handles merged directories.
620
        for file_id in unchanged_merged:
3775.2.22 by Robert Collins
CommitBuilder.record_iter_changes handles changed-in-branch directories.
621
            # Record a merged version of these items that did not change vs the
622
            # basis. This can be either identical parallel changes, or a revert
623
            # of a specific file after a merge. The recorded content will be
624
            # that of the current tree (which is the same as the basis), but
625
            # the per-file graph will reflect a merge.
3775.2.19 by Robert Collins
CommitBuilder.record_iter_changes handles merged directories.
626
            # NB:XXX: We are reconstructing path information we had, this
627
            # should be preserved instead.
628
            # inv delta  change: (file_id, (path_in_source, path_in_target),
629
            #   changed_content, versioned, parent, name, kind,
630
            #   executable)
3775.2.32 by Robert Collins
Trivial review feedback.
631
            basis_entry = basis_inv[file_id]
3775.2.19 by Robert Collins
CommitBuilder.record_iter_changes handles merged directories.
632
            change = (file_id,
633
                (basis_inv.id2path(file_id), tree.id2path(file_id)),
634
                False, (True, True),
635
                (basis_entry.parent_id, basis_entry.parent_id),
636
                (basis_entry.name, basis_entry.name),
637
                (basis_entry.kind, basis_entry.kind),
638
                (basis_entry.executable, basis_entry.executable))
639
            changes[file_id] = (change, merged_ids[file_id])
3775.2.11 by Robert Collins
CommitBuilder handles renamed directory and unmodified entries with single parents, for record_iter_changes.
640
        # changes contains tuples with the change and a set of inventory
641
        # candidates for the file.
3775.2.4 by Robert Collins
Start on a CommitBuilder.record_iter_changes method.
642
        # inv delta is:
643
        # old_path, new_path, file_id, new_inventory_entry
3775.2.7 by Robert Collins
CommitBuilder handles no-change commits to roots properly with record_iter_changes.
644
        seen_root = False # Is the root in the basis delta?
3775.2.29 by Robert Collins
Updates to the form of add_inventory_by_delta that landed in trunk.
645
        inv_delta = self._basis_delta
3775.2.4 by Robert Collins
Start on a CommitBuilder.record_iter_changes method.
646
        modified_rev = self._new_revision_id
3775.2.11 by Robert Collins
CommitBuilder handles renamed directory and unmodified entries with single parents, for record_iter_changes.
647
        for change, head_candidates in changes.values():
3775.2.4 by Robert Collins
Start on a CommitBuilder.record_iter_changes method.
648
            if change[3][1]: # versioned in target.
3775.2.22 by Robert Collins
CommitBuilder.record_iter_changes handles changed-in-branch directories.
649
                # Several things may be happening here:
650
                # We may have a fork in the per-file graph
651
                #  - record a change with the content from tree
652
                # We may have a change against < all trees  
653
                #  - carry over the tree that hasn't changed
654
                # We may have a change against all trees
655
                #  - record the change with the content from tree
3775.2.11 by Robert Collins
CommitBuilder handles renamed directory and unmodified entries with single parents, for record_iter_changes.
656
                kind = change[6][1]
3775.2.12 by Robert Collins
CommitBuilder.record_iter_changes handles renamed files.
657
                file_id = change[0]
658
                entry = _entry_factory[kind](file_id, change[5][1],
659
                    change[4][1])
3775.2.19 by Robert Collins
CommitBuilder.record_iter_changes handles merged directories.
660
                head_set = self._heads(change[0], set(head_candidates))
661
                heads = []
662
                # Preserve ordering.
663
                for head_candidate in head_candidates:
664
                    if head_candidate in head_set:
665
                        heads.append(head_candidate)
666
                        head_set.remove(head_candidate)
3775.2.22 by Robert Collins
CommitBuilder.record_iter_changes handles changed-in-branch directories.
667
                carried_over = False
3775.2.33 by Robert Collins
Fix bug with merges of new files, increasing test coverage to ensure its kept fixed.
668
                if len(heads) == 1:
3775.2.22 by Robert Collins
CommitBuilder.record_iter_changes handles changed-in-branch directories.
669
                    # Could be a carry-over situation:
3775.2.34 by Robert Collins
Handle committing new files again.
670
                    parent_entry_revs = parent_entries.get(file_id, None)
671
                    if parent_entry_revs:
672
                        parent_entry = parent_entry_revs.get(heads[0], None)
673
                    else:
674
                        parent_entry = None
3775.2.22 by Robert Collins
CommitBuilder.record_iter_changes handles changed-in-branch directories.
675
                    if parent_entry is None:
676
                        # The parent iter_changes was called against is the one
677
                        # that is the per-file head, so any change is relevant
678
                        # iter_changes is valid.
679
                        carry_over_possible = False
680
                    else:
681
                        # could be a carry over situation
682
                        # A change against the basis may just indicate a merge,
683
                        # we need to check the content against the source of the
684
                        # merge to determine if it was changed after the merge
685
                        # or carried over.
3775.2.23 by Robert Collins
CommitBuilder.record_iter_changes handles changed-in-branch files.
686
                        if (parent_entry.kind != entry.kind or
687
                            parent_entry.parent_id != entry.parent_id or
3775.2.22 by Robert Collins
CommitBuilder.record_iter_changes handles changed-in-branch directories.
688
                            parent_entry.name != entry.name):
689
                            # Metadata common to all entries has changed
690
                            # against per-file parent
691
                            carry_over_possible = False
692
                        else:
693
                            carry_over_possible = True
694
                        # per-type checks for changes against the parent_entry
695
                        # are done below.
696
                else:
697
                    # Cannot be a carry-over situation
698
                    carry_over_possible = False
699
                # Populate the entry in the delta
700
                if kind == 'file':
3775.2.23 by Robert Collins
CommitBuilder.record_iter_changes handles changed-in-branch files.
701
                    # XXX: There is still a small race here: If someone reverts the content of a file
702
                    # after iter_changes examines and decides it has changed,
703
                    # we will unconditionally record a new version even if some
704
                    # other process reverts it while commit is running (with
705
                    # the revert happening after iter_changes did it's
706
                    # examination).
707
                    if change[7][1]:
708
                        entry.executable = True
709
                    else:
710
                        entry.executable = False
711
                    if (carry_over_possible and 
712
                        parent_entry.executable == entry.executable):
713
                            # Check the file length, content hash after reading
714
                            # the file.
715
                            nostore_sha = parent_entry.text_sha1
716
                    else:
717
                        nostore_sha = None
718
                    file_obj, stat_value = tree.get_file_with_stat(file_id, change[1][1])
719
                    try:
720
                        lines = file_obj.readlines()
721
                    finally:
722
                        file_obj.close()
723
                    try:
724
                        entry.text_sha1, entry.text_size = self._add_text_to_weave(
725
                            file_id, lines, heads, nostore_sha)
726
                    except errors.ExistingContent:
727
                        # No content change against a carry_over parent
728
                        carried_over = True
729
                        entry.text_size = parent_entry.text_size
730
                        entry.text_sha1 = parent_entry.text_sha1
3775.2.22 by Robert Collins
CommitBuilder.record_iter_changes handles changed-in-branch directories.
731
                elif kind == 'symlink':
3775.2.24 by Robert Collins
CommitBuilder.record_iter_changes handles changed-in-branch symlinks.
732
                    # Wants a path hint?
733
                    entry.symlink_target = tree.get_symlink_target(file_id)
734
                    if (carry_over_possible and
735
                        parent_entry.symlink_target == entry.symlink_target):
736
                            carried_over = True
3775.2.22 by Robert Collins
CommitBuilder.record_iter_changes handles changed-in-branch directories.
737
                    else:
3775.2.13 by Robert Collins
CommitBuilder.record_iter_changes handles renamed symlinks.
738
                        self._add_text_to_weave(change[0], [], heads, None)
3775.2.22 by Robert Collins
CommitBuilder.record_iter_changes handles changed-in-branch directories.
739
                elif kind == 'directory':
740
                    if carry_over_possible:
741
                        carried_over = True
742
                    else:
3775.2.19 by Robert Collins
CommitBuilder.record_iter_changes handles merged directories.
743
                        # Nothing to set on the entry.
744
                        # XXX: split into the Root and nonRoot versions.
745
                        if change[1][1] != '' or self.repository.supports_rich_root():
746
                            self._add_text_to_weave(change[0], [], heads, None)
3775.2.22 by Robert Collins
CommitBuilder.record_iter_changes handles changed-in-branch directories.
747
                elif kind == 'tree-reference':
3775.2.27 by Robert Collins
CommitBuilder.record_iter_changes handles files becoming directories and links.
748
                    raise AssertionError('unknown kind %r' % kind)
3775.2.22 by Robert Collins
CommitBuilder.record_iter_changes handles changed-in-branch directories.
749
                else:
3775.2.27 by Robert Collins
CommitBuilder.record_iter_changes handles files becoming directories and links.
750
                    raise AssertionError('unknown kind %r' % kind)
3775.2.22 by Robert Collins
CommitBuilder.record_iter_changes handles changed-in-branch directories.
751
                if not carried_over:
752
                    entry.revision = modified_rev
3775.2.23 by Robert Collins
CommitBuilder.record_iter_changes handles changed-in-branch files.
753
                else:
754
                    entry.revision = parent_entry.revision
3775.2.4 by Robert Collins
Start on a CommitBuilder.record_iter_changes method.
755
            else:
756
                entry = None
3775.2.7 by Robert Collins
CommitBuilder handles no-change commits to roots properly with record_iter_changes.
757
            new_path = change[1][1]
758
            inv_delta.append((change[1][0], new_path, change[0], entry))
759
            if new_path == '':
760
                seen_root = True
3775.2.4 by Robert Collins
Start on a CommitBuilder.record_iter_changes method.
761
        self.new_inventory = None
3775.2.7 by Robert Collins
CommitBuilder handles no-change commits to roots properly with record_iter_changes.
762
        if len(inv_delta):
3775.2.9 by Robert Collins
CommitBuilder handles deletes via record_iter_entries.
763
            self._any_changes = True
3775.2.7 by Robert Collins
CommitBuilder handles no-change commits to roots properly with record_iter_changes.
764
        if not seen_root:
765
            # housekeeping root entry changes do not affect no-change commits.
3775.2.9 by Robert Collins
CommitBuilder handles deletes via record_iter_entries.
766
            self._require_root_change(tree)
3775.2.29 by Robert Collins
Updates to the form of add_inventory_by_delta that landed in trunk.
767
        self.basis_delta_revision = basis_revision_id
3775.2.4 by Robert Collins
Start on a CommitBuilder.record_iter_changes method.
768
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
769
    def _add_text_to_weave(self, file_id, new_lines, parents, nostore_sha):
2592.3.136 by Robert Collins
Merge bzr.dev.
770
        # Note: as we read the content directly from the tree, we know its not
771
        # been turned into unicode or badly split - but a broken tree
772
        # implementation could give us bad output from readlines() so this is
773
        # not a guarantee of safety. What would be better is always checking
774
        # the content during test suite execution. RBC 20070912
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
775
        parent_keys = tuple((file_id, parent) for parent in parents)
776
        return self.repository.texts.add_lines(
777
            (file_id, self._new_revision_id), parent_keys, new_lines,
3316.2.12 by Robert Collins
Catch some extra deprecated calls.
778
            nostore_sha=nostore_sha, random_id=self.random_revid,
779
            check_content=False)[0:2]
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
780
781
782
class RootCommitBuilder(CommitBuilder):
783
    """This commitbuilder actually records the root id"""
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
784
2825.5.2 by Robert Collins
Review feedback, and fix pointless commits with nested trees to raise PointlessCommit appropriately.
785
    # the root entry gets versioned properly by this builder.
2840.1.1 by Ian Clatworthy
faster pointless commit detection (Robert Collins)
786
    _versioned_root = True
2825.5.2 by Robert Collins
Review feedback, and fix pointless commits with nested trees to raise PointlessCommit appropriately.
787
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
788
    def _check_root(self, ie, parent_invs, tree):
789
        """Helper for record_entry_contents.
790
791
        :param ie: An entry being added.
792
        :param parent_invs: The inventories of the parent revisions of the
793
            commit.
794
        :param tree: The tree that is being committed.
795
        """
796
3775.2.9 by Robert Collins
CommitBuilder handles deletes via record_iter_entries.
797
    def _require_root_change(self, tree):
3775.2.7 by Robert Collins
CommitBuilder handles no-change commits to roots properly with record_iter_changes.
798
        """Enforce an appropriate root object change.
799
800
        This is called once when record_iter_changes is called, if and only if
801
        the root was not in the delta calculated by record_iter_changes.
3775.2.9 by Robert Collins
CommitBuilder handles deletes via record_iter_entries.
802
803
        :param tree: The tree which is being committed.
3775.2.7 by Robert Collins
CommitBuilder handles no-change commits to roots properly with record_iter_changes.
804
        """
805
        # versioned roots do not change unless the tree found a change.
806
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
807
2220.2.3 by Martin Pool
Add tag: revision namespace.
808
######################################################################
809
# Repositories
810
1185.66.5 by Aaron Bentley
Renamed RevisionStorage to Repository
811
class Repository(object):
1185.70.3 by Martin Pool
Various updates to make storage branch mergeable:
812
    """Repository holding history for one or more branches.
813
814
    The repository holds and retrieves historical information including
815
    revisions and file history.  It's normally accessed only by the Branch,
816
    which views a particular line of development through that history.
817
3350.6.7 by Robert Collins
Review feedback, making things more clear, adding documentation on what is used where.
818
    The Repository builds on top of some byte storage facilies (the revisions,
819
    signatures, inventories and texts attributes) and a Transport, which
820
    respectively provide byte storage and a means to access the (possibly
1185.70.3 by Martin Pool
Various updates to make storage branch mergeable:
821
    remote) disk.
3407.2.13 by Martin Pool
Remove indirection through control_files to get transports
822
3350.6.7 by Robert Collins
Review feedback, making things more clear, adding documentation on what is used where.
823
    The byte storage facilities are addressed via tuples, which we refer to
824
    as 'keys' throughout the code base. Revision_keys, inventory_keys and
825
    signature_keys are all 1-tuples: (revision_id,). text_keys are two-tuples:
826
    (file_id, revision_id). We use this interface because it allows low
827
    friction with the underlying code that implements disk indices, network
828
    encoding and other parts of bzrlib.
829
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
830
    :ivar revisions: A bzrlib.versionedfile.VersionedFiles instance containing
831
        the serialised revisions for the repository. This can be used to obtain
832
        revision graph information or to access raw serialised revisions.
833
        The result of trying to insert data into the repository via this store
834
        is undefined: it should be considered read-only except for implementors
835
        of repositories.
3350.6.7 by Robert Collins
Review feedback, making things more clear, adding documentation on what is used where.
836
    :ivar signatures: A bzrlib.versionedfile.VersionedFiles instance containing
837
        the serialised signatures for the repository. This can be used to
838
        obtain access to raw serialised signatures.  The result of trying to
839
        insert data into the repository via this store is undefined: it should
840
        be considered read-only except for implementors of repositories.
841
    :ivar inventories: A bzrlib.versionedfile.VersionedFiles instance containing
842
        the serialised inventories for the repository. This can be used to
843
        obtain unserialised inventories.  The result of trying to insert data
844
        into the repository via this store is undefined: it should be
845
        considered read-only except for implementors of repositories.
846
    :ivar texts: A bzrlib.versionedfile.VersionedFiles instance containing the
847
        texts of files and directories for the repository. This can be used to
848
        obtain file texts or file graphs. Note that Repository.iter_file_bytes
849
        is usually a better interface for accessing file texts.
850
        The result of trying to insert data into the repository via this store
851
        is undefined: it should be considered read-only except for implementors
852
        of repositories.
3407.2.13 by Martin Pool
Remove indirection through control_files to get transports
853
    :ivar _transport: Transport for file access to repository, typically
854
        pointing to .bzr/repository.
1185.70.3 by Martin Pool
Various updates to make storage branch mergeable:
855
    """
1185.65.17 by Robert Collins
Merge from integration, mode-changes are broken.
856
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
857
    # What class to use for a CommitBuilder. Often its simpler to change this
858
    # in a Repository class subclass rather than to override
859
    # get_commit_builder.
860
    _commit_builder_class = CommitBuilder
861
    # The search regex used by xml based repositories to determine what things
862
    # where changed in a single commit.
2163.2.1 by John Arbash Meinel
Speed up the fileids_altered_by_revision_ids processing
863
    _file_ids_altered_regex = lazy_regex.lazy_compile(
864
        r'file_id="(?P<file_id>[^"]+)"'
2776.4.6 by Robert Collins
Fixup various commit test failures falling out from the other commit changes.
865
        r'.* revision="(?P<revision_id>[^"]+)"'
2163.2.1 by John Arbash Meinel
Speed up the fileids_altered_by_revision_ids processing
866
        )
867
3825.4.1 by Andrew Bennetts
Add suppress_errors to abort_write_group.
868
    def abort_write_group(self, suppress_errors=False):
2617.6.2 by Robert Collins
Add abort_write_group and wire write_groups into fetch and commit.
869
        """Commit the contents accrued within the current write group.
870
3825.4.6 by Andrew Bennetts
Document the suppress_errors flag in the docstring.
871
        :param suppress_errors: if true, abort_write_group will catch and log
872
            unexpected errors that happen during the abort, rather than
873
            allowing them to propagate.  Defaults to False.
874
2617.6.2 by Robert Collins
Add abort_write_group and wire write_groups into fetch and commit.
875
        :seealso: start_write_group.
876
        """
877
        if self._write_group is not self.get_transaction():
878
            # has an unlock or relock occured ?
879
            raise errors.BzrError('mismatched lock context and write group.')
3825.4.1 by Andrew Bennetts
Add suppress_errors to abort_write_group.
880
        try:
881
            self._abort_write_group()
882
        except Exception, exc:
883
            self._write_group = None
884
            if not suppress_errors:
885
                raise
886
            mutter('abort_write_group failed')
887
            log_exception_quietly()
888
            note('bzr: ERROR (ignored): %s', exc)
2617.6.2 by Robert Collins
Add abort_write_group and wire write_groups into fetch and commit.
889
        self._write_group = None
890
891
    def _abort_write_group(self):
892
        """Template method for per-repository write group cleanup.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
893
894
        This is called during abort before the write group is considered to be
2617.6.2 by Robert Collins
Add abort_write_group and wire write_groups into fetch and commit.
895
        finished and should cleanup any internal state accrued during the write
896
        group. There is no requirement that data handed to the repository be
897
        *not* made available - this is not a rollback - but neither should any
898
        attempt be made to ensure that data added is fully commited. Abort is
899
        invoked when an error has occured so futher disk or network operations
900
        may not be possible or may error and if possible should not be
901
        attempted.
902
        """
903
3221.12.1 by Robert Collins
Backport development1 format (stackable packs) to before-shallow-branches.
904
    def add_fallback_repository(self, repository):
905
        """Add a repository to use for looking up data not held locally.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
906
3221.12.1 by Robert Collins
Backport development1 format (stackable packs) to before-shallow-branches.
907
        :param repository: A repository.
908
        """
909
        if not self._format.supports_external_lookups:
910
            raise errors.UnstackableRepositoryFormat(self._format, self.base)
3582.1.7 by Martin Pool
add_fallback_repository gives more detail on incompatibilities
911
        self._check_fallback_repository(repository)
3221.12.1 by Robert Collins
Backport development1 format (stackable packs) to before-shallow-branches.
912
        self._fallback_repositories.append(repository)
3221.12.13 by Robert Collins
Implement generic stacking rather than pack-internals based stacking.
913
        self.texts.add_fallback_versioned_files(repository.texts)
914
        self.inventories.add_fallback_versioned_files(repository.inventories)
915
        self.revisions.add_fallback_versioned_files(repository.revisions)
916
        self.signatures.add_fallback_versioned_files(repository.signatures)
3221.12.1 by Robert Collins
Backport development1 format (stackable packs) to before-shallow-branches.
917
3582.1.7 by Martin Pool
add_fallback_repository gives more detail on incompatibilities
918
    def _check_fallback_repository(self, repository):
3221.12.4 by Robert Collins
Implement basic repository supporting external references.
919
        """Check that this repository can fallback to repository safely.
3582.1.7 by Martin Pool
add_fallback_repository gives more detail on incompatibilities
920
921
        Raise an error if not.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
922
3221.12.4 by Robert Collins
Implement basic repository supporting external references.
923
        :param repository: A repository to fallback to.
924
        """
3582.1.7 by Martin Pool
add_fallback_repository gives more detail on incompatibilities
925
        return InterRepository._assert_same_model(self, repository)
3221.12.4 by Robert Collins
Implement basic repository supporting external references.
926
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
927
    def add_inventory(self, revision_id, inv, parents):
928
        """Add the inventory inv to the repository as revision_id.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
929
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
930
        :param parents: The revision ids of the parents that revision_id
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
931
                        is known to have and are in the repository already.
932
3169.2.1 by Robert Collins
New method ``iter_inventories`` on Repository for access to many
933
        :returns: The validator(which is a sha1 digest, though what is sha'd is
934
            repository format specific) of the serialized inventory.
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
935
        """
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
936
        if not self.is_in_write_group():
937
            raise AssertionError("%r not in write group" % (self,))
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
938
        _mod_revision.check_not_reserved_id(revision_id)
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
939
        if not (inv.revision_id is None or inv.revision_id == revision_id):
940
            raise AssertionError(
941
                "Mismatch between inventory revision"
942
                " id and insertion revid (%r, %r)"
943
                % (inv.revision_id, revision_id))
944
        if inv.root is None:
945
            raise AssertionError()
2817.2.1 by Robert Collins
* Inventory serialisation no longer double-sha's the content.
946
        inv_lines = self._serialise_inventory_to_lines(inv)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
947
        return self._inventory_add_lines(revision_id, parents,
2817.2.1 by Robert Collins
* Inventory serialisation no longer double-sha's the content.
948
            inv_lines, check_content=False)
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
949
3879.2.2 by John Arbash Meinel
Rename add_inventory_delta to add_inventory_by_delta.
950
    def add_inventory_by_delta(self, basis_revision_id, delta, new_revision_id,
951
                               parents):
3775.2.1 by Robert Collins
Create bzrlib.repository.Repository.add_inventory_delta for adding inventories via deltas.
952
        """Add a new inventory expressed as a delta against another revision.
3879.2.2 by John Arbash Meinel
Rename add_inventory_delta to add_inventory_by_delta.
953
3775.2.1 by Robert Collins
Create bzrlib.repository.Repository.add_inventory_delta for adding inventories via deltas.
954
        :param basis_revision_id: The inventory id the delta was created
3879.2.2 by John Arbash Meinel
Rename add_inventory_delta to add_inventory_by_delta.
955
            against. (This does not have to be a direct parent.)
3775.2.1 by Robert Collins
Create bzrlib.repository.Repository.add_inventory_delta for adding inventories via deltas.
956
        :param delta: The inventory delta (see Inventory.apply_delta for
957
            details).
958
        :param new_revision_id: The revision id that the inventory is being
959
            added for.
960
        :param parents: The revision ids of the parents that revision_id is
961
            known to have and are in the repository already. These are supplied
962
            for repositories that depend on the inventory graph for revision
963
            graph access, as well as for those that pun ancestry with delta
964
            compression.
965
3879.3.1 by John Arbash Meinel
Change the return of add_inventory_by_delta to also return the Inventory.
966
        :returns: (validator, new_inv)
967
            The validator(which is a sha1 digest, though what is sha'd is
968
            repository format specific) of the serialized inventory, and the
969
            resulting inventory.
3775.2.1 by Robert Collins
Create bzrlib.repository.Repository.add_inventory_delta for adding inventories via deltas.
970
        """
971
        if not self.is_in_write_group():
972
            raise AssertionError("%r not in write group" % (self,))
973
        _mod_revision.check_not_reserved_id(new_revision_id)
974
        basis_tree = self.revision_tree(basis_revision_id)
975
        basis_tree.lock_read()
976
        try:
977
            # Note that this mutates the inventory of basis_tree, which not all
978
            # inventory implementations may support: A better idiom would be to
979
            # return a new inventory, but as there is no revision tree cache in
980
            # repository this is safe for now - RBC 20081013
981
            basis_inv = basis_tree.inventory
982
            basis_inv.apply_delta(delta)
983
            basis_inv.revision_id = new_revision_id
3879.3.1 by John Arbash Meinel
Change the return of add_inventory_by_delta to also return the Inventory.
984
            return (self.add_inventory(new_revision_id, basis_inv, parents),
985
                    basis_inv)
3775.2.1 by Robert Collins
Create bzrlib.repository.Repository.add_inventory_delta for adding inventories via deltas.
986
        finally:
987
            basis_tree.unlock()
988
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
989
    def _inventory_add_lines(self, revision_id, parents, lines,
2805.6.7 by Robert Collins
Review feedback.
990
        check_content=True):
2817.2.1 by Robert Collins
* Inventory serialisation no longer double-sha's the content.
991
        """Store lines in inv_vf and return the sha1 of the inventory."""
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
992
        parents = [(parent,) for parent in parents]
993
        return self.inventories.add_lines((revision_id,), parents, lines,
2817.2.1 by Robert Collins
* Inventory serialisation no longer double-sha's the content.
994
            check_content=check_content)[0]
1740.3.6 by Jelmer Vernooij
Move inventory writing to the commit builder.
995
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
996
    def add_revision(self, revision_id, rev, inv=None, config=None):
997
        """Add rev to the revision store as revision_id.
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
998
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
999
        :param revision_id: the revision id to use.
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
1000
        :param rev: The revision object.
1001
        :param inv: The inventory for the revision. if None, it will be looked
1002
                    up in the inventory storer
1003
        :param config: If None no digital signature will be created.
1004
                       If supplied its signature_needed method will be used
1005
                       to determine if a signature should be made.
1006
        """
2249.5.13 by John Arbash Meinel
Finish auditing Repository, and fix generate_ids to always generate utf8 ids.
1007
        # TODO: jam 20070210 Shouldn't we check rev.revision_id and
1008
        #       rev.parent_ids?
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
1009
        _mod_revision.check_not_reserved_id(revision_id)
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
1010
        if config is not None and config.signature_needed():
1011
            if inv is None:
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
1012
                inv = self.get_inventory(revision_id)
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
1013
            plaintext = Testament(rev, inv).as_short_text()
1014
            self.store_revision_signature(
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
1015
                gpg.GPGStrategy(config), plaintext, revision_id)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1016
        # check inventory present
1017
        if not self.inventories.get_parent_map([(revision_id,)]):
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
1018
            if inv is None:
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
1019
                raise errors.WeaveRevisionNotPresent(revision_id,
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1020
                                                     self.inventories)
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
1021
            else:
1022
                # yes, this is not suitable for adding with ghosts.
3380.1.6 by Aaron Bentley
Ensure fetching munges sha1s
1023
                rev.inventory_sha1 = self.add_inventory(revision_id, inv,
3305.1.1 by Jelmer Vernooij
Make sure that specifying the inv= argument to add_revision() sets the
1024
                                                        rev.parent_ids)
3380.1.6 by Aaron Bentley
Ensure fetching munges sha1s
1025
        else:
3350.8.3 by Robert Collins
VF.get_sha1s needed changing to be stackable.
1026
            key = (revision_id,)
1027
            rev.inventory_sha1 = self.inventories.get_sha1s([key])[key]
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1028
        self._add_revision(rev)
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
1029
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1030
    def _add_revision(self, revision):
1031
        text = self._serializer.write_revision_to_string(revision)
1032
        key = (revision.revision_id,)
1033
        parents = tuple((parent,) for parent in revision.parent_ids)
1034
        self.revisions.add_lines(key, parents, osutils.split_lines(text))
2520.4.10 by Aaron Bentley
Enable installation of revisions
1035
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
1036
    def all_revision_ids(self):
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1037
        """Returns a list of all the revision ids in the repository.
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
1038
3221.12.1 by Robert Collins
Backport development1 format (stackable packs) to before-shallow-branches.
1039
        This is conceptually deprecated because code should generally work on
1040
        the graph reachable from a particular revision, and ignore any other
1041
        revisions that might be present.  There is no direct replacement
1042
        method.
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
1043
        """
2592.3.114 by Robert Collins
More evil mutterings.
1044
        if 'evil' in debug.debug_flags:
2850.3.1 by Robert Collins
Move various weave specific code out of the base Repository class to weaverepo.py.
1045
            mutter_callsite(2, "all_revision_ids is linear with history.")
3221.12.4 by Robert Collins
Implement basic repository supporting external references.
1046
        return self._all_revision_ids()
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
1047
1048
    def _all_revision_ids(self):
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1049
        """Returns a list of all the revision ids in the 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.
1050
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1051
        These are in as much topological order as the underlying store can
2850.3.1 by Robert Collins
Move various weave specific code out of the base Repository class to weaverepo.py.
1052
        present.
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.
1053
        """
2850.3.1 by Robert Collins
Move various weave specific code out of the base Repository class to weaverepo.py.
1054
        raise NotImplementedError(self._all_revision_ids)
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.
1055
1687.1.7 by Robert Collins
Teach Repository about break_lock.
1056
    def break_lock(self):
1057
        """Break a lock if one is present from another instance.
1058
1059
        Uses the ui factory to ask for confirmation if the lock may be from
1060
        an active process.
1061
        """
1062
        self.control_files.break_lock()
1063
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.
1064
    @needs_read_lock
1065
    def _eliminate_revisions_not_present(self, revision_ids):
1066
        """Check every revision id in revision_ids to see if we have it.
1067
1068
        Returns a set of the present revisions.
1069
        """
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1070
        result = []
3369.2.1 by John Arbash Meinel
Knit => knit fetching also has some very bad 'for x in revision_ids: has_revision_id()' calls
1071
        graph = self.get_graph()
1072
        parent_map = graph.get_parent_map(revision_ids)
1073
        # The old API returned a list, should this actually be a set?
1074
        return parent_map.keys()
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1075
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1076
    @staticmethod
1077
    def create(a_bzrdir):
1078
        """Construct the current default format repository in a_bzrdir."""
1079
        return RepositoryFormat.get_default_format().initialize(a_bzrdir)
1080
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1081
    def __init__(self, _format, a_bzrdir, control_files):
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
1082
        """instantiate a Repository.
1083
1084
        :param _format: The format of the repository on disk.
1085
        :param a_bzrdir: The BzrDir of the repository.
1086
1087
        In the future we will have a single api for all stores for
1088
        getting file texts, inventories and revisions, then
1089
        this construct will accept instances of those things.
1090
        """
1608.2.1 by Martin Pool
[merge] Storage filename escaping
1091
        super(Repository, self).__init__()
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1092
        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
1093
        # 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.
1094
        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
1095
        self.control_files = control_files
3407.2.13 by Martin Pool
Remove indirection through control_files to get transports
1096
        self._transport = control_files._transport
3407.2.14 by Martin Pool
Remove more cases of getting transport via control_files
1097
        self.base = self._transport.base
2671.4.2 by Robert Collins
Review feedback.
1098
        # for tests
1099
        self._reconcile_does_inventory_gc = True
2745.6.16 by Aaron Bentley
Update from review
1100
        self._reconcile_fixes_text_parents = False
2951.1.3 by Robert Collins
Partial support for native reconcile with packs.
1101
        self._reconcile_backsup_inventory = True
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1102
        # not right yet - should be more semantically clear ?
1103
        #
1608.2.1 by Martin Pool
[merge] Storage filename escaping
1104
        # TODO: make sure to construct the right store classes, etc, depending
1105
        # on whether escaping is required.
1904.2.3 by Martin Pool
Give a warning on access to old repository formats
1106
        self._warn_if_deprecated()
2617.6.1 by Robert Collins
* New method on Repository - ``start_write_group``, ``end_write_group``
1107
        self._write_group = None
3221.12.1 by Robert Collins
Backport development1 format (stackable packs) to before-shallow-branches.
1108
        # Additional places to query for data.
1109
        self._fallback_repositories = []
3882.6.23 by John Arbash Meinel
Change the XMLSerializer.read_inventory_from_string api.
1110
        # An InventoryEntry cache, used during deserialization
1111
        self._inventory_entry_cache = fifo_cache.FIFOCache(10*1024)
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
1112
1668.1.3 by Martin Pool
[patch] use the correct transaction when committing snapshot (Malone: #43959)
1113
    def __repr__(self):
2592.4.5 by Martin Pool
Add Repository.base on all repositories.
1114
        return '%s(%r)' % (self.__class__.__name__,
1115
                           self.base)
1668.1.3 by Martin Pool
[patch] use the correct transaction when committing snapshot (Malone: #43959)
1116
2671.1.4 by Andrew Bennetts
Rename is_same_repository to has_same_location, thanks Aaron!
1117
    def has_same_location(self, other):
2671.1.3 by Andrew Bennetts
Remove Repository.__eq__/__ne__ methods, replace with is_same_repository method.
1118
        """Returns a boolean indicating if this repository is at the same
1119
        location as another repository.
1120
1121
        This might return False even when two repository objects are accessing
1122
        the same physical repository via different URLs.
1123
        """
2592.3.162 by Robert Collins
Remove some arbitrary differences from bzr.dev.
1124
        if self.__class__ is not other.__class__:
1125
            return False
3407.2.3 by Martin Pool
Branch and Repository use their own ._transport rather than going through .control_files
1126
        return (self._transport.base == other._transport.base)
2671.1.1 by Andrew Bennetts
Add support for comparing Repositories with == and != operators.
1127
2617.6.1 by Robert Collins
* New method on Repository - ``start_write_group``, ``end_write_group``
1128
    def is_in_write_group(self):
1129
        """Return True if there is an open write group.
1130
1131
        :seealso: start_write_group.
1132
        """
1133
        return self._write_group is not None
1134
1694.2.6 by Martin Pool
[merge] bzr.dev
1135
    def is_locked(self):
1136
        return self.control_files.is_locked()
1137
2592.3.188 by Robert Collins
Allow pack repositories to have multiple writers active at one time, for greater concurrency.
1138
    def is_write_locked(self):
1139
        """Return True if this object is write locked."""
1140
        return self.is_locked() and self.control_files._lock_mode == 'w'
1141
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
1142
    def lock_write(self, token=None):
1143
        """Lock this repository for writing.
2617.6.8 by Robert Collins
Review feedback and documentation.
1144
1145
        This causes caching within the repository obejct to start accumlating
1146
        data during reads, and allows a 'write_group' to be obtained. Write
1147
        groups must be used for actual data insertion.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1148
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
1149
        :param token: if this is already locked, then lock_write will fail
1150
            unless the token matches the existing lock.
1151
        :returns: a token if this instance supports tokens, otherwise None.
1152
        :raises TokenLockingNotSupported: when a token is given but this
1153
            instance doesn't support using token locks.
1154
        :raises MismatchedToken: if the specified token doesn't match the token
1155
            of the existing lock.
2617.6.8 by Robert Collins
Review feedback and documentation.
1156
        :seealso: start_write_group.
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
1157
2018.5.145 by Andrew Bennetts
Add a brief explanation of what tokens are used for to lock_write docstrings.
1158
        A token should be passed in if you know that you have locked the object
1159
        some other way, and need to synchronise this object's state with that
1160
        fact.
1161
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
1162
        XXX: this docstring is duplicated in many places, e.g. lockable_files.py
1163
        """
4145.1.2 by Robert Collins
Add a refresh_data method on Repository allowing cleaner handling of insertions into RemoteRepository objects with _real_repository instances.
1164
        locked = self.is_locked()
2617.6.2 by Robert Collins
Add abort_write_group and wire write_groups into fetch and commit.
1165
        result = self.control_files.lock_write(token=token)
3221.12.13 by Robert Collins
Implement generic stacking rather than pack-internals based stacking.
1166
        for repo in self._fallback_repositories:
1167
            # Writes don't affect fallback repos
1168
            repo.lock_read()
4145.1.2 by Robert Collins
Add a refresh_data method on Repository allowing cleaner handling of insertions into RemoteRepository objects with _real_repository instances.
1169
        if not locked:
1170
            self._refresh_data()
2617.6.2 by Robert Collins
Add abort_write_group and wire write_groups into fetch and commit.
1171
        return result
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
1172
1173
    def lock_read(self):
4145.1.2 by Robert Collins
Add a refresh_data method on Repository allowing cleaner handling of insertions into RemoteRepository objects with _real_repository instances.
1174
        locked = self.is_locked()
1553.5.55 by Martin Pool
[revert] broken changes
1175
        self.control_files.lock_read()
3221.12.13 by Robert Collins
Implement generic stacking rather than pack-internals based stacking.
1176
        for repo in self._fallback_repositories:
1177
            repo.lock_read()
4145.1.2 by Robert Collins
Add a refresh_data method on Repository allowing cleaner handling of insertions into RemoteRepository objects with _real_repository instances.
1178
        if not locked:
1179
            self._refresh_data()
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
1180
1694.2.6 by Martin Pool
[merge] bzr.dev
1181
    def get_physical_lock_status(self):
1182
        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
1183
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
1184
    def leave_lock_in_place(self):
1185
        """Tell this repository not to release the physical lock when this
1186
        object is unlocked.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1187
2018.5.76 by Andrew Bennetts
Testing that repository.{dont_,}leave_lock_in_place raises NotImplementedError if lock_write returns None.
1188
        If lock_write doesn't return a token, then this method is not supported.
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
1189
        """
1190
        self.control_files.leave_in_place()
1191
1192
    def dont_leave_lock_in_place(self):
1193
        """Tell this repository to release the physical lock when this
1194
        object is unlocked, even if it didn't originally acquire it.
2018.5.76 by Andrew Bennetts
Testing that repository.{dont_,}leave_lock_in_place raises NotImplementedError if lock_write returns None.
1195
1196
        If lock_write doesn't return a token, then this method is not supported.
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
1197
        """
1198
        self.control_files.dont_leave_in_place()
1199
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.
1200
    @needs_read_lock
2258.1.2 by Robert Collins
New version of gather_stats which gathers aggregate data too.
1201
    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).
1202
        """Gather statistics from a revision id.
1203
2258.1.2 by Robert Collins
New version of gather_stats which gathers aggregate data too.
1204
        :param revid: The revision id to gather statistics from, if None, then
1205
            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).
1206
        :param committers: Optional parameter controlling whether to grab
2258.1.2 by Robert Collins
New version of gather_stats which gathers aggregate data too.
1207
            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).
1208
        :return: A dictionary of statistics. Currently this contains:
1209
            committers: The number of committers if requested.
1210
            firstrev: A tuple with timestamp, timezone for the penultimate left
1211
                most ancestor of revid, if revid is not the NULL_REVISION.
1212
            latestrev: A tuple with timestamp, timezone for revid, if revid is
1213
                not the NULL_REVISION.
2258.1.2 by Robert Collins
New version of gather_stats which gathers aggregate data too.
1214
            revisions: The total revision count in the repository.
1215
            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).
1216
        """
1217
        result = {}
2258.1.2 by Robert Collins
New version of gather_stats which gathers aggregate data too.
1218
        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).
1219
            result['committers'] = 0
2258.1.2 by Robert Collins
New version of gather_stats which gathers aggregate data too.
1220
        if revid and revid != _mod_revision.NULL_REVISION:
1221
            if committers:
1222
                all_committers = set()
1223
            revisions = self.get_ancestry(revid)
1224
            # pop the leading None
1225
            revisions.pop(0)
1226
            first_revision = None
1227
            if not committers:
1228
                # ignore the revisions in the middle - just grab first and last
1229
                revisions = revisions[0], revisions[-1]
1230
            for revision in self.get_revisions(revisions):
1231
                if not first_revision:
1232
                    first_revision = revision
1233
                if committers:
1234
                    all_committers.add(revision.committer)
1235
            last_revision = revision
1236
            if committers:
1237
                result['committers'] = len(all_committers)
1238
            result['firstrev'] = (first_revision.timestamp,
1239
                first_revision.timezone)
1240
            result['latestrev'] = (last_revision.timestamp,
1241
                last_revision.timezone)
1242
1243
        # now gather global repository information
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1244
        # XXX: This is available for many repos regardless of listability.
2258.1.2 by Robert Collins
New version of gather_stats which gathers aggregate data too.
1245
        if self.bzrdir.root_transport.listable():
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1246
            # XXX: do we want to __define len__() ?
3350.6.10 by Martin Pool
VersionedFiles review cleanups
1247
            # Maybe the versionedfiles object should provide a different
1248
            # method to get the number of keys.
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1249
            result['revisions'] = len(self.revisions.keys())
1250
            # result['size'] = t
2258.1.1 by Robert Collins
Move info branch statistics gathering into the repository to allow smart server optimisation (Robert Collins).
1251
        return result
1252
3140.1.2 by Aaron Bentley
Add ability to find branches inside repositories
1253
    def find_branches(self, using=False):
1254
        """Find branches underneath this repository.
1255
3140.1.7 by Aaron Bentley
Update docs
1256
        This will include branches inside other branches.
1257
3140.1.2 by Aaron Bentley
Add ability to find branches inside repositories
1258
        :param using: If True, list only branches using this repository.
1259
        """
3140.1.9 by Aaron Bentley
Optimize find_branches for standalone repositories
1260
        if using and not self.is_shared():
1261
            try:
1262
                return [self.bzrdir.open_branch()]
1263
            except errors.NotBranchError:
1264
                return []
3140.1.2 by Aaron Bentley
Add ability to find branches inside repositories
1265
        class Evaluator(object):
1266
1267
            def __init__(self):
1268
                self.first_call = True
1269
1270
            def __call__(self, bzrdir):
1271
                # On the first call, the parameter is always the bzrdir
1272
                # containing the current repo.
1273
                if not self.first_call:
1274
                    try:
1275
                        repository = bzrdir.open_repository()
1276
                    except errors.NoRepositoryPresent:
1277
                        pass
1278
                    else:
1279
                        return False, (None, repository)
1280
                self.first_call = False
1281
                try:
1282
                    value = (bzrdir.open_branch(), None)
1283
                except errors.NotBranchError:
1284
                    value = (None, None)
1285
                return True, value
1286
1287
        branches = []
1288
        for branch, repository in bzrdir.BzrDir.find_bzrdirs(
1289
                self.bzrdir.root_transport, evaluate=Evaluator()):
1290
            if branch is not None:
1291
                branches.append(branch)
1292
            if not using and repository is not None:
1293
                branches.extend(repository.find_branches())
1294
        return branches
1295
2258.1.1 by Robert Collins
Move info branch statistics gathering into the repository to allow smart server optimisation (Robert Collins).
1296
    @needs_read_lock
3184.1.8 by Robert Collins
* ``InterRepository.missing_revision_ids`` is now deprecated in favour of
1297
    def search_missing_revision_ids(self, other, revision_id=None, find_ghosts=True):
1298
        """Return the revision ids that other has that this does not.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1299
3184.1.8 by Robert Collins
* ``InterRepository.missing_revision_ids`` is now deprecated in favour of
1300
        These are returned in topological order.
1301
1302
        revision_id: only return revision ids included by revision_id.
1303
        """
1304
        return InterRepository.get(other, self).search_missing_revision_ids(
1305
            revision_id, find_ghosts)
1306
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1307
    @staticmethod
1308
    def open(base):
1309
        """Open the repository rooted at base.
1310
1311
        For instance, if the repository is at URL/.bzr/repository,
1312
        Repository.open(URL) -> a Repository instance.
1313
        """
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
1314
        control = bzrdir.BzrDir.open(base)
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1315
        return control.open_repository()
1316
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
1317
    def copy_content_into(self, destination, revision_id=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.
1318
        """Make a complete copy of the content in self into destination.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1319
1320
        This is a destructive operation! Do not use it on existing
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.
1321
        repositories.
1322
        """
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
1323
        return InterRepository.get(self, destination).copy_content(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.
1324
2617.6.2 by Robert Collins
Add abort_write_group and wire write_groups into fetch and commit.
1325
    def commit_write_group(self):
1326
        """Commit the contents accrued within the current write group.
2617.6.1 by Robert Collins
* New method on Repository - ``start_write_group``, ``end_write_group``
1327
1328
        :seealso: start_write_group.
1329
        """
1330
        if self._write_group is not self.get_transaction():
1331
            # has an unlock or relock occured ?
2592.3.38 by Robert Collins
All experimental format tests passing again.
1332
            raise errors.BzrError('mismatched lock context %r and '
1333
                'write group %r.' %
1334
                (self.get_transaction(), self._write_group))
2617.6.2 by Robert Collins
Add abort_write_group and wire write_groups into fetch and commit.
1335
        self._commit_write_group()
2617.6.1 by Robert Collins
* New method on Repository - ``start_write_group``, ``end_write_group``
1336
        self._write_group = None
1337
2617.6.2 by Robert Collins
Add abort_write_group and wire write_groups into fetch and commit.
1338
    def _commit_write_group(self):
1339
        """Template method for per-repository write group cleanup.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1340
1341
        This is called before the write group is considered to be
2617.6.2 by Robert Collins
Add abort_write_group and wire write_groups into fetch and commit.
1342
        finished and should ensure that all data handed to the repository
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1343
        for writing during the write group is safely committed (to the
2617.6.2 by Robert Collins
Add abort_write_group and wire write_groups into fetch and commit.
1344
        extent possible considering file system caching etc).
1345
        """
1346
4002.1.1 by Andrew Bennetts
Implement suspend_write_group/resume_write_group.
1347
    def suspend_write_group(self):
1348
        raise errors.UnsuspendableWriteGroup(self)
1349
4145.1.2 by Robert Collins
Add a refresh_data method on Repository allowing cleaner handling of insertions into RemoteRepository objects with _real_repository instances.
1350
    def refresh_data(self):
1351
        """Re-read any data needed to to synchronise with disk.
1352
1353
        This method is intended to be called after another repository instance
1354
        (such as one used by a smart server) has inserted data into the
1355
        repository. It may not be called during a write group, but may be
1356
        called at any other time.
1357
        """
1358
        if self.is_in_write_group():
1359
            raise errors.InternalBzrError(
1360
                "May not refresh_data while in a write group.")
1361
        self._refresh_data()
1362
4002.1.1 by Andrew Bennetts
Implement suspend_write_group/resume_write_group.
1363
    def resume_write_group(self, tokens):
1364
        if not self.is_write_locked():
1365
            raise errors.NotWriteLocked(self)
1366
        if self._write_group:
1367
            raise errors.BzrError('already in a write group')
1368
        self._resume_write_group(tokens)
1369
        # so we can detect unlock/relock - the write group is now entered.
1370
        self._write_group = self.get_transaction()
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
1371
4002.1.1 by Andrew Bennetts
Implement suspend_write_group/resume_write_group.
1372
    def _resume_write_group(self, tokens):
1373
        raise errors.UnsuspendableWriteGroup(self)
1374
4070.9.2 by Andrew Bennetts
Rough prototype of allowing a SearchResult to be passed to fetch, and using that to improve network conversations.
1375
    def fetch(self, source, revision_id=None, pb=None, find_ghosts=False,
1376
            fetch_spec=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.
1377
        """Fetch the content required to construct revision_id from source.
1378
4070.9.14 by Andrew Bennetts
Tweaks requested by Robert's review.
1379
        If revision_id is None and fetch_spec is None, then all content is
1380
        copied.
1381
4145.1.1 by Robert Collins
Explicitly prevent fetching while the target repository is in a write group.
1382
        fetch() may not be used when the repository is in a write group -
1383
        either finish the current write group before using fetch, or use
1384
        fetch before starting the write group.
1385
2949.1.1 by Robert Collins
Change Repository.fetch to provide a find_ghosts parameter which triggers ghost filling.
1386
        :param find_ghosts: Find and copy revisions in the source that are
1387
            ghosts in the target (and not reachable directly by walking out to
1388
            the first-present revision in target from revision_id).
4070.9.14 by Andrew Bennetts
Tweaks requested by Robert's review.
1389
        :param revision_id: If specified, all the content needed for this
1390
            revision ID will be copied to the target.  Fetch will determine for
1391
            itself which content needs to be copied.
1392
        :param fetch_spec: If specified, a SearchResult or
1393
            PendingAncestryResult that describes which revisions to copy.  This
1394
            allows copying multiple heads at once.  Mutually exclusive with
1395
            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.
1396
        """
4070.9.2 by Andrew Bennetts
Rough prototype of allowing a SearchResult to be passed to fetch, and using that to improve network conversations.
1397
        if fetch_spec is not None and revision_id is not None:
1398
            raise AssertionError(
1399
                "fetch_spec and revision_id are mutually exclusive.")
4145.1.1 by Robert Collins
Explicitly prevent fetching while the target repository is in a write group.
1400
        if self.is_in_write_group():
4145.1.3 by Robert Collins
NEWS conflicts.
1401
            raise errors.InternalBzrError(
1402
                "May not fetch while in a write group.")
2592.3.115 by Robert Collins
Move same repository check up to Repository.fetch to allow all fetch implementations to benefit.
1403
        # fast path same-url fetch operations
4070.9.2 by Andrew Bennetts
Rough prototype of allowing a SearchResult to be passed to fetch, and using that to improve network conversations.
1404
        if self.has_same_location(source) and fetch_spec is None:
2592.3.115 by Robert Collins
Move same repository check up to Repository.fetch to allow all fetch implementations to benefit.
1405
            # check that last_revision is in 'from' and then return a
1406
            # no-operation.
1407
            if (revision_id is not None and
1408
                not _mod_revision.is_null(revision_id)):
1409
                self.get_revision(revision_id)
1410
            return 0, []
3582.1.3 by Martin Pool
Repository.fetch no longer needs to translate NotImplementedErro to IncompatibleRepositories
1411
        # if there is no specific appropriate InterRepository, this will get
1412
        # the InterRepository base class, which raises an
1413
        # IncompatibleRepositories when asked to fetch.
2323.8.3 by Aaron Bentley
Reduce scope of try/except, update NEWS
1414
        inter = InterRepository.get(source, self)
3582.1.3 by Martin Pool
Repository.fetch no longer needs to translate NotImplementedErro to IncompatibleRepositories
1415
        return inter.fetch(revision_id=revision_id, pb=pb,
4070.9.2 by Andrew Bennetts
Rough prototype of allowing a SearchResult to be passed to fetch, and using that to improve network conversations.
1416
            find_ghosts=find_ghosts, fetch_spec=fetch_spec)
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1417
2520.4.54 by Aaron Bentley
Hang a create_bundle method off repository
1418
    def create_bundle(self, target, base, fileobj, format=None):
1419
        return serializer.write_bundle(self, target, base, fileobj, format)
1420
2803.2.1 by Robert Collins
* CommitBuilder now advertises itself as requiring the root entry to be
1421
    def get_commit_builder(self, branch, parents, config, timestamp=None,
1422
                           timezone=None, committer=None, revprops=None,
1740.3.7 by Jelmer Vernooij
Move committer, log, revprops, timestamp and timezone to CommitBuilder.
1423
                           revision_id=None):
1424
        """Obtain a CommitBuilder for this repository.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1425
1740.3.7 by Jelmer Vernooij
Move committer, log, revprops, timestamp and timezone to CommitBuilder.
1426
        :param branch: Branch to commit to.
1427
        :param parents: Revision ids of the parents of the new revision.
1428
        :param config: Configuration to use.
1429
        :param timestamp: Optional timestamp recorded for commit.
1430
        :param timezone: Optional timezone for timestamp.
1431
        :param committer: Optional committer to set for commit.
1432
        :param revprops: Optional dictionary of revision properties.
1433
        :param revision_id: Optional revision id.
1434
        """
2818.3.2 by Robert Collins
Review feedback.
1435
        result = self._commit_builder_class(self, parents, config,
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
1436
            timestamp, timezone, committer, revprops, revision_id)
2617.6.2 by Robert Collins
Add abort_write_group and wire write_groups into fetch and commit.
1437
        self.start_write_group()
1438
        return result
1740.3.1 by Jelmer Vernooij
Introduce and use CommitBuilder objects.
1439
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
1440
    def unlock(self):
2617.6.1 by Robert Collins
* New method on Repository - ``start_write_group``, ``end_write_group``
1441
        if (self.control_files._lock_count == 1 and
1442
            self.control_files._lock_mode == 'w'):
1443
            if self._write_group is not None:
2592.3.244 by Martin Pool
unlock while in a write group now aborts the write group, unlocks, and errors.
1444
                self.abort_write_group()
1445
                self.control_files.unlock()
2617.6.1 by Robert Collins
* New method on Repository - ``start_write_group``, ``end_write_group``
1446
                raise errors.BzrError(
1447
                    'Must end write groups before releasing write locks.')
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
1448
        self.control_files.unlock()
3882.6.23 by John Arbash Meinel
Change the XMLSerializer.read_inventory_from_string api.
1449
        if self.control_files._lock_count == 0:
1450
            self._inventory_entry_cache.clear()
3221.12.13 by Robert Collins
Implement generic stacking rather than pack-internals based stacking.
1451
        for repo in self._fallback_repositories:
1452
            repo.unlock()
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
1453
1185.65.27 by Robert Collins
Tweak storage towards mergability.
1454
    @needs_read_lock
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
1455
    def clone(self, a_bzrdir, revision_id=None):
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1456
        """Clone this repository into a_bzrdir using the current format.
1457
1458
        Currently no check is made that the format of this repository and
1459
        the bzrdir format are compatible. FIXME RBC 20060201.
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
1460
1461
        :return: The newly created destination repository.
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1462
        """
2440.1.1 by Martin Pool
Add new Repository.sprout,
1463
        # TODO: deprecate after 0.16; cloning this with all its settings is
1464
        # probably not very useful -- mbp 20070423
1465
        dest_repo = self._create_sprouting_repo(a_bzrdir, shared=self.is_shared())
1466
        self.copy_content_into(dest_repo, revision_id)
1467
        return dest_repo
1468
2617.6.1 by Robert Collins
* New method on Repository - ``start_write_group``, ``end_write_group``
1469
    def start_write_group(self):
1470
        """Start a write group in the repository.
1471
1472
        Write groups are used by repositories which do not have a 1:1 mapping
1473
        between file ids and backend store to manage the insertion of data from
1474
        both fetch and commit operations.
1475
2617.6.2 by Robert Collins
Add abort_write_group and wire write_groups into fetch and commit.
1476
        A write lock is required around the start_write_group/commit_write_group
2617.6.1 by Robert Collins
* New method on Repository - ``start_write_group``, ``end_write_group``
1477
        for the support of lock-requiring repository formats.
2617.6.8 by Robert Collins
Review feedback and documentation.
1478
1479
        One can only insert data into a repository inside a write group.
1480
2617.6.6 by Robert Collins
Some review feedback.
1481
        :return: None.
2617.6.1 by Robert Collins
* New method on Repository - ``start_write_group``, ``end_write_group``
1482
        """
2592.3.188 by Robert Collins
Allow pack repositories to have multiple writers active at one time, for greater concurrency.
1483
        if not self.is_write_locked():
2617.6.1 by Robert Collins
* New method on Repository - ``start_write_group``, ``end_write_group``
1484
            raise errors.NotWriteLocked(self)
1485
        if self._write_group:
1486
            raise errors.BzrError('already in a write group')
2617.6.2 by Robert Collins
Add abort_write_group and wire write_groups into fetch and commit.
1487
        self._start_write_group()
1488
        # so we can detect unlock/relock - the write group is now entered.
2617.6.1 by Robert Collins
* New method on Repository - ``start_write_group``, ``end_write_group``
1489
        self._write_group = self.get_transaction()
1490
2617.6.2 by Robert Collins
Add abort_write_group and wire write_groups into fetch and commit.
1491
    def _start_write_group(self):
1492
        """Template method for per-repository write group startup.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1493
1494
        This is called before the write group is considered to be
2617.6.2 by Robert Collins
Add abort_write_group and wire write_groups into fetch and commit.
1495
        entered.
1496
        """
1497
2440.1.1 by Martin Pool
Add new Repository.sprout,
1498
    @needs_read_lock
1499
    def sprout(self, to_bzrdir, revision_id=None):
1500
        """Create a descendent repository for new development.
1501
1502
        Unlike clone, this does not copy the settings of the repository.
1503
        """
1504
        dest_repo = self._create_sprouting_repo(to_bzrdir, shared=False)
1505
        dest_repo.fetch(self, revision_id=revision_id)
1506
        return dest_repo
1507
1508
    def _create_sprouting_repo(self, a_bzrdir, shared):
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1509
        if not isinstance(a_bzrdir._format, self.bzrdir._format.__class__):
1510
            # use target default format.
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
1511
            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.
1512
        else:
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
1513
            # Most control formats need the repository to be specifically
1514
            # created, but on some old all-in-one formats it's not needed
1515
            try:
2440.1.1 by Martin Pool
Add new Repository.sprout,
1516
                dest_repo = self._format.initialize(a_bzrdir, shared=shared)
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
1517
            except errors.UninitializableFormat:
1518
                dest_repo = a_bzrdir.open_repository()
1519
        return dest_repo
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1520
4022.1.1 by Robert Collins
Refactoring of fetch to have a sender and sink component enabling splitting the logic over a network stream. (Robert Collins, Andrew Bennetts)
1521
    def _get_sink(self):
1522
        """Return a sink for streaming into this repository."""
1523
        return StreamSink(self)
1524
4060.1.3 by Robert Collins
Implement the separate source component for fetch - repository.StreamSource.
1525
    def _get_source(self, to_format):
1526
        """Return a source for streaming from this repository."""
1527
        return StreamSource(self, to_format)
1528
1563.2.22 by Robert Collins
Move responsibility for repository.has_revision into RevisionStore
1529
    @needs_read_lock
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
1530
    def has_revision(self, revision_id):
1563.2.22 by Robert Collins
Move responsibility for repository.has_revision into RevisionStore
1531
        """True if this repository has a copy of the revision."""
3172.3.1 by Robert Collins
Repository has a new method ``has_revisions`` which signals the presence
1532
        return revision_id in self.has_revisions((revision_id,))
1533
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1534
    @needs_read_lock
3172.3.1 by Robert Collins
Repository has a new method ``has_revisions`` which signals the presence
1535
    def has_revisions(self, revision_ids):
1536
        """Probe to find out the presence of multiple revisions.
1537
1538
        :param revision_ids: An iterable of revision_ids.
1539
        :return: A set of the revision_ids that were present.
1540
        """
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1541
        parent_map = self.revisions.get_parent_map(
1542
            [(rev_id,) for rev_id in revision_ids])
1543
        result = set()
1544
        if _mod_revision.NULL_REVISION in revision_ids:
1545
            result.add(_mod_revision.NULL_REVISION)
1546
        result.update([key[0] for key in parent_map])
1547
        return result
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
1548
1185.65.27 by Robert Collins
Tweak storage towards mergability.
1549
    @needs_read_lock
2850.3.1 by Robert Collins
Move various weave specific code out of the base Repository class to weaverepo.py.
1550
    def get_revision(self, revision_id):
1551
        """Return the Revision object for a named revision."""
1552
        return self.get_revisions([revision_id])[0]
1553
1554
    @needs_read_lock
1570.1.13 by Robert Collins
Check for incorrect revision parentage in the weave during revision access.
1555
    def get_revision_reconcile(self, revision_id):
1556
        """'reconcile' helper routine that allows access to a revision always.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1557
1570.1.13 by Robert Collins
Check for incorrect revision parentage in the weave during revision access.
1558
        This variant of get_revision does not cross check the weave graph
1559
        against the revision one as get_revision does: but it should only
1560
        be used by reconcile, or reconcile-alike commands that are correcting
1561
        or testing the revision graph.
1562
        """
2850.3.1 by Robert Collins
Move various weave specific code out of the base Repository class to weaverepo.py.
1563
        return self._get_revisions([revision_id])[0]
2249.5.13 by John Arbash Meinel
Finish auditing Repository, and fix generate_ids to always generate utf8 ids.
1564
1756.1.2 by Aaron Bentley
Show logs using get_revisions
1565
    @needs_read_lock
1566
    def get_revisions(self, revision_ids):
2850.3.1 by Robert Collins
Move various weave specific code out of the base Repository class to weaverepo.py.
1567
        """Get many revisions at once."""
1568
        return self._get_revisions(revision_ids)
1569
1570
    @needs_read_lock
1571
    def _get_revisions(self, revision_ids):
1572
        """Core work logic to get many revisions without sanity checks."""
1573
        for rev_id in revision_ids:
1574
            if not rev_id or not isinstance(rev_id, basestring):
1575
                raise errors.InvalidRevisionId(revision_id=rev_id, branch=self)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1576
        keys = [(key,) for key in revision_ids]
1577
        stream = self.revisions.get_record_stream(keys, 'unordered', True)
1578
        revs = {}
1579
        for record in stream:
1580
            if record.storage_kind == 'absent':
1581
                raise errors.NoSuchRevision(self, record.key[0])
1582
            text = record.get_bytes_as('fulltext')
1583
            rev = self._serializer.read_revision_from_string(text)
1584
            revs[record.key[0]] = rev
1585
        return [revs[revid] for revid in revision_ids]
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
1586
1185.65.27 by Robert Collins
Tweak storage towards mergability.
1587
    @needs_read_lock
1563.2.29 by Robert Collins
Remove all but fetch references to repository.revision_store.
1588
    def get_revision_xml(self, revision_id):
2249.5.13 by John Arbash Meinel
Finish auditing Repository, and fix generate_ids to always generate utf8 ids.
1589
        # TODO: jam 20070210 This shouldn't be necessary since get_revision
1590
        #       would have already do it.
1591
        # TODO: jam 20070210 Just use _serializer.write_revision_to_string()
1592
        rev = self.get_revision(revision_id)
3224.5.25 by Andrew Bennetts
More minor import tidying suggested by pyflakes.
1593
        rev_tmp = cStringIO.StringIO()
1563.2.29 by Robert Collins
Remove all but fetch references to repository.revision_store.
1594
        # the current serializer..
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1595
        self._serializer.write_revision(rev, rev_tmp)
1563.2.29 by Robert Collins
Remove all but fetch references to repository.revision_store.
1596
        rev_tmp.seek(0)
1597
        return rev_tmp.getvalue()
1598
4137.3.2 by Ian Clatworthy
Repository.get_deltas_for_revisions() now supports file-id filtering
1599
    def get_deltas_for_revisions(self, revisions, specific_fileids=None):
1756.3.19 by Aaron Bentley
Documentation and cleanups
1600
        """Produce a generator of revision deltas.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1601
1756.3.19 by Aaron Bentley
Documentation and cleanups
1602
        Note that the input is a sequence of REVISIONS, not revision_ids.
1603
        Trees will be held in memory until the generator exits.
1604
        Each delta is relative to the revision's lefthand predecessor.
4137.3.2 by Ian Clatworthy
Repository.get_deltas_for_revisions() now supports file-id filtering
1605
1606
        :param specific_fileids: if not None, the result is filtered
1607
          so that only those file-ids, their parents and their
1608
          children are included.
1756.3.19 by Aaron Bentley
Documentation and cleanups
1609
        """
4137.3.2 by Ian Clatworthy
Repository.get_deltas_for_revisions() now supports file-id filtering
1610
        # Get the revision-ids of interest
1756.3.3 by Aaron Bentley
More refactoring, introduce revision_trees.
1611
        required_trees = set()
1612
        for revision in revisions:
1613
            required_trees.add(revision.revision_id)
1614
            required_trees.update(revision.parent_ids[:1])
4137.3.2 by Ian Clatworthy
Repository.get_deltas_for_revisions() now supports file-id filtering
1615
1616
        # Get the matching filtered trees. Note that it's more
1617
        # efficient to pass filtered trees to changes_from() rather
1618
        # than doing the filtering afterwards. changes_from() could
1619
        # arguably do the filtering itself but it's path-based, not
1620
        # file-id based, so filtering before or afterwards is
1621
        # currently easier.
1622
        if specific_fileids is None:
1623
            trees = dict((t.get_revision_id(), t) for
1624
                t in self.revision_trees(required_trees))
1625
        else:
1626
            trees = dict((t.get_revision_id(), t) for
1627
                t in self._filtered_revision_trees(required_trees,
1628
                specific_fileids))
1629
1630
        # Calculate the deltas
1756.3.3 by Aaron Bentley
More refactoring, introduce revision_trees.
1631
        for revision in revisions:
1632
            if not revision.parent_ids:
3668.5.1 by Jelmer Vernooij
Use NULL_REVISION rather than None for Repository.revision_tree().
1633
                old_tree = self.revision_tree(_mod_revision.NULL_REVISION)
1756.3.3 by Aaron Bentley
More refactoring, introduce revision_trees.
1634
            else:
1635
                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.
1636
            yield trees[revision.revision_id].changes_from(old_tree)
1756.3.3 by Aaron Bentley
More refactoring, introduce revision_trees.
1637
1756.3.19 by Aaron Bentley
Documentation and cleanups
1638
    @needs_read_lock
4137.3.2 by Ian Clatworthy
Repository.get_deltas_for_revisions() now supports file-id filtering
1639
    def get_revision_delta(self, revision_id, specific_fileids=None):
1744.2.2 by Johan Rydberg
Add get_revision_delta to Repository; and make Branch.get_revision_delta use it.
1640
        """Return the delta for one revision.
1641
1642
        The delta is relative to the left-hand predecessor of the
1643
        revision.
4137.3.2 by Ian Clatworthy
Repository.get_deltas_for_revisions() now supports file-id filtering
1644
1645
        :param specific_fileids: if not None, the result is filtered
1646
          so that only those file-ids, their parents and their
1647
          children are included.
1744.2.2 by Johan Rydberg
Add get_revision_delta to Repository; and make Branch.get_revision_delta use it.
1648
        """
1756.3.3 by Aaron Bentley
More refactoring, introduce revision_trees.
1649
        r = self.get_revision(revision_id)
4137.3.2 by Ian Clatworthy
Repository.get_deltas_for_revisions() now supports file-id filtering
1650
        return list(self.get_deltas_for_revisions([r],
1651
            specific_fileids=specific_fileids))[0]
1744.2.2 by Johan Rydberg
Add get_revision_delta to Repository; and make Branch.get_revision_delta use it.
1652
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
1653
    @needs_write_lock
1654
    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.
1655
        signature = gpg_strategy.sign(plaintext)
2996.2.4 by Aaron Bentley
Rename function to add_signature_text
1656
        self.add_signature_text(revision_id, signature)
2996.2.3 by Aaron Bentley
Add tests for install_revisions and add_signature
1657
1658
    @needs_write_lock
2996.2.4 by Aaron Bentley
Rename function to add_signature_text
1659
    def add_signature_text(self, revision_id, signature):
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1660
        self.signatures.add_lines((revision_id,), (),
1661
            osutils.split_lines(signature))
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
1662
2988.1.2 by Robert Collins
New Repository API find_text_key_references for use by reconcile and check.
1663
    def find_text_key_references(self):
1664
        """Find the text key references within the repository.
1665
1666
        :return: A dictionary mapping text keys ((fileid, revision_id) tuples)
1667
            to whether they were referred to by the inventory of the
1668
            revision_id that they contain. The inventory texts from all present
1669
            revision ids are assessed to generate this report.
1670
        """
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1671
        revision_keys = self.revisions.keys()
1672
        w = self.inventories
2988.1.2 by Robert Collins
New Repository API find_text_key_references for use by reconcile and check.
1673
        pb = ui.ui_factory.nested_progress_bar()
1674
        try:
1675
            return self._find_text_key_references_from_xml_inventory_lines(
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1676
                w.iter_lines_added_or_present_in_keys(revision_keys, pb=pb))
2988.1.2 by Robert Collins
New Repository API find_text_key_references for use by reconcile and check.
1677
        finally:
1678
            pb.finished()
1679
2988.1.1 by Robert Collins
Refactor fetch's xml inventory parsing into a core routine that extracts the data and a separate one that filters for fetch.
1680
    def _find_text_key_references_from_xml_inventory_lines(self,
1681
        line_iterator):
1682
        """Core routine for extracting references to texts from inventories.
2592.3.110 by Robert Collins
Filter out texts and signatures not referenced by the revisions being copied during pack to pack fetching.
1683
1684
        This performs the translation of xml lines to revision ids.
1685
2975.3.1 by Robert Collins
Change (without backwards compatibility) the
1686
        :param line_iterator: An iterator of lines, origin_version_id
2988.1.1 by Robert Collins
Refactor fetch's xml inventory parsing into a core routine that extracts the data and a separate one that filters for fetch.
1687
        :return: A dictionary mapping text keys ((fileid, revision_id) tuples)
1688
            to whether they were referred to by the inventory of the
1689
            revision_id that they contain. Note that if that revision_id was
1690
            not part of the line_iterator's output then False will be given -
1691
            even though it may actually refer to that key.
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1692
        """
2988.2.2 by Robert Collins
Review feedback.
1693
        if not self._serializer.support_altered_by_hack:
1694
            raise AssertionError(
1695
                "_find_text_key_references_from_xml_inventory_lines only "
1696
                "supported for branches which store inventory as unnested xml"
1697
                ", not on %r" % self)
1694.2.6 by Martin Pool
[merge] bzr.dev
1698
        result = {}
1563.2.35 by Robert Collins
cleanup deprecation warnings and finish conversion so the inventory is knit based too.
1699
1694.2.6 by Martin Pool
[merge] bzr.dev
1700
        # this code needs to read every new line in every inventory for the
1701
        # inventories [revision_ids]. Seeing a line twice is ok. Seeing a line
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1702
        # 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.
1703
        # harmful because we are filtering by the revision id marker in the
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1704
        # 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.
1705
        # 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.
1706
        # only those added in an inventory in rev X can contain a revision=X
1707
        # line.
2163.2.3 by John Arbash Meinel
Change to local variables to save another 300ms
1708
        unescape_revid_cache = {}
1709
        unescape_fileid_cache = {}
1710
2163.2.5 by John Arbash Meinel
Inline the cache lookup, and explain why
1711
        # jam 20061218 In a big fetch, this handles hundreds of thousands
1712
        # of lines, so it has had a lot of inlining and optimizing done.
1713
        # Sorry that it is a little bit messy.
2163.2.3 by John Arbash Meinel
Change to local variables to save another 300ms
1714
        # Move several functions to be local variables, since this is a long
1715
        # running loop.
1716
        search = self._file_ids_altered_regex.search
2163.2.5 by John Arbash Meinel
Inline the cache lookup, and explain why
1717
        unescape = _unescape_xml
2163.2.3 by John Arbash Meinel
Change to local variables to save another 300ms
1718
        setdefault = result.setdefault
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1719
        for line, line_key in line_iterator:
2592.3.110 by Robert Collins
Filter out texts and signatures not referenced by the revisions being copied during pack to pack fetching.
1720
            match = search(line)
1721
            if match is None:
1722
                continue
1723
            # One call to match.group() returning multiple items is quite a
1724
            # bit faster than 2 calls to match.group() each returning 1
1725
            file_id, revision_id = match.group('file_id', 'revision_id')
1726
1727
            # Inlining the cache lookups helps a lot when you make 170,000
1728
            # lines and 350k ids, versus 8.4 unique ids.
1729
            # Using a cache helps in 2 ways:
1730
            #   1) Avoids unnecessary decoding calls
1731
            #   2) Re-uses cached strings, which helps in future set and
1732
            #      equality checks.
1733
            # (2) is enough that removing encoding entirely along with
1734
            # the cache (so we are using plain strings) results in no
1735
            # performance improvement.
1736
            try:
1737
                revision_id = unescape_revid_cache[revision_id]
1738
            except KeyError:
1739
                unescaped = unescape(revision_id)
1740
                unescape_revid_cache[revision_id] = unescaped
1741
                revision_id = unescaped
1742
2988.2.2 by Robert Collins
Review feedback.
1743
            # Note that unconditionally unescaping means that we deserialise
1744
            # every fileid, which for general 'pull' is not great, but we don't
1745
            # really want to have some many fulltexts that this matters anyway.
1746
            # RBC 20071114.
2988.1.1 by Robert Collins
Refactor fetch's xml inventory parsing into a core routine that extracts the data and a separate one that filters for fetch.
1747
            try:
1748
                file_id = unescape_fileid_cache[file_id]
1749
            except KeyError:
1750
                unescaped = unescape(file_id)
1751
                unescape_fileid_cache[file_id] = unescaped
1752
                file_id = unescaped
1753
1754
            key = (file_id, revision_id)
1755
            setdefault(key, False)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1756
            if revision_id == line_key[-1]:
2988.1.1 by Robert Collins
Refactor fetch's xml inventory parsing into a core routine that extracts the data and a separate one that filters for fetch.
1757
                result[key] = True
1758
        return result
1759
4098.4.1 by Robert Collins
Handle inconsistent inventory data more gracefully at a small performance cost during fetch.
1760
    def _inventory_xml_lines_for_keys(self, keys):
1761
        """Get a line iterator of the sort needed for findind references.
1762
1763
        Not relevant for non-xml inventory repositories.
1764
1765
        Ghosts in revision_keys are ignored.
1766
1767
        :param revision_keys: The revision keys for the inventories to inspect.
1768
        :return: An iterator over (inventory line, revid) for the fulltexts of
1769
            all of the xml inventories specified by revision_keys.
1770
        """
1771
        stream = self.inventories.get_record_stream(keys, 'unordered', True)
1772
        for record in stream:
1773
            if record.storage_kind != 'absent':
1774
                chunks = record.get_bytes_as('chunked')
1775
                revid = record.key[-1]
1776
                lines = osutils.chunks_to_lines(chunks)
1777
                for line in lines:
1778
                    yield line, revid
1779
2988.1.1 by Robert Collins
Refactor fetch's xml inventory parsing into a core routine that extracts the data and a separate one that filters for fetch.
1780
    def _find_file_ids_from_xml_inventory_lines(self, line_iterator,
1781
        revision_ids):
1782
        """Helper routine for fileids_altered_by_revision_ids.
1783
1784
        This performs the translation of xml lines to revision ids.
1785
1786
        :param line_iterator: An iterator of lines, origin_version_id
1787
        :param revision_ids: The revision ids to filter for. This should be a
1788
            set or other type which supports efficient __contains__ lookups, as
1789
            the revision id from each parsed line will be looked up in the
1790
            revision_ids filter.
1791
        :return: a dictionary mapping altered file-ids to an iterable of
1792
        revision_ids. Each altered file-ids has the exact revision_ids that
1793
        altered it listed explicitly.
1794
        """
4098.4.1 by Robert Collins
Handle inconsistent inventory data more gracefully at a small performance cost during fetch.
1795
        seen = set(self._find_text_key_references_from_xml_inventory_lines(
1796
                line_iterator).iterkeys())
1797
        # Note that revision_ids are revision keys.
1798
        parent_maps = self.revisions.get_parent_map(revision_ids)
1799
        parents = set()
1800
        map(parents.update, parent_maps.itervalues())
1801
        parents.difference_update(revision_ids)
1802
        parent_seen = set(self._find_text_key_references_from_xml_inventory_lines(
1803
            self._inventory_xml_lines_for_keys(parents)))
1804
        new_keys = seen - parent_seen
2988.1.1 by Robert Collins
Refactor fetch's xml inventory parsing into a core routine that extracts the data and a separate one that filters for fetch.
1805
        result = {}
1806
        setdefault = result.setdefault
4098.4.1 by Robert Collins
Handle inconsistent inventory data more gracefully at a small performance cost during fetch.
1807
        for key in new_keys:
1808
            setdefault(key[0], set()).add(key[-1])
2592.3.110 by Robert Collins
Filter out texts and signatures not referenced by the revisions being copied during pack to pack fetching.
1809
        return result
1810
3422.1.1 by John Arbash Meinel
merge in bzr-1.5rc1, revert the transaction cache change
1811
    def fileids_altered_by_revision_ids(self, revision_ids, _inv_weave=None):
2592.3.110 by Robert Collins
Filter out texts and signatures not referenced by the revisions being copied during pack to pack fetching.
1812
        """Find the file ids and versions affected by revisions.
1813
1814
        :param revisions: an iterable containing revision ids.
3422.1.1 by John Arbash Meinel
merge in bzr-1.5rc1, revert the transaction cache change
1815
        :param _inv_weave: The inventory weave from this repository or None.
1816
            If None, the inventory weave will be opened automatically.
2592.3.110 by Robert Collins
Filter out texts and signatures not referenced by the revisions being copied during pack to pack fetching.
1817
        :return: a dictionary mapping altered file-ids to an iterable of
1818
        revision_ids. Each altered file-ids has the exact revision_ids that
1819
        altered it listed explicitly.
1820
        """
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1821
        selected_keys = set((revid,) for revid in revision_ids)
1822
        w = _inv_weave or self.inventories
2039.1.1 by Aaron Bentley
Clean up progress properly when interrupted during fetch (#54000)
1823
        pb = ui.ui_factory.nested_progress_bar()
1824
        try:
2592.3.110 by Robert Collins
Filter out texts and signatures not referenced by the revisions being copied during pack to pack fetching.
1825
            return self._find_file_ids_from_xml_inventory_lines(
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1826
                w.iter_lines_added_or_present_in_keys(
1827
                    selected_keys, pb=pb),
1828
                selected_keys)
2039.1.1 by Aaron Bentley
Clean up progress properly when interrupted during fetch (#54000)
1829
        finally:
1830
            pb.finished()
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1831
2708.1.7 by Aaron Bentley
Rename extract_files_bytes to iter_files_bytes
1832
    def iter_files_bytes(self, desired_files):
2708.1.9 by Aaron Bentley
Clean-up docs and imports
1833
        """Iterate through file versions.
1834
2708.1.10 by Aaron Bentley
Update docstrings
1835
        Files will not necessarily be returned in the order they occur in
1836
        desired_files.  No specific order is guaranteed.
1837
2708.1.9 by Aaron Bentley
Clean-up docs and imports
1838
        Yields pairs of identifier, bytes_iterator.  identifier is an opaque
2708.1.10 by Aaron Bentley
Update docstrings
1839
        value supplied by the caller as part of desired_files.  It should
1840
        uniquely identify the file version in the caller's context.  (Examples:
1841
        an index number or a TreeTransform trans_id.)
1842
1843
        bytes_iterator is an iterable of bytestrings for the file.  The
1844
        kind of iterable and length of the bytestrings are unspecified, but for
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1845
        this implementation, it is a list of bytes produced by
1846
        VersionedFile.get_record_stream().
2708.1.10 by Aaron Bentley
Update docstrings
1847
2708.1.9 by Aaron Bentley
Clean-up docs and imports
1848
        :param desired_files: a list of (file_id, revision_id, identifier)
2708.1.10 by Aaron Bentley
Update docstrings
1849
            triples
2708.1.9 by Aaron Bentley
Clean-up docs and imports
1850
        """
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1851
        text_keys = {}
2708.1.3 by Aaron Bentley
Implement extract_files_bytes on Repository
1852
        for file_id, revision_id, callable_data in desired_files:
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1853
            text_keys[(file_id, revision_id)] = callable_data
1854
        for record in self.texts.get_record_stream(text_keys, 'unordered', True):
1855
            if record.storage_kind == 'absent':
1856
                raise errors.RevisionNotPresent(record.key, self)
4202.1.1 by John Arbash Meinel
Update Repository.iter_files_bytes() to return an iterable of bytestrings.
1857
            yield text_keys[record.key], record.get_bytes_as('chunked')
2708.1.3 by Aaron Bentley
Implement extract_files_bytes on Repository
1858
3063.2.1 by Robert Collins
Solve reconciling erroring when multiple portions of a single delta chain are being reinserted.
1859
    def _generate_text_key_index(self, text_key_references=None,
1860
        ancestors=None):
2988.1.3 by Robert Collins
Add a new repositoy method _generate_text_key_index for use by reconcile/check.
1861
        """Generate a new text key index for the repository.
1862
1863
        This is an expensive function that will take considerable time to run.
1864
1865
        :return: A dict mapping text keys ((file_id, revision_id) tuples) to a
1866
            list of parents, also text keys. When a given key has no parents,
1867
            the parents list will be [NULL_REVISION].
1868
        """
1869
        # All revisions, to find inventory parents.
3063.2.1 by Robert Collins
Solve reconciling erroring when multiple portions of a single delta chain are being reinserted.
1870
        if ancestors is None:
3287.6.1 by Robert Collins
* ``VersionedFile.get_graph`` is deprecated, with no replacement method.
1871
            graph = self.get_graph()
1872
            ancestors = graph.get_parent_map(self.all_revision_ids())
2951.2.9 by Robert Collins
* ``pack-0.92`` repositories can now be reconciled.
1873
        if text_key_references is None:
1874
            text_key_references = self.find_text_key_references()
2988.3.1 by Robert Collins
Handle the progress bar in _generate_text_key_index correctly.
1875
        pb = ui.ui_factory.nested_progress_bar()
1876
        try:
1877
            return self._do_generate_text_key_index(ancestors,
1878
                text_key_references, pb)
1879
        finally:
1880
            pb.finished()
1881
1882
    def _do_generate_text_key_index(self, ancestors, text_key_references, pb):
1883
        """Helper for _generate_text_key_index to avoid deep nesting."""
2988.1.3 by Robert Collins
Add a new repositoy method _generate_text_key_index for use by reconcile/check.
1884
        revision_order = tsort.topo_sort(ancestors)
1885
        invalid_keys = set()
1886
        revision_keys = {}
1887
        for revision_id in revision_order:
1888
            revision_keys[revision_id] = set()
1889
        text_count = len(text_key_references)
1890
        # a cache of the text keys to allow reuse; costs a dict of all the
1891
        # keys, but saves a 2-tuple for every child of a given key.
1892
        text_key_cache = {}
1893
        for text_key, valid in text_key_references.iteritems():
1894
            if not valid:
1895
                invalid_keys.add(text_key)
1896
            else:
1897
                revision_keys[text_key[1]].add(text_key)
1898
            text_key_cache[text_key] = text_key
1899
        del text_key_references
1900
        text_index = {}
1901
        text_graph = graph.Graph(graph.DictParentsProvider(text_index))
1902
        NULL_REVISION = _mod_revision.NULL_REVISION
2988.1.5 by Robert Collins
Use a LRU cache when generating the text index to reduce inventory deserialisations.
1903
        # Set a cache with a size of 10 - this suffices for bzr.dev but may be
1904
        # too small for large or very branchy trees. However, for 55K path
1905
        # trees, it would be easy to use too much memory trivially. Ideally we
1906
        # could gauge this by looking at available real memory etc, but this is
1907
        # always a tricky proposition.
1908
        inventory_cache = lru_cache.LRUCache(10)
2988.1.3 by Robert Collins
Add a new repositoy method _generate_text_key_index for use by reconcile/check.
1909
        batch_size = 10 # should be ~150MB on a 55K path tree
1910
        batch_count = len(revision_order) / batch_size + 1
1911
        processed_texts = 0
4103.3.2 by Martin Pool
Remove trailing punctuation from progress messages
1912
        pb.update("Calculating text parents", processed_texts, text_count)
2988.1.3 by Robert Collins
Add a new repositoy method _generate_text_key_index for use by reconcile/check.
1913
        for offset in xrange(batch_count):
1914
            to_query = revision_order[offset * batch_size:(offset + 1) *
1915
                batch_size]
1916
            if not to_query:
1917
                break
1918
            for rev_tree in self.revision_trees(to_query):
1919
                revision_id = rev_tree.get_revision_id()
1920
                parent_ids = ancestors[revision_id]
1921
                for text_key in revision_keys[revision_id]:
4103.3.2 by Martin Pool
Remove trailing punctuation from progress messages
1922
                    pb.update("Calculating text parents", processed_texts)
2988.1.3 by Robert Collins
Add a new repositoy method _generate_text_key_index for use by reconcile/check.
1923
                    processed_texts += 1
1924
                    candidate_parents = []
1925
                    for parent_id in parent_ids:
1926
                        parent_text_key = (text_key[0], parent_id)
1927
                        try:
1928
                            check_parent = parent_text_key not in \
1929
                                revision_keys[parent_id]
1930
                        except KeyError:
1931
                            # the parent parent_id is a ghost:
1932
                            check_parent = False
1933
                            # truncate the derived graph against this ghost.
1934
                            parent_text_key = None
1935
                        if check_parent:
1936
                            # look at the parent commit details inventories to
1937
                            # determine possible candidates in the per file graph.
1938
                            # TODO: cache here.
2988.1.5 by Robert Collins
Use a LRU cache when generating the text index to reduce inventory deserialisations.
1939
                            try:
1940
                                inv = inventory_cache[parent_id]
1941
                            except KeyError:
1942
                                inv = self.revision_tree(parent_id).inventory
1943
                                inventory_cache[parent_id] = inv
1944
                            parent_entry = inv._byid.get(text_key[0], None)
2988.1.3 by Robert Collins
Add a new repositoy method _generate_text_key_index for use by reconcile/check.
1945
                            if parent_entry is not None:
1946
                                parent_text_key = (
1947
                                    text_key[0], parent_entry.revision)
1948
                            else:
1949
                                parent_text_key = None
1950
                        if parent_text_key is not None:
1951
                            candidate_parents.append(
1952
                                text_key_cache[parent_text_key])
1953
                    parent_heads = text_graph.heads(candidate_parents)
1954
                    new_parents = list(parent_heads)
1955
                    new_parents.sort(key=lambda x:candidate_parents.index(x))
1956
                    if new_parents == []:
1957
                        new_parents = [NULL_REVISION]
1958
                    text_index[text_key] = new_parents
1959
1960
        for text_key in invalid_keys:
1961
            text_index[text_key] = [NULL_REVISION]
1962
        return text_index
1963
2668.2.8 by Andrew Bennetts
Rename get_data_to_fetch_for_revision_ids as item_keys_introduced_by.
1964
    def item_keys_introduced_by(self, revision_ids, _files_pb=None):
1965
        """Get an iterable listing the keys of all the data introduced by a set
1966
        of revision IDs.
1967
1968
        The keys will be ordered so that the corresponding items can be safely
1969
        fetched and inserted in that order.
1970
1971
        :returns: An iterable producing tuples of (knit-kind, file-id,
1972
            versions).  knit-kind is one of 'file', 'inventory', 'signatures',
1973
            'revisions'.  file-id is None unless knit-kind is 'file'.
2535.3.6 by Andrew Bennetts
Move some "what repo data to fetch logic" from RepoFetcher to Repository.
1974
        """
1975
        # XXX: it's a bit weird to control the inventory weave caching in this
2535.3.7 by Andrew Bennetts
Remove now unused _fetch_weave_texts, make progress reporting closer to how it was before I refactored __fetch.
1976
        # generator.  Ideally the caching would be done in fetch.py I think.  Or
1977
        # maybe this generator should explicitly have the contract that it
1978
        # should not be iterated until the previously yielded item has been
1979
        # processed?
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1980
        inv_w = self.inventories
2535.3.6 by Andrew Bennetts
Move some "what repo data to fetch logic" from RepoFetcher to Repository.
1981
1982
        # file ids that changed
3422.1.1 by John Arbash Meinel
merge in bzr-1.5rc1, revert the transaction cache change
1983
        file_ids = self.fileids_altered_by_revision_ids(revision_ids, inv_w)
2535.3.8 by Andrew Bennetts
Unbreak progress reporting.
1984
        count = 0
1985
        num_file_ids = len(file_ids)
2535.3.6 by Andrew Bennetts
Move some "what repo data to fetch logic" from RepoFetcher to Repository.
1986
        for file_id, altered_versions in file_ids.iteritems():
2668.2.8 by Andrew Bennetts
Rename get_data_to_fetch_for_revision_ids as item_keys_introduced_by.
1987
            if _files_pb is not None:
1988
                _files_pb.update("fetch texts", count, num_file_ids)
2535.3.8 by Andrew Bennetts
Unbreak progress reporting.
1989
            count += 1
2535.3.6 by Andrew Bennetts
Move some "what repo data to fetch logic" from RepoFetcher to Repository.
1990
            yield ("file", file_id, altered_versions)
2535.3.9 by Andrew Bennetts
More comments.
1991
        # We're done with the files_pb.  Note that it finished by the caller,
1992
        # just as it was created by the caller.
2668.2.8 by Andrew Bennetts
Rename get_data_to_fetch_for_revision_ids as item_keys_introduced_by.
1993
        del _files_pb
2535.3.6 by Andrew Bennetts
Move some "what repo data to fetch logic" from RepoFetcher to Repository.
1994
1995
        # inventory
1996
        yield ("inventory", None, revision_ids)
1997
1998
        # signatures
3825.5.2 by Andrew Bennetts
Ensure that item_keys_introduced_by returns the
1999
        # XXX: Note ATM no callers actually pay attention to this return
2000
        #      instead they just use the list of revision ids and ignore
2001
        #      missing sigs. Consider removing this work entirely
2002
        revisions_with_signatures = set(self.signatures.get_parent_map(
2003
            [(r,) for r in revision_ids]))
3825.5.1 by Andrew Bennetts
Improve determining signatures to transfer in item_keys_introduced_by.
2004
        revisions_with_signatures = set(
3825.5.2 by Andrew Bennetts
Ensure that item_keys_introduced_by returns the
2005
            [r for (r,) in revisions_with_signatures])
3825.5.1 by Andrew Bennetts
Improve determining signatures to transfer in item_keys_introduced_by.
2006
        revisions_with_signatures.intersection_update(revision_ids)
2535.3.25 by Andrew Bennetts
Fetch signatures too.
2007
        yield ("signatures", None, revisions_with_signatures)
2535.3.6 by Andrew Bennetts
Move some "what repo data to fetch logic" from RepoFetcher to Repository.
2008
2009
        # revisions
2010
        yield ("revisions", None, revision_ids)
2011
1185.65.27 by Robert Collins
Tweak storage towards mergability.
2012
    @needs_read_lock
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
2013
    def get_inventory(self, revision_id):
3169.2.1 by Robert Collins
New method ``iter_inventories`` on Repository for access to many
2014
        """Get Inventory object by revision id."""
2015
        return self.iter_inventories([revision_id]).next()
2016
2017
    def iter_inventories(self, revision_ids):
2018
        """Get many inventories by revision_ids.
2019
2020
        This will buffer some or all of the texts used in constructing the
2021
        inventories in memory, but will only parse a single inventory at a
2022
        time.
2023
4202.2.1 by Ian Clatworthy
get directory logging working again
2024
        :param revision_ids: The expected revision ids of the inventories.
3169.2.1 by Robert Collins
New method ``iter_inventories`` on Repository for access to many
2025
        :return: An iterator of inventories.
2026
        """
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
2027
        if ((None in revision_ids)
2028
            or (_mod_revision.NULL_REVISION in revision_ids)):
2029
            raise ValueError('cannot get null revision inventory')
3169.2.1 by Robert Collins
New method ``iter_inventories`` on Repository for access to many
2030
        return self._iter_inventories(revision_ids)
2031
2032
    def _iter_inventories(self, revision_ids):
2033
        """single-document based inventory iteration."""
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2034
        for text, revision_id in self._iter_inventory_xmls(revision_ids):
3169.2.1 by Robert Collins
New method ``iter_inventories`` on Repository for access to many
2035
            yield self.deserialise_inventory(revision_id, text)
1740.2.3 by Aaron Bentley
Only reserialize the working tree basis inventory when needed.
2036
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2037
    def _iter_inventory_xmls(self, revision_ids):
2038
        keys = [(revision_id,) for revision_id in revision_ids]
2039
        stream = self.inventories.get_record_stream(keys, 'unordered', True)
3890.2.3 by John Arbash Meinel
Use the 'chunked' interface to keep memory consumption minimal during revision_trees()
2040
        text_chunks = {}
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2041
        for record in stream:
2042
            if record.storage_kind != 'absent':
3890.2.3 by John Arbash Meinel
Use the 'chunked' interface to keep memory consumption minimal during revision_trees()
2043
                text_chunks[record.key] = record.get_bytes_as('chunked')
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2044
            else:
2045
                raise errors.NoSuchRevision(self, record.key)
2046
        for key in keys:
3890.2.3 by John Arbash Meinel
Use the 'chunked' interface to keep memory consumption minimal during revision_trees()
2047
            chunks = text_chunks.pop(key)
2048
            yield ''.join(chunks), key[-1]
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2049
1740.2.3 by Aaron Bentley
Only reserialize the working tree basis inventory when needed.
2050
    def deserialise_inventory(self, revision_id, xml):
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2051
        """Transform the xml into an inventory object.
1740.2.3 by Aaron Bentley
Only reserialize the working tree basis inventory when needed.
2052
2053
        :param revision_id: The expected revision id of the inventory.
2054
        :param xml: A serialised inventory.
2055
        """
3882.6.23 by John Arbash Meinel
Change the XMLSerializer.read_inventory_from_string api.
2056
        result = self._serializer.read_inventory_from_string(xml, revision_id,
2057
                    entry_cache=self._inventory_entry_cache)
3169.2.3 by Robert Collins
Use an if, not an assert, as we test with -O.
2058
        if result.revision_id != revision_id:
2059
            raise AssertionError('revision id mismatch %s != %s' % (
2060
                result.revision_id, revision_id))
3169.2.2 by Robert Collins
Add a test to Repository.deserialise_inventory that the resulting ivnentory is the one asked for, and update relevant tests. Also tweak the model 1 to 2 regenerate inventories logic to use the revision trees parent marker which is more accurate in some cases.
2061
        return result
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
2062
1910.2.22 by Aaron Bentley
Make commits preserve root entry data
2063
    def serialise_inventory(self, inv):
1910.2.48 by Aaron Bentley
Update from review comments
2064
        return self._serializer.write_inventory_to_string(inv)
1910.2.22 by Aaron Bentley
Make commits preserve root entry data
2065
2817.2.1 by Robert Collins
* Inventory serialisation no longer double-sha's the content.
2066
    def _serialise_inventory_to_lines(self, inv):
2067
        return self._serializer.write_inventory_to_lines(inv)
2068
2520.4.113 by Aaron Bentley
Avoid peeking at Repository._serializer
2069
    def get_serializer_format(self):
2070
        return self._serializer.format_num
2071
1185.65.27 by Robert Collins
Tweak storage towards mergability.
2072
    @needs_read_lock
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
2073
    def get_inventory_xml(self, revision_id):
2074
        """Get inventory XML as a file object."""
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2075
        texts = self._iter_inventory_xmls([revision_id])
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
2076
        try:
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2077
            text, revision_id = texts.next()
2078
        except StopIteration:
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
2079
            raise errors.HistoryMissing(self, 'inventory', revision_id)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2080
        return text
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
2081
1185.65.27 by Robert Collins
Tweak storage towards mergability.
2082
    @needs_read_lock
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
2083
    def get_inventory_sha1(self, revision_id):
2084
        """Return the sha1 hash of the inventory entry
2085
        """
2086
        return self.get_revision(revision_id).inventory_sha1
2087
2230.3.54 by Aaron Bentley
Move reverse history iteration to repository
2088
    def iter_reverse_revision_history(self, revision_id):
2089
        """Iterate backwards through revision ids in the lefthand history
2090
2091
        :param revision_id: The revision id to start with.  All its lefthand
2092
            ancestors will be traversed.
2093
        """
3287.5.2 by Robert Collins
Deprecate VersionedFile.get_parents, breaking pulling from a ghost containing knit or pack repository to weaves, which improves correctness and allows simplification of core code.
2094
        graph = self.get_graph()
2230.3.54 by Aaron Bentley
Move reverse history iteration to repository
2095
        next_id = revision_id
2096
        while True:
3287.5.2 by Robert Collins
Deprecate VersionedFile.get_parents, breaking pulling from a ghost containing knit or pack repository to weaves, which improves correctness and allows simplification of core code.
2097
            if next_id in (None, _mod_revision.NULL_REVISION):
2098
                return
2230.3.54 by Aaron Bentley
Move reverse history iteration to repository
2099
            yield next_id
3287.5.10 by Robert Collins
Note iter_reverse_revision_history exception decision.
2100
            # Note: The following line may raise KeyError in the event of
2101
            # truncated history. We decided not to have a try:except:raise
2102
            # RevisionNotPresent here until we see a use for it, because of the
2103
            # cost in an inner loop that is by its very nature O(history).
2104
            # Robert Collins 20080326
3287.5.2 by Robert Collins
Deprecate VersionedFile.get_parents, breaking pulling from a ghost containing knit or pack repository to weaves, which improves correctness and allows simplification of core code.
2105
            parents = graph.get_parent_map([next_id])[next_id]
2230.3.54 by Aaron Bentley
Move reverse history iteration to repository
2106
            if len(parents) == 0:
2107
                return
2108
            else:
2109
                next_id = parents[0]
2110
1594.2.3 by Robert Collins
bugfix revision.MultipleRevisionSources.get_revision_graph to integrate ghosts between sources. [slow on weaves, fast on knits.
2111
    @needs_read_lock
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
2112
    def get_revision_inventory(self, revision_id):
2113
        """Return inventory of a past revision."""
2114
        # TODO: Unify this with get_inventory()
2115
        # bzr 0.0.6 and later imposes the constraint that the inventory_id
2116
        # must be the same as its revision, so this is trivial.
1534.4.28 by Robert Collins
first cut at merge from integration.
2117
        if revision_id is None:
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
2118
            # This does not make sense: if there is no revision,
2119
            # then it is the current tree inventory surely ?!
2120
            # and thus get_root_id() is something that looks at the last
2121
            # commit on the branch, and the get_root_id is an inventory check.
2122
            raise NotImplementedError
2123
            # return Inventory(self.get_root_id())
2124
        else:
2125
            return self.get_inventory(revision_id)
2126
1534.6.3 by Robert Collins
find_repository sufficiently robust.
2127
    def is_shared(self):
2128
        """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.
2129
        raise NotImplementedError(self.is_shared)
1534.6.3 by Robert Collins
find_repository sufficiently robust.
2130
1594.2.7 by Robert Collins
Add versionedfile.fix_parents api for correcting data post hoc.
2131
    @needs_write_lock
1692.1.1 by Robert Collins
* Repository.reconcile now takes a thorough keyword parameter to allow
2132
    def reconcile(self, other=None, thorough=False):
1594.2.7 by Robert Collins
Add versionedfile.fix_parents api for correcting data post hoc.
2133
        """Reconcile this repository."""
2134
        from bzrlib.reconcile import RepoReconciler
1692.1.1 by Robert Collins
* Repository.reconcile now takes a thorough keyword parameter to allow
2135
        reconciler = RepoReconciler(self, thorough=thorough)
1594.2.7 by Robert Collins
Add versionedfile.fix_parents api for correcting data post hoc.
2136
        reconciler.reconcile()
2137
        return reconciler
2440.1.1 by Martin Pool
Add new Repository.sprout,
2138
2617.6.2 by Robert Collins
Add abort_write_group and wire write_groups into fetch and commit.
2139
    def _refresh_data(self):
2140
        """Helper called from lock_* to ensure coherency with disk.
2141
2142
        The default implementation does nothing; it is however possible
2143
        for repositories to maintain loaded indices across multiple locks
2144
        by checking inside their implementation of this method to see
2145
        whether their indices are still valid. This depends of course on
4145.1.2 by Robert Collins
Add a refresh_data method on Repository allowing cleaner handling of insertions into RemoteRepository objects with _real_repository instances.
2146
        the disk format being validatable in this manner. This method is
2147
        also called by the refresh_data() public interface to cause a refresh
2148
        to occur while in a write lock so that data inserted by a smart server
2149
        push operation is visible on the client's instance of the physical
2150
        repository.
2617.6.2 by Robert Collins
Add abort_write_group and wire write_groups into fetch and commit.
2151
        """
2152
1534.6.3 by Robert Collins
find_repository sufficiently robust.
2153
    @needs_read_lock
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
2154
    def revision_tree(self, revision_id):
2155
        """Return Tree for a revision on this branch.
2156
3668.5.2 by Jelmer Vernooij
Fix docstring.
2157
        `revision_id` may be NULL_REVISION for the empty tree revision.
1852.5.1 by Robert Collins
Deprecate EmptyTree in favour of using Repository.revision_tree.
2158
        """
3668.5.1 by Jelmer Vernooij
Use NULL_REVISION rather than None for Repository.revision_tree().
2159
        revision_id = _mod_revision.ensure_null(revision_id)
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
2160
        # TODO: refactor this to use an existing revision object
2161
        # so we don't need to read it in twice.
3668.5.1 by Jelmer Vernooij
Use NULL_REVISION rather than None for Repository.revision_tree().
2162
        if revision_id == _mod_revision.NULL_REVISION:
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2163
            return RevisionTree(self, Inventory(root_id=None),
1731.1.61 by Aaron Bentley
Merge bzr.dev
2164
                                _mod_revision.NULL_REVISION)
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
2165
        else:
2166
            inv = self.get_revision_inventory(revision_id)
1185.65.17 by Robert Collins
Merge from integration, mode-changes are broken.
2167
            return RevisionTree(self, inv, revision_id)
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
2168
1756.3.3 by Aaron Bentley
More refactoring, introduce revision_trees.
2169
    def revision_trees(self, revision_ids):
4137.3.2 by Ian Clatworthy
Repository.get_deltas_for_revisions() now supports file-id filtering
2170
        """Return Trees for revisions in this repository.
1756.3.3 by Aaron Bentley
More refactoring, introduce revision_trees.
2171
4137.3.2 by Ian Clatworthy
Repository.get_deltas_for_revisions() now supports file-id filtering
2172
        :param revision_ids: a sequence of revision-ids;
2173
          a revision-id may not be None or 'null:'
2174
        """
3169.2.1 by Robert Collins
New method ``iter_inventories`` on Repository for access to many
2175
        inventories = self.iter_inventories(revision_ids)
2176
        for inv in inventories:
2177
            yield RevisionTree(self, inv, inv.revision_id)
1756.3.3 by Aaron Bentley
More refactoring, introduce revision_trees.
2178
4137.3.2 by Ian Clatworthy
Repository.get_deltas_for_revisions() now supports file-id filtering
2179
    def _filtered_revision_trees(self, revision_ids, file_ids):
2180
        """Return Tree for a revision on this branch with only some files.
2181
2182
        :param revision_ids: a sequence of revision-ids;
2183
          a revision-id may not be None or 'null:'
2184
        :param file_ids: if not None, the result is filtered
2185
          so that only those file-ids, their parents and their
2186
          children are included.
2187
        """
2188
        inventories = self.iter_inventories(revision_ids)
2189
        for inv in inventories:
2190
            # Should we introduce a FilteredRevisionTree class rather
2191
            # than pre-filter the inventory here?
2192
            filtered_inv = inv.filter(file_ids)
2193
            yield RevisionTree(self, filtered_inv, filtered_inv.revision_id)
2194
1756.3.3 by Aaron Bentley
More refactoring, introduce revision_trees.
2195
    @needs_read_lock
2530.1.1 by Aaron Bentley
Make topological sorting optional for get_ancestry
2196
    def get_ancestry(self, revision_id, topo_sorted=True):
1185.66.2 by Aaron Bentley
Moved get_ancestry to RevisionStorage
2197
        """Return a list of revision-ids integrated by a revision.
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
2198
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2199
        The first element of the list is always None, indicating the origin
2200
        revision.  This might change when we have history horizons, or
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
2201
        perhaps we should have a new API.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2202
1185.66.2 by Aaron Bentley
Moved get_ancestry to RevisionStorage
2203
        This is topologically sorted.
2204
        """
2598.5.1 by Aaron Bentley
Start eliminating the use of None to indicate null revision
2205
        if _mod_revision.is_null(revision_id):
1185.66.2 by Aaron Bentley
Moved get_ancestry to RevisionStorage
2206
            return [None]
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
2207
        if not self.has_revision(revision_id):
2208
            raise errors.NoSuchRevision(self, revision_id)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2209
        graph = self.get_graph()
2210
        keys = set()
2211
        search = graph._make_breadth_first_searcher([revision_id])
2212
        while True:
2213
            try:
2214
                found, ghosts = search.next_with_ghosts()
2215
            except StopIteration:
2216
                break
2217
            keys.update(found)
2218
        if _mod_revision.NULL_REVISION in keys:
2219
            keys.remove(_mod_revision.NULL_REVISION)
2220
        if topo_sorted:
2221
            parent_map = graph.get_parent_map(keys)
2222
            keys = tsort.topo_sort(parent_map)
2223
        return [None] + list(keys)
1185.66.2 by Aaron Bentley
Moved get_ancestry to RevisionStorage
2224
2604.2.1 by Robert Collins
(robertc) Introduce a pack command.
2225
    def pack(self):
2226
        """Compress the data within the repository.
2227
2228
        This operation only makes sense for some repository types. For other
2229
        types it should be a no-op that just returns.
2230
2231
        This stub method does not require a lock, but subclasses should use
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2232
        @needs_write_lock as this is a long running call its reasonable to
2604.2.1 by Robert Collins
(robertc) Introduce a pack command.
2233
        implicitly lock for the user.
2234
        """
2235
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
2236
    def get_transaction(self):
2237
        return self.control_files.get_transaction()
2238
3517.4.17 by Martin Pool
Redo base Repository.get_parent_map to use .revisions graph
2239
    def get_parent_map(self, revision_ids):
3099.3.1 by John Arbash Meinel
Implement get_parent_map for ParentProviders
2240
        """See graph._StackedParentsProvider.get_parent_map"""
3517.4.17 by Martin Pool
Redo base Repository.get_parent_map to use .revisions graph
2241
        # revisions index works in keys; this just works in revisions
2242
        # therefore wrap and unwrap
2243
        query_keys = []
2244
        result = {}
2245
        for revision_id in revision_ids:
2246
            if revision_id == _mod_revision.NULL_REVISION:
2247
                result[revision_id] = ()
2248
            elif revision_id is None:
3373.5.2 by John Arbash Meinel
Add repository_implementation tests for get_parent_map
2249
                raise ValueError('get_parent_map(None) is not valid')
3517.4.17 by Martin Pool
Redo base Repository.get_parent_map to use .revisions graph
2250
            else:
2251
                query_keys.append((revision_id ,))
2252
        for ((revision_id,), parent_keys) in \
2253
                self.revisions.get_parent_map(query_keys).iteritems():
2254
            if parent_keys:
2255
                result[revision_id] = tuple(parent_revid
2256
                    for (parent_revid,) in parent_keys)
2257
            else:
2258
                result[revision_id] = (_mod_revision.NULL_REVISION,)
2259
        return result
2490.2.13 by Aaron Bentley
Update distinct -> lowest, refactor, add ParentsProvider concept
2260
2261
    def _make_parents_provider(self):
2262
        return self
2263
2490.2.21 by Aaron Bentley
Rename graph to deprecated_graph
2264
    def get_graph(self, other_repository=None):
2490.2.13 by Aaron Bentley
Update distinct -> lowest, refactor, add ParentsProvider concept
2265
        """Return the graph walker for this repository format"""
2266
        parents_provider = self._make_parents_provider()
2490.2.14 by Aaron Bentley
Avoid StackedParentsProvider when underlying repos match
2267
        if (other_repository is not None and
3211.3.1 by Jelmer Vernooij
Use convenience function to check whether two repository handles are referring to the same repository.
2268
            not self.has_same_location(other_repository)):
2490.2.21 by Aaron Bentley
Rename graph to deprecated_graph
2269
            parents_provider = graph._StackedParentsProvider(
2490.2.13 by Aaron Bentley
Update distinct -> lowest, refactor, add ParentsProvider concept
2270
                [parents_provider, other_repository._make_parents_provider()])
2490.2.22 by Aaron Bentley
Rename GraphWalker -> Graph, _AncestryWalker -> _BreadthFirstSearcher
2271
        return graph.Graph(parents_provider)
2490.2.13 by Aaron Bentley
Update distinct -> lowest, refactor, add ParentsProvider concept
2272
4145.2.1 by Ian Clatworthy
faster check
2273
    def _get_versioned_file_checker(self, text_key_references=None):
2274
        """Return an object suitable for checking versioned files.
2275
        
2276
        :param text_key_references: if non-None, an already built
2277
            dictionary mapping text keys ((fileid, revision_id) tuples)
2278
            to whether they were referred to by the inventory of the
2279
            revision_id that they contain. If None, this will be
2280
            calculated.
2281
        """
2282
        return _VersionedFileChecker(self,
2283
            text_key_references=text_key_references)
2745.6.47 by Andrew Bennetts
Move check_parents out of VersionedFile.
2284
3184.1.9 by Robert Collins
* ``Repository.get_data_stream`` is now deprecated in favour of
2285
    def revision_ids_to_search_result(self, result_set):
2286
        """Convert a set of revision ids to a graph SearchResult."""
2287
        result_parents = set()
2288
        for parents in self.get_graph().get_parent_map(
2289
            result_set).itervalues():
2290
            result_parents.update(parents)
2291
        included_keys = result_set.intersection(result_parents)
2292
        start_keys = result_set.difference(included_keys)
2293
        exclude_keys = result_parents.difference(result_set)
2294
        result = graph.SearchResult(start_keys, exclude_keys,
2295
            len(result_set), result_set)
2296
        return result
2297
1185.65.27 by Robert Collins
Tweak storage towards mergability.
2298
    @needs_write_lock
1534.6.5 by Robert Collins
Cloning of repos preserves shared and make-working-tree attributes.
2299
    def set_make_working_trees(self, new_value):
2300
        """Set the policy flag for making working trees when creating branches.
2301
2302
        This only applies to branches that use this repository.
2303
2304
        The default is 'True'.
2305
        :param new_value: True to restore the default, False to disable making
2306
                          working trees.
2307
        """
1596.2.12 by Robert Collins
Merge and make Knit Repository use the revision store for all possible queries.
2308
        raise NotImplementedError(self.set_make_working_trees)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2309
1534.6.5 by Robert Collins
Cloning of repos preserves shared and make-working-tree attributes.
2310
    def make_working_trees(self):
2311
        """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.
2312
        raise NotImplementedError(self.make_working_trees)
1534.6.5 by Robert Collins
Cloning of repos preserves shared and make-working-tree attributes.
2313
2314
    @needs_write_lock
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
2315
    def sign_revision(self, revision_id, gpg_strategy):
2316
        plaintext = Testament.from_revision(self, revision_id).as_short_text()
2317
        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.
2318
1563.2.29 by Robert Collins
Remove all but fetch references to repository.revision_store.
2319
    @needs_read_lock
2320
    def has_signature_for_revision_id(self, revision_id):
2321
        """Query for a revision signature for revision_id in the repository."""
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2322
        if not self.has_revision(revision_id):
2323
            raise errors.NoSuchRevision(self, revision_id)
2324
        sig_present = (1 == len(
2325
            self.signatures.get_parent_map([(revision_id,)])))
2326
        return sig_present
1563.2.29 by Robert Collins
Remove all but fetch references to repository.revision_store.
2327
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
2328
    @needs_read_lock
2329
    def get_signature_text(self, revision_id):
2330
        """Return the text for a signature."""
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2331
        stream = self.signatures.get_record_stream([(revision_id,)],
2332
            'unordered', True)
2333
        record = stream.next()
2334
        if record.storage_kind == 'absent':
2335
            raise errors.NoSuchRevision(self, revision_id)
2336
        return record.get_bytes_as('fulltext')
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
2337
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
2338
    @needs_read_lock
2745.6.36 by Andrew Bennetts
Deprecate revision_ids arg to Repository.check and other tweaks.
2339
    def check(self, revision_ids=None):
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
2340
        """Check consistency of all history of given revision_ids.
2341
2342
        Different repository implementations should override _check().
2343
2344
        :param revision_ids: A non-empty list of revision_ids whose ancestry
2345
             will be checked.  Typically the last revision_id of a branch.
2346
        """
2347
        return self._check(revision_ids)
2348
2349
    def _check(self, revision_ids):
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
2350
        result = check.Check(self)
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
2351
        result.check()
2352
        return result
2353
1904.2.3 by Martin Pool
Give a warning on access to old repository formats
2354
    def _warn_if_deprecated(self):
1904.2.5 by Martin Pool
Fix format warning inside test suite and add test
2355
        global _deprecation_warning_done
2356
        if _deprecation_warning_done:
2357
            return
2358
        _deprecation_warning_done = True
1904.2.3 by Martin Pool
Give a warning on access to old repository formats
2359
        warning("Format %s for %s is deprecated - please use 'bzr upgrade' to get better performance"
2360
                % (self._format, self.bzrdir.transport.base))
2361
1910.2.63 by Aaron Bentley
Add supports_rich_root member to repository
2362
    def supports_rich_root(self):
2363
        return self._format.rich_root_data
2364
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.
2365
    def _check_ascii_revisionid(self, revision_id, method):
2366
        """Private helper for ascii-only repositories."""
2367
        # weave repositories refuse to store revisionids that are non-ascii.
2368
        if revision_id is not None:
2369
            # weaves require ascii revision ids.
2370
            if isinstance(revision_id, unicode):
2371
                try:
2372
                    revision_id.encode('ascii')
2373
                except UnicodeEncodeError:
2374
                    raise errors.NonAsciiRevisionId(method, self)
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
2375
            else:
2376
                try:
2377
                    revision_id.decode('ascii')
2378
                except UnicodeDecodeError:
2379
                    raise errors.NonAsciiRevisionId(method, self)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2380
2819.2.4 by Andrew Bennetts
Add a 'revision_graph_can_have_wrong_parents' method to repository.
2381
    def revision_graph_can_have_wrong_parents(self):
2382
        """Is it possible for this repository to have a revision graph with
2383
        incorrect parents?
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.
2384
2819.2.4 by Andrew Bennetts
Add a 'revision_graph_can_have_wrong_parents' method to repository.
2385
        If True, then this repository must also implement
2386
        _find_inconsistent_revision_parents so that check and reconcile can
2387
        check for inconsistencies before proceeding with other checks that may
2388
        depend on the revision index being consistent.
2389
        """
2390
        raise NotImplementedError(self.revision_graph_can_have_wrong_parents)
3184.1.9 by Robert Collins
* ``Repository.get_data_stream`` is now deprecated in favour of
2391
2392
2241.1.18 by mbp at sourcefrog
Restore use of deprecating delegator for old formats in bzrlib.repository.
2393
# remove these delegates a while after bzr 0.15
2394
def __make_delegated(name, from_module):
2395
    def _deprecated_repository_forwarder():
2396
        symbol_versioning.warn('%s moved to %s in bzr 0.15'
2397
            % (name, from_module),
2241.1.20 by mbp at sourcefrog
update tests for new locations of weave repos
2398
            DeprecationWarning,
2399
            stacklevel=2)
2241.1.18 by mbp at sourcefrog
Restore use of deprecating delegator for old formats in bzrlib.repository.
2400
        m = __import__(from_module, globals(), locals(), [name])
2401
        try:
2402
            return getattr(m, name)
2403
        except AttributeError:
2404
            raise AttributeError('module %s has no name %s'
2405
                    % (m, name))
2406
    globals()[name] = _deprecated_repository_forwarder
2407
2408
for _name in [
2409
        'AllInOneRepository',
2410
        'WeaveMetaDirRepository',
2411
        'PreSplitOutRepositoryFormat',
2412
        'RepositoryFormat4',
2413
        'RepositoryFormat5',
2414
        'RepositoryFormat6',
2415
        'RepositoryFormat7',
2416
        ]:
2417
    __make_delegated(_name, 'bzrlib.repofmt.weaverepo')
2418
2419
for _name in [
2420
        'KnitRepository',
2421
        'RepositoryFormatKnit',
2422
        'RepositoryFormatKnit1',
2423
        ]:
2424
    __make_delegated(_name, 'bzrlib.repofmt.knitrepo')
2425
2426
2996.2.2 by Aaron Bentley
Create install_revisions function
2427
def install_revision(repository, rev, revision_tree):
2428
    """Install all revision data into a repository."""
2429
    install_revisions(repository, [(rev, revision_tree, None)])
2430
2431
3146.6.1 by Aaron Bentley
InterDifferingSerializer shows a progress bar
2432
def install_revisions(repository, iterable, num_revisions=None, pb=None):
2996.2.4 by Aaron Bentley
Rename function to add_signature_text
2433
    """Install all revision data into a repository.
2434
2435
    Accepts an iterable of revision, tree, signature tuples.  The signature
2436
    may be None.
2437
    """
2592.3.96 by Robert Collins
Merge index improvements (includes bzr.dev).
2438
    repository.start_write_group()
2439
    try:
3146.6.1 by Aaron Bentley
InterDifferingSerializer shows a progress bar
2440
        for n, (revision, revision_tree, signature) in enumerate(iterable):
2996.2.2 by Aaron Bentley
Create install_revisions function
2441
            _install_revision(repository, revision, revision_tree, signature)
3146.6.1 by Aaron Bentley
InterDifferingSerializer shows a progress bar
2442
            if pb is not None:
2443
                pb.update('Transferring revisions', n + 1, num_revisions)
2592.3.96 by Robert Collins
Merge index improvements (includes bzr.dev).
2444
    except:
2445
        repository.abort_write_group()
2592.3.101 by Robert Collins
Correctly propogate exceptions from repository.install_revisions.
2446
        raise
2592.3.96 by Robert Collins
Merge index improvements (includes bzr.dev).
2447
    else:
2448
        repository.commit_write_group()
2449
2450
2996.2.1 by Aaron Bentley
Add KnitRepositoryFormat4
2451
def _install_revision(repository, rev, revision_tree, signature):
2592.3.96 by Robert Collins
Merge index improvements (includes bzr.dev).
2452
    """Install all revision data into a repository."""
1185.82.84 by Aaron Bentley
Moved stuff around
2453
    present_parents = []
2454
    parent_trees = {}
2455
    for p_id in rev.parent_ids:
2456
        if repository.has_revision(p_id):
2457
            present_parents.append(p_id)
2458
            parent_trees[p_id] = repository.revision_tree(p_id)
2459
        else:
3668.5.1 by Jelmer Vernooij
Use NULL_REVISION rather than None for Repository.revision_tree().
2460
            parent_trees[p_id] = repository.revision_tree(
2461
                                     _mod_revision.NULL_REVISION)
1185.82.84 by Aaron Bentley
Moved stuff around
2462
2463
    inv = revision_tree.inventory
1910.2.51 by Aaron Bentley
Bundles now corrupt repositories
2464
    entries = inv.iter_entries()
2617.6.6 by Robert Collins
Some review feedback.
2465
    # backwards compatibility hack: skip the root id.
1910.2.63 by Aaron Bentley
Add supports_rich_root member to repository
2466
    if not repository.supports_rich_root():
1910.2.60 by Aaron Bentley
Ensure that new-model revisions aren't installed into old-model repos
2467
        path, root = entries.next()
2468
        if root.revision != rev.revision_id:
1910.2.63 by Aaron Bentley
Add supports_rich_root member to repository
2469
            raise errors.IncompatibleRevision(repr(repository))
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2470
    text_keys = {}
2471
    for path, ie in entries:
2472
        text_keys[(ie.file_id, ie.revision)] = ie
2473
    text_parent_map = repository.texts.get_parent_map(text_keys)
2474
    missing_texts = set(text_keys) - set(text_parent_map)
1185.82.84 by Aaron Bentley
Moved stuff around
2475
    # Add the texts that are not already present
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2476
    for text_key in missing_texts:
2477
        ie = text_keys[text_key]
2478
        text_parents = []
2479
        # FIXME: TODO: The following loop overlaps/duplicates that done by
2480
        # commit to determine parents. There is a latent/real bug here where
2481
        # the parents inserted are not those commit would do - in particular
2482
        # they are not filtered by heads(). RBC, AB
2483
        for revision, tree in parent_trees.iteritems():
2484
            if ie.file_id not in tree:
2485
                continue
2486
            parent_id = tree.inventory[ie.file_id].revision
2487
            if parent_id in text_parents:
2488
                continue
2489
            text_parents.append((ie.file_id, parent_id))
2490
        lines = revision_tree.get_file(ie.file_id).readlines()
2491
        repository.texts.add_lines(text_key, text_parents, lines)
1185.82.84 by Aaron Bentley
Moved stuff around
2492
    try:
2493
        # install the inventory
2494
        repository.add_inventory(rev.revision_id, inv, present_parents)
2495
    except errors.RevisionAlreadyPresent:
2496
        pass
2996.2.1 by Aaron Bentley
Add KnitRepositoryFormat4
2497
    if signature is not None:
2996.2.8 by Aaron Bentley
Fix add_signature discrepancies
2498
        repository.add_signature_text(rev.revision_id, signature)
1185.82.84 by Aaron Bentley
Moved stuff around
2499
    repository.add_revision(rev.revision_id, rev, inv)
2500
2501
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
2502
class MetaDirRepository(Repository):
3407.2.13 by Martin Pool
Remove indirection through control_files to get transports
2503
    """Repositories in the new meta-dir layout.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2504
3407.2.13 by Martin Pool
Remove indirection through control_files to get transports
2505
    :ivar _transport: Transport for access to repository control files,
2506
        typically pointing to .bzr/repository.
2507
    """
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
2508
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2509
    def __init__(self, _format, a_bzrdir, control_files):
2510
        super(MetaDirRepository, self).__init__(_format, a_bzrdir, control_files)
3407.2.3 by Martin Pool
Branch and Repository use their own ._transport rather than going through .control_files
2511
        self._transport = control_files._transport
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
2512
1596.2.12 by Robert Collins
Merge and make Knit Repository use the revision store for all possible queries.
2513
    def is_shared(self):
2514
        """Return True if this repository is flagged as a shared repository."""
3407.2.3 by Martin Pool
Branch and Repository use their own ._transport rather than going through .control_files
2515
        return self._transport.has('shared-storage')
1596.2.12 by Robert Collins
Merge and make Knit Repository use the revision store for all possible queries.
2516
2517
    @needs_write_lock
2518
    def set_make_working_trees(self, new_value):
2519
        """Set the policy flag for making working trees when creating branches.
2520
2521
        This only applies to branches that use this repository.
2522
2523
        The default is 'True'.
2524
        :param new_value: True to restore the default, False to disable making
2525
                          working trees.
2526
        """
2527
        if new_value:
2528
            try:
3407.2.3 by Martin Pool
Branch and Repository use their own ._transport rather than going through .control_files
2529
                self._transport.delete('no-working-trees')
1596.2.12 by Robert Collins
Merge and make Knit Repository use the revision store for all possible queries.
2530
            except errors.NoSuchFile:
2531
                pass
2532
        else:
3407.2.5 by Martin Pool
Deprecate LockableFiles.put_utf8
2533
            self._transport.put_bytes('no-working-trees', '',
3407.2.18 by Martin Pool
BzrDir takes responsibility for default file/dir modes
2534
                mode=self.bzrdir._get_file_mode())
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2535
1596.2.12 by Robert Collins
Merge and make Knit Repository use the revision store for all possible queries.
2536
    def make_working_trees(self):
2537
        """Returns the policy for making working trees on new branches."""
3407.2.3 by Martin Pool
Branch and Repository use their own ._transport rather than going through .control_files
2538
        return not self._transport.has('no-working-trees')
1596.2.12 by Robert Collins
Merge and make Knit Repository use the revision store for all possible queries.
2539
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
2540
3316.2.3 by Robert Collins
Remove manual notification of transaction finishing on versioned files.
2541
class MetaDirVersionedFileRepository(MetaDirRepository):
2542
    """Repositories in a meta-dir, that work via versioned file objects."""
2543
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2544
    def __init__(self, _format, a_bzrdir, control_files):
3316.2.5 by Robert Collins
Review feedback.
2545
        super(MetaDirVersionedFileRepository, self).__init__(_format, a_bzrdir,
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2546
            control_files)
3316.2.3 by Robert Collins
Remove manual notification of transaction finishing on versioned files.
2547
2548
4032.3.1 by Robert Collins
Add a BranchFormat.network_name() method as preparation for creating branches via RPC calls.
2549
network_format_registry = registry.FormatRegistry()
3990.5.3 by Robert Collins
Docs and polish on RepositoryFormat.network_name.
2550
"""Registry of formats indexed by their network name.
2551
2552
The network name for a repository format is an identifier that can be used when
2553
referring to formats with smart server operations. See
2554
RepositoryFormat.network_name() for more detail.
2555
"""
3990.5.1 by Andrew Bennetts
Add network_name() to RepositoryFormat.
2556
2557
4032.3.1 by Robert Collins
Add a BranchFormat.network_name() method as preparation for creating branches via RPC calls.
2558
format_registry = registry.FormatRegistry(network_format_registry)
3990.5.3 by Robert Collins
Docs and polish on RepositoryFormat.network_name.
2559
"""Registry of formats, indexed by their BzrDirMetaFormat format string.
2241.1.11 by Martin Pool
Get rid of RepositoryFormat*_instance objects. Instead the format
2560
2561
This can contain either format instances themselves, or classes/factories that
2562
can be called to obtain one.
2563
"""
2241.1.2 by Martin Pool
change to using external Repository format registry
2564
2220.2.3 by Martin Pool
Add tag: revision namespace.
2565
2566
#####################################################################
2567
# Repository Formats
1910.2.46 by Aaron Bentley
Whitespace fix
2568
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
2569
class RepositoryFormat(object):
2570
    """A repository format.
2571
3990.5.3 by Robert Collins
Docs and polish on RepositoryFormat.network_name.
2572
    Formats provide four things:
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
2573
     * An initialization routine to construct repository data on disk.
3990.5.3 by Robert Collins
Docs and polish on RepositoryFormat.network_name.
2574
     * a optional format string which is used when the BzrDir supports
2575
       versioned children.
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
2576
     * an open routine which returns a Repository instance.
3990.5.3 by Robert Collins
Docs and polish on RepositoryFormat.network_name.
2577
     * A network name for referring to the format in smart server RPC
2578
       methods.
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
2579
2889.1.2 by Robert Collins
Review feedback.
2580
    There is one and only one Format subclass for each on-disk format. But
2581
    there can be one Repository subclass that is used for several different
2582
    formats. The _format attribute on a Repository instance can be used to
2583
    determine the disk format.
2889.1.1 by Robert Collins
* The class ``bzrlib.repofmt.knitrepo.KnitRepository3`` has been folded into
2584
3990.5.3 by Robert Collins
Docs and polish on RepositoryFormat.network_name.
2585
    Formats are placed in a registry by their format string for reference
2586
    during opening. These should be subclasses of RepositoryFormat for
2587
    consistency.
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
2588
2589
    Once a format is deprecated, just deprecate the initialize and open
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2590
    methods on the format class. Do not deprecate the object, as the
3990.5.3 by Robert Collins
Docs and polish on RepositoryFormat.network_name.
2591
    object may be created even when a repository instnace hasn't been
2592
    created.
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
2593
2594
    Common instance attributes:
2595
    _matchingbzrdir - the bzrdir format that the repository format was
2596
    originally written to work with. This can be used if manually
2597
    constructing a bzrdir and repository, or more commonly for test suite
3128.1.3 by Vincent Ladeuil
Since we are there s/parameteris.*/parameteriz&/.
2598
    parameterization.
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
2599
    """
2600
2949.1.2 by Robert Collins
* Fetch with pack repositories will no longer read the entire history graph.
2601
    # Set to True or False in derived classes. True indicates that the format
2602
    # supports ghosts gracefully.
2603
    supports_ghosts = None
3221.3.1 by Robert Collins
* Repository formats have a new supported-feature attribute
2604
    # Can this repository be given external locations to lookup additional
2605
    # data. Set to True or False in derived classes.
2606
    supports_external_lookups = None
4053.1.4 by Robert Collins
Move the fetch control attributes from Repository to RepositoryFormat.
2607
    # What order should fetch operations request streams in?
2608
    # The default is unordered as that is the cheapest for an origin to
2609
    # provide.
2610
    _fetch_order = 'unordered'
2611
    # Does this repository format use deltas that can be fetched as-deltas ?
2612
    # (E.g. knits, where the knit deltas can be transplanted intact.
2613
    # We default to False, which will ensure that enough data to get
2614
    # a full text out of any fetch stream will be grabbed.
2615
    _fetch_uses_deltas = False
2616
    # Should fetch trigger a reconcile after the fetch? Only needed for
2617
    # some repository formats that can suffer internal inconsistencies.
2618
    _fetch_reconcile = False
4183.5.1 by Robert Collins
Add RepositoryFormat.fast_deltas to signal fast delta creation.
2619
    # Does this format have < O(tree_size) delta generation. Used to hint what
2620
    # code path for commit, amongst other things.
2621
    fast_deltas = None
2949.1.2 by Robert Collins
* Fetch with pack repositories will no longer read the entire history graph.
2622
1904.2.3 by Martin Pool
Give a warning on access to old repository formats
2623
    def __str__(self):
2624
        return "<%s>" % self.__class__.__name__
2625
2241.1.11 by Martin Pool
Get rid of RepositoryFormat*_instance objects. Instead the format
2626
    def __eq__(self, other):
2627
        # format objects are generally stateless
2628
        return isinstance(other, self.__class__)
2629
2100.3.35 by Aaron Bentley
equality operations on bzrdir
2630
    def __ne__(self, other):
2100.3.31 by Aaron Bentley
Merged bzr.dev (17 tests failing)
2631
        return not self == other
2632
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
2633
    @classmethod
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
2634
    def find_format(klass, a_bzrdir):
2241.1.1 by Martin Pool
Change RepositoryFormat to use a Registry rather than ad-hoc dictionary
2635
        """Return the format for the repository object in a_bzrdir.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2636
2241.1.1 by Martin Pool
Change RepositoryFormat to use a Registry rather than ad-hoc dictionary
2637
        This is used by bzr native formats that have a "format" file in
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2638
        the repository.  Other methods may be used by different types of
2241.1.1 by Martin Pool
Change RepositoryFormat to use a Registry rather than ad-hoc dictionary
2639
        control directory.
2640
        """
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
2641
        try:
2642
            transport = a_bzrdir.get_repository_transport(None)
2643
            format_string = transport.get("format").read()
2241.1.2 by Martin Pool
change to using external Repository format registry
2644
            return format_registry.get(format_string)
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
2645
        except errors.NoSuchFile:
2646
            raise errors.NoRepositoryPresent(a_bzrdir)
2647
        except KeyError:
3246.3.2 by Daniel Watkins
Modified uses of errors.UnknownFormatError.
2648
            raise errors.UnknownFormatError(format=format_string,
2649
                                            kind='repository')
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
2650
2241.1.1 by Martin Pool
Change RepositoryFormat to use a Registry rather than ad-hoc dictionary
2651
    @classmethod
2241.1.2 by Martin Pool
change to using external Repository format registry
2652
    def register_format(klass, format):
2653
        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
2654
2655
    @classmethod
2656
    def unregister_format(klass, format):
2241.1.2 by Martin Pool
change to using external Repository format registry
2657
        format_registry.remove(format.get_format_string())
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2658
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
2659
    @classmethod
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
2660
    def get_default_format(klass):
2661
        """Return the current default format."""
2204.5.3 by Aaron Bentley
zap old repository default handling
2662
        from bzrlib import bzrdir
2663
        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
2664
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
2665
    def get_format_string(self):
2666
        """Return the ASCII format string that identifies this format.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2667
2668
        Note that in pre format ?? repositories the format string is
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
2669
        not permitted nor written to disk.
2670
        """
2671
        raise NotImplementedError(self.get_format_string)
2672
1624.3.19 by Olaf Conradi
New call get_format_description to give a user-friendly description of a
2673
    def get_format_description(self):
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
2674
        """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
2675
        raise NotImplementedError(self.get_format_description)
2676
2241.1.6 by Martin Pool
Move Knit repositories into the submodule bzrlib.repofmt.knitrepo and
2677
    # TODO: this shouldn't be in the base class, it's specific to things that
2678
    # 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.
2679
    def _get_versioned_file_store(self,
2680
                                  name,
2681
                                  transport,
2682
                                  control_files,
2683
                                  prefixed=True,
2241.1.10 by Martin Pool
Remove more references to weaves from the repository.py file
2684
                                  versionedfile_class=None,
1946.2.5 by John Arbash Meinel
Make knit stores delay creation, but not control stores
2685
                                  versionedfile_kwargs={},
1608.2.12 by Martin Pool
Store-escaping must quote uppercase characters too, so that they're safely
2686
                                  escaped=False):
2241.1.10 by Martin Pool
Remove more references to weaves from the repository.py file
2687
        if versionedfile_class is None:
2688
            versionedfile_class = self._versionedfile_class
1563.2.17 by Robert Collins
Change knits repositories to use a knit versioned file store for file texts.
2689
        weave_transport = control_files._transport.clone(name)
2690
        dir_mode = control_files._dir_mode
2691
        file_mode = control_files._file_mode
2692
        return VersionedFileStore(weave_transport, prefixed=prefixed,
1608.2.12 by Martin Pool
Store-escaping must quote uppercase characters too, so that they're safely
2693
                                  dir_mode=dir_mode,
2694
                                  file_mode=file_mode,
2695
                                  versionedfile_class=versionedfile_class,
1946.2.5 by John Arbash Meinel
Make knit stores delay creation, but not control stores
2696
                                  versionedfile_kwargs=versionedfile_kwargs,
1608.2.12 by Martin Pool
Store-escaping must quote uppercase characters too, so that they're safely
2697
                                  escaped=escaped)
1563.2.17 by Robert Collins
Change knits repositories to use a knit versioned file store for file texts.
2698
1534.6.1 by Robert Collins
allow API creation of shared repositories
2699
    def initialize(self, a_bzrdir, shared=False):
2700
        """Initialize a repository of this format in a_bzrdir.
2701
2702
        :param a_bzrdir: The bzrdir to put the new repository in it.
2703
        :param shared: The repository should be initialized as a sharable one.
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
2704
        :returns: The new repository object.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2705
1534.6.1 by Robert Collins
allow API creation of shared repositories
2706
        This may raise UninitializableFormat if shared repository are not
2707
        compatible the a_bzrdir.
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
2708
        """
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
2709
        raise NotImplementedError(self.initialize)
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
2710
2711
    def is_supported(self):
2712
        """Is this format supported?
2713
2714
        Supported formats must be initializable and openable.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2715
        Unsupported formats may not support initialization or committing or
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
2716
        some other features depending on the reason for not being supported.
2717
        """
2718
        return True
2719
3990.5.3 by Robert Collins
Docs and polish on RepositoryFormat.network_name.
2720
    def network_name(self):
2721
        """A simple byte string uniquely identifying this format for RPC calls.
2722
2723
        MetaDir repository formats use their disk format string to identify the
2724
        repository over the wire. All in one formats such as bzr < 0.8, and
2725
        foreign formats like svn/git and hg should use some marker which is
2726
        unique and immutable.
2727
        """
2728
        raise NotImplementedError(self.network_name)
2729
1910.2.12 by Aaron Bentley
Implement knit repo format 2
2730
    def check_conversion_target(self, target_format):
2731
        raise NotImplementedError(self.check_conversion_target)
2732
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
2733
    def open(self, a_bzrdir, _found=False):
2734
        """Return an instance of this format for the bzrdir a_bzrdir.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2735
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
2736
        _found is a private parameter, do not use it.
2737
        """
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
2738
        raise NotImplementedError(self.open)
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
2739
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
2740
2741
class MetaDirRepositoryFormat(RepositoryFormat):
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
2742
    """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
2743
1910.2.14 by Aaron Bentley
Fail when trying to use interrepository on Knit2 and Knit1
2744
    rich_root_data = False
2323.5.17 by Martin Pool
Add supports_tree_reference to all repo formats (robert)
2745
    supports_tree_reference = False
3221.3.1 by Robert Collins
* Repository formats have a new supported-feature attribute
2746
    supports_external_lookups = False
3845.1.1 by John Arbash Meinel
Ensure that RepositoryFormat._matchingbzrdir.repository_format matches.
2747
2748
    @property
2749
    def _matchingbzrdir(self):
2750
        matching = bzrdir.BzrDirMetaFormat1()
2751
        matching.repository_format = self
2752
        return matching
1910.2.14 by Aaron Bentley
Fail when trying to use interrepository on Knit2 and Knit1
2753
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.
2754
    def __init__(self):
2755
        super(MetaDirRepositoryFormat, self).__init__()
2756
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
2757
    def _create_control_files(self, a_bzrdir):
2758
        """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.
2759
        # FIXME: RBC 20060125 don't peek under the covers
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
2760
        # NB: no need to escape relative paths that are url safe.
2761
        repository_transport = a_bzrdir.get_repository_transport(self)
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
2762
        control_files = lockable_files.LockableFiles(repository_transport,
2763
                                'lock', lockdir.LockDir)
1553.5.61 by Martin Pool
Locks protecting LockableFiles must now be explicitly created before use.
2764
        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
2765
        return control_files
2766
2767
    def _upload_blank_content(self, a_bzrdir, dirs, files, utf8_files, shared):
2768
        """Upload the initial blank content."""
2769
        control_files = self._create_control_files(a_bzrdir)
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
2770
        control_files.lock_write()
3407.2.4 by Martin Pool
Small cleanups to initial creation of repository files
2771
        transport = control_files._transport
2772
        if shared == True:
2773
            utf8_files += [('shared-storage', '')]
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
2774
        try:
3407.2.18 by Martin Pool
BzrDir takes responsibility for default file/dir modes
2775
            transport.mkdir_multi(dirs, mode=a_bzrdir._get_dir_mode())
3407.2.4 by Martin Pool
Small cleanups to initial creation of repository files
2776
            for (filename, content_stream) in files:
2777
                transport.put_file(filename, content_stream,
3407.2.18 by Martin Pool
BzrDir takes responsibility for default file/dir modes
2778
                    mode=a_bzrdir._get_file_mode())
3407.2.4 by Martin Pool
Small cleanups to initial creation of repository files
2779
            for (filename, content_bytes) in utf8_files:
2780
                transport.put_bytes_non_atomic(filename, content_bytes,
3407.2.18 by Martin Pool
BzrDir takes responsibility for default file/dir modes
2781
                    mode=a_bzrdir._get_file_mode())
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
2782
        finally:
2783
            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
2784
3990.5.1 by Andrew Bennetts
Add network_name() to RepositoryFormat.
2785
    def network_name(self):
2786
        """Metadir formats have matching disk and network format strings."""
2787
        return self.get_format_string()
2788
2789
3990.5.3 by Robert Collins
Docs and polish on RepositoryFormat.network_name.
2790
# Pre-0.8 formats that don't have a disk format string (because they are
2791
# versioned by the matching control directory). We use the control directories
2792
# disk format string as a key for the network_name because they meet the
2793
# constraints (simple string, unique, immmutable).
3990.5.1 by Andrew Bennetts
Add network_name() to RepositoryFormat.
2794
network_format_registry.register_lazy(
2795
    "Bazaar-NG branch, format 5\n",
2796
    'bzrlib.repofmt.weaverepo',
2797
    'RepositoryFormat5',
2798
)
2799
network_format_registry.register_lazy(
2800
    "Bazaar-NG branch, format 6\n",
2801
    'bzrlib.repofmt.weaverepo',
2802
    'RepositoryFormat6',
2803
)
2804
2805
# formats which have no format string are not discoverable or independently
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2806
# creatable on disk, so are not registered in format_registry.  They're
2241.1.11 by Martin Pool
Get rid of RepositoryFormat*_instance objects. Instead the format
2807
# all in bzrlib.repofmt.weaverepo now.  When an instance of one of these is
2808
# needed, it's constructed directly by the BzrDir.  Non-native formats where
2809
# the repository is not separately opened are similar.
2810
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
2811
format_registry.register_lazy(
2812
    'Bazaar-NG Repository format 7',
2813
    'bzrlib.repofmt.weaverepo',
2241.1.11 by Martin Pool
Get rid of RepositoryFormat*_instance objects. Instead the format
2814
    'RepositoryFormat7'
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
2815
    )
2592.3.22 by Robert Collins
Add new experimental repository formats.
2816
2241.1.6 by Martin Pool
Move Knit repositories into the submodule bzrlib.repofmt.knitrepo and
2817
format_registry.register_lazy(
2818
    'Bazaar-NG Knit Repository Format 1',
2819
    'bzrlib.repofmt.knitrepo',
2241.1.11 by Martin Pool
Get rid of RepositoryFormat*_instance objects. Instead the format
2820
    'RepositoryFormatKnit1',
2241.1.6 by Martin Pool
Move Knit repositories into the submodule bzrlib.repofmt.knitrepo and
2821
    )
2822
2241.1.5 by Martin Pool
Move KnitFormat2 into repofmt
2823
format_registry.register_lazy(
2255.2.230 by Robert Collins
Update tree format signatures to mention introducing bzr version.
2824
    'Bazaar Knit Repository Format 3 (bzr 0.15)\n',
2100.3.31 by Aaron Bentley
Merged bzr.dev (17 tests failing)
2825
    'bzrlib.repofmt.knitrepo',
2826
    'RepositoryFormatKnit3',
2827
    )
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
2828
2996.2.1 by Aaron Bentley
Add KnitRepositoryFormat4
2829
format_registry.register_lazy(
2830
    'Bazaar Knit Repository Format 4 (bzr 1.0)\n',
2831
    'bzrlib.repofmt.knitrepo',
2832
    'RepositoryFormatKnit4',
2833
    )
2834
2939.2.1 by Ian Clatworthy
use 'knitpack' naming instead of 'experimental' for pack formats
2835
# Pack-based formats. There is one format for pre-subtrees, and one for
2836
# post-subtrees to allow ease of testing.
3152.2.1 by Robert Collins
* A new repository format 'development' has been added. This format will
2837
# NOTE: These are experimental in 0.92. Stable in 1.0 and above
2592.3.22 by Robert Collins
Add new experimental repository formats.
2838
format_registry.register_lazy(
2939.2.6 by Ian Clatworthy
more review feedback from lifeless and poolie
2839
    'Bazaar pack repository format 1 (needs bzr 0.92)\n',
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
2840
    'bzrlib.repofmt.pack_repo',
2592.3.224 by Martin Pool
Rename GraphKnitRepository etc to KnitPackRepository
2841
    'RepositoryFormatKnitPack1',
2592.3.22 by Robert Collins
Add new experimental repository formats.
2842
    )
2843
format_registry.register_lazy(
2939.2.6 by Ian Clatworthy
more review feedback from lifeless and poolie
2844
    'Bazaar pack repository format 1 with subtree support (needs bzr 0.92)\n',
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
2845
    'bzrlib.repofmt.pack_repo',
2592.3.224 by Martin Pool
Rename GraphKnitRepository etc to KnitPackRepository
2846
    'RepositoryFormatKnitPack3',
2592.3.22 by Robert Collins
Add new experimental repository formats.
2847
    )
2996.2.11 by Aaron Bentley
Implement rich-root-pack format ( #164639)
2848
format_registry.register_lazy(
2849
    'Bazaar pack repository format 1 with rich root (needs bzr 1.0)\n',
2850
    'bzrlib.repofmt.pack_repo',
2851
    'RepositoryFormatKnitPack4',
2852
    )
3549.1.5 by Martin Pool
Add stable format names for stacked branches
2853
format_registry.register_lazy(
2854
    'Bazaar RepositoryFormatKnitPack5 (bzr 1.6)\n',
2855
    'bzrlib.repofmt.pack_repo',
2856
    'RepositoryFormatKnitPack5',
2857
    )
2858
format_registry.register_lazy(
3606.10.1 by John Arbash Meinel
Create a new --1.6-rich-root, deprecate the old one.
2859
    'Bazaar RepositoryFormatKnitPack5RichRoot (bzr 1.6.1)\n',
2860
    'bzrlib.repofmt.pack_repo',
2861
    'RepositoryFormatKnitPack5RichRoot',
2862
    )
2863
format_registry.register_lazy(
3549.1.6 by Martin Pool
Change stacked-subtree to stacked-rich-root
2864
    'Bazaar RepositoryFormatKnitPack5RichRoot (bzr 1.6)\n',
3549.1.5 by Martin Pool
Add stable format names for stacked branches
2865
    'bzrlib.repofmt.pack_repo',
3606.10.1 by John Arbash Meinel
Create a new --1.6-rich-root, deprecate the old one.
2866
    'RepositoryFormatKnitPack5RichRootBroken',
3549.1.5 by Martin Pool
Add stable format names for stacked branches
2867
    )
3805.3.1 by John Arbash Meinel
Add repository 1.9 format, and update the documentation.
2868
format_registry.register_lazy(
2869
    'Bazaar RepositoryFormatKnitPack6 (bzr 1.9)\n',
2870
    'bzrlib.repofmt.pack_repo',
2871
    'RepositoryFormatKnitPack6',
2872
    )
2873
format_registry.register_lazy(
2874
    'Bazaar RepositoryFormatKnitPack6RichRoot (bzr 1.9)\n',
2875
    'bzrlib.repofmt.pack_repo',
2876
    'RepositoryFormatKnitPack6RichRoot',
2877
    )
3549.1.5 by Martin Pool
Add stable format names for stacked branches
2878
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2879
# Development formats.
3735.1.1 by Robert Collins
Add development2 formats using BTree indices.
2880
# 1.7->1.8 go below here
2881
format_registry.register_lazy(
2882
    "Bazaar development format 2 (needs bzr.dev from before 1.8)\n",
2883
    'bzrlib.repofmt.pack_repo',
2884
    'RepositoryFormatPackDevelopment2',
2885
    )
2886
format_registry.register_lazy(
2887
    ("Bazaar development format 2 with subtree support "
2888
        "(needs bzr.dev from before 1.8)\n"),
2889
    'bzrlib.repofmt.pack_repo',
2890
    'RepositoryFormatPackDevelopment2Subtree',
2891
    )
2592.3.22 by Robert Collins
Add new experimental repository formats.
2892
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
2893
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.
2894
class InterRepository(InterObject):
1534.1.27 by Robert Collins
Start InterRepository with InterRepository.get.
2895
    """This class represents operations taking place between two repositories.
2896
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.
2897
    Its instances have methods like copy_content and fetch, and contain
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2898
    references to the source and target repositories these operations can be
1534.1.27 by Robert Collins
Start InterRepository with InterRepository.get.
2899
    carried out on.
2900
2901
    Often we will provide convenience methods on 'repository' which carry out
2902
    operations with another repository - they will always forward to
2903
    InterRepository.get(other).method_name(parameters).
2904
    """
2905
4144.2.1 by Andrew Bennetts
Always batch revisions to ask of target when doing _walk_to_common_revisions, rather than special-casing in Inter*Remote*.
2906
    _walk_to_common_revisions_batch_size = 50
1910.2.15 by Aaron Bentley
Back out inter.get changes, make optimizers an ordered list
2907
    _optimisers = []
1534.1.28 by Robert Collins
Allow for optimised InterRepository selection.
2908
    """The available optimised InterRepository types."""
2909
4060.1.3 by Robert Collins
Implement the separate source component for fetch - repository.StreamSource.
2910
    @needs_write_lock
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
2911
    def copy_content(self, revision_id=None):
4060.1.3 by Robert Collins
Implement the separate source component for fetch - repository.StreamSource.
2912
        """Make a complete copy of the content in self into destination.
2913
2914
        This is a destructive operation! Do not use it on existing
2915
        repositories.
2916
2917
        :param revision_id: Only copy the content needed to construct
2918
                            revision_id and its parents.
2919
        """
2920
        try:
2921
            self.target.set_make_working_trees(self.source.make_working_trees())
2922
        except NotImplementedError:
2923
            pass
2924
        self.target.fetch(self.source, revision_id=revision_id)
1910.2.15 by Aaron Bentley
Back out inter.get changes, make optimizers an ordered list
2925
4110.2.23 by Martin Pool
blackbox hpss test should check repository was remotely locked
2926
    @needs_write_lock
4070.9.2 by Andrew Bennetts
Rough prototype of allowing a SearchResult to be passed to fetch, and using that to improve network conversations.
2927
    def fetch(self, revision_id=None, pb=None, find_ghosts=False,
2928
            fetch_spec=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.
2929
        """Fetch the content required to construct revision_id.
2930
1910.7.17 by Andrew Bennetts
Various cosmetic changes.
2931
        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.
2932
2933
        :param revision_id: if None all content is copied, if NULL_REVISION no
2934
                            content is copied.
2935
        :param pb: optional progress bar to use for progress reports. If not
2936
                   provided a default one will be created.
4065.1.1 by Robert Collins
Change the return value of fetch() to None.
2937
        :return: 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.
2938
        """
4060.1.3 by Robert Collins
Implement the separate source component for fetch - repository.StreamSource.
2939
        from bzrlib.fetch import RepoFetcher
2940
        f = RepoFetcher(to_repository=self.target,
2941
                               from_repository=self.source,
2942
                               last_revision=revision_id,
4070.9.2 by Andrew Bennetts
Rough prototype of allowing a SearchResult to be passed to fetch, and using that to improve network conversations.
2943
                               fetch_spec=fetch_spec,
4060.1.3 by Robert Collins
Implement the separate source component for fetch - repository.StreamSource.
2944
                               pb=pb, find_ghosts=find_ghosts)
3172.4.4 by Robert Collins
Review feedback.
2945
2946
    def _walk_to_common_revisions(self, revision_ids):
2947
        """Walk out from revision_ids in source to revisions target has.
2948
2949
        :param revision_ids: The start point for the search.
2950
        :return: A set of revision ids.
2951
        """
4144.3.12 by Andrew Bennetts
Remove target_get_graph and target_get_parent_map attributes from InterRepository; nothing overrides them anymore.
2952
        target_graph = self.target.get_graph()
1551.19.41 by Aaron Bentley
Accelerate no-op pull
2953
        revision_ids = frozenset(revision_ids)
3452.2.6 by Andrew Bennetts
Batch get_parent_map calls in InterPackToRemotePack._walk_to_common_revisions to
2954
        # Fast path for the case where all the revisions are already in the
2955
        # target repo.
2956
        # (Although this does incur an extra round trip for the
2957
        # fairly common case where the target doesn't already have the revision
2958
        # we're pushing.)
1551.19.41 by Aaron Bentley
Accelerate no-op pull
2959
        if set(target_graph.get_parent_map(revision_ids)) == revision_ids:
2960
            return graph.SearchResult(revision_ids, set(), 0, set())
3172.4.4 by Robert Collins
Review feedback.
2961
        missing_revs = set()
1551.19.41 by Aaron Bentley
Accelerate no-op pull
2962
        source_graph = self.source.get_graph()
3172.4.4 by Robert Collins
Review feedback.
2963
        # ensure we don't pay silly lookup costs.
1551.19.41 by Aaron Bentley
Accelerate no-op pull
2964
        searcher = source_graph._make_breadth_first_searcher(revision_ids)
3172.4.4 by Robert Collins
Review feedback.
2965
        null_set = frozenset([_mod_revision.NULL_REVISION])
3731.4.2 by Andrew Bennetts
Move ghost check out of the inner loop.
2966
        searcher_exhausted = False
3172.4.4 by Robert Collins
Review feedback.
2967
        while True:
3452.2.6 by Andrew Bennetts
Batch get_parent_map calls in InterPackToRemotePack._walk_to_common_revisions to
2968
            next_revs = set()
3731.4.2 by Andrew Bennetts
Move ghost check out of the inner loop.
2969
            ghosts = set()
2970
            # Iterate the searcher until we have enough next_revs
3452.2.6 by Andrew Bennetts
Batch get_parent_map calls in InterPackToRemotePack._walk_to_common_revisions to
2971
            while len(next_revs) < self._walk_to_common_revisions_batch_size:
2972
                try:
3731.4.2 by Andrew Bennetts
Move ghost check out of the inner loop.
2973
                    next_revs_part, ghosts_part = searcher.next_with_ghosts()
3452.2.6 by Andrew Bennetts
Batch get_parent_map calls in InterPackToRemotePack._walk_to_common_revisions to
2974
                    next_revs.update(next_revs_part)
3731.4.2 by Andrew Bennetts
Move ghost check out of the inner loop.
2975
                    ghosts.update(ghosts_part)
3452.2.6 by Andrew Bennetts
Batch get_parent_map calls in InterPackToRemotePack._walk_to_common_revisions to
2976
                except StopIteration:
3731.4.2 by Andrew Bennetts
Move ghost check out of the inner loop.
2977
                    searcher_exhausted = True
3452.2.6 by Andrew Bennetts
Batch get_parent_map calls in InterPackToRemotePack._walk_to_common_revisions to
2978
                    break
3731.4.3 by Andrew Bennetts
Rework ghost checking in _walk_to_common_revisions.
2979
            # If there are ghosts in the source graph, and the caller asked for
2980
            # them, make sure that they are present in the target.
3731.4.5 by Andrew Bennetts
Clarify the code slightly.
2981
            # We don't care about other ghosts as we can't fetch them and
2982
            # haven't been asked to.
2983
            ghosts_to_check = set(revision_ids.intersection(ghosts))
2984
            revs_to_get = set(next_revs).union(ghosts_to_check)
2985
            if revs_to_get:
2986
                have_revs = set(target_graph.get_parent_map(revs_to_get))
3731.4.2 by Andrew Bennetts
Move ghost check out of the inner loop.
2987
                # we always have NULL_REVISION present.
3731.4.5 by Andrew Bennetts
Clarify the code slightly.
2988
                have_revs = have_revs.union(null_set)
2989
                # Check if the target is missing any ghosts we need.
3731.4.3 by Andrew Bennetts
Rework ghost checking in _walk_to_common_revisions.
2990
                ghosts_to_check.difference_update(have_revs)
2991
                if ghosts_to_check:
2992
                    # One of the caller's revision_ids is a ghost in both the
2993
                    # source and the target.
2994
                    raise errors.NoSuchRevision(
2995
                        self.source, ghosts_to_check.pop())
3731.4.2 by Andrew Bennetts
Move ghost check out of the inner loop.
2996
                missing_revs.update(next_revs - have_revs)
3808.1.4 by John Arbash Meinel
make _walk_to_common responsible for stopping ancestors
2997
                # Because we may have walked past the original stop point, make
2998
                # sure everything is stopped
2999
                stop_revs = searcher.find_seen_ancestors(have_revs)
3000
                searcher.stop_searching_any(stop_revs)
3731.4.2 by Andrew Bennetts
Move ghost check out of the inner loop.
3001
            if searcher_exhausted:
3172.4.4 by Robert Collins
Review feedback.
3002
                break
3184.1.8 by Robert Collins
* ``InterRepository.missing_revision_ids`` is now deprecated in favour of
3003
        return searcher.get_result()
3808.1.4 by John Arbash Meinel
make _walk_to_common responsible for stopping ancestors
3004
3184.1.8 by Robert Collins
* ``InterRepository.missing_revision_ids`` is now deprecated in favour of
3005
    @needs_read_lock
3006
    def search_missing_revision_ids(self, revision_id=None, find_ghosts=True):
3007
        """Return the revision ids that source has that target does not.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3008
3184.1.8 by Robert Collins
* ``InterRepository.missing_revision_ids`` is now deprecated in favour of
3009
        :param revision_id: only return revision ids included by this
3010
                            revision_id.
3011
        :param find_ghosts: If True find missing revisions in deep history
3012
            rather than just finding the surface difference.
3013
        :return: A bzrlib.graph.SearchResult.
3014
        """
3172.4.1 by Robert Collins
* Fetching via bzr+ssh will no longer fill ghosts by default (this is
3015
        # stop searching at found target revisions.
3016
        if not find_ghosts and revision_id is not None:
3172.4.4 by Robert Collins
Review feedback.
3017
            return self._walk_to_common_revisions([revision_id])
1910.2.15 by Aaron Bentley
Back out inter.get changes, make optimizers an ordered list
3018
        # generic, possibly worst case, slow code path.
3019
        target_ids = set(self.target.all_revision_ids())
3020
        if revision_id is not None:
3021
            source_ids = self.source.get_ancestry(revision_id)
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
3022
            if source_ids[0] is not None:
3023
                raise AssertionError()
1910.2.15 by Aaron Bentley
Back out inter.get changes, make optimizers an ordered list
3024
            source_ids.pop(0)
3025
        else:
3026
            source_ids = self.source.all_revision_ids()
3027
        result_set = set(source_ids).difference(target_ids)
3184.1.9 by Robert Collins
* ``Repository.get_data_stream`` is now deprecated in favour of
3028
        return self.source.revision_ids_to_search_result(result_set)
1910.2.15 by Aaron Bentley
Back out inter.get changes, make optimizers an ordered list
3029
2592.3.28 by Robert Collins
Make InterKnitOptimiser be used between any same-model knit repository.
3030
    @staticmethod
3031
    def _same_model(source, target):
3582.1.2 by Martin Pool
Default InterRepository.fetch raises IncompatibleRepositories
3032
        """True if source and target have the same data representation.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3033
3582.1.2 by Martin Pool
Default InterRepository.fetch raises IncompatibleRepositories
3034
        Note: this is always called on the base class; overriding it in a
3035
        subclass will have no effect.
3036
        """
3037
        try:
3038
            InterRepository._assert_same_model(source, target)
3039
            return True
3040
        except errors.IncompatibleRepositories, e:
3041
            return False
3042
3043
    @staticmethod
3044
    def _assert_same_model(source, target):
3045
        """Raise an exception if two repositories do not use the same model.
3046
        """
2592.3.28 by Robert Collins
Make InterKnitOptimiser be used between any same-model knit repository.
3047
        if source.supports_rich_root() != target.supports_rich_root():
3582.1.2 by Martin Pool
Default InterRepository.fetch raises IncompatibleRepositories
3048
            raise errors.IncompatibleRepositories(source, target,
3049
                "different rich-root support")
2592.3.28 by Robert Collins
Make InterKnitOptimiser be used between any same-model knit repository.
3050
        if source._serializer != target._serializer:
3582.1.2 by Martin Pool
Default InterRepository.fetch raises IncompatibleRepositories
3051
            raise errors.IncompatibleRepositories(source, target,
3052
                "different serializers")
2592.3.28 by Robert Collins
Make InterKnitOptimiser be used between any same-model knit repository.
3053
1910.2.15 by Aaron Bentley
Back out inter.get changes, make optimizers an ordered list
3054
3055
class InterSameDataRepository(InterRepository):
3056
    """Code for converting between repositories that represent the same data.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3057
1910.2.15 by Aaron Bentley
Back out inter.get changes, make optimizers an ordered list
3058
    Data format and model must match for this to work.
3059
    """
3060
2241.1.6 by Martin Pool
Move Knit repositories into the submodule bzrlib.repofmt.knitrepo and
3061
    @classmethod
2241.1.7 by Martin Pool
rename method
3062
    def _get_repo_format_to_test(self):
2814.1.1 by Robert Collins
* Pushing, pulling and branching branches with subtree references was not
3063
        """Repository format for testing with.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3064
2814.1.1 by Robert Collins
* Pushing, pulling and branching branches with subtree references was not
3065
        InterSameData can pull from subtree to subtree and from non-subtree to
3066
        non-subtree, so we test this with the richest repository format.
3067
        """
3068
        from bzrlib.repofmt import knitrepo
3069
        return knitrepo.RepositoryFormatKnit3()
1910.2.15 by Aaron Bentley
Back out inter.get changes, make optimizers an ordered list
3070
1910.2.14 by Aaron Bentley
Fail when trying to use interrepository on Knit2 and Knit1
3071
    @staticmethod
3072
    def is_compatible(source, target):
2592.3.28 by Robert Collins
Make InterKnitOptimiser be used between any same-model knit repository.
3073
        return InterRepository._same_model(source, target)
1910.2.14 by Aaron Bentley
Fail when trying to use interrepository on Knit2 and Knit1
3074
1910.2.15 by Aaron Bentley
Back out inter.get changes, make optimizers an ordered list
3075
2241.1.12 by Martin Pool
Restore InterWeaveRepo
3076
class InterWeaveRepo(InterSameDataRepository):
2850.3.1 by Robert Collins
Move various weave specific code out of the base Repository class to weaverepo.py.
3077
    """Optimised code paths between Weave based repositories.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3078
2850.3.1 by Robert Collins
Move various weave specific code out of the base Repository class to weaverepo.py.
3079
    This should be in bzrlib/repofmt/weaverepo.py but we have not yet
3080
    implemented lazy inter-object optimisation.
3081
    """
2241.1.12 by Martin Pool
Restore InterWeaveRepo
3082
2241.1.13 by Martin Pool
Re-register InterWeaveRepo, fix test integration, add test for it
3083
    @classmethod
2241.1.12 by Martin Pool
Restore InterWeaveRepo
3084
    def _get_repo_format_to_test(self):
3085
        from bzrlib.repofmt import weaverepo
3086
        return weaverepo.RepositoryFormat7()
3087
3088
    @staticmethod
3089
    def is_compatible(source, target):
3090
        """Be compatible with known Weave formats.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3091
2241.1.12 by Martin Pool
Restore InterWeaveRepo
3092
        We don't test for the stores being of specific types because that
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3093
        could lead to confusing results, and there is no need to be
2241.1.12 by Martin Pool
Restore InterWeaveRepo
3094
        overly general.
3095
        """
3096
        from bzrlib.repofmt.weaverepo import (
3097
                RepositoryFormat5,
3098
                RepositoryFormat6,
3099
                RepositoryFormat7,
3100
                )
3101
        try:
3102
            return (isinstance(source._format, (RepositoryFormat5,
3103
                                                RepositoryFormat6,
3104
                                                RepositoryFormat7)) and
3105
                    isinstance(target._format, (RepositoryFormat5,
3106
                                                RepositoryFormat6,
3107
                                                RepositoryFormat7)))
3108
        except AttributeError:
3109
            return False
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3110
2241.1.12 by Martin Pool
Restore InterWeaveRepo
3111
    @needs_write_lock
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
3112
    def copy_content(self, revision_id=None):
2241.1.12 by Martin Pool
Restore InterWeaveRepo
3113
        """See InterRepository.copy_content()."""
3114
        # weave specific optimised path:
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
3115
        try:
3116
            self.target.set_make_working_trees(self.source.make_working_trees())
3349.1.2 by Aaron Bentley
Change ValueError to RepositoryUpgradeRequired
3117
        except (errors.RepositoryUpgradeRequired, NotImplemented):
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
3118
            pass
3119
        # FIXME do not peek!
3407.2.14 by Martin Pool
Remove more cases of getting transport via control_files
3120
        if self.source._transport.listable():
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
3121
            pb = ui.ui_factory.nested_progress_bar()
2241.1.12 by Martin Pool
Restore InterWeaveRepo
3122
            try:
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
3123
                self.target.texts.insert_record_stream(
3124
                    self.source.texts.get_record_stream(
3125
                        self.source.texts.keys(), 'topological', False))
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
3126
                pb.update('copying inventory', 0, 1)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
3127
                self.target.inventories.insert_record_stream(
3128
                    self.source.inventories.get_record_stream(
3129
                        self.source.inventories.keys(), 'topological', False))
3130
                self.target.signatures.insert_record_stream(
3131
                    self.source.signatures.get_record_stream(
3132
                        self.source.signatures.keys(),
3133
                        'unordered', True))
3134
                self.target.revisions.insert_record_stream(
3135
                    self.source.revisions.get_record_stream(
3136
                        self.source.revisions.keys(),
3137
                        'topological', True))
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
3138
            finally:
3139
                pb.finished()
3140
        else:
2241.1.12 by Martin Pool
Restore InterWeaveRepo
3141
            self.target.fetch(self.source, revision_id=revision_id)
3142
3143
    @needs_read_lock
3184.1.8 by Robert Collins
* ``InterRepository.missing_revision_ids`` is now deprecated in favour of
3144
    def search_missing_revision_ids(self, revision_id=None, find_ghosts=True):
2241.1.12 by Martin Pool
Restore InterWeaveRepo
3145
        """See InterRepository.missing_revision_ids()."""
3146
        # we want all revisions to satisfy revision_id in source.
3147
        # but we don't want to stat every file here and there.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3148
        # we want then, all revisions other needs to satisfy revision_id
2241.1.12 by Martin Pool
Restore InterWeaveRepo
3149
        # checked, but not those that we have locally.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3150
        # so the first thing is to get a subset of the revisions to
2241.1.12 by Martin Pool
Restore InterWeaveRepo
3151
        # satisfy revision_id in source, and then eliminate those that
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3152
        # we do already have.
2241.1.12 by Martin Pool
Restore InterWeaveRepo
3153
        # this is slow on high latency connection to self, but as as this
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3154
        # disk format scales terribly for push anyway due to rewriting
2241.1.12 by Martin Pool
Restore InterWeaveRepo
3155
        # inventory.weave, this is considered acceptable.
3156
        # - RBC 20060209
3157
        if revision_id is not None:
3158
            source_ids = self.source.get_ancestry(revision_id)
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
3159
            if source_ids[0] is not None:
3160
                raise AssertionError()
2241.1.12 by Martin Pool
Restore InterWeaveRepo
3161
            source_ids.pop(0)
3162
        else:
3163
            source_ids = self.source._all_possible_ids()
3164
        source_ids_set = set(source_ids)
3165
        # source_ids is the worst possible case we may need to pull.
3166
        # now we want to filter source_ids against what we actually
3167
        # have in target, but don't try to check for existence where we know
3168
        # we do not have a revision as that would be pointless.
3169
        target_ids = set(self.target._all_possible_ids())
3170
        possibly_present_revisions = target_ids.intersection(source_ids_set)
3184.1.8 by Robert Collins
* ``InterRepository.missing_revision_ids`` is now deprecated in favour of
3171
        actually_present_revisions = set(
3172
            self.target._eliminate_revisions_not_present(possibly_present_revisions))
2241.1.12 by Martin Pool
Restore InterWeaveRepo
3173
        required_revisions = source_ids_set.difference(actually_present_revisions)
3174
        if revision_id is not None:
3175
            # we used get_ancestry to determine source_ids then we are assured all
3176
            # revisions referenced are present as they are installed in topological order.
3177
            # and the tip revision was validated by get_ancestry.
3184.1.8 by Robert Collins
* ``InterRepository.missing_revision_ids`` is now deprecated in favour of
3178
            result_set = required_revisions
2241.1.12 by Martin Pool
Restore InterWeaveRepo
3179
        else:
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3180
            # if we just grabbed the possibly available ids, then
2241.1.12 by Martin Pool
Restore InterWeaveRepo
3181
            # we only have an estimate of whats available and need to validate
3182
            # that against the revision records.
3184.1.8 by Robert Collins
* ``InterRepository.missing_revision_ids`` is now deprecated in favour of
3183
            result_set = set(
3184
                self.source._eliminate_revisions_not_present(required_revisions))
3184.1.9 by Robert Collins
* ``Repository.get_data_stream`` is now deprecated in favour of
3185
        return self.source.revision_ids_to_search_result(result_set)
2241.1.12 by Martin Pool
Restore InterWeaveRepo
3186
3187
1910.2.15 by Aaron Bentley
Back out inter.get changes, make optimizers an ordered list
3188
class InterKnitRepo(InterSameDataRepository):
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
3189
    """Optimised code paths between Knit based repositories."""
3190
2241.1.6 by Martin Pool
Move Knit repositories into the submodule bzrlib.repofmt.knitrepo and
3191
    @classmethod
2241.1.7 by Martin Pool
rename method
3192
    def _get_repo_format_to_test(self):
2241.1.6 by Martin Pool
Move Knit repositories into the submodule bzrlib.repofmt.knitrepo and
3193
        from bzrlib.repofmt import knitrepo
3194
        return knitrepo.RepositoryFormatKnit1()
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
3195
3196
    @staticmethod
3197
    def is_compatible(source, target):
3198
        """Be compatible with known Knit formats.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3199
1759.2.2 by Jelmer Vernooij
Revert some of my spelling fixes and fix some typos after review by Aaron.
3200
        We don't test for the stores being of specific types because that
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3201
        could lead to confusing results, and there is no need to be
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
3202
        overly general.
3203
        """
2592.3.28 by Robert Collins
Make InterKnitOptimiser be used between any same-model knit repository.
3204
        from bzrlib.repofmt.knitrepo import RepositoryFormatKnit
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
3205
        try:
2592.3.28 by Robert Collins
Make InterKnitOptimiser be used between any same-model knit repository.
3206
            are_knits = (isinstance(source._format, RepositoryFormatKnit) and
3207
                isinstance(target._format, RepositoryFormatKnit))
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
3208
        except AttributeError:
3209
            return False
2592.3.28 by Robert Collins
Make InterKnitOptimiser be used between any same-model knit repository.
3210
        return are_knits and InterRepository._same_model(source, target)
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
3211
3212
    @needs_read_lock
3184.1.8 by Robert Collins
* ``InterRepository.missing_revision_ids`` is now deprecated in favour of
3213
    def search_missing_revision_ids(self, revision_id=None, find_ghosts=True):
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
3214
        """See InterRepository.missing_revision_ids()."""
3215
        if revision_id is not None:
3216
            source_ids = self.source.get_ancestry(revision_id)
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
3217
            if source_ids[0] is not None:
3218
                raise AssertionError()
1668.1.14 by Martin Pool
merge olaf - InvalidRevisionId fixes
3219
            source_ids.pop(0)
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
3220
        else:
2850.3.1 by Robert Collins
Move various weave specific code out of the base Repository class to weaverepo.py.
3221
            source_ids = self.source.all_revision_ids()
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
3222
        source_ids_set = set(source_ids)
3223
        # source_ids is the worst possible case we may need to pull.
3224
        # 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.
3225
        # 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.
3226
        # we do not have a revision as that would be pointless.
2850.3.1 by Robert Collins
Move various weave specific code out of the base Repository class to weaverepo.py.
3227
        target_ids = set(self.target.all_revision_ids())
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
3228
        possibly_present_revisions = target_ids.intersection(source_ids_set)
3184.1.8 by Robert Collins
* ``InterRepository.missing_revision_ids`` is now deprecated in favour of
3229
        actually_present_revisions = set(
3230
            self.target._eliminate_revisions_not_present(possibly_present_revisions))
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
3231
        required_revisions = source_ids_set.difference(actually_present_revisions)
3232
        if revision_id is not None:
3233
            # we used get_ancestry to determine source_ids then we are assured all
3234
            # revisions referenced are present as they are installed in topological order.
3235
            # and the tip revision was validated by get_ancestry.
3184.1.8 by Robert Collins
* ``InterRepository.missing_revision_ids`` is now deprecated in favour of
3236
            result_set = required_revisions
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
3237
        else:
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3238
            # if we just grabbed the possibly available ids, then
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
3239
            # we only have an estimate of whats available and need to validate
3240
            # that against the revision records.
3184.1.8 by Robert Collins
* ``InterRepository.missing_revision_ids`` is now deprecated in favour of
3241
            result_set = set(
3242
                self.source._eliminate_revisions_not_present(required_revisions))
3184.1.9 by Robert Collins
* ``Repository.get_data_stream`` is now deprecated in favour of
3243
        return self.source.revision_ids_to_search_result(result_set)
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
3244
1910.2.17 by Aaron Bentley
Get fetching from 1 to 2 under test
3245
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
3246
class InterPackRepo(InterSameDataRepository):
3247
    """Optimised code paths between Pack based repositories."""
3248
3249
    @classmethod
3250
    def _get_repo_format_to_test(self):
3251
        from bzrlib.repofmt import pack_repo
2592.3.224 by Martin Pool
Rename GraphKnitRepository etc to KnitPackRepository
3252
        return pack_repo.RepositoryFormatKnitPack1()
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
3253
3254
    @staticmethod
3255
    def is_compatible(source, target):
3256
        """Be compatible with known Pack formats.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3257
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
3258
        We don't test for the stores being of specific types because that
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3259
        could lead to confusing results, and there is no need to be
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
3260
        overly general.
3261
        """
3262
        from bzrlib.repofmt.pack_repo import RepositoryFormatPack
3263
        try:
2592.3.91 by Robert Collins
Incrementally closing in on a correct fetch for packs.
3264
            are_packs = (isinstance(source._format, RepositoryFormatPack) and
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
3265
                isinstance(target._format, RepositoryFormatPack))
3266
        except AttributeError:
3267
            return False
2592.3.91 by Robert Collins
Incrementally closing in on a correct fetch for packs.
3268
        return are_packs and InterRepository._same_model(source, target)
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
3269
3270
    @needs_write_lock
4070.9.2 by Andrew Bennetts
Rough prototype of allowing a SearchResult to be passed to fetch, and using that to improve network conversations.
3271
    def fetch(self, revision_id=None, pb=None, find_ghosts=False,
3272
            fetch_spec=None):
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
3273
        """See InterRepository.fetch()."""
3582.2.1 by Jonathan Lange
Fix up problems with fetching revisions. Almost entirely abentley's work.
3274
        if (len(self.source._fallback_repositories) > 0 or
3275
            len(self.target._fallback_repositories) > 0):
3582.1.13 by Martin Pool
Better comment about fetching to or from stacked repositories
3276
            # The pack layer is not aware of fallback repositories, so when
3277
            # fetching from a stacked repository or into a stacked repository
3278
            # we use the generic fetch logic which uses the VersionedFiles
3279
            # attributes on repository.
3565.3.3 by Robert Collins
* Fetching data between repositories that have the same model but no
3280
            from bzrlib.fetch import RepoFetcher
3281
            fetcher = RepoFetcher(self.target, self.source, revision_id,
4070.9.2 by Andrew Bennetts
Rough prototype of allowing a SearchResult to be passed to fetch, and using that to improve network conversations.
3282
                    pb, find_ghosts, fetch_spec=fetch_spec)
3283
        if fetch_spec is not None:
4070.9.16 by Andrew Bennetts
Fix small error introduced when doing review tweaks.
3284
            if len(list(fetch_spec.heads)) != 1:
3285
                raise AssertionError(
3286
                    "InterPackRepo.fetch doesn't support "
3287
                    "fetching multiple heads yet.")
4152.1.2 by Robert Collins
Add streaming from a stacked branch when the sort order is compatible with doing so.
3288
            revision_id = list(fetch_spec.heads)[0]
4070.9.2 by Andrew Bennetts
Rough prototype of allowing a SearchResult to be passed to fetch, and using that to improve network conversations.
3289
            fetch_spec = None
2592.3.90 by Robert Collins
Slightly broken, but branch and fetch performance is now roughly on par (for bzr.dev) with knits - should be much faster for large repos.
3290
        if revision_id is None:
3291
            # TODO:
3292
            # everything to do - use pack logic
3293
            # to fetch from all packs to one without
2592.3.93 by Robert Collins
Steps toward filtering revisions/inventories/texts during fetch.
3294
            # inventory parsing etc, IFF nothing to be copied is in the target.
2592.3.90 by Robert Collins
Slightly broken, but branch and fetch performance is now roughly on par (for bzr.dev) with knits - should be much faster for large repos.
3295
            # till then:
3221.13.2 by Robert Collins
Add a shallow parameter to bzrdir.sprout, which involved fixing a lateny bug in pack to pack fetching with ghost discovery.
3296
            source_revision_ids = frozenset(self.source.all_revision_ids())
3297
            revision_ids = source_revision_ids - \
4144.3.12 by Andrew Bennetts
Remove target_get_graph and target_get_parent_map attributes from InterRepository; nothing overrides them anymore.
3298
                frozenset(self.target.get_parent_map(source_revision_ids))
1551.19.36 by Aaron Bentley
Prevent fetch all from causing pack collisions
3299
            revision_keys = [(revid,) for revid in revision_ids]
4144.3.11 by Andrew Bennetts
Remove InterPackToRemotePack too.
3300
            index = self.target._pack_collection.revision_index.combined_index
1551.19.36 by Aaron Bentley
Prevent fetch all from causing pack collisions
3301
            present_revision_ids = set(item[1][0] for item in
3302
                index.iter_entries(revision_keys))
3303
            revision_ids = set(revision_ids) - present_revision_ids
2592.3.93 by Robert Collins
Steps toward filtering revisions/inventories/texts during fetch.
3304
            # implementing the TODO will involve:
3305
            # - detecting when all of a pack is selected
3306
            # - avoiding as much as possible pre-selection, so the
3307
            # more-core routines such as create_pack_from_packs can filter in
3308
            # a just-in-time fashion. (though having a HEADS list on a
3309
            # repository might make this a lot easier, because we could
3310
            # sensibly detect 'new revisions' without doing a full index scan.
2592.3.91 by Robert Collins
Incrementally closing in on a correct fetch for packs.
3311
        elif _mod_revision.is_null(revision_id):
3312
            # nothing to do:
3010.1.5 by Robert Collins
Test that missing_revision_ids handles the case of the source not having the requested revision correctly with and without find_ghosts.
3313
            return (0, [])
2592.3.90 by Robert Collins
Slightly broken, but branch and fetch performance is now roughly on par (for bzr.dev) with knits - should be much faster for large repos.
3314
        else:
3315
            try:
3184.1.8 by Robert Collins
* ``InterRepository.missing_revision_ids`` is now deprecated in favour of
3316
                revision_ids = self.search_missing_revision_ids(revision_id,
3317
                    find_ghosts=find_ghosts).get_keys()
2592.3.90 by Robert Collins
Slightly broken, but branch and fetch performance is now roughly on par (for bzr.dev) with knits - should be much faster for large repos.
3318
            except errors.NoSuchRevision:
3319
                raise errors.InstallFailed([revision_id])
1551.19.41 by Aaron Bentley
Accelerate no-op pull
3320
            if len(revision_ids) == 0:
3321
                return (0, [])
3452.2.2 by Andrew Bennetts
Experimental PackRepository.{check_references,autopack} RPCs.
3322
        return self._pack(self.source, self.target, revision_ids)
3452.2.1 by Andrew Bennetts
An experimental InterRepo for remote packs.
3323
3324
    def _pack(self, source, target, revision_ids):
3325
        from bzrlib.repofmt.pack_repo import Packer
3326
        packs = source._pack_collection.all_packs()
4144.3.11 by Andrew Bennetts
Remove InterPackToRemotePack too.
3327
        pack = Packer(self.target._pack_collection, packs, '.fetch',
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
3328
            revision_ids).pack()
2592.3.91 by Robert Collins
Incrementally closing in on a correct fetch for packs.
3329
        if pack is not None:
4144.3.11 by Andrew Bennetts
Remove InterPackToRemotePack too.
3330
            self.target._pack_collection._save_pack_names()
3801.1.14 by Andrew Bennetts
Reduce duplication in InterPackToRemotePack.
3331
            copied_revs = pack.get_revision_count()
2592.3.108 by Robert Collins
Autopack after pack to pack fetching too.
3332
            # Trigger an autopack. This may duplicate effort as we've just done
3333
            # a pack creation, but for now it is simpler to think about as
3334
            # 'upload data, then repack if needed'.
4144.3.11 by Andrew Bennetts
Remove InterPackToRemotePack too.
3335
            self.target._pack_collection.autopack()
3801.1.14 by Andrew Bennetts
Reduce duplication in InterPackToRemotePack.
3336
            return (copied_revs, [])
2592.3.91 by Robert Collins
Incrementally closing in on a correct fetch for packs.
3337
        else:
3010.1.5 by Robert Collins
Test that missing_revision_ids handles the case of the source not having the requested revision correctly with and without find_ghosts.
3338
            return (0, [])
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
3339
3340
    @needs_read_lock
4070.9.3 by Andrew Bennetts
Fix a bug, remove some cruft, reduce some ratchets.
3341
    def search_missing_revision_ids(self, revision_id=None, find_ghosts=True):
2949.1.2 by Robert Collins
* Fetch with pack repositories will no longer read the entire history graph.
3342
        """See InterRepository.missing_revision_ids().
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3343
3172.4.1 by Robert Collins
* Fetching via bzr+ssh will no longer fill ghosts by default (this is
3344
        :param find_ghosts: Find ghosts throughout the ancestry of
2949.1.2 by Robert Collins
* Fetch with pack repositories will no longer read the entire history graph.
3345
            revision_id.
3346
        """
4070.9.3 by Andrew Bennetts
Fix a bug, remove some cruft, reduce some ratchets.
3347
        if not find_ghosts and revision_id is not None:
3348
            return self._walk_to_common_revisions([revision_id])
2949.1.2 by Robert Collins
* Fetch with pack repositories will no longer read the entire history graph.
3349
        elif revision_id is not None:
3221.13.2 by Robert Collins
Add a shallow parameter to bzrdir.sprout, which involved fixing a lateny bug in pack to pack fetching with ghost discovery.
3350
            # Find ghosts: search for revisions pointing from one repository to
3221.18.1 by Ian Clatworthy
tweaks by ianc during review
3351
            # the other, and vice versa, anywhere in the history of revision_id.
4144.3.12 by Andrew Bennetts
Remove target_get_graph and target_get_parent_map attributes from InterRepository; nothing overrides them anymore.
3352
            graph = self.target.get_graph(other_repository=self.source)
3221.13.7 by Ian Clatworthy
ensure NoSuchRevision raised when needed in InterPackRepo
3353
            searcher = graph._make_breadth_first_searcher([revision_id])
3354
            found_ids = set()
3355
            while True:
3356
                try:
3357
                    next_revs, ghosts = searcher.next_with_ghosts()
3358
                except StopIteration:
3359
                    break
3360
                if revision_id in ghosts:
3361
                    raise errors.NoSuchRevision(self.source, revision_id)
3362
                found_ids.update(next_revs)
3363
                found_ids.update(ghosts)
3364
            found_ids = frozenset(found_ids)
3221.13.2 by Robert Collins
Add a shallow parameter to bzrdir.sprout, which involved fixing a lateny bug in pack to pack fetching with ghost discovery.
3365
            # Double query here: should be able to avoid this by changing the
3366
            # graph api further.
3367
            result_set = found_ids - frozenset(
4144.3.12 by Andrew Bennetts
Remove target_get_graph and target_get_parent_map attributes from InterRepository; nothing overrides them anymore.
3368
                self.target.get_parent_map(found_ids))
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
3369
        else:
2592.3.151 by Robert Collins
Use the revision index, not the inventory index, for missing and fetch operations.
3370
            source_ids = self.source.all_revision_ids()
3221.13.2 by Robert Collins
Add a shallow parameter to bzrdir.sprout, which involved fixing a lateny bug in pack to pack fetching with ghost discovery.
3371
            # source_ids is the worst possible case we may need to pull.
3372
            # now we want to filter source_ids against what we actually
3373
            # have in target, but don't try to check for existence where we know
3374
            # we do not have a revision as that would be pointless.
3375
            target_ids = set(self.target.all_revision_ids())
3376
            result_set = set(source_ids).difference(target_ids)
3184.1.9 by Robert Collins
* ``Repository.get_data_stream`` is now deprecated in favour of
3377
        return self.source.revision_ids_to_search_result(result_set)
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
3378
3379
2996.2.1 by Aaron Bentley
Add KnitRepositoryFormat4
3380
class InterDifferingSerializer(InterKnitRepo):
3381
3382
    @classmethod
3383
    def _get_repo_format_to_test(self):
3384
        return None
3385
3386
    @staticmethod
3387
    def is_compatible(source, target):
3388
        """Be compatible with Knit2 source and Knit3 target"""
3389
        if source.supports_rich_root() != target.supports_rich_root():
3390
            return False
3391
        # Ideally, we'd support fetching if the source had no tree references
3392
        # even if it supported them...
3393
        if (getattr(source, '_format.supports_tree_reference', False) and
3394
            not getattr(target, '_format.supports_tree_reference', False)):
3395
            return False
3396
        return True
3397
4017.4.1 by John Arbash Meinel
Change the generic fetch logic to improve delta selection.
3398
    def _get_delta_for_revision(self, tree, parent_ids, basis_id, cache):
3399
        """Get the best delta and base for this revision.
3400
3401
        :return: (basis_id, delta)
3402
        """
3403
        possible_trees = [(parent_id, cache[parent_id])
3404
                          for parent_id in parent_ids
3405
                           if parent_id in cache]
3406
        if len(possible_trees) == 0:
3407
            # There either aren't any parents, or the parents aren't in the
3408
            # cache, so just use the last converted tree
3409
            possible_trees.append((basis_id, cache[basis_id]))
3410
        deltas = []
3411
        for basis_id, basis_tree in possible_trees:
3412
            delta = tree.inventory._make_delta(basis_tree.inventory)
3413
            deltas.append((len(delta), basis_id, delta))
3414
        deltas.sort()
3415
        return deltas[0][1:]
3416
3417
    def _fetch_batch(self, revision_ids, basis_id, cache):
3879.2.8 by John Arbash Meinel
Bring in the CHK inter-differing-serializer fetch code.
3418
        """Fetch across a few revisions.
3419
3420
        :param revision_ids: The revisions to copy
4017.4.1 by John Arbash Meinel
Change the generic fetch logic to improve delta selection.
3421
        :param basis_id: The revision_id of a tree that must be in cache, used
3422
            as a basis for delta when no other base is available
3423
        :param cache: A cache of RevisionTrees that we can use.
3424
        :return: The revision_id of the last converted tree. The RevisionTree
3425
            for it will be in cache
3879.2.8 by John Arbash Meinel
Bring in the CHK inter-differing-serializer fetch code.
3426
        """
3427
        # Walk though all revisions; get inventory deltas, copy referenced
3428
        # texts that delta references, insert the delta, revision and
3429
        # signature.
3430
        text_keys = set()
3431
        pending_deltas = []
3432
        pending_revisions = []
4017.4.1 by John Arbash Meinel
Change the generic fetch logic to improve delta selection.
3433
        parent_map = self.source.get_parent_map(revision_ids)
3879.2.8 by John Arbash Meinel
Bring in the CHK inter-differing-serializer fetch code.
3434
        for tree in self.source.revision_trees(revision_ids):
3435
            current_revision_id = tree.get_revision_id()
4017.4.1 by John Arbash Meinel
Change the generic fetch logic to improve delta selection.
3436
            parent_ids = parent_map.get(current_revision_id, ())
3437
            basis_id, delta = self._get_delta_for_revision(tree, parent_ids,
3438
                                                           basis_id, cache)
3439
            # Find text entries that need to be copied
3879.2.8 by John Arbash Meinel
Bring in the CHK inter-differing-serializer fetch code.
3440
            for old_path, new_path, file_id, entry in delta:
3441
                if new_path is not None:
3442
                    if not (new_path or self.target.supports_rich_root()):
4017.4.1 by John Arbash Meinel
Change the generic fetch logic to improve delta selection.
3443
                        # We don't copy the text for the root node unless the
3444
                        # target supports_rich_root.
3879.2.8 by John Arbash Meinel
Bring in the CHK inter-differing-serializer fetch code.
3445
                        continue
4098.4.1 by Robert Collins
Handle inconsistent inventory data more gracefully at a small performance cost during fetch.
3446
                    text_keys.add((file_id, entry.revision))
3879.2.8 by John Arbash Meinel
Bring in the CHK inter-differing-serializer fetch code.
3447
            revision = self.source.get_revision(current_revision_id)
3448
            pending_deltas.append((basis_id, delta,
3449
                current_revision_id, revision.parent_ids))
3450
            pending_revisions.append(revision)
4017.4.1 by John Arbash Meinel
Change the generic fetch logic to improve delta selection.
3451
            cache[current_revision_id] = tree
3879.2.8 by John Arbash Meinel
Bring in the CHK inter-differing-serializer fetch code.
3452
            basis_id = current_revision_id
3453
        # Copy file texts
3454
        from_texts = self.source.texts
3455
        to_texts = self.target.texts
3456
        to_texts.insert_record_stream(from_texts.get_record_stream(
4053.1.4 by Robert Collins
Move the fetch control attributes from Repository to RepositoryFormat.
3457
            text_keys, self.target._format._fetch_order,
3458
            not self.target._format._fetch_uses_deltas))
3879.2.8 by John Arbash Meinel
Bring in the CHK inter-differing-serializer fetch code.
3459
        # insert deltas
3460
        for delta in pending_deltas:
3461
            self.target.add_inventory_by_delta(*delta)
3462
        # insert signatures and revisions
3463
        for revision in pending_revisions:
3464
            try:
3465
                signature = self.source.get_signature_text(
3466
                    revision.revision_id)
3467
                self.target.add_signature_text(revision.revision_id,
3468
                    signature)
3469
            except errors.NoSuchRevision:
3470
                pass
3471
            self.target.add_revision(revision.revision_id, revision)
4017.4.1 by John Arbash Meinel
Change the generic fetch logic to improve delta selection.
3472
        return basis_id
3879.2.8 by John Arbash Meinel
Bring in the CHK inter-differing-serializer fetch code.
3473
3474
    def _fetch_all_revisions(self, revision_ids, pb):
3475
        """Fetch everything for the list of revisions.
3476
3477
        :param revision_ids: The list of revisions to fetch. Must be in
3478
            topological order.
3479
        :param pb: A ProgressBar
3480
        :return: None
3481
        """
3482
        basis_id, basis_tree = self._get_basis(revision_ids[0])
3483
        batch_size = 100
4017.4.1 by John Arbash Meinel
Change the generic fetch logic to improve delta selection.
3484
        cache = lru_cache.LRUCache(100)
3485
        cache[basis_id] = basis_tree
3486
        del basis_tree # We don't want to hang on to it here
3879.2.8 by John Arbash Meinel
Bring in the CHK inter-differing-serializer fetch code.
3487
        for offset in range(0, len(revision_ids), batch_size):
3488
            self.target.start_write_group()
3489
            try:
3490
                pb.update('Transferring revisions', offset,
3879.2.13 by John Arbash Meinel
There was a test that asserted we called pb.update() with the last revision.
3491
                          len(revision_ids))
3879.2.8 by John Arbash Meinel
Bring in the CHK inter-differing-serializer fetch code.
3492
                batch = revision_ids[offset:offset+batch_size]
4017.4.1 by John Arbash Meinel
Change the generic fetch logic to improve delta selection.
3493
                basis_id = self._fetch_batch(batch, basis_id, cache)
3879.2.8 by John Arbash Meinel
Bring in the CHK inter-differing-serializer fetch code.
3494
            except:
3495
                self.target.abort_write_group()
3496
                raise
3497
            else:
3498
                self.target.commit_write_group()
3879.2.13 by John Arbash Meinel
There was a test that asserted we called pb.update() with the last revision.
3499
        pb.update('Transferring revisions', len(revision_ids),
3500
                  len(revision_ids))
3879.2.8 by John Arbash Meinel
Bring in the CHK inter-differing-serializer fetch code.
3501
2996.2.1 by Aaron Bentley
Add KnitRepositoryFormat4
3502
    @needs_write_lock
4070.9.2 by Andrew Bennetts
Rough prototype of allowing a SearchResult to be passed to fetch, and using that to improve network conversations.
3503
    def fetch(self, revision_id=None, pb=None, find_ghosts=False,
3504
            fetch_spec=None):
2996.2.1 by Aaron Bentley
Add KnitRepositoryFormat4
3505
        """See InterRepository.fetch()."""
4070.9.2 by Andrew Bennetts
Rough prototype of allowing a SearchResult to be passed to fetch, and using that to improve network conversations.
3506
        if fetch_spec is not None:
3507
            raise AssertionError("Not implemented yet...")
3184.1.9 by Robert Collins
* ``Repository.get_data_stream`` is now deprecated in favour of
3508
        revision_ids = self.target.search_missing_revision_ids(self.source,
3184.1.8 by Robert Collins
* ``InterRepository.missing_revision_ids`` is now deprecated in favour of
3509
            revision_id, find_ghosts=find_ghosts).get_keys()
3879.2.8 by John Arbash Meinel
Bring in the CHK inter-differing-serializer fetch code.
3510
        if not revision_ids:
3511
            return 0, 0
3184.1.8 by Robert Collins
* ``InterRepository.missing_revision_ids`` is now deprecated in favour of
3512
        revision_ids = tsort.topo_sort(
3184.1.9 by Robert Collins
* ``Repository.get_data_stream`` is now deprecated in favour of
3513
            self.source.get_graph().get_parent_map(revision_ids))
3146.6.1 by Aaron Bentley
InterDifferingSerializer shows a progress bar
3514
        if pb is None:
3515
            my_pb = ui.ui_factory.nested_progress_bar()
3516
            pb = my_pb
3517
        else:
4110.2.5 by Martin Pool
Deprecate passing pbs in to fetch()
3518
            symbol_versioning.warn(
3519
                symbol_versioning.deprecated_in((1, 14, 0))
3520
                % "pb parameter to fetch()")
3146.6.1 by Aaron Bentley
InterDifferingSerializer shows a progress bar
3521
            my_pb = None
3522
        try:
3879.2.8 by John Arbash Meinel
Bring in the CHK inter-differing-serializer fetch code.
3523
            self._fetch_all_revisions(revision_ids, pb)
3146.6.1 by Aaron Bentley
InterDifferingSerializer shows a progress bar
3524
        finally:
3525
            if my_pb is not None:
3526
                my_pb.finished()
2996.2.1 by Aaron Bentley
Add KnitRepositoryFormat4
3527
        return len(revision_ids), 0
3528
3879.2.8 by John Arbash Meinel
Bring in the CHK inter-differing-serializer fetch code.
3529
    def _get_basis(self, first_revision_id):
3530
        """Get a revision and tree which exists in the target.
3531
3532
        This assumes that first_revision_id is selected for transmission
3533
        because all other ancestors are already present. If we can't find an
3534
        ancestor we fall back to NULL_REVISION since we know that is safe.
3535
3536
        :return: (basis_id, basis_tree)
3537
        """
3538
        first_rev = self.source.get_revision(first_revision_id)
3539
        try:
3540
            basis_id = first_rev.parent_ids[0]
3541
            # only valid as a basis if the target has it
3542
            self.target.get_revision(basis_id)
3543
            # Try to get a basis tree - if its a ghost it will hit the
3544
            # NoSuchRevision case.
3545
            basis_tree = self.source.revision_tree(basis_id)
3546
        except (IndexError, errors.NoSuchRevision):
3547
            basis_id = _mod_revision.NULL_REVISION
3548
            basis_tree = self.source.revision_tree(basis_id)
3549
        return basis_id, basis_tree
3550
2996.2.1 by Aaron Bentley
Add KnitRepositoryFormat4
3551
3552
InterRepository.register_optimiser(InterDifferingSerializer)
1910.2.15 by Aaron Bentley
Back out inter.get changes, make optimizers an ordered list
3553
InterRepository.register_optimiser(InterSameDataRepository)
2241.1.13 by Martin Pool
Re-register InterWeaveRepo, fix test integration, add test for it
3554
InterRepository.register_optimiser(InterWeaveRepo)
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
3555
InterRepository.register_optimiser(InterKnitRepo)
2592.3.90 by Robert Collins
Slightly broken, but branch and fetch performance is now roughly on par (for bzr.dev) with knits - should be much faster for large repos.
3556
InterRepository.register_optimiser(InterPackRepo)
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.
3557
3558
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.
3559
class CopyConverter(object):
3560
    """A repository conversion tool which just performs a copy of the content.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3561
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.
3562
    This is slow but quite reliable.
3563
    """
3564
3565
    def __init__(self, target_format):
3566
        """Create a CopyConverter.
3567
3568
        :param target_format: The format the resulting repository should be.
3569
        """
3570
        self.target_format = target_format
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3571
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.
3572
    def convert(self, repo, pb):
3573
        """Perform the conversion of to_convert, giving feedback via pb.
3574
3575
        :param to_convert: The disk object to convert.
3576
        :param pb: a progress bar to use for progress information.
3577
        """
3578
        self.pb = pb
3579
        self.count = 0
1596.2.22 by Robert Collins
Fetch changes to use new pb.
3580
        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.
3581
        # this is only useful with metadir layouts - separated repo content.
3582
        # trigger an assertion if not such
3583
        repo._format.get_format_string()
3584
        self.repo_dir = repo.bzrdir
3585
        self.step('Moving repository to repository.backup')
3586
        self.repo_dir.transport.move('repository', 'repository.backup')
3587
        backup_transport =  self.repo_dir.transport.clone('repository.backup')
1910.2.12 by Aaron Bentley
Implement knit repo format 2
3588
        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.
3589
        self.source_repo = repo._format.open(self.repo_dir,
3590
            _found=True,
3591
            _override_transport=backup_transport)
3592
        self.step('Creating new repository')
3593
        converted = self.target_format.initialize(self.repo_dir,
3594
                                                  self.source_repo.is_shared())
3595
        converted.lock_write()
3596
        try:
3597
            self.step('Copying content into repository.')
3598
            self.source_repo.copy_content_into(converted)
3599
        finally:
3600
            converted.unlock()
3601
        self.step('Deleting old repository content.')
3602
        self.repo_dir.transport.delete_tree('repository.backup')
3603
        self.pb.note('repository converted')
3604
3605
    def step(self, message):
3606
        """Update the pb by a step."""
3607
        self.count +=1
3608
        self.pb.update(message, self.count, self.total)
1596.1.1 by Martin Pool
Use simple xml unescaping rather than importing xml.sax
3609
3610
1843.2.4 by Aaron Bentley
Switch to John Meinel's _unescape_xml implementation
3611
_unescape_map = {
3612
    'apos':"'",
3613
    'quot':'"',
3614
    'amp':'&',
3615
    'lt':'<',
3616
    'gt':'>'
3617
}
3618
3619
3620
def _unescaper(match, _map=_unescape_map):
2294.1.2 by John Arbash Meinel
Track down and add tests that all tree.commit() can handle
3621
    code = match.group(1)
3622
    try:
3623
        return _map[code]
3624
    except KeyError:
3625
        if not code.startswith('#'):
3626
            raise
2294.1.10 by John Arbash Meinel
Switch all apis over to utf8 file ids. All tests pass
3627
        return unichr(int(code[1:])).encode('utf8')
1843.2.4 by Aaron Bentley
Switch to John Meinel's _unescape_xml implementation
3628
3629
3630
_unescape_re = None
3631
3632
1596.1.1 by Martin Pool
Use simple xml unescaping rather than importing xml.sax
3633
def _unescape_xml(data):
1843.2.4 by Aaron Bentley
Switch to John Meinel's _unescape_xml implementation
3634
    """Unescape predefined XML entities in a string of data."""
3635
    global _unescape_re
3636
    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.
3637
        _unescape_re = re.compile('\&([^;]*);')
1843.2.4 by Aaron Bentley
Switch to John Meinel's _unescape_xml implementation
3638
    return _unescape_re.sub(_unescaper, data)
2745.6.3 by Aaron Bentley
Implement versionedfile checking for bzr check
3639
3640
3036.1.3 by Robert Collins
Privatise VersionedFileChecker.
3641
class _VersionedFileChecker(object):
2745.6.47 by Andrew Bennetts
Move check_parents out of VersionedFile.
3642
4145.2.1 by Ian Clatworthy
faster check
3643
    def __init__(self, repository, text_key_references=None):
2745.6.47 by Andrew Bennetts
Move check_parents out of VersionedFile.
3644
        self.repository = repository
4145.2.1 by Ian Clatworthy
faster check
3645
        self.text_index = self.repository._generate_text_key_index(
3646
            text_key_references=text_key_references)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3647
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
3648
    def calculate_file_version_parents(self, text_key):
2927.2.10 by Andrew Bennetts
More docstrings, elaborate a comment with an XXX, and remove a little bit of cruft.
3649
        """Calculate the correct parents for a file version according to
3650
        the inventories.
3651
        """
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
3652
        parent_keys = self.text_index[text_key]
2988.1.8 by Robert Collins
Change check and reconcile to use the new _generate_text_key_index rather
3653
        if parent_keys == [_mod_revision.NULL_REVISION]:
3654
            return ()
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
3655
        return tuple(parent_keys)
2745.6.47 by Andrew Bennetts
Move check_parents out of VersionedFile.
3656
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
3657
    def check_file_version_parents(self, texts, progress_bar=None):
2927.2.10 by Andrew Bennetts
More docstrings, elaborate a comment with an XXX, and remove a little bit of cruft.
3658
        """Check the parents stored in a versioned file are correct.
3659
3660
        It also detects file versions that are not referenced by their
3661
        corresponding revision's inventory.
3662
2927.2.14 by Andrew Bennetts
Tweaks suggested by review.
3663
        :returns: A tuple of (wrong_parents, dangling_file_versions).
2927.2.10 by Andrew Bennetts
More docstrings, elaborate a comment with an XXX, and remove a little bit of cruft.
3664
            wrong_parents is a dict mapping {revision_id: (stored_parents,
3665
            correct_parents)} for each revision_id where the stored parents
2927.2.14 by Andrew Bennetts
Tweaks suggested by review.
3666
            are not correct.  dangling_file_versions is a set of (file_id,
3667
            revision_id) tuples for versions that are present in this versioned
3668
            file, but not used by the corresponding inventory.
2927.2.10 by Andrew Bennetts
More docstrings, elaborate a comment with an XXX, and remove a little bit of cruft.
3669
        """
2927.2.3 by Andrew Bennetts
Add fulltexts to avoid bug 155730.
3670
        wrong_parents = {}
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
3671
        self.file_ids = set([file_id for file_id, _ in
3672
            self.text_index.iterkeys()])
3673
        # text keys is now grouped by file_id
3674
        n_weaves = len(self.file_ids)
3675
        files_in_revisions = {}
3676
        revisions_of_files = {}
3677
        n_versions = len(self.text_index)
3678
        progress_bar.update('loading text store', 0, n_versions)
3679
        parent_map = self.repository.texts.get_parent_map(self.text_index)
3680
        # On unlistable transports this could well be empty/error...
3681
        text_keys = self.repository.texts.keys()
3682
        unused_keys = frozenset(text_keys) - set(self.text_index)
3683
        for num, key in enumerate(self.text_index.iterkeys()):
3684
            if progress_bar is not None:
3685
                progress_bar.update('checking text graph', num, n_versions)
3686
            correct_parents = self.calculate_file_version_parents(key)
2927.2.6 by Andrew Bennetts
Make some more check tests pass.
3687
            try:
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
3688
                knit_parents = parent_map[key]
3689
            except errors.RevisionNotPresent:
3690
                # Missing text!
3691
                knit_parents = None
3692
            if correct_parents != knit_parents:
3693
                wrong_parents[key] = (knit_parents, correct_parents)
3694
        return wrong_parents, unused_keys
3287.6.8 by Robert Collins
Reduce code duplication as per review.
3695
3696
3697
def _old_get_graph(repository, revision_id):
3698
    """DO NOT USE. That is all. I'm serious."""
3699
    graph = repository.get_graph()
3700
    revision_graph = dict(((key, value) for key, value in
3701
        graph.iter_ancestry([revision_id]) if value is not None))
3702
    return _strip_NULL_ghosts(revision_graph)
3703
3704
3705
def _strip_NULL_ghosts(revision_graph):
3706
    """Also don't use this. more compatibility code for unmigrated clients."""
3707
    # Filter ghosts, and null:
3708
    if _mod_revision.NULL_REVISION in revision_graph:
3709
        del revision_graph[_mod_revision.NULL_REVISION]
3710
    for key, parents in revision_graph.items():
3711
        revision_graph[key] = tuple(parent for parent in parents if parent
3712
            in revision_graph)
3713
    return revision_graph
4022.1.1 by Robert Collins
Refactoring of fetch to have a sender and sink component enabling splitting the logic over a network stream. (Robert Collins, Andrew Bennetts)
3714
3715
3716
class StreamSink(object):
3717
    """An object that can insert a stream into a repository.
3718
3719
    This interface handles the complexity of reserialising inventories and
3720
    revisions from different formats, and allows unidirectional insertion into
3721
    stacked repositories without looking for the missing basis parents
3722
    beforehand.
3723
    """
3724
3725
    def __init__(self, target_repo):
3726
        self.target_repo = target_repo
3727
4032.3.7 by Robert Collins
Move write locking and write group responsibilities into the Sink objects themselves, allowing complete avoidance of unnecessary calls when the sink is a RemoteSink.
3728
    def insert_stream(self, stream, src_format, resume_tokens):
4022.1.1 by Robert Collins
Refactoring of fetch to have a sender and sink component enabling splitting the logic over a network stream. (Robert Collins, Andrew Bennetts)
3729
        """Insert a stream's content into the target repository.
3730
3731
        :param src_format: a bzr repository format.
3732
4032.3.7 by Robert Collins
Move write locking and write group responsibilities into the Sink objects themselves, allowing complete avoidance of unnecessary calls when the sink is a RemoteSink.
3733
        :return: a list of resume tokens and an  iterable of keys additional
3734
            items required before the insertion can be completed.
4022.1.1 by Robert Collins
Refactoring of fetch to have a sender and sink component enabling splitting the logic over a network stream. (Robert Collins, Andrew Bennetts)
3735
        """
4032.3.7 by Robert Collins
Move write locking and write group responsibilities into the Sink objects themselves, allowing complete avoidance of unnecessary calls when the sink is a RemoteSink.
3736
        self.target_repo.lock_write()
3737
        try:
3738
            if resume_tokens:
3739
                self.target_repo.resume_write_group(resume_tokens)
3740
            else:
3741
                self.target_repo.start_write_group()
3742
            try:
3743
                # locked_insert_stream performs a commit|suspend.
3744
                return self._locked_insert_stream(stream, src_format)
3745
            except:
3746
                self.target_repo.abort_write_group(suppress_errors=True)
3747
                raise
3748
        finally:
3749
            self.target_repo.unlock()
3750
3751
    def _locked_insert_stream(self, stream, src_format):
4022.1.1 by Robert Collins
Refactoring of fetch to have a sender and sink component enabling splitting the logic over a network stream. (Robert Collins, Andrew Bennetts)
3752
        to_serializer = self.target_repo._format._serializer
3753
        src_serializer = src_format._serializer
4187.3.2 by Andrew Bennetts
Only enable the hack when the serializers match, otherwise we cause ShortReadvErrors.
3754
        if to_serializer == src_serializer:
3755
            # If serializers match and the target is a pack repository, set the
3756
            # write cache size on the new pack.  This avoids poor performance
3757
            # on transports where append is unbuffered (such as
4187.3.4 by Andrew Bennetts
Better docstrings and comments.
3758
            # RemoteTransport).  This is safe to do because nothing should read
4187.3.2 by Andrew Bennetts
Only enable the hack when the serializers match, otherwise we cause ShortReadvErrors.
3759
            # back from the target repository while a stream with matching
3760
            # serialization is being inserted.
4187.3.4 by Andrew Bennetts
Better docstrings and comments.
3761
            # The exception is that a delta record from the source that should
3762
            # be a fulltext may need to be expanded by the target (see
3763
            # test_fetch_revisions_with_deltas_into_pack); but we take care to
3764
            # explicitly flush any buffered writes first in that rare case.
4187.3.2 by Andrew Bennetts
Only enable the hack when the serializers match, otherwise we cause ShortReadvErrors.
3765
            try:
3766
                new_pack = self.target_repo._pack_collection._new_pack
3767
            except AttributeError:
3768
                # Not a pack repository
3769
                pass
3770
            else:
3771
                new_pack.set_write_cache_size(1024*1024)
4022.1.1 by Robert Collins
Refactoring of fetch to have a sender and sink component enabling splitting the logic over a network stream. (Robert Collins, Andrew Bennetts)
3772
        for substream_type, substream in stream:
3773
            if substream_type == 'texts':
3774
                self.target_repo.texts.insert_record_stream(substream)
3775
            elif substream_type == 'inventories':
3776
                if src_serializer == to_serializer:
3777
                    self.target_repo.inventories.insert_record_stream(
3778
                        substream)
3779
                else:
3780
                    self._extract_and_insert_inventories(
3781
                        substream, src_serializer)
3782
            elif substream_type == 'revisions':
3783
                # This may fallback to extract-and-insert more often than
3784
                # required if the serializers are different only in terms of
3785
                # the inventory.
3786
                if src_serializer == to_serializer:
3787
                    self.target_repo.revisions.insert_record_stream(
3788
                        substream)
3789
                else:
3790
                    self._extract_and_insert_revisions(substream,
3791
                        src_serializer)
3792
            elif substream_type == 'signatures':
3793
                self.target_repo.signatures.insert_record_stream(substream)
3794
            else:
3795
                raise AssertionError('kaboom! %s' % (substream_type,))
4032.3.7 by Robert Collins
Move write locking and write group responsibilities into the Sink objects themselves, allowing complete avoidance of unnecessary calls when the sink is a RemoteSink.
3796
        try:
3797
            missing_keys = set()
3798
            for prefix, versioned_file in (
3799
                ('texts', self.target_repo.texts),
3800
                ('inventories', self.target_repo.inventories),
3801
                ('revisions', self.target_repo.revisions),
3802
                ('signatures', self.target_repo.signatures),
3803
                ):
3804
                missing_keys.update((prefix,) + key for key in
3805
                    versioned_file.get_missing_compression_parent_keys())
3806
        except NotImplementedError:
3807
            # cannot even attempt suspending, and missing would have failed
3808
            # during stream insertion.
3809
            missing_keys = set()
3810
        else:
3811
            if missing_keys:
3812
                # suspend the write group and tell the caller what we is
3813
                # missing. We know we can suspend or else we would not have
3814
                # entered this code path. (All repositories that can handle
3815
                # missing keys can handle suspending a write group).
3816
                write_group_tokens = self.target_repo.suspend_write_group()
3817
                return write_group_tokens, missing_keys
3818
        self.target_repo.commit_write_group()
3819
        return [], set()
4022.1.1 by Robert Collins
Refactoring of fetch to have a sender and sink component enabling splitting the logic over a network stream. (Robert Collins, Andrew Bennetts)
3820
3821
    def _extract_and_insert_inventories(self, substream, serializer):
3822
        """Generate a new inventory versionedfile in target, converting data.
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
3823
4022.1.1 by Robert Collins
Refactoring of fetch to have a sender and sink component enabling splitting the logic over a network stream. (Robert Collins, Andrew Bennetts)
3824
        The inventory is retrieved from the source, (deserializing it), and
3825
        stored in the target (reserializing it in a different format).
3826
        """
3827
        for record in substream:
3828
            bytes = record.get_bytes_as('fulltext')
3829
            revision_id = record.key[0]
3830
            inv = serializer.read_inventory_from_string(bytes, revision_id)
3831
            parents = [key[0] for key in record.parents]
3832
            self.target_repo.add_inventory(revision_id, inv, parents)
3833
3834
    def _extract_and_insert_revisions(self, substream, serializer):
3835
        for record in substream:
3836
            bytes = record.get_bytes_as('fulltext')
3837
            revision_id = record.key[0]
3838
            rev = serializer.read_revision_from_string(bytes)
3839
            if rev.revision_id != revision_id:
3840
                raise AssertionError('wtf: %s != %s' % (rev, revision_id))
3841
            self.target_repo.add_revision(revision_id, rev)
3842
3843
    def finished(self):
4053.1.4 by Robert Collins
Move the fetch control attributes from Repository to RepositoryFormat.
3844
        if self.target_repo._format._fetch_reconcile:
4022.1.1 by Robert Collins
Refactoring of fetch to have a sender and sink component enabling splitting the logic over a network stream. (Robert Collins, Andrew Bennetts)
3845
            self.target_repo.reconcile()
3846
4060.1.3 by Robert Collins
Implement the separate source component for fetch - repository.StreamSource.
3847
3848
class StreamSource(object):
4065.1.2 by Robert Collins
Merge bzr.dev [fix conflicts with fetch refactoring].
3849
    """A source of a stream for fetching between repositories."""
4060.1.3 by Robert Collins
Implement the separate source component for fetch - repository.StreamSource.
3850
3851
    def __init__(self, from_repository, to_format):
3852
        """Create a StreamSource streaming from from_repository."""
3853
        self.from_repository = from_repository
3854
        self.to_format = to_format
3855
3856
    def delta_on_metadata(self):
3857
        """Return True if delta's are permitted on metadata streams.
3858
3859
        That is on revisions and signatures.
3860
        """
3861
        src_serializer = self.from_repository._format._serializer
3862
        target_serializer = self.to_format._serializer
3863
        return (self.to_format._fetch_uses_deltas and
3864
            src_serializer == target_serializer)
3865
3866
    def _fetch_revision_texts(self, revs):
3867
        # fetch signatures first and then the revision texts
3868
        # may need to be a InterRevisionStore call here.
3869
        from_sf = self.from_repository.signatures
3870
        # A missing signature is just skipped.
3871
        keys = [(rev_id,) for rev_id in revs]
4060.1.4 by Robert Collins
Streaming fetch from remote servers.
3872
        signatures = versionedfile.filter_absent(from_sf.get_record_stream(
4060.1.3 by Robert Collins
Implement the separate source component for fetch - repository.StreamSource.
3873
            keys,
3874
            self.to_format._fetch_order,
3875
            not self.to_format._fetch_uses_deltas))
3876
        # If a revision has a delta, this is actually expanded inside the
3877
        # insert_record_stream code now, which is an alternate fix for
3878
        # bug #261339
3879
        from_rf = self.from_repository.revisions
3880
        revisions = from_rf.get_record_stream(
3881
            keys,
3882
            self.to_format._fetch_order,
3883
            not self.delta_on_metadata())
3884
        return [('signatures', signatures), ('revisions', revisions)]
3885
3886
    def _generate_root_texts(self, revs):
3887
        """This will be called by __fetch between fetching weave texts and
3888
        fetching the inventory weave.
3889
3890
        Subclasses should override this if they need to generate root texts
3891
        after fetching weave texts.
3892
        """
3893
        if self._rich_root_upgrade():
3894
            import bzrlib.fetch
3895
            return bzrlib.fetch.Inter1and2Helper(
3896
                self.from_repository).generate_root_texts(revs)
3897
        else:
3898
            return []
3899
3900
    def get_stream(self, search):
3901
        phase = 'file'
3902
        revs = search.get_keys()
3903
        graph = self.from_repository.get_graph()
3904
        revs = list(graph.iter_topo_order(revs))
3905
        data_to_fetch = self.from_repository.item_keys_introduced_by(revs)
3906
        text_keys = []
3907
        for knit_kind, file_id, revisions in data_to_fetch:
3908
            if knit_kind != phase:
3909
                phase = knit_kind
3910
                # Make a new progress bar for this phase
3911
            if knit_kind == "file":
3912
                # Accumulate file texts
3913
                text_keys.extend([(file_id, revision) for revision in
3914
                    revisions])
3915
            elif knit_kind == "inventory":
3916
                # Now copy the file texts.
3917
                from_texts = self.from_repository.texts
3918
                yield ('texts', from_texts.get_record_stream(
3919
                    text_keys, self.to_format._fetch_order,
3920
                    not self.to_format._fetch_uses_deltas))
3921
                # Cause an error if a text occurs after we have done the
3922
                # copy.
3923
                text_keys = None
3924
                # Before we process the inventory we generate the root
3925
                # texts (if necessary) so that the inventories references
3926
                # will be valid.
3927
                for _ in self._generate_root_texts(revs):
3928
                    yield _
3929
                # NB: This currently reopens the inventory weave in source;
3930
                # using a single stream interface instead would avoid this.
3931
                from_weave = self.from_repository.inventories
3932
                # we fetch only the referenced inventories because we do not
3933
                # know for unselected inventories whether all their required
3934
                # texts are present in the other repository - it could be
3935
                # corrupt.
3936
                yield ('inventories', from_weave.get_record_stream(
3937
                    [(rev_id,) for rev_id in revs],
3938
                    self.inventory_fetch_order(),
3939
                    not self.delta_on_metadata()))
3940
            elif knit_kind == "signatures":
3941
                # Nothing to do here; this will be taken care of when
3942
                # _fetch_revision_texts happens.
3943
                pass
3944
            elif knit_kind == "revisions":
3945
                for record in self._fetch_revision_texts(revs):
3946
                    yield record
3947
            else:
3948
                raise AssertionError("Unknown knit kind %r" % knit_kind)
3949
3950
    def get_stream_for_missing_keys(self, missing_keys):
3951
        # missing keys can only occur when we are byte copying and not
3952
        # translating (because translation means we don't send
3953
        # unreconstructable deltas ever).
3954
        keys = {}
3955
        keys['texts'] = set()
3956
        keys['revisions'] = set()
3957
        keys['inventories'] = set()
3958
        keys['signatures'] = set()
3959
        for key in missing_keys:
3960
            keys[key[0]].add(key[1:])
3961
        if len(keys['revisions']):
3962
            # If we allowed copying revisions at this point, we could end up
3963
            # copying a revision without copying its required texts: a
3964
            # violation of the requirements for repository integrity.
3965
            raise AssertionError(
3966
                'cannot copy revisions to fill in missing deltas %s' % (
3967
                    keys['revisions'],))
3968
        for substream_kind, keys in keys.iteritems():
3969
            vf = getattr(self.from_repository, substream_kind)
3970
            # Ask for full texts always so that we don't need more round trips
3971
            # after this stream.
3972
            stream = vf.get_record_stream(keys,
3973
                self.to_format._fetch_order, True)
3974
            yield substream_kind, stream
3975
3976
    def inventory_fetch_order(self):
3977
        if self._rich_root_upgrade():
3978
            return 'topological'
3979
        else:
3980
            return self.to_format._fetch_order
3981
3982
    def _rich_root_upgrade(self):
3983
        return (not self.from_repository._format.rich_root_data and
3984
            self.to_format.rich_root_data)
3985