/brz/remove-bazaar

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