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