/brz/remove-bazaar

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