/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
2220.2.1 by Martin Pool
Start adding space for tags stored in the repository
1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
2
#
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
7
#
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
12
#
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
1185.65.10 by Robert Collins
Rename Controlfiles to LockableFiles.
16
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
17
from cStringIO import StringIO
18
19
from bzrlib.lazy_import import lazy_import
20
lazy_import(globals(), """
1740.3.7 by Jelmer Vernooij
Move committer, log, revprops, timestamp and timezone to CommitBuilder.
21
import re
22
import time
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
23
1910.2.22 by Aaron Bentley
Make commits preserve root entry data
24
from bzrlib import (
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
25
    bzrdir,
26
    check,
2745.1.1 by Robert Collins
Add a number of -Devil checkpoints.
27
    debug,
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
28
    errors,
2116.4.1 by John Arbash Meinel
Update file and revision id generators.
29
    generate_ids,
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
30
    gpg,
31
    graph,
2163.2.1 by John Arbash Meinel
Speed up the fileids_altered_by_revision_ids processing
32
    lazy_regex,
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
33
    lockable_files,
34
    lockdir,
2988.1.5 by Robert Collins
Use a LRU cache when generating the text index to reduce inventory deserialisations.
35
    lru_cache,
1910.2.22 by Aaron Bentley
Make commits preserve root entry data
36
    osutils,
2241.1.1 by Martin Pool
Change RepositoryFormat to use a Registry rather than ad-hoc dictionary
37
    registry,
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
38
    remote,
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
39
    revision as _mod_revision,
40
    symbol_versioning,
1910.2.22 by Aaron Bentley
Make commits preserve root entry data
41
    transactions,
2988.1.3 by Robert Collins
Add a new repositoy method _generate_text_key_index for use by reconcile/check.
42
    tsort,
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
43
    ui,
44
    )
2520.4.54 by Aaron Bentley
Hang a create_bundle method off repository
45
from bzrlib.bundle import serializer
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
46
from bzrlib.revisiontree import RevisionTree
47
from bzrlib.store.versioned import VersionedFileStore
48
from bzrlib.store.text import TextStore
49
from bzrlib.testament import Testament
2535.3.40 by Andrew Bennetts
Tidy up more XXXs.
50
from bzrlib.util import bencode
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
51
""")
52
1534.4.28 by Robert Collins
first cut at merge from integration.
53
from bzrlib.decorators import needs_read_lock, needs_write_lock
1563.2.12 by Robert Collins
Checkpointing: created InterObject to factor out common inter object worker code, added InterVersionedFile and tests to allow making join work between any versionedfile.
54
from bzrlib.inter import InterObject
1910.2.3 by Aaron Bentley
All tests pass
55
from bzrlib.inventory import Inventory, InventoryDirectory, ROOT_ID
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
56
from bzrlib.symbol_versioning import (
57
        deprecated_method,
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
58
        )
2745.1.1 by Robert Collins
Add a number of -Devil checkpoints.
59
from bzrlib.trace import mutter, mutter_callsite, note, warning
1185.70.3 by Martin Pool
Various updates to make storage branch mergeable:
60
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
61
1904.2.5 by Martin Pool
Fix format warning inside test suite and add test
62
# Old formats display a warning, but only once
63
_deprecation_warning_done = False
64
65
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
66
class CommitBuilder(object):
67
    """Provides an interface to build up a commit.
68
69
    This allows describing a tree to be committed without needing to 
70
    know the internals of the format of the repository.
71
    """
72
    
73
    # all clients should supply tree roots.
74
    record_root_entry = True
2825.5.2 by Robert Collins
Review feedback, and fix pointless commits with nested trees to raise PointlessCommit appropriately.
75
    # the default CommitBuilder does not manage trees whose root is versioned.
76
    _versioned_root = False
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
77
2979.2.2 by Robert Collins
Per-file graph heads detection during commit for pack repositories.
78
    def __init__(self, repository, parents, config, timestamp=None,
79
                 timezone=None, committer=None, revprops=None,
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
80
                 revision_id=None):
81
        """Initiate a CommitBuilder.
82
83
        :param repository: Repository to commit to.
84
        :param parents: Revision ids of the parents of the new revision.
85
        :param config: Configuration to use.
86
        :param timestamp: Optional timestamp recorded for commit.
87
        :param timezone: Optional timezone for timestamp.
88
        :param committer: Optional committer to set for commit.
89
        :param revprops: Optional dictionary of revision properties.
90
        :param revision_id: Optional revision id.
91
        """
92
        self._config = config
93
94
        if committer is None:
95
            self._committer = self._config.username()
96
        else:
97
            self._committer = committer
98
99
        self.new_inventory = Inventory(None)
2858.2.1 by Martin Pool
Remove most calls to safe_file_id and safe_revision_id.
100
        self._new_revision_id = revision_id
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
101
        self.parents = parents
102
        self.repository = repository
103
104
        self._revprops = {}
105
        if revprops is not None:
106
            self._revprops.update(revprops)
107
108
        if timestamp is None:
109
            timestamp = time.time()
110
        # Restrict resolution to 1ms
111
        self._timestamp = round(timestamp, 3)
112
113
        if timezone is None:
114
            self._timezone = osutils.local_time_offset()
115
        else:
116
            self._timezone = int(timezone)
117
118
        self._generate_revision_if_needed()
2979.2.5 by Robert Collins
Make CommitBuilder.heads be _heads as its internal to CommitBuilder only.
119
        self.__heads = graph.HeadsCache(repository.get_graph()).heads
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
120
121
    def commit(self, message):
122
        """Make the actual commit.
123
124
        :return: The revision id of the recorded revision.
125
        """
126
        rev = _mod_revision.Revision(
127
                       timestamp=self._timestamp,
128
                       timezone=self._timezone,
129
                       committer=self._committer,
130
                       message=message,
131
                       inventory_sha1=self.inv_sha1,
132
                       revision_id=self._new_revision_id,
133
                       properties=self._revprops)
134
        rev.parent_ids = self.parents
135
        self.repository.add_revision(self._new_revision_id, rev,
136
            self.new_inventory, self._config)
137
        self.repository.commit_write_group()
138
        return self._new_revision_id
139
140
    def abort(self):
141
        """Abort the commit that is being built.
142
        """
143
        self.repository.abort_write_group()
144
145
    def revision_tree(self):
146
        """Return the tree that was just committed.
147
148
        After calling commit() this can be called to get a RevisionTree
149
        representing the newly committed tree. This is preferred to
150
        calling Repository.revision_tree() because that may require
151
        deserializing the inventory, while we already have a copy in
152
        memory.
153
        """
154
        return RevisionTree(self.repository, self.new_inventory,
155
                            self._new_revision_id)
156
157
    def finish_inventory(self):
158
        """Tell the builder that the inventory is finished."""
159
        if self.new_inventory.root is None:
2903.2.9 by Martin Pool
Review cleanups, mostly documentation
160
            raise AssertionError('Root entry should be supplied to'
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
161
                ' record_entry_contents, as of bzr 0.10.',
162
                 DeprecationWarning, stacklevel=2)
163
            self.new_inventory.add(InventoryDirectory(ROOT_ID, '', None))
164
        self.new_inventory.revision_id = self._new_revision_id
165
        self.inv_sha1 = self.repository.add_inventory(
166
            self._new_revision_id,
167
            self.new_inventory,
168
            self.parents
169
            )
170
171
    def _gen_revision_id(self):
172
        """Return new revision-id."""
173
        return generate_ids.gen_revision_id(self._config.username(),
174
                                            self._timestamp)
175
176
    def _generate_revision_if_needed(self):
177
        """Create a revision id if None was supplied.
178
        
179
        If the repository can not support user-specified revision ids
180
        they should override this function and raise CannotSetRevisionId
181
        if _new_revision_id is not None.
182
183
        :raises: CannotSetRevisionId
184
        """
185
        if self._new_revision_id is None:
186
            self._new_revision_id = self._gen_revision_id()
187
            self.random_revid = True
188
        else:
189
            self.random_revid = False
190
2979.2.5 by Robert Collins
Make CommitBuilder.heads be _heads as its internal to CommitBuilder only.
191
    def _heads(self, file_id, revision_ids):
2979.2.1 by Robert Collins
Make it possible for different commit builders to override heads().
192
        """Calculate the graph heads for revision_ids in the graph of file_id.
193
194
        This can use either a per-file graph or a global revision graph as we
195
        have an identity relationship between the two graphs.
196
        """
2979.2.5 by Robert Collins
Make CommitBuilder.heads be _heads as its internal to CommitBuilder only.
197
        return self.__heads(revision_ids)
2979.2.1 by Robert Collins
Make it possible for different commit builders to override heads().
198
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
199
    def _check_root(self, ie, parent_invs, tree):
200
        """Helper for record_entry_contents.
201
202
        :param ie: An entry being added.
203
        :param parent_invs: The inventories of the parent revisions of the
204
            commit.
205
        :param tree: The tree that is being committed.
206
        """
2871.1.2 by Robert Collins
* ``CommitBuilder.record_entry_contents`` now requires the root entry of a
207
        # In this revision format, root entries have no knit or weave When
208
        # serializing out to disk and back in root.revision is always
209
        # _new_revision_id
210
        ie.revision = self._new_revision_id
2818.3.1 by Robert Collins
Change CommitBuilder factory delegation to allow simple declaration.
211
2871.1.4 by Robert Collins
Merge bzr.dev.
212
    def _get_delta(self, ie, basis_inv, path):
213
        """Get a delta against the basis inventory for ie."""
214
        if ie.file_id not in basis_inv:
215
            # add
216
            return (None, path, ie.file_id, ie)
217
        elif ie != basis_inv[ie.file_id]:
218
            # common but altered
219
            # TODO: avoid tis id2path call.
220
            return (basis_inv.id2path(ie.file_id), path, ie.file_id, ie)
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
221
        else:
2871.1.4 by Robert Collins
Merge bzr.dev.
222
            # common, unaltered
223
            return None
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
224
225
    def record_entry_contents(self, ie, parent_invs, path, tree,
226
        content_summary):
227
        """Record the content of ie from tree into the commit if needed.
228
229
        Side effect: sets ie.revision when unchanged
230
231
        :param ie: An inventory entry present in the commit.
232
        :param parent_invs: The inventories of the parent revisions of the
233
            commit.
234
        :param path: The path the entry is at in the tree.
235
        :param tree: The tree which contains this entry and should be used to 
236
            obtain content.
237
        :param content_summary: Summary data from the tree about the paths
238
            content - stat, length, exec, sha/link target. This is only
239
            accessed when the entry has a revision of None - that is when it is
240
            a candidate to commit.
2871.1.3 by Robert Collins
* The CommitBuilder method ``record_entry_contents`` now returns summary
241
        :return: A tuple (change_delta, version_recorded). change_delta is 
242
            an inventory_delta change for this entry against the basis tree of
243
            the commit, or None if no change occured against the basis tree.
244
            version_recorded is True if a new version of the entry has been
245
            recorded. For instance, committing a merge where a file was only
246
            changed on the other side will return (delta, False).
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
247
        """
248
        if self.new_inventory.root is None:
2871.1.2 by Robert Collins
* ``CommitBuilder.record_entry_contents`` now requires the root entry of a
249
            if ie.parent_id is not None:
250
                raise errors.RootMissing()
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
251
            self._check_root(ie, parent_invs, tree)
252
        if ie.revision is None:
253
            kind = content_summary[0]
254
        else:
255
            # ie is carried over from a prior commit
256
            kind = ie.kind
257
        # XXX: repository specific check for nested tree support goes here - if
258
        # the repo doesn't want nested trees we skip it ?
259
        if (kind == 'tree-reference' and
260
            not self.repository._format.supports_tree_reference):
261
            # mismatch between commit builder logic and repository:
262
            # this needs the entry creation pushed down into the builder.
2776.4.18 by Robert Collins
Review feedback.
263
            raise NotImplementedError('Missing repository subtree support.')
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
264
        self.new_inventory.add(ie)
265
2871.1.3 by Robert Collins
* The CommitBuilder method ``record_entry_contents`` now returns summary
266
        # TODO: slow, take it out of the inner loop.
267
        try:
268
            basis_inv = parent_invs[0]
269
        except IndexError:
270
            basis_inv = Inventory(root_id=None)
271
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
272
        # ie.revision is always None if the InventoryEntry is considered
2776.4.13 by Robert Collins
Merge bzr.dev.
273
        # for committing. We may record the previous parents revision if the
274
        # 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.
275
        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
276
            if not self._versioned_root and path == '':
2871.1.3 by Robert Collins
* The CommitBuilder method ``record_entry_contents`` now returns summary
277
                # repositories that do not version the root set the root's
278
                # revision to the new commit even when no change occurs, and
279
                # this masks when a change may have occurred against the basis,
280
                # so calculate if one happened.
2903.2.5 by Martin Pool
record_entry_contents should give back deltas for changed roots; clean it up a bit
281
                if ie.file_id in basis_inv:
282
                    delta = (basis_inv.id2path(ie.file_id), path,
283
                        ie.file_id, ie)
284
                else:
2871.1.3 by Robert Collins
* The CommitBuilder method ``record_entry_contents`` now returns summary
285
                    # add
286
                    delta = (None, path, ie.file_id, ie)
2903.2.5 by Martin Pool
record_entry_contents should give back deltas for changed roots; clean it up a bit
287
                return delta, False
288
            else:
289
                # we don't need to commit this, because the caller already
290
                # determined that an existing revision of this file is
291
                # appropriate.
2903.2.9 by Martin Pool
Review cleanups, mostly documentation
292
                return None, (ie.revision == self._new_revision_id)
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
293
        # XXX: Friction: parent_candidates should return a list not a dict
294
        #      so that we don't have to walk the inventories again.
295
        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.
296
        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.
297
        heads = []
298
        for inv in parent_invs:
299
            if ie.file_id in inv:
300
                old_rev = inv[ie.file_id].revision
301
                if old_rev in head_set:
302
                    heads.append(inv[ie.file_id].revision)
303
                    head_set.remove(inv[ie.file_id].revision)
304
305
        store = False
306
        # now we check to see if we need to write a new record to the
307
        # file-graph.
308
        # We write a new entry unless there is one head to the ancestors, and
309
        # the kind-derived content is unchanged.
310
311
        # Cheapest check first: no ancestors, or more the one head in the
312
        # ancestors, we write a new node.
313
        if len(heads) != 1:
314
            store = True
315
        if not store:
316
            # There is a single head, look it up for comparison
317
            parent_entry = parent_candiate_entries[heads[0]]
318
            # if the non-content specific data has changed, we'll be writing a
319
            # node:
320
            if (parent_entry.parent_id != ie.parent_id or
321
                parent_entry.name != ie.name):
322
                store = True
323
        # now we need to do content specific checks:
324
        if not store:
325
            # if the kind changed the content obviously has
326
            if kind != parent_entry.kind:
327
                store = True
328
        if kind == 'file':
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
329
            if content_summary[2] is None:
330
                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.
331
            if not store:
332
                if (# if the file length changed we have to store:
333
                    parent_entry.text_size != content_summary[1] or
334
                    # if the exec bit has changed we have to store:
335
                    parent_entry.executable != content_summary[2]):
336
                    store = True
337
                elif parent_entry.text_sha1 == content_summary[3]:
338
                    # all meta and content is unchanged (using a hash cache
339
                    # hit to check the sha)
340
                    ie.revision = parent_entry.revision
341
                    ie.text_size = parent_entry.text_size
342
                    ie.text_sha1 = parent_entry.text_sha1
343
                    ie.executable = parent_entry.executable
2871.1.4 by Robert Collins
Merge bzr.dev.
344
                    return self._get_delta(ie, basis_inv, path), False
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
345
                else:
346
                    # Either there is only a hash change(no hash cache entry,
347
                    # or same size content change), or there is no change on
348
                    # this file at all.
2776.4.19 by Robert Collins
Final review tweaks.
349
                    # Provide the parent's hash to the store layer, so that the
350
                    # 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.
351
                    nostore_sha = parent_entry.text_sha1
352
            if store:
2776.4.18 by Robert Collins
Review feedback.
353
                # We want to record a new node regardless of the presence or
354
                # 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.
355
                nostore_sha = None
2776.4.18 by Robert Collins
Review feedback.
356
            ie.executable = content_summary[2]
357
            lines = tree.get_file(ie.file_id, path).readlines()
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
358
            try:
359
                ie.text_sha1, ie.text_size = self._add_text_to_weave(
360
                    ie.file_id, lines, heads, nostore_sha)
361
            except errors.ExistingContent:
2776.4.18 by Robert Collins
Review feedback.
362
                # Turns out that the file content was unchanged, and we were
363
                # only going to store a new node if it was changed. Carry over
364
                # the entry.
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
365
                ie.revision = parent_entry.revision
366
                ie.text_size = parent_entry.text_size
367
                ie.text_sha1 = parent_entry.text_sha1
368
                ie.executable = parent_entry.executable
2871.1.4 by Robert Collins
Merge bzr.dev.
369
                return self._get_delta(ie, basis_inv, path), False
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
370
        elif kind == 'directory':
371
            if not store:
372
                # all data is meta here, nothing specific to directory, so
373
                # carry over:
374
                ie.revision = parent_entry.revision
2871.1.4 by Robert Collins
Merge bzr.dev.
375
                return self._get_delta(ie, basis_inv, path), False
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
376
            lines = []
377
            self._add_text_to_weave(ie.file_id, lines, heads, None)
378
        elif kind == 'symlink':
379
            current_link_target = content_summary[3]
380
            if not store:
2776.4.18 by Robert Collins
Review feedback.
381
                # 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.
382
                # changed.
383
                if current_link_target != parent_entry.symlink_target:
384
                    store = True
385
            if not store:
386
                # unchanged, carry over.
387
                ie.revision = parent_entry.revision
388
                ie.symlink_target = parent_entry.symlink_target
2871.1.4 by Robert Collins
Merge bzr.dev.
389
                return self._get_delta(ie, basis_inv, path), False
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
390
            ie.symlink_target = current_link_target
391
            lines = []
392
            self._add_text_to_weave(ie.file_id, lines, heads, None)
393
        elif kind == 'tree-reference':
394
            if not store:
395
                if content_summary[3] != parent_entry.reference_revision:
396
                    store = True
397
            if not store:
398
                # unchanged, carry over.
399
                ie.reference_revision = parent_entry.reference_revision
400
                ie.revision = parent_entry.revision
2871.1.4 by Robert Collins
Merge bzr.dev.
401
                return self._get_delta(ie, basis_inv, path), False
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
402
            ie.reference_revision = content_summary[3]
403
            lines = []
404
            self._add_text_to_weave(ie.file_id, lines, heads, None)
405
        else:
406
            raise NotImplementedError('unknown kind')
407
        ie.revision = self._new_revision_id
2871.1.4 by Robert Collins
Merge bzr.dev.
408
        return self._get_delta(ie, basis_inv, path), True
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
409
410
    def _add_text_to_weave(self, file_id, new_lines, parents, nostore_sha):
2592.3.136 by Robert Collins
Merge bzr.dev.
411
        # Note: as we read the content directly from the tree, we know its not
412
        # been turned into unicode or badly split - but a broken tree
413
        # implementation could give us bad output from readlines() so this is
414
        # not a guarantee of safety. What would be better is always checking
415
        # the content during test suite execution. RBC 20070912
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
416
        parent_keys = tuple((file_id, parent) for parent in parents)
417
        return self.repository.texts.add_lines(
418
            (file_id, self._new_revision_id), parent_keys, new_lines,
3316.2.12 by Robert Collins
Catch some extra deprecated calls.
419
            nostore_sha=nostore_sha, random_id=self.random_revid,
420
            check_content=False)[0:2]
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
421
422
423
class RootCommitBuilder(CommitBuilder):
424
    """This commitbuilder actually records the root id"""
425
    
2825.5.2 by Robert Collins
Review feedback, and fix pointless commits with nested trees to raise PointlessCommit appropriately.
426
    # the root entry gets versioned properly by this builder.
2840.1.1 by Ian Clatworthy
faster pointless commit detection (Robert Collins)
427
    _versioned_root = True
2825.5.2 by Robert Collins
Review feedback, and fix pointless commits with nested trees to raise PointlessCommit appropriately.
428
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
429
    def _check_root(self, ie, parent_invs, tree):
430
        """Helper for record_entry_contents.
431
432
        :param ie: An entry being added.
433
        :param parent_invs: The inventories of the parent revisions of the
434
            commit.
435
        :param tree: The tree that is being committed.
436
        """
437
438
2220.2.3 by Martin Pool
Add tag: revision namespace.
439
######################################################################
440
# Repositories
441
1185.66.5 by Aaron Bentley
Renamed RevisionStorage to Repository
442
class Repository(object):
1185.70.3 by Martin Pool
Various updates to make storage branch mergeable:
443
    """Repository holding history for one or more branches.
444
445
    The repository holds and retrieves historical information including
446
    revisions and file history.  It's normally accessed only by the Branch,
447
    which views a particular line of development through that history.
448
3350.6.7 by Robert Collins
Review feedback, making things more clear, adding documentation on what is used where.
449
    The Repository builds on top of some byte storage facilies (the revisions,
450
    signatures, inventories and texts attributes) and a Transport, which
451
    respectively provide byte storage and a means to access the (possibly
1185.70.3 by Martin Pool
Various updates to make storage branch mergeable:
452
    remote) disk.
3407.2.13 by Martin Pool
Remove indirection through control_files to get transports
453
3350.6.7 by Robert Collins
Review feedback, making things more clear, adding documentation on what is used where.
454
    The byte storage facilities are addressed via tuples, which we refer to
455
    as 'keys' throughout the code base. Revision_keys, inventory_keys and
456
    signature_keys are all 1-tuples: (revision_id,). text_keys are two-tuples:
457
    (file_id, revision_id). We use this interface because it allows low
458
    friction with the underlying code that implements disk indices, network
459
    encoding and other parts of bzrlib.
460
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.
461
    :ivar revisions: A bzrlib.versionedfile.VersionedFiles instance containing
462
        the serialised revisions for the repository. This can be used to obtain
463
        revision graph information or to access raw serialised revisions.
464
        The result of trying to insert data into the repository via this store
465
        is undefined: it should be considered read-only except for implementors
466
        of repositories.
3350.6.7 by Robert Collins
Review feedback, making things more clear, adding documentation on what is used where.
467
    :ivar signatures: A bzrlib.versionedfile.VersionedFiles instance containing
468
        the serialised signatures for the repository. This can be used to
469
        obtain access to raw serialised signatures.  The result of trying to
470
        insert data into the repository via this store is undefined: it should
471
        be considered read-only except for implementors of repositories.
472
    :ivar inventories: A bzrlib.versionedfile.VersionedFiles instance containing
473
        the serialised inventories for the repository. This can be used to
474
        obtain unserialised inventories.  The result of trying to insert data
475
        into the repository via this store is undefined: it should be
476
        considered read-only except for implementors of repositories.
477
    :ivar texts: A bzrlib.versionedfile.VersionedFiles instance containing the
478
        texts of files and directories for the repository. This can be used to
479
        obtain file texts or file graphs. Note that Repository.iter_file_bytes
480
        is usually a better interface for accessing file texts.
481
        The result of trying to insert data into the repository via this store
482
        is undefined: it should be considered read-only except for implementors
483
        of repositories.
3407.2.13 by Martin Pool
Remove indirection through control_files to get transports
484
    :ivar _transport: Transport for file access to repository, typically
485
        pointing to .bzr/repository.
1185.70.3 by Martin Pool
Various updates to make storage branch mergeable:
486
    """
1185.65.17 by Robert Collins
Merge from integration, mode-changes are broken.
487
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
488
    # What class to use for a CommitBuilder. Often its simpler to change this
489
    # in a Repository class subclass rather than to override
490
    # get_commit_builder.
491
    _commit_builder_class = CommitBuilder
492
    # The search regex used by xml based repositories to determine what things
493
    # where changed in a single commit.
2163.2.1 by John Arbash Meinel
Speed up the fileids_altered_by_revision_ids processing
494
    _file_ids_altered_regex = lazy_regex.lazy_compile(
495
        r'file_id="(?P<file_id>[^"]+)"'
2776.4.6 by Robert Collins
Fixup various commit test failures falling out from the other commit changes.
496
        r'.* revision="(?P<revision_id>[^"]+)"'
2163.2.1 by John Arbash Meinel
Speed up the fileids_altered_by_revision_ids processing
497
        )
498
2617.6.2 by Robert Collins
Add abort_write_group and wire write_groups into fetch and commit.
499
    def abort_write_group(self):
500
        """Commit the contents accrued within the current write group.
501
502
        :seealso: start_write_group.
503
        """
504
        if self._write_group is not self.get_transaction():
505
            # has an unlock or relock occured ?
506
            raise errors.BzrError('mismatched lock context and write group.')
507
        self._abort_write_group()
508
        self._write_group = None
509
510
    def _abort_write_group(self):
511
        """Template method for per-repository write group cleanup.
512
        
513
        This is called during abort before the write group is considered to be 
514
        finished and should cleanup any internal state accrued during the write
515
        group. There is no requirement that data handed to the repository be
516
        *not* made available - this is not a rollback - but neither should any
517
        attempt be made to ensure that data added is fully commited. Abort is
518
        invoked when an error has occured so futher disk or network operations
519
        may not be possible or may error and if possible should not be
520
        attempted.
521
        """
522
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
523
    def add_inventory(self, revision_id, inv, parents):
524
        """Add the inventory inv to the repository as revision_id.
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
525
        
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
526
        :param parents: The revision ids of the parents that revision_id
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
527
                        is known to have and are in the repository already.
528
3169.2.1 by Robert Collins
New method ``iter_inventories`` on Repository for access to many
529
        :returns: The validator(which is a sha1 digest, though what is sha'd is
530
            repository format specific) of the serialized inventory.
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
531
        """
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
532
        if not self.is_in_write_group():
533
            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
534
        _mod_revision.check_not_reserved_id(revision_id)
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
535
        if not (inv.revision_id is None or inv.revision_id == revision_id):
536
            raise AssertionError(
537
                "Mismatch between inventory revision"
538
                " id and insertion revid (%r, %r)"
539
                % (inv.revision_id, revision_id))
540
        if inv.root is None:
541
            raise AssertionError()
2817.2.1 by Robert Collins
* Inventory serialisation no longer double-sha's the content.
542
        inv_lines = self._serialise_inventory_to_lines(inv)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
543
        return self._inventory_add_lines(revision_id, parents,
2817.2.1 by Robert Collins
* Inventory serialisation no longer double-sha's the content.
544
            inv_lines, check_content=False)
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
545
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.
546
    def _inventory_add_lines(self, revision_id, parents, lines,
2805.6.7 by Robert Collins
Review feedback.
547
        check_content=True):
2817.2.1 by Robert Collins
* Inventory serialisation no longer double-sha's the content.
548
        """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.
549
        parents = [(parent,) for parent in parents]
550
        return self.inventories.add_lines((revision_id,), parents, lines,
2817.2.1 by Robert Collins
* Inventory serialisation no longer double-sha's the content.
551
            check_content=check_content)[0]
1740.3.6 by Jelmer Vernooij
Move inventory writing to the commit builder.
552
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
553
    def add_revision(self, revision_id, rev, inv=None, config=None):
554
        """Add rev to the revision store as revision_id.
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
555
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
556
        :param revision_id: the revision id to use.
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
557
        :param rev: The revision object.
558
        :param inv: The inventory for the revision. if None, it will be looked
559
                    up in the inventory storer
560
        :param config: If None no digital signature will be created.
561
                       If supplied its signature_needed method will be used
562
                       to determine if a signature should be made.
563
        """
2249.5.13 by John Arbash Meinel
Finish auditing Repository, and fix generate_ids to always generate utf8 ids.
564
        # TODO: jam 20070210 Shouldn't we check rev.revision_id and
565
        #       rev.parent_ids?
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
566
        _mod_revision.check_not_reserved_id(revision_id)
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
567
        if config is not None and config.signature_needed():
568
            if inv is None:
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
569
                inv = self.get_inventory(revision_id)
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
570
            plaintext = Testament(rev, inv).as_short_text()
571
            self.store_revision_signature(
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
572
                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.
573
        # check inventory present
574
        if not self.inventories.get_parent_map([(revision_id,)]):
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
575
            if inv is None:
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
576
                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.
577
                                                     self.inventories)
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
578
            else:
579
                # yes, this is not suitable for adding with ghosts.
3380.1.6 by Aaron Bentley
Ensure fetching munges sha1s
580
                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
581
                                                        rev.parent_ids)
3380.1.6 by Aaron Bentley
Ensure fetching munges sha1s
582
        else:
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.
583
            rev.inventory_sha1 = self.inventories.get_sha1s([(revision_id,)])[0]
584
        self._add_revision(rev)
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
585
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.
586
    def _add_revision(self, revision):
587
        text = self._serializer.write_revision_to_string(revision)
588
        key = (revision.revision_id,)
589
        parents = tuple((parent,) for parent in revision.parent_ids)
590
        self.revisions.add_lines(key, parents, osutils.split_lines(text))
2520.4.10 by Aaron Bentley
Enable installation of revisions
591
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
592
    def all_revision_ids(self):
593
        """Returns a list of all the revision ids in the repository. 
594
595
        This is deprecated because code should generally work on the graph
596
        reachable from a particular revision, and ignore any other revisions
597
        that might be present.  There is no direct replacement method.
598
        """
2592.3.114 by Robert Collins
More evil mutterings.
599
        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.
600
            mutter_callsite(2, "all_revision_ids is linear with history.")
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
601
        return self._all_revision_ids()
602
603
    def _all_revision_ids(self):
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
604
        """Returns a list of all the revision ids in the repository. 
605
606
        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.
607
        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.
608
        """
2850.3.1 by Robert Collins
Move various weave specific code out of the base Repository class to weaverepo.py.
609
        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.
610
1687.1.7 by Robert Collins
Teach Repository about break_lock.
611
    def break_lock(self):
612
        """Break a lock if one is present from another instance.
613
614
        Uses the ui factory to ask for confirmation if the lock may be from
615
        an active process.
616
        """
617
        self.control_files.break_lock()
618
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.
619
    @needs_read_lock
620
    def _eliminate_revisions_not_present(self, revision_ids):
621
        """Check every revision id in revision_ids to see if we have it.
622
623
        Returns a set of the present revisions.
624
        """
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
625
        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
626
        graph = self.get_graph()
627
        parent_map = graph.get_parent_map(revision_ids)
628
        # The old API returned a list, should this actually be a set?
629
        return parent_map.keys()
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
630
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
631
    @staticmethod
632
    def create(a_bzrdir):
633
        """Construct the current default format repository in a_bzrdir."""
634
        return RepositoryFormat.get_default_format().initialize(a_bzrdir)
635
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.
636
    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
637
        """instantiate a Repository.
638
639
        :param _format: The format of the repository on disk.
640
        :param a_bzrdir: The BzrDir of 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.
641
        :param revisions: The revisions store for the repository.
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
642
643
        In the future we will have a single api for all stores for
644
        getting file texts, inventories and revisions, then
645
        this construct will accept instances of those things.
646
        """
1608.2.1 by Martin Pool
[merge] Storage filename escaping
647
        super(Repository, self).__init__()
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
648
        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
649
        # 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.
650
        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
651
        self.control_files = control_files
3407.2.13 by Martin Pool
Remove indirection through control_files to get transports
652
        self._transport = control_files._transport
3407.2.14 by Martin Pool
Remove more cases of getting transport via control_files
653
        self.base = self._transport.base
2671.4.2 by Robert Collins
Review feedback.
654
        # for tests
655
        self._reconcile_does_inventory_gc = True
2745.6.16 by Aaron Bentley
Update from review
656
        self._reconcile_fixes_text_parents = False
2951.1.3 by Robert Collins
Partial support for native reconcile with packs.
657
        self._reconcile_backsup_inventory = True
1563.2.23 by Robert Collins
Add add_revision and get_revision methods to RevisionStore
658
        # not right yet - should be more semantically clear ? 
659
        # 
1608.2.1 by Martin Pool
[merge] Storage filename escaping
660
        # TODO: make sure to construct the right store classes, etc, depending
661
        # on whether escaping is required.
1904.2.3 by Martin Pool
Give a warning on access to old repository formats
662
        self._warn_if_deprecated()
2617.6.1 by Robert Collins
* New method on Repository - ``start_write_group``, ``end_write_group``
663
        self._write_group = None
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
664
1668.1.3 by Martin Pool
[patch] use the correct transaction when committing snapshot (Malone: #43959)
665
    def __repr__(self):
2592.4.5 by Martin Pool
Add Repository.base on all repositories.
666
        return '%s(%r)' % (self.__class__.__name__,
667
                           self.base)
1668.1.3 by Martin Pool
[patch] use the correct transaction when committing snapshot (Malone: #43959)
668
2671.1.4 by Andrew Bennetts
Rename is_same_repository to has_same_location, thanks Aaron!
669
    def has_same_location(self, other):
2671.1.3 by Andrew Bennetts
Remove Repository.__eq__/__ne__ methods, replace with is_same_repository method.
670
        """Returns a boolean indicating if this repository is at the same
671
        location as another repository.
672
673
        This might return False even when two repository objects are accessing
674
        the same physical repository via different URLs.
675
        """
2592.3.162 by Robert Collins
Remove some arbitrary differences from bzr.dev.
676
        if self.__class__ is not other.__class__:
677
            return False
3407.2.3 by Martin Pool
Branch and Repository use their own ._transport rather than going through .control_files
678
        return (self._transport.base == other._transport.base)
2671.1.1 by Andrew Bennetts
Add support for comparing Repositories with == and != operators.
679
2617.6.1 by Robert Collins
* New method on Repository - ``start_write_group``, ``end_write_group``
680
    def is_in_write_group(self):
681
        """Return True if there is an open write group.
682
683
        :seealso: start_write_group.
684
        """
685
        return self._write_group is not None
686
1694.2.6 by Martin Pool
[merge] bzr.dev
687
    def is_locked(self):
688
        return self.control_files.is_locked()
689
2592.3.188 by Robert Collins
Allow pack repositories to have multiple writers active at one time, for greater concurrency.
690
    def is_write_locked(self):
691
        """Return True if this object is write locked."""
692
        return self.is_locked() and self.control_files._lock_mode == 'w'
693
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
694
    def lock_write(self, token=None):
695
        """Lock this repository for writing.
2617.6.8 by Robert Collins
Review feedback and documentation.
696
697
        This causes caching within the repository obejct to start accumlating
698
        data during reads, and allows a 'write_group' to be obtained. Write
699
        groups must be used for actual data insertion.
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
700
        
701
        :param token: if this is already locked, then lock_write will fail
702
            unless the token matches the existing lock.
703
        :returns: a token if this instance supports tokens, otherwise None.
704
        :raises TokenLockingNotSupported: when a token is given but this
705
            instance doesn't support using token locks.
706
        :raises MismatchedToken: if the specified token doesn't match the token
707
            of the existing lock.
2617.6.8 by Robert Collins
Review feedback and documentation.
708
        :seealso: start_write_group.
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
709
2018.5.145 by Andrew Bennetts
Add a brief explanation of what tokens are used for to lock_write docstrings.
710
        A token should be passed in if you know that you have locked the object
711
        some other way, and need to synchronise this object's state with that
712
        fact.
713
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
714
        XXX: this docstring is duplicated in many places, e.g. lockable_files.py
715
        """
2617.6.2 by Robert Collins
Add abort_write_group and wire write_groups into fetch and commit.
716
        result = self.control_files.lock_write(token=token)
717
        self._refresh_data()
718
        return result
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
719
720
    def lock_read(self):
1553.5.55 by Martin Pool
[revert] broken changes
721
        self.control_files.lock_read()
2617.6.2 by Robert Collins
Add abort_write_group and wire write_groups into fetch and commit.
722
        self._refresh_data()
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
723
1694.2.6 by Martin Pool
[merge] bzr.dev
724
    def get_physical_lock_status(self):
725
        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
726
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
727
    def leave_lock_in_place(self):
728
        """Tell this repository not to release the physical lock when this
729
        object is unlocked.
2018.5.76 by Andrew Bennetts
Testing that repository.{dont_,}leave_lock_in_place raises NotImplementedError if lock_write returns None.
730
        
731
        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.
732
        """
733
        self.control_files.leave_in_place()
734
735
    def dont_leave_lock_in_place(self):
736
        """Tell this repository to release the physical lock when this
737
        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.
738
739
        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.
740
        """
741
        self.control_files.dont_leave_in_place()
742
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.
743
    @needs_read_lock
2258.1.2 by Robert Collins
New version of gather_stats which gathers aggregate data too.
744
    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).
745
        """Gather statistics from a revision id.
746
2258.1.2 by Robert Collins
New version of gather_stats which gathers aggregate data too.
747
        :param revid: The revision id to gather statistics from, if None, then
748
            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).
749
        :param committers: Optional parameter controlling whether to grab
2258.1.2 by Robert Collins
New version of gather_stats which gathers aggregate data too.
750
            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).
751
        :return: A dictionary of statistics. Currently this contains:
752
            committers: The number of committers if requested.
753
            firstrev: A tuple with timestamp, timezone for the penultimate left
754
                most ancestor of revid, if revid is not the NULL_REVISION.
755
            latestrev: A tuple with timestamp, timezone for revid, if revid is
756
                not the NULL_REVISION.
2258.1.2 by Robert Collins
New version of gather_stats which gathers aggregate data too.
757
            revisions: The total revision count in the repository.
758
            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).
759
        """
760
        result = {}
2258.1.2 by Robert Collins
New version of gather_stats which gathers aggregate data too.
761
        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).
762
            result['committers'] = 0
2258.1.2 by Robert Collins
New version of gather_stats which gathers aggregate data too.
763
        if revid and revid != _mod_revision.NULL_REVISION:
764
            if committers:
765
                all_committers = set()
766
            revisions = self.get_ancestry(revid)
767
            # pop the leading None
768
            revisions.pop(0)
769
            first_revision = None
770
            if not committers:
771
                # ignore the revisions in the middle - just grab first and last
772
                revisions = revisions[0], revisions[-1]
773
            for revision in self.get_revisions(revisions):
774
                if not first_revision:
775
                    first_revision = revision
776
                if committers:
777
                    all_committers.add(revision.committer)
778
            last_revision = revision
779
            if committers:
780
                result['committers'] = len(all_committers)
781
            result['firstrev'] = (first_revision.timestamp,
782
                first_revision.timezone)
783
            result['latestrev'] = (last_revision.timestamp,
784
                last_revision.timezone)
785
786
        # 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.
787
        # XXX: This is available for many repos regardless of listability.
2258.1.2 by Robert Collins
New version of gather_stats which gathers aggregate data too.
788
        if self.bzrdir.root_transport.listable():
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
789
            # XXX: do we want to __define len__() ?
790
            result['revisions'] = len(self.revisions.keys())
791
            # result['size'] = t
2258.1.1 by Robert Collins
Move info branch statistics gathering into the repository to allow smart server optimisation (Robert Collins).
792
        return result
793
3140.1.2 by Aaron Bentley
Add ability to find branches inside repositories
794
    def find_branches(self, using=False):
795
        """Find branches underneath this repository.
796
3140.1.7 by Aaron Bentley
Update docs
797
        This will include branches inside other branches.
798
3140.1.2 by Aaron Bentley
Add ability to find branches inside repositories
799
        :param using: If True, list only branches using this repository.
800
        """
3140.1.9 by Aaron Bentley
Optimize find_branches for standalone repositories
801
        if using and not self.is_shared():
802
            try:
803
                return [self.bzrdir.open_branch()]
804
            except errors.NotBranchError:
805
                return []
3140.1.2 by Aaron Bentley
Add ability to find branches inside repositories
806
        class Evaluator(object):
807
808
            def __init__(self):
809
                self.first_call = True
810
811
            def __call__(self, bzrdir):
812
                # On the first call, the parameter is always the bzrdir
813
                # containing the current repo.
814
                if not self.first_call:
815
                    try:
816
                        repository = bzrdir.open_repository()
817
                    except errors.NoRepositoryPresent:
818
                        pass
819
                    else:
820
                        return False, (None, repository)
821
                self.first_call = False
822
                try:
823
                    value = (bzrdir.open_branch(), None)
824
                except errors.NotBranchError:
825
                    value = (None, None)
826
                return True, value
827
828
        branches = []
829
        for branch, repository in bzrdir.BzrDir.find_bzrdirs(
830
                self.bzrdir.root_transport, evaluate=Evaluator()):
831
            if branch is not None:
832
                branches.append(branch)
833
            if not using and repository is not None:
834
                branches.extend(repository.find_branches())
835
        return branches
836
2258.1.1 by Robert Collins
Move info branch statistics gathering into the repository to allow smart server optimisation (Robert Collins).
837
    @needs_read_lock
3184.1.8 by Robert Collins
* ``InterRepository.missing_revision_ids`` is now deprecated in favour of
838
    def search_missing_revision_ids(self, other, revision_id=None, find_ghosts=True):
839
        """Return the revision ids that other has that this does not.
840
        
841
        These are returned in topological order.
842
843
        revision_id: only return revision ids included by revision_id.
844
        """
845
        return InterRepository.get(other, self).search_missing_revision_ids(
846
            revision_id, find_ghosts)
847
848
    @deprecated_method(symbol_versioning.one_two)
849
    @needs_read_lock
3010.1.5 by Robert Collins
Test that missing_revision_ids handles the case of the source not having the requested revision correctly with and without find_ghosts.
850
    def missing_revision_ids(self, other, revision_id=None, find_ghosts=True):
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
851
        """Return the revision ids that other has that this does not.
852
        
853
        These are returned in topological order.
854
855
        revision_id: only return revision ids included by revision_id.
856
        """
3184.1.8 by Robert Collins
* ``InterRepository.missing_revision_ids`` is now deprecated in favour of
857
        keys =  self.search_missing_revision_ids(
858
            other, revision_id, find_ghosts).get_keys()
859
        other.lock_read()
860
        try:
861
            parents = other.get_graph().get_parent_map(keys)
862
        finally:
863
            other.unlock()
864
        return tsort.topo_sort(parents)
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
865
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
866
    @staticmethod
867
    def open(base):
868
        """Open the repository rooted at base.
869
870
        For instance, if the repository is at URL/.bzr/repository,
871
        Repository.open(URL) -> a Repository instance.
872
        """
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
873
        control = bzrdir.BzrDir.open(base)
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
874
        return control.open_repository()
875
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
876
    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.
877
        """Make a complete copy of the content in self into destination.
878
        
879
        This is a destructive operation! Do not use it on existing 
880
        repositories.
881
        """
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
882
        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.
883
2617.6.2 by Robert Collins
Add abort_write_group and wire write_groups into fetch and commit.
884
    def commit_write_group(self):
885
        """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``
886
887
        :seealso: start_write_group.
888
        """
889
        if self._write_group is not self.get_transaction():
890
            # has an unlock or relock occured ?
2592.3.38 by Robert Collins
All experimental format tests passing again.
891
            raise errors.BzrError('mismatched lock context %r and '
892
                'write group %r.' %
893
                (self.get_transaction(), self._write_group))
2617.6.2 by Robert Collins
Add abort_write_group and wire write_groups into fetch and commit.
894
        self._commit_write_group()
2617.6.1 by Robert Collins
* New method on Repository - ``start_write_group``, ``end_write_group``
895
        self._write_group = None
896
2617.6.2 by Robert Collins
Add abort_write_group and wire write_groups into fetch and commit.
897
    def _commit_write_group(self):
898
        """Template method for per-repository write group cleanup.
899
        
900
        This is called before the write group is considered to be 
901
        finished and should ensure that all data handed to the repository
902
        for writing during the write group is safely committed (to the 
903
        extent possible considering file system caching etc).
904
        """
905
2949.1.1 by Robert Collins
Change Repository.fetch to provide a find_ghosts parameter which triggers ghost filling.
906
    def fetch(self, source, revision_id=None, pb=None, find_ghosts=False):
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.
907
        """Fetch the content required to construct revision_id from source.
908
909
        If revision_id is None all content is copied.
2949.1.1 by Robert Collins
Change Repository.fetch to provide a find_ghosts parameter which triggers ghost filling.
910
        :param find_ghosts: Find and copy revisions in the source that are
911
            ghosts in the target (and not reachable directly by walking out to
912
            the first-present revision in target from 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.
913
        """
2592.3.115 by Robert Collins
Move same repository check up to Repository.fetch to allow all fetch implementations to benefit.
914
        # fast path same-url fetch operations
915
        if self.has_same_location(source):
916
            # check that last_revision is in 'from' and then return a
917
            # no-operation.
918
            if (revision_id is not None and
919
                not _mod_revision.is_null(revision_id)):
920
                self.get_revision(revision_id)
921
            return 0, []
2323.8.3 by Aaron Bentley
Reduce scope of try/except, update NEWS
922
        inter = InterRepository.get(source, self)
2323.8.2 by Aaron Bentley
Give a nicer error on fetch when repos are in incompatible formats
923
        try:
2949.1.2 by Robert Collins
* Fetch with pack repositories will no longer read the entire history graph.
924
            return inter.fetch(revision_id=revision_id, pb=pb, find_ghosts=find_ghosts)
2323.8.2 by Aaron Bentley
Give a nicer error on fetch when repos are in incompatible formats
925
        except NotImplementedError:
926
            raise errors.IncompatibleRepositories(source, self)
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
927
2520.4.54 by Aaron Bentley
Hang a create_bundle method off repository
928
    def create_bundle(self, target, base, fileobj, format=None):
929
        return serializer.write_bundle(self, target, base, fileobj, format)
930
2803.2.1 by Robert Collins
* CommitBuilder now advertises itself as requiring the root entry to be
931
    def get_commit_builder(self, branch, parents, config, timestamp=None,
932
                           timezone=None, committer=None, revprops=None,
1740.3.7 by Jelmer Vernooij
Move committer, log, revprops, timestamp and timezone to CommitBuilder.
933
                           revision_id=None):
934
        """Obtain a CommitBuilder for this repository.
935
        
936
        :param branch: Branch to commit to.
937
        :param parents: Revision ids of the parents of the new revision.
938
        :param config: Configuration to use.
939
        :param timestamp: Optional timestamp recorded for commit.
940
        :param timezone: Optional timezone for timestamp.
941
        :param committer: Optional committer to set for commit.
942
        :param revprops: Optional dictionary of revision properties.
943
        :param revision_id: Optional revision id.
944
        """
2818.3.2 by Robert Collins
Review feedback.
945
        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.
946
            timestamp, timezone, committer, revprops, revision_id)
2617.6.2 by Robert Collins
Add abort_write_group and wire write_groups into fetch and commit.
947
        self.start_write_group()
948
        return result
1740.3.1 by Jelmer Vernooij
Introduce and use CommitBuilder objects.
949
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
950
    def unlock(self):
2617.6.1 by Robert Collins
* New method on Repository - ``start_write_group``, ``end_write_group``
951
        if (self.control_files._lock_count == 1 and
952
            self.control_files._lock_mode == 'w'):
953
            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.
954
                self.abort_write_group()
955
                self.control_files.unlock()
2617.6.1 by Robert Collins
* New method on Repository - ``start_write_group``, ``end_write_group``
956
                raise errors.BzrError(
957
                    'Must end write groups before releasing write locks.')
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
958
        self.control_files.unlock()
959
1185.65.27 by Robert Collins
Tweak storage towards mergability.
960
    @needs_read_lock
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
961
    def clone(self, a_bzrdir, revision_id=None):
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
962
        """Clone this repository into a_bzrdir using the current format.
963
964
        Currently no check is made that the format of this repository and
965
        the bzrdir format are compatible. FIXME RBC 20060201.
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
966
967
        :return: The newly created destination repository.
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
968
        """
2440.1.1 by Martin Pool
Add new Repository.sprout,
969
        # TODO: deprecate after 0.16; cloning this with all its settings is
970
        # probably not very useful -- mbp 20070423
971
        dest_repo = self._create_sprouting_repo(a_bzrdir, shared=self.is_shared())
972
        self.copy_content_into(dest_repo, revision_id)
973
        return dest_repo
974
2617.6.1 by Robert Collins
* New method on Repository - ``start_write_group``, ``end_write_group``
975
    def start_write_group(self):
976
        """Start a write group in the repository.
977
978
        Write groups are used by repositories which do not have a 1:1 mapping
979
        between file ids and backend store to manage the insertion of data from
980
        both fetch and commit operations.
981
2617.6.2 by Robert Collins
Add abort_write_group and wire write_groups into fetch and commit.
982
        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``
983
        for the support of lock-requiring repository formats.
2617.6.8 by Robert Collins
Review feedback and documentation.
984
985
        One can only insert data into a repository inside a write group.
986
2617.6.6 by Robert Collins
Some review feedback.
987
        :return: None.
2617.6.1 by Robert Collins
* New method on Repository - ``start_write_group``, ``end_write_group``
988
        """
2592.3.188 by Robert Collins
Allow pack repositories to have multiple writers active at one time, for greater concurrency.
989
        if not self.is_write_locked():
2617.6.1 by Robert Collins
* New method on Repository - ``start_write_group``, ``end_write_group``
990
            raise errors.NotWriteLocked(self)
991
        if self._write_group:
992
            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.
993
        self._start_write_group()
994
        # 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``
995
        self._write_group = self.get_transaction()
996
2617.6.2 by Robert Collins
Add abort_write_group and wire write_groups into fetch and commit.
997
    def _start_write_group(self):
998
        """Template method for per-repository write group startup.
999
        
1000
        This is called before the write group is considered to be 
1001
        entered.
1002
        """
1003
2440.1.1 by Martin Pool
Add new Repository.sprout,
1004
    @needs_read_lock
1005
    def sprout(self, to_bzrdir, revision_id=None):
1006
        """Create a descendent repository for new development.
1007
1008
        Unlike clone, this does not copy the settings of the repository.
1009
        """
1010
        dest_repo = self._create_sprouting_repo(to_bzrdir, shared=False)
1011
        dest_repo.fetch(self, revision_id=revision_id)
1012
        return dest_repo
1013
1014
    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.
1015
        if not isinstance(a_bzrdir._format, self.bzrdir._format.__class__):
1016
            # use target default format.
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
1017
            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.
1018
        else:
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
1019
            # Most control formats need the repository to be specifically
1020
            # created, but on some old all-in-one formats it's not needed
1021
            try:
2440.1.1 by Martin Pool
Add new Repository.sprout,
1022
                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.
1023
            except errors.UninitializableFormat:
1024
                dest_repo = a_bzrdir.open_repository()
1025
        return dest_repo
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1026
1563.2.22 by Robert Collins
Move responsibility for repository.has_revision into RevisionStore
1027
    @needs_read_lock
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
1028
    def has_revision(self, revision_id):
1563.2.22 by Robert Collins
Move responsibility for repository.has_revision into RevisionStore
1029
        """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
1030
        return revision_id in self.has_revisions((revision_id,))
1031
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.
1032
    @needs_read_lock
3172.3.1 by Robert Collins
Repository has a new method ``has_revisions`` which signals the presence
1033
    def has_revisions(self, revision_ids):
1034
        """Probe to find out the presence of multiple revisions.
1035
1036
        :param revision_ids: An iterable of revision_ids.
1037
        :return: A set of the revision_ids that were present.
1038
        """
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1039
        parent_map = self.revisions.get_parent_map(
1040
            [(rev_id,) for rev_id in revision_ids])
1041
        result = set()
1042
        if _mod_revision.NULL_REVISION in revision_ids:
1043
            result.add(_mod_revision.NULL_REVISION)
1044
        result.update([key[0] for key in parent_map])
1045
        return result
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
1046
1185.65.27 by Robert Collins
Tweak storage towards mergability.
1047
    @needs_read_lock
2850.3.1 by Robert Collins
Move various weave specific code out of the base Repository class to weaverepo.py.
1048
    def get_revision(self, revision_id):
1049
        """Return the Revision object for a named revision."""
1050
        return self.get_revisions([revision_id])[0]
1051
1052
    @needs_read_lock
1570.1.13 by Robert Collins
Check for incorrect revision parentage in the weave during revision access.
1053
    def get_revision_reconcile(self, revision_id):
1054
        """'reconcile' helper routine that allows access to a revision always.
1055
        
1056
        This variant of get_revision does not cross check the weave graph
1057
        against the revision one as get_revision does: but it should only
1058
        be used by reconcile, or reconcile-alike commands that are correcting
1059
        or testing the revision graph.
1060
        """
2850.3.1 by Robert Collins
Move various weave specific code out of the base Repository class to weaverepo.py.
1061
        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.
1062
1756.1.2 by Aaron Bentley
Show logs using get_revisions
1063
    @needs_read_lock
1064
    def get_revisions(self, revision_ids):
2850.3.1 by Robert Collins
Move various weave specific code out of the base Repository class to weaverepo.py.
1065
        """Get many revisions at once."""
1066
        return self._get_revisions(revision_ids)
1067
1068
    @needs_read_lock
1069
    def _get_revisions(self, revision_ids):
1070
        """Core work logic to get many revisions without sanity checks."""
1071
        for rev_id in revision_ids:
1072
            if not rev_id or not isinstance(rev_id, basestring):
1073
                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.
1074
        keys = [(key,) for key in revision_ids]
1075
        stream = self.revisions.get_record_stream(keys, 'unordered', True)
1076
        revs = {}
1077
        for record in stream:
1078
            if record.storage_kind == 'absent':
1079
                raise errors.NoSuchRevision(self, record.key[0])
1080
            text = record.get_bytes_as('fulltext')
1081
            rev = self._serializer.read_revision_from_string(text)
1082
            revs[record.key[0]] = rev
1083
        return [revs[revid] for revid in revision_ids]
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
1084
1185.65.27 by Robert Collins
Tweak storage towards mergability.
1085
    @needs_read_lock
1563.2.29 by Robert Collins
Remove all but fetch references to repository.revision_store.
1086
    def get_revision_xml(self, revision_id):
2249.5.13 by John Arbash Meinel
Finish auditing Repository, and fix generate_ids to always generate utf8 ids.
1087
        # TODO: jam 20070210 This shouldn't be necessary since get_revision
1088
        #       would have already do it.
1089
        # TODO: jam 20070210 Just use _serializer.write_revision_to_string()
1090
        rev = self.get_revision(revision_id)
1563.2.29 by Robert Collins
Remove all but fetch references to repository.revision_store.
1091
        rev_tmp = StringIO()
1092
        # the current serializer..
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1093
        self._serializer.write_revision(rev, rev_tmp)
1563.2.29 by Robert Collins
Remove all but fetch references to repository.revision_store.
1094
        rev_tmp.seek(0)
1095
        return rev_tmp.getvalue()
1096
1756.3.22 by Aaron Bentley
Tweaks from review
1097
    def get_deltas_for_revisions(self, revisions):
1756.3.19 by Aaron Bentley
Documentation and cleanups
1098
        """Produce a generator of revision deltas.
1099
        
1100
        Note that the input is a sequence of REVISIONS, not revision_ids.
1101
        Trees will be held in memory until the generator exits.
1102
        Each delta is relative to the revision's lefthand predecessor.
1103
        """
1756.3.3 by Aaron Bentley
More refactoring, introduce revision_trees.
1104
        required_trees = set()
1105
        for revision in revisions:
1106
            required_trees.add(revision.revision_id)
1107
            required_trees.update(revision.parent_ids[:1])
1108
        trees = dict((t.get_revision_id(), t) for 
1109
                     t in self.revision_trees(required_trees))
1110
        for revision in revisions:
1111
            if not revision.parent_ids:
1852.5.1 by Robert Collins
Deprecate EmptyTree in favour of using Repository.revision_tree.
1112
                old_tree = self.revision_tree(None)
1756.3.3 by Aaron Bentley
More refactoring, introduce revision_trees.
1113
            else:
1114
                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.
1115
            yield trees[revision.revision_id].changes_from(old_tree)
1756.3.3 by Aaron Bentley
More refactoring, introduce revision_trees.
1116
1756.3.19 by Aaron Bentley
Documentation and cleanups
1117
    @needs_read_lock
1744.2.2 by Johan Rydberg
Add get_revision_delta to Repository; and make Branch.get_revision_delta use it.
1118
    def get_revision_delta(self, revision_id):
1119
        """Return the delta for one revision.
1120
1121
        The delta is relative to the left-hand predecessor of the
1122
        revision.
1123
        """
1756.3.3 by Aaron Bentley
More refactoring, introduce revision_trees.
1124
        r = self.get_revision(revision_id)
1756.3.22 by Aaron Bentley
Tweaks from review
1125
        return list(self.get_deltas_for_revisions([r]))[0]
1744.2.2 by Johan Rydberg
Add get_revision_delta to Repository; and make Branch.get_revision_delta use it.
1126
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
1127
    @needs_write_lock
1128
    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.
1129
        signature = gpg_strategy.sign(plaintext)
2996.2.4 by Aaron Bentley
Rename function to add_signature_text
1130
        self.add_signature_text(revision_id, signature)
2996.2.3 by Aaron Bentley
Add tests for install_revisions and add_signature
1131
1132
    @needs_write_lock
2996.2.4 by Aaron Bentley
Rename function to add_signature_text
1133
    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.
1134
        self.signatures.add_lines((revision_id,), (),
1135
            osutils.split_lines(signature))
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
1136
2988.1.2 by Robert Collins
New Repository API find_text_key_references for use by reconcile and check.
1137
    def find_text_key_references(self):
1138
        """Find the text key references within the repository.
1139
1140
        :return: a dictionary mapping (file_id, revision_id) tuples to altered file-ids to an iterable of
1141
        revision_ids. Each altered file-ids has the exact revision_ids that
1142
        altered it listed explicitly.
1143
        :return: A dictionary mapping text keys ((fileid, revision_id) tuples)
1144
            to whether they were referred to by the inventory of the
1145
            revision_id that they contain. The inventory texts from all present
1146
            revision ids are assessed to generate this report.
1147
        """
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.
1148
        revision_keys = self.revisions.keys()
1149
        w = self.inventories
2988.1.2 by Robert Collins
New Repository API find_text_key_references for use by reconcile and check.
1150
        pb = ui.ui_factory.nested_progress_bar()
1151
        try:
1152
            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.
1153
                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.
1154
        finally:
1155
            pb.finished()
1156
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.
1157
    def _find_text_key_references_from_xml_inventory_lines(self,
1158
        line_iterator):
1159
        """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.
1160
1161
        This performs the translation of xml lines to revision ids.
1162
2975.3.1 by Robert Collins
Change (without backwards compatibility) the
1163
        :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.
1164
        :return: A dictionary mapping text keys ((fileid, revision_id) tuples)
1165
            to whether they were referred to by the inventory of the
1166
            revision_id that they contain. Note that if that revision_id was
1167
            not part of the line_iterator's output then False will be given -
1168
            even though it may actually refer to that key.
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1169
        """
2988.2.2 by Robert Collins
Review feedback.
1170
        if not self._serializer.support_altered_by_hack:
1171
            raise AssertionError(
1172
                "_find_text_key_references_from_xml_inventory_lines only "
1173
                "supported for branches which store inventory as unnested xml"
1174
                ", not on %r" % self)
1694.2.6 by Martin Pool
[merge] bzr.dev
1175
        result = {}
1563.2.35 by Robert Collins
cleanup deprecation warnings and finish conversion so the inventory is knit based too.
1176
1694.2.6 by Martin Pool
[merge] bzr.dev
1177
        # this code needs to read every new line in every inventory for the
1178
        # inventories [revision_ids]. Seeing a line twice is ok. Seeing a line
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
1179
        # 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.
1180
        # harmful because we are filtering by the revision id marker in the
1694.2.6 by Martin Pool
[merge] bzr.dev
1181
        # 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.
1182
        # 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.
1183
        # only those added in an inventory in rev X can contain a revision=X
1184
        # line.
2163.2.3 by John Arbash Meinel
Change to local variables to save another 300ms
1185
        unescape_revid_cache = {}
1186
        unescape_fileid_cache = {}
1187
2163.2.5 by John Arbash Meinel
Inline the cache lookup, and explain why
1188
        # jam 20061218 In a big fetch, this handles hundreds of thousands
1189
        # of lines, so it has had a lot of inlining and optimizing done.
1190
        # Sorry that it is a little bit messy.
2163.2.3 by John Arbash Meinel
Change to local variables to save another 300ms
1191
        # Move several functions to be local variables, since this is a long
1192
        # running loop.
1193
        search = self._file_ids_altered_regex.search
2163.2.5 by John Arbash Meinel
Inline the cache lookup, and explain why
1194
        unescape = _unescape_xml
2163.2.3 by John Arbash Meinel
Change to local variables to save another 300ms
1195
        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.
1196
        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.
1197
            match = search(line)
1198
            if match is None:
1199
                continue
1200
            # One call to match.group() returning multiple items is quite a
1201
            # bit faster than 2 calls to match.group() each returning 1
1202
            file_id, revision_id = match.group('file_id', 'revision_id')
1203
1204
            # Inlining the cache lookups helps a lot when you make 170,000
1205
            # lines and 350k ids, versus 8.4 unique ids.
1206
            # Using a cache helps in 2 ways:
1207
            #   1) Avoids unnecessary decoding calls
1208
            #   2) Re-uses cached strings, which helps in future set and
1209
            #      equality checks.
1210
            # (2) is enough that removing encoding entirely along with
1211
            # the cache (so we are using plain strings) results in no
1212
            # performance improvement.
1213
            try:
1214
                revision_id = unescape_revid_cache[revision_id]
1215
            except KeyError:
1216
                unescaped = unescape(revision_id)
1217
                unescape_revid_cache[revision_id] = unescaped
1218
                revision_id = unescaped
1219
2988.2.2 by Robert Collins
Review feedback.
1220
            # Note that unconditionally unescaping means that we deserialise
1221
            # every fileid, which for general 'pull' is not great, but we don't
1222
            # really want to have some many fulltexts that this matters anyway.
1223
            # 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.
1224
            try:
1225
                file_id = unescape_fileid_cache[file_id]
1226
            except KeyError:
1227
                unescaped = unescape(file_id)
1228
                unescape_fileid_cache[file_id] = unescaped
1229
                file_id = unescaped
1230
1231
            key = (file_id, revision_id)
1232
            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.
1233
            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.
1234
                result[key] = True
1235
        return result
1236
1237
    def _find_file_ids_from_xml_inventory_lines(self, line_iterator,
1238
        revision_ids):
1239
        """Helper routine for fileids_altered_by_revision_ids.
1240
1241
        This performs the translation of xml lines to revision ids.
1242
1243
        :param line_iterator: An iterator of lines, origin_version_id
1244
        :param revision_ids: The revision ids to filter for. This should be a
1245
            set or other type which supports efficient __contains__ lookups, as
1246
            the revision id from each parsed line will be looked up in the
1247
            revision_ids filter.
1248
        :return: a dictionary mapping altered file-ids to an iterable of
1249
        revision_ids. Each altered file-ids has the exact revision_ids that
1250
        altered it listed explicitly.
1251
        """
1252
        result = {}
1253
        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.
1254
        for key in \
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.
1255
            self._find_text_key_references_from_xml_inventory_lines(
1256
                line_iterator).iterkeys():
2975.3.1 by Robert Collins
Change (without backwards compatibility) the
1257
            # once data is all ensured-consistent; then this is
1258
            # if revision_id == version_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.
1259
            if key[-1:] in revision_ids:
1260
                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.
1261
        return result
1262
3422.1.1 by John Arbash Meinel
merge in bzr-1.5rc1, revert the transaction cache change
1263
    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.
1264
        """Find the file ids and versions affected by revisions.
1265
1266
        :param revisions: an iterable containing revision ids.
3422.1.1 by John Arbash Meinel
merge in bzr-1.5rc1, revert the transaction cache change
1267
        :param _inv_weave: The inventory weave from this repository or None.
1268
            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.
1269
        :return: a dictionary mapping altered file-ids to an iterable of
1270
        revision_ids. Each altered file-ids has the exact revision_ids that
1271
        altered it listed explicitly.
1272
        """
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.
1273
        selected_keys = set((revid,) for revid in revision_ids)
1274
        w = _inv_weave or self.inventories
2039.1.1 by Aaron Bentley
Clean up progress properly when interrupted during fetch (#54000)
1275
        pb = ui.ui_factory.nested_progress_bar()
1276
        try:
2592.3.110 by Robert Collins
Filter out texts and signatures not referenced by the revisions being copied during pack to pack fetching.
1277
            return self._find_file_ids_from_xml_inventory_lines(
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1278
                w.iter_lines_added_or_present_in_keys(
1279
                    selected_keys, pb=pb),
1280
                selected_keys)
2039.1.1 by Aaron Bentley
Clean up progress properly when interrupted during fetch (#54000)
1281
        finally:
1282
            pb.finished()
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1283
2708.1.7 by Aaron Bentley
Rename extract_files_bytes to iter_files_bytes
1284
    def iter_files_bytes(self, desired_files):
2708.1.9 by Aaron Bentley
Clean-up docs and imports
1285
        """Iterate through file versions.
1286
2708.1.10 by Aaron Bentley
Update docstrings
1287
        Files will not necessarily be returned in the order they occur in
1288
        desired_files.  No specific order is guaranteed.
1289
2708.1.9 by Aaron Bentley
Clean-up docs and imports
1290
        Yields pairs of identifier, bytes_iterator.  identifier is an opaque
2708.1.10 by Aaron Bentley
Update docstrings
1291
        value supplied by the caller as part of desired_files.  It should
1292
        uniquely identify the file version in the caller's context.  (Examples:
1293
        an index number or a TreeTransform trans_id.)
1294
1295
        bytes_iterator is an iterable of bytestrings for the file.  The
1296
        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.
1297
        this implementation, it is a list of bytes produced by
1298
        VersionedFile.get_record_stream().
2708.1.10 by Aaron Bentley
Update docstrings
1299
2708.1.9 by Aaron Bentley
Clean-up docs and imports
1300
        :param desired_files: a list of (file_id, revision_id, identifier)
2708.1.10 by Aaron Bentley
Update docstrings
1301
            triples
2708.1.9 by Aaron Bentley
Clean-up docs and imports
1302
        """
2708.1.3 by Aaron Bentley
Implement extract_files_bytes on Repository
1303
        transaction = self.get_transaction()
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.
1304
        text_keys = {}
2708.1.3 by Aaron Bentley
Implement extract_files_bytes on Repository
1305
        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.
1306
            text_keys[(file_id, revision_id)] = callable_data
1307
        for record in self.texts.get_record_stream(text_keys, 'unordered', True):
1308
            if record.storage_kind == 'absent':
1309
                raise errors.RevisionNotPresent(record.key, self)
1310
            yield text_keys[record.key], record.get_bytes_as('fulltext')
2708.1.3 by Aaron Bentley
Implement extract_files_bytes on Repository
1311
3063.2.1 by Robert Collins
Solve reconciling erroring when multiple portions of a single delta chain are being reinserted.
1312
    def _generate_text_key_index(self, text_key_references=None,
1313
        ancestors=None):
2988.1.3 by Robert Collins
Add a new repositoy method _generate_text_key_index for use by reconcile/check.
1314
        """Generate a new text key index for the repository.
1315
1316
        This is an expensive function that will take considerable time to run.
1317
1318
        :return: A dict mapping text keys ((file_id, revision_id) tuples) to a
1319
            list of parents, also text keys. When a given key has no parents,
1320
            the parents list will be [NULL_REVISION].
1321
        """
1322
        # 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.
1323
        if ancestors is None:
3287.6.1 by Robert Collins
* ``VersionedFile.get_graph`` is deprecated, with no replacement method.
1324
            graph = self.get_graph()
1325
            ancestors = graph.get_parent_map(self.all_revision_ids())
2951.2.9 by Robert Collins
* ``pack-0.92`` repositories can now be reconciled.
1326
        if text_key_references is None:
1327
            text_key_references = self.find_text_key_references()
2988.3.1 by Robert Collins
Handle the progress bar in _generate_text_key_index correctly.
1328
        pb = ui.ui_factory.nested_progress_bar()
1329
        try:
1330
            return self._do_generate_text_key_index(ancestors,
1331
                text_key_references, pb)
1332
        finally:
1333
            pb.finished()
1334
1335
    def _do_generate_text_key_index(self, ancestors, text_key_references, pb):
1336
        """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.
1337
        revision_order = tsort.topo_sort(ancestors)
1338
        invalid_keys = set()
1339
        revision_keys = {}
1340
        for revision_id in revision_order:
1341
            revision_keys[revision_id] = set()
1342
        text_count = len(text_key_references)
1343
        # a cache of the text keys to allow reuse; costs a dict of all the
1344
        # keys, but saves a 2-tuple for every child of a given key.
1345
        text_key_cache = {}
1346
        for text_key, valid in text_key_references.iteritems():
1347
            if not valid:
1348
                invalid_keys.add(text_key)
1349
            else:
1350
                revision_keys[text_key[1]].add(text_key)
1351
            text_key_cache[text_key] = text_key
1352
        del text_key_references
1353
        text_index = {}
1354
        text_graph = graph.Graph(graph.DictParentsProvider(text_index))
1355
        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.
1356
        # Set a cache with a size of 10 - this suffices for bzr.dev but may be
1357
        # too small for large or very branchy trees. However, for 55K path
1358
        # trees, it would be easy to use too much memory trivially. Ideally we
1359
        # could gauge this by looking at available real memory etc, but this is
1360
        # always a tricky proposition.
1361
        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.
1362
        batch_size = 10 # should be ~150MB on a 55K path tree
1363
        batch_count = len(revision_order) / batch_size + 1
1364
        processed_texts = 0
1365
        pb.update("Calculating text parents.", processed_texts, text_count)
1366
        for offset in xrange(batch_count):
1367
            to_query = revision_order[offset * batch_size:(offset + 1) *
1368
                batch_size]
1369
            if not to_query:
1370
                break
1371
            for rev_tree in self.revision_trees(to_query):
1372
                revision_id = rev_tree.get_revision_id()
1373
                parent_ids = ancestors[revision_id]
1374
                for text_key in revision_keys[revision_id]:
1375
                    pb.update("Calculating text parents.", processed_texts)
1376
                    processed_texts += 1
1377
                    candidate_parents = []
1378
                    for parent_id in parent_ids:
1379
                        parent_text_key = (text_key[0], parent_id)
1380
                        try:
1381
                            check_parent = parent_text_key not in \
1382
                                revision_keys[parent_id]
1383
                        except KeyError:
1384
                            # the parent parent_id is a ghost:
1385
                            check_parent = False
1386
                            # truncate the derived graph against this ghost.
1387
                            parent_text_key = None
1388
                        if check_parent:
1389
                            # look at the parent commit details inventories to
1390
                            # determine possible candidates in the per file graph.
1391
                            # TODO: cache here.
2988.1.5 by Robert Collins
Use a LRU cache when generating the text index to reduce inventory deserialisations.
1392
                            try:
1393
                                inv = inventory_cache[parent_id]
1394
                            except KeyError:
1395
                                inv = self.revision_tree(parent_id).inventory
1396
                                inventory_cache[parent_id] = inv
1397
                            parent_entry = inv._byid.get(text_key[0], None)
2988.1.3 by Robert Collins
Add a new repositoy method _generate_text_key_index for use by reconcile/check.
1398
                            if parent_entry is not None:
1399
                                parent_text_key = (
1400
                                    text_key[0], parent_entry.revision)
1401
                            else:
1402
                                parent_text_key = None
1403
                        if parent_text_key is not None:
1404
                            candidate_parents.append(
1405
                                text_key_cache[parent_text_key])
1406
                    parent_heads = text_graph.heads(candidate_parents)
1407
                    new_parents = list(parent_heads)
1408
                    new_parents.sort(key=lambda x:candidate_parents.index(x))
1409
                    if new_parents == []:
1410
                        new_parents = [NULL_REVISION]
1411
                    text_index[text_key] = new_parents
1412
1413
        for text_key in invalid_keys:
1414
            text_index[text_key] = [NULL_REVISION]
1415
        return text_index
1416
2668.2.8 by Andrew Bennetts
Rename get_data_to_fetch_for_revision_ids as item_keys_introduced_by.
1417
    def item_keys_introduced_by(self, revision_ids, _files_pb=None):
1418
        """Get an iterable listing the keys of all the data introduced by a set
1419
        of revision IDs.
1420
1421
        The keys will be ordered so that the corresponding items can be safely
1422
        fetched and inserted in that order.
1423
1424
        :returns: An iterable producing tuples of (knit-kind, file-id,
1425
            versions).  knit-kind is one of 'file', 'inventory', 'signatures',
1426
            '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.
1427
        """
1428
        # 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.
1429
        # generator.  Ideally the caching would be done in fetch.py I think.  Or
1430
        # maybe this generator should explicitly have the contract that it
1431
        # should not be iterated until the previously yielded item has been
1432
        # 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.
1433
        inv_w = self.inventories
2535.3.6 by Andrew Bennetts
Move some "what repo data to fetch logic" from RepoFetcher to Repository.
1434
1435
        # file ids that changed
3422.1.1 by John Arbash Meinel
merge in bzr-1.5rc1, revert the transaction cache change
1436
        file_ids = self.fileids_altered_by_revision_ids(revision_ids, inv_w)
2535.3.8 by Andrew Bennetts
Unbreak progress reporting.
1437
        count = 0
1438
        num_file_ids = len(file_ids)
2535.3.6 by Andrew Bennetts
Move some "what repo data to fetch logic" from RepoFetcher to Repository.
1439
        for file_id, altered_versions in file_ids.iteritems():
2668.2.8 by Andrew Bennetts
Rename get_data_to_fetch_for_revision_ids as item_keys_introduced_by.
1440
            if _files_pb is not None:
1441
                _files_pb.update("fetch texts", count, num_file_ids)
2535.3.8 by Andrew Bennetts
Unbreak progress reporting.
1442
            count += 1
2535.3.6 by Andrew Bennetts
Move some "what repo data to fetch logic" from RepoFetcher to Repository.
1443
            yield ("file", file_id, altered_versions)
2535.3.9 by Andrew Bennetts
More comments.
1444
        # We're done with the files_pb.  Note that it finished by the caller,
1445
        # just as it was created by the caller.
2668.2.8 by Andrew Bennetts
Rename get_data_to_fetch_for_revision_ids as item_keys_introduced_by.
1446
        del _files_pb
2535.3.6 by Andrew Bennetts
Move some "what repo data to fetch logic" from RepoFetcher to Repository.
1447
1448
        # inventory
1449
        yield ("inventory", None, revision_ids)
1450
1451
        # signatures
2535.3.25 by Andrew Bennetts
Fetch signatures too.
1452
        revisions_with_signatures = set()
1453
        for rev_id in revision_ids:
1454
            try:
1455
                self.get_signature_text(rev_id)
1456
            except errors.NoSuchRevision:
1457
                # not signed.
1458
                pass
1459
            else:
1460
                revisions_with_signatures.add(rev_id)
1461
        yield ("signatures", None, revisions_with_signatures)
2535.3.6 by Andrew Bennetts
Move some "what repo data to fetch logic" from RepoFetcher to Repository.
1462
1463
        # revisions
1464
        yield ("revisions", None, revision_ids)
1465
1185.65.27 by Robert Collins
Tweak storage towards mergability.
1466
    @needs_read_lock
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
1467
    def get_inventory(self, revision_id):
3169.2.1 by Robert Collins
New method ``iter_inventories`` on Repository for access to many
1468
        """Get Inventory object by revision id."""
1469
        return self.iter_inventories([revision_id]).next()
1470
1471
    def iter_inventories(self, revision_ids):
1472
        """Get many inventories by revision_ids.
1473
1474
        This will buffer some or all of the texts used in constructing the
1475
        inventories in memory, but will only parse a single inventory at a
1476
        time.
1477
1478
        :return: An iterator of inventories.
1479
        """
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
1480
        if ((None in revision_ids)
1481
            or (_mod_revision.NULL_REVISION in revision_ids)):
1482
            raise ValueError('cannot get null revision inventory')
3169.2.1 by Robert Collins
New method ``iter_inventories`` on Repository for access to many
1483
        return self._iter_inventories(revision_ids)
1484
1485
    def _iter_inventories(self, revision_ids):
1486
        """single-document based inventory iteration."""
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1487
        for text, revision_id in self._iter_inventory_xmls(revision_ids):
3169.2.1 by Robert Collins
New method ``iter_inventories`` on Repository for access to many
1488
            yield self.deserialise_inventory(revision_id, text)
1740.2.3 by Aaron Bentley
Only reserialize the working tree basis inventory when needed.
1489
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.
1490
    def _iter_inventory_xmls(self, revision_ids):
1491
        keys = [(revision_id,) for revision_id in revision_ids]
1492
        stream = self.inventories.get_record_stream(keys, 'unordered', True)
1493
        texts = {}
1494
        for record in stream:
1495
            if record.storage_kind != 'absent':
1496
                texts[record.key] = record.get_bytes_as('fulltext')
1497
            else:
1498
                raise errors.NoSuchRevision(self, record.key)
1499
        for key in keys:
1500
            yield texts[key], key[-1]
1501
1740.2.3 by Aaron Bentley
Only reserialize the working tree basis inventory when needed.
1502
    def deserialise_inventory(self, revision_id, xml):
1503
        """Transform the xml into an inventory object. 
1504
1505
        :param revision_id: The expected revision id of the inventory.
1506
        :param xml: A serialised inventory.
1507
        """
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.
1508
        result = self._serializer.read_inventory_from_string(xml, revision_id)
3169.2.3 by Robert Collins
Use an if, not an assert, as we test with -O.
1509
        if result.revision_id != revision_id:
1510
            raise AssertionError('revision id mismatch %s != %s' % (
1511
                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.
1512
        return result
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
1513
1910.2.22 by Aaron Bentley
Make commits preserve root entry data
1514
    def serialise_inventory(self, inv):
1910.2.48 by Aaron Bentley
Update from review comments
1515
        return self._serializer.write_inventory_to_string(inv)
1910.2.22 by Aaron Bentley
Make commits preserve root entry data
1516
2817.2.1 by Robert Collins
* Inventory serialisation no longer double-sha's the content.
1517
    def _serialise_inventory_to_lines(self, inv):
1518
        return self._serializer.write_inventory_to_lines(inv)
1519
2520.4.113 by Aaron Bentley
Avoid peeking at Repository._serializer
1520
    def get_serializer_format(self):
1521
        return self._serializer.format_num
1522
1185.65.27 by Robert Collins
Tweak storage towards mergability.
1523
    @needs_read_lock
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
1524
    def get_inventory_xml(self, revision_id):
1525
        """Get inventory XML as a file object."""
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1526
        texts = self._iter_inventory_xmls([revision_id])
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
1527
        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.
1528
            text, revision_id = texts.next()
1529
        except StopIteration:
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
1530
            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.
1531
        return text
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
1532
1185.65.27 by Robert Collins
Tweak storage towards mergability.
1533
    @needs_read_lock
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
1534
    def get_inventory_sha1(self, revision_id):
1535
        """Return the sha1 hash of the inventory entry
1536
        """
1537
        return self.get_revision(revision_id).inventory_sha1
1538
2230.3.54 by Aaron Bentley
Move reverse history iteration to repository
1539
    def iter_reverse_revision_history(self, revision_id):
1540
        """Iterate backwards through revision ids in the lefthand history
1541
1542
        :param revision_id: The revision id to start with.  All its lefthand
1543
            ancestors will be traversed.
1544
        """
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.
1545
        graph = self.get_graph()
2230.3.54 by Aaron Bentley
Move reverse history iteration to repository
1546
        next_id = revision_id
1547
        while True:
3287.5.2 by Robert Collins
Deprecate VersionedFile.get_parents, breaking pulling from a ghost containing knit or pack repository to weaves, which improves correctness and allows simplification of core code.
1548
            if next_id in (None, _mod_revision.NULL_REVISION):
1549
                return
2230.3.54 by Aaron Bentley
Move reverse history iteration to repository
1550
            yield next_id
3287.5.10 by Robert Collins
Note iter_reverse_revision_history exception decision.
1551
            # Note: The following line may raise KeyError in the event of
1552
            # truncated history. We decided not to have a try:except:raise
1553
            # RevisionNotPresent here until we see a use for it, because of the
1554
            # cost in an inner loop that is by its very nature O(history).
1555
            # Robert Collins 20080326
3287.5.2 by Robert Collins
Deprecate VersionedFile.get_parents, breaking pulling from a ghost containing knit or pack repository to weaves, which improves correctness and allows simplification of core code.
1556
            parents = graph.get_parent_map([next_id])[next_id]
2230.3.54 by Aaron Bentley
Move reverse history iteration to repository
1557
            if len(parents) == 0:
1558
                return
1559
            else:
1560
                next_id = parents[0]
1561
1594.2.3 by Robert Collins
bugfix revision.MultipleRevisionSources.get_revision_graph to integrate ghosts between sources. [slow on weaves, fast on knits.
1562
    @needs_read_lock
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
1563
    def get_revision_inventory(self, revision_id):
1564
        """Return inventory of a past revision."""
1565
        # TODO: Unify this with get_inventory()
1566
        # bzr 0.0.6 and later imposes the constraint that the inventory_id
1567
        # must be the same as its revision, so this is trivial.
1534.4.28 by Robert Collins
first cut at merge from integration.
1568
        if revision_id is None:
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
1569
            # This does not make sense: if there is no revision,
1570
            # then it is the current tree inventory surely ?!
1571
            # and thus get_root_id() is something that looks at the last
1572
            # commit on the branch, and the get_root_id is an inventory check.
1573
            raise NotImplementedError
1574
            # return Inventory(self.get_root_id())
1575
        else:
1576
            return self.get_inventory(revision_id)
1577
1185.65.27 by Robert Collins
Tweak storage towards mergability.
1578
    @needs_read_lock
1534.6.3 by Robert Collins
find_repository sufficiently robust.
1579
    def is_shared(self):
1580
        """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.
1581
        raise NotImplementedError(self.is_shared)
1534.6.3 by Robert Collins
find_repository sufficiently robust.
1582
1594.2.7 by Robert Collins
Add versionedfile.fix_parents api for correcting data post hoc.
1583
    @needs_write_lock
1692.1.1 by Robert Collins
* Repository.reconcile now takes a thorough keyword parameter to allow
1584
    def reconcile(self, other=None, thorough=False):
1594.2.7 by Robert Collins
Add versionedfile.fix_parents api for correcting data post hoc.
1585
        """Reconcile this repository."""
1586
        from bzrlib.reconcile import RepoReconciler
1692.1.1 by Robert Collins
* Repository.reconcile now takes a thorough keyword parameter to allow
1587
        reconciler = RepoReconciler(self, thorough=thorough)
1594.2.7 by Robert Collins
Add versionedfile.fix_parents api for correcting data post hoc.
1588
        reconciler.reconcile()
1589
        return reconciler
2440.1.1 by Martin Pool
Add new Repository.sprout,
1590
2617.6.2 by Robert Collins
Add abort_write_group and wire write_groups into fetch and commit.
1591
    def _refresh_data(self):
1592
        """Helper called from lock_* to ensure coherency with disk.
1593
1594
        The default implementation does nothing; it is however possible
1595
        for repositories to maintain loaded indices across multiple locks
1596
        by checking inside their implementation of this method to see
1597
        whether their indices are still valid. This depends of course on
1598
        the disk format being validatable in this manner.
1599
        """
1600
1534.6.3 by Robert Collins
find_repository sufficiently robust.
1601
    @needs_read_lock
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
1602
    def revision_tree(self, revision_id):
1603
        """Return Tree for a revision on this branch.
1604
1852.5.1 by Robert Collins
Deprecate EmptyTree in favour of using Repository.revision_tree.
1605
        `revision_id` may be None for the empty tree revision.
1606
        """
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
1607
        # TODO: refactor this to use an existing revision object
1608
        # so we don't need to read it in twice.
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
1609
        if revision_id is None or revision_id == _mod_revision.NULL_REVISION:
1731.1.61 by Aaron Bentley
Merge bzr.dev
1610
            return RevisionTree(self, Inventory(root_id=None), 
1611
                                _mod_revision.NULL_REVISION)
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
1612
        else:
1613
            inv = self.get_revision_inventory(revision_id)
1185.65.17 by Robert Collins
Merge from integration, mode-changes are broken.
1614
            return RevisionTree(self, inv, revision_id)
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
1615
1756.3.3 by Aaron Bentley
More refactoring, introduce revision_trees.
1616
    def revision_trees(self, revision_ids):
1617
        """Return Tree for a revision on this branch.
1618
1756.3.19 by Aaron Bentley
Documentation and cleanups
1619
        `revision_id` may not be None or 'null:'"""
3169.2.1 by Robert Collins
New method ``iter_inventories`` on Repository for access to many
1620
        inventories = self.iter_inventories(revision_ids)
1621
        for inv in inventories:
1622
            yield RevisionTree(self, inv, inv.revision_id)
1756.3.3 by Aaron Bentley
More refactoring, introduce revision_trees.
1623
1624
    @needs_read_lock
2530.1.1 by Aaron Bentley
Make topological sorting optional for get_ancestry
1625
    def get_ancestry(self, revision_id, topo_sorted=True):
1185.66.2 by Aaron Bentley
Moved get_ancestry to RevisionStorage
1626
        """Return a list of revision-ids integrated by a revision.
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
1627
1628
        The first element of the list is always None, indicating the origin 
1629
        revision.  This might change when we have history horizons, or 
1630
        perhaps we should have a new API.
1185.66.2 by Aaron Bentley
Moved get_ancestry to RevisionStorage
1631
        
1632
        This is topologically sorted.
1633
        """
2598.5.1 by Aaron Bentley
Start eliminating the use of None to indicate null revision
1634
        if _mod_revision.is_null(revision_id):
1185.66.2 by Aaron Bentley
Moved get_ancestry to RevisionStorage
1635
            return [None]
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1636
        if not self.has_revision(revision_id):
1637
            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.
1638
        graph = self.get_graph()
1639
        keys = set()
1640
        search = graph._make_breadth_first_searcher([revision_id])
1641
        while True:
1642
            try:
1643
                found, ghosts = search.next_with_ghosts()
1644
            except StopIteration:
1645
                break
1646
            keys.update(found)
1647
        if _mod_revision.NULL_REVISION in keys:
1648
            keys.remove(_mod_revision.NULL_REVISION)
1649
        if topo_sorted:
1650
            parent_map = graph.get_parent_map(keys)
1651
            keys = tsort.topo_sort(parent_map)
1652
        return [None] + list(keys)
1185.66.2 by Aaron Bentley
Moved get_ancestry to RevisionStorage
1653
2604.2.1 by Robert Collins
(robertc) Introduce a pack command.
1654
    def pack(self):
1655
        """Compress the data within the repository.
1656
1657
        This operation only makes sense for some repository types. For other
1658
        types it should be a no-op that just returns.
1659
1660
        This stub method does not require a lock, but subclasses should use
1661
        @needs_write_lock as this is a long running call its reasonable to 
1662
        implicitly lock for the user.
1663
        """
1664
1185.65.4 by Aaron Bentley
Fixed cat command
1665
    @needs_read_lock
1666
    def print_file(self, file, revision_id):
1185.65.29 by Robert Collins
Implement final review suggestions.
1667
        """Print `file` to stdout.
1668
        
1669
        FIXME RBC 20060125 as John Meinel points out this is a bad api
1670
        - it writes to stdout, it assumes that that is valid etc. Fix
1671
        by creating a new more flexible convenience function.
1672
        """
1185.65.4 by Aaron Bentley
Fixed cat command
1673
        tree = self.revision_tree(revision_id)
1674
        # use inventory as it was in that revision
1675
        file_id = tree.inventory.path2id(file)
1676
        if not file_id:
1685.1.26 by John Arbash Meinel
Repository had a bug with what exception was raised when a file was missing
1677
            # TODO: jam 20060427 Write a test for this code path
1678
            #       it had a bug in it, and was raising the wrong
1679
            #       exception.
1680
            raise errors.BzrError("%r is not present in revision %s" % (file, revision_id))
1185.65.4 by Aaron Bentley
Fixed cat command
1681
        tree.print_file(file_id)
1682
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
1683
    def get_transaction(self):
1684
        return self.control_files.get_transaction()
1685
3099.3.3 by John Arbash Meinel
Deprecate get_parents() in favor of get_parent_map()
1686
    @deprecated_method(symbol_versioning.one_one)
2490.2.13 by Aaron Bentley
Update distinct -> lowest, refactor, add ParentsProvider concept
1687
    def get_parents(self, revision_ids):
2490.2.22 by Aaron Bentley
Rename GraphWalker -> Graph, _AncestryWalker -> _BreadthFirstSearcher
1688
        """See StackedParentsProvider.get_parents"""
3099.3.1 by John Arbash Meinel
Implement get_parent_map for ParentProviders
1689
        parent_map = self.get_parent_map(revision_ids)
1690
        return [parent_map.get(r, None) for r in revision_ids]
1691
1692
    def get_parent_map(self, keys):
1693
        """See graph._StackedParentsProvider.get_parent_map"""
1694
        parent_map = {}
1695
        for revision_id in keys:
3373.5.2 by John Arbash Meinel
Add repository_implementation tests for get_parent_map
1696
            if revision_id is None:
1697
                raise ValueError('get_parent_map(None) is not valid')
2490.2.13 by Aaron Bentley
Update distinct -> lowest, refactor, add ParentsProvider concept
1698
            if revision_id == _mod_revision.NULL_REVISION:
3146.1.2 by Aaron Bentley
ParentsProviders now provide tuples of parents, never lists
1699
                parent_map[revision_id] = ()
2490.2.13 by Aaron Bentley
Update distinct -> lowest, refactor, add ParentsProvider concept
1700
            else:
1701
                try:
3146.1.2 by Aaron Bentley
ParentsProviders now provide tuples of parents, never lists
1702
                    parent_id_list = self.get_revision(revision_id).parent_ids
2490.2.13 by Aaron Bentley
Update distinct -> lowest, refactor, add ParentsProvider concept
1703
                except errors.NoSuchRevision:
3099.3.1 by John Arbash Meinel
Implement get_parent_map for ParentProviders
1704
                    pass
2490.2.13 by Aaron Bentley
Update distinct -> lowest, refactor, add ParentsProvider concept
1705
                else:
3146.1.2 by Aaron Bentley
ParentsProviders now provide tuples of parents, never lists
1706
                    if len(parent_id_list) == 0:
1707
                        parent_ids = (_mod_revision.NULL_REVISION,)
1708
                    else:
1709
                        parent_ids = tuple(parent_id_list)
3099.3.1 by John Arbash Meinel
Implement get_parent_map for ParentProviders
1710
                    parent_map[revision_id] = parent_ids
1711
        return parent_map
2490.2.13 by Aaron Bentley
Update distinct -> lowest, refactor, add ParentsProvider concept
1712
1713
    def _make_parents_provider(self):
1714
        return self
1715
2490.2.21 by Aaron Bentley
Rename graph to deprecated_graph
1716
    def get_graph(self, other_repository=None):
2490.2.13 by Aaron Bentley
Update distinct -> lowest, refactor, add ParentsProvider concept
1717
        """Return the graph walker for this repository format"""
1718
        parents_provider = self._make_parents_provider()
2490.2.14 by Aaron Bentley
Avoid StackedParentsProvider when underlying repos match
1719
        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.
1720
            not self.has_same_location(other_repository)):
2490.2.21 by Aaron Bentley
Rename graph to deprecated_graph
1721
            parents_provider = graph._StackedParentsProvider(
2490.2.13 by Aaron Bentley
Update distinct -> lowest, refactor, add ParentsProvider concept
1722
                [parents_provider, other_repository._make_parents_provider()])
2490.2.22 by Aaron Bentley
Rename GraphWalker -> Graph, _AncestryWalker -> _BreadthFirstSearcher
1723
        return graph.Graph(parents_provider)
2490.2.13 by Aaron Bentley
Update distinct -> lowest, refactor, add ParentsProvider concept
1724
3036.1.3 by Robert Collins
Privatise VersionedFileChecker.
1725
    def _get_versioned_file_checker(self):
2988.1.6 by Robert Collins
Change the contract for VersionedFileChecker to consolidate related parameters rather than splitting them across two api calls. This allows better reuse of a single checker object.
1726
        """Return an object suitable for checking versioned files."""
3036.1.3 by Robert Collins
Privatise VersionedFileChecker.
1727
        return _VersionedFileChecker(self)
2745.6.47 by Andrew Bennetts
Move check_parents out of VersionedFile.
1728
3184.1.9 by Robert Collins
* ``Repository.get_data_stream`` is now deprecated in favour of
1729
    def revision_ids_to_search_result(self, result_set):
1730
        """Convert a set of revision ids to a graph SearchResult."""
1731
        result_parents = set()
1732
        for parents in self.get_graph().get_parent_map(
1733
            result_set).itervalues():
1734
            result_parents.update(parents)
1735
        included_keys = result_set.intersection(result_parents)
1736
        start_keys = result_set.difference(included_keys)
1737
        exclude_keys = result_parents.difference(result_set)
1738
        result = graph.SearchResult(start_keys, exclude_keys,
1739
            len(result_set), result_set)
1740
        return result
1741
1185.65.27 by Robert Collins
Tweak storage towards mergability.
1742
    @needs_write_lock
1534.6.5 by Robert Collins
Cloning of repos preserves shared and make-working-tree attributes.
1743
    def set_make_working_trees(self, new_value):
1744
        """Set the policy flag for making working trees when creating branches.
1745
1746
        This only applies to branches that use this repository.
1747
1748
        The default is 'True'.
1749
        :param new_value: True to restore the default, False to disable making
1750
                          working trees.
1751
        """
1596.2.12 by Robert Collins
Merge and make Knit Repository use the revision store for all possible queries.
1752
        raise NotImplementedError(self.set_make_working_trees)
1534.6.5 by Robert Collins
Cloning of repos preserves shared and make-working-tree attributes.
1753
    
1754
    def make_working_trees(self):
1755
        """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.
1756
        raise NotImplementedError(self.make_working_trees)
1534.6.5 by Robert Collins
Cloning of repos preserves shared and make-working-tree attributes.
1757
1758
    @needs_write_lock
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
1759
    def sign_revision(self, revision_id, gpg_strategy):
1760
        plaintext = Testament.from_revision(self, revision_id).as_short_text()
1761
        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.
1762
1563.2.29 by Robert Collins
Remove all but fetch references to repository.revision_store.
1763
    @needs_read_lock
1764
    def has_signature_for_revision_id(self, revision_id):
1765
        """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.
1766
        if not self.has_revision(revision_id):
1767
            raise errors.NoSuchRevision(self, revision_id)
1768
        sig_present = (1 == len(
1769
            self.signatures.get_parent_map([(revision_id,)])))
1770
        return sig_present
1563.2.29 by Robert Collins
Remove all but fetch references to repository.revision_store.
1771
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
1772
    @needs_read_lock
1773
    def get_signature_text(self, revision_id):
1774
        """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.
1775
        stream = self.signatures.get_record_stream([(revision_id,)],
1776
            'unordered', True)
1777
        record = stream.next()
1778
        if record.storage_kind == 'absent':
1779
            raise errors.NoSuchRevision(self, revision_id)
1780
        return record.get_bytes_as('fulltext')
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
1781
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
1782
    @needs_read_lock
2745.6.36 by Andrew Bennetts
Deprecate revision_ids arg to Repository.check and other tweaks.
1783
    def check(self, revision_ids=None):
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
1784
        """Check consistency of all history of given revision_ids.
1785
1786
        Different repository implementations should override _check().
1787
1788
        :param revision_ids: A non-empty list of revision_ids whose ancestry
1789
             will be checked.  Typically the last revision_id of a branch.
1790
        """
1791
        return self._check(revision_ids)
1792
1793
    def _check(self, revision_ids):
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
1794
        result = check.Check(self)
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
1795
        result.check()
1796
        return result
1797
1904.2.3 by Martin Pool
Give a warning on access to old repository formats
1798
    def _warn_if_deprecated(self):
1904.2.5 by Martin Pool
Fix format warning inside test suite and add test
1799
        global _deprecation_warning_done
1800
        if _deprecation_warning_done:
1801
            return
1802
        _deprecation_warning_done = True
1904.2.3 by Martin Pool
Give a warning on access to old repository formats
1803
        warning("Format %s for %s is deprecated - please use 'bzr upgrade' to get better performance"
1804
                % (self._format, self.bzrdir.transport.base))
1805
1910.2.63 by Aaron Bentley
Add supports_rich_root member to repository
1806
    def supports_rich_root(self):
1807
        return self._format.rich_root_data
1808
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.
1809
    def _check_ascii_revisionid(self, revision_id, method):
1810
        """Private helper for ascii-only repositories."""
1811
        # weave repositories refuse to store revisionids that are non-ascii.
1812
        if revision_id is not None:
1813
            # weaves require ascii revision ids.
1814
            if isinstance(revision_id, unicode):
1815
                try:
1816
                    revision_id.encode('ascii')
1817
                except UnicodeEncodeError:
1818
                    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
1819
            else:
1820
                try:
1821
                    revision_id.decode('ascii')
1822
                except UnicodeDecodeError:
1823
                    raise errors.NonAsciiRevisionId(method, self)
2819.2.4 by Andrew Bennetts
Add a 'revision_graph_can_have_wrong_parents' method to repository.
1824
    
1825
    def revision_graph_can_have_wrong_parents(self):
1826
        """Is it possible for this repository to have a revision graph with
1827
        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.
1828
2819.2.4 by Andrew Bennetts
Add a 'revision_graph_can_have_wrong_parents' method to repository.
1829
        If True, then this repository must also implement
1830
        _find_inconsistent_revision_parents so that check and reconcile can
1831
        check for inconsistencies before proceeding with other checks that may
1832
        depend on the revision index being consistent.
1833
        """
1834
        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
1835
1836
2241.1.18 by mbp at sourcefrog
Restore use of deprecating delegator for old formats in bzrlib.repository.
1837
# remove these delegates a while after bzr 0.15
1838
def __make_delegated(name, from_module):
1839
    def _deprecated_repository_forwarder():
1840
        symbol_versioning.warn('%s moved to %s in bzr 0.15'
1841
            % (name, from_module),
2241.1.20 by mbp at sourcefrog
update tests for new locations of weave repos
1842
            DeprecationWarning,
1843
            stacklevel=2)
2241.1.18 by mbp at sourcefrog
Restore use of deprecating delegator for old formats in bzrlib.repository.
1844
        m = __import__(from_module, globals(), locals(), [name])
1845
        try:
1846
            return getattr(m, name)
1847
        except AttributeError:
1848
            raise AttributeError('module %s has no name %s'
1849
                    % (m, name))
1850
    globals()[name] = _deprecated_repository_forwarder
1851
1852
for _name in [
1853
        'AllInOneRepository',
1854
        'WeaveMetaDirRepository',
1855
        'PreSplitOutRepositoryFormat',
1856
        'RepositoryFormat4',
1857
        'RepositoryFormat5',
1858
        'RepositoryFormat6',
1859
        'RepositoryFormat7',
1860
        ]:
1861
    __make_delegated(_name, 'bzrlib.repofmt.weaverepo')
1862
1863
for _name in [
1864
        'KnitRepository',
1865
        'RepositoryFormatKnit',
1866
        'RepositoryFormatKnit1',
1867
        ]:
1868
    __make_delegated(_name, 'bzrlib.repofmt.knitrepo')
1869
1870
2996.2.2 by Aaron Bentley
Create install_revisions function
1871
def install_revision(repository, rev, revision_tree):
1872
    """Install all revision data into a repository."""
1873
    install_revisions(repository, [(rev, revision_tree, None)])
1874
1875
3146.6.1 by Aaron Bentley
InterDifferingSerializer shows a progress bar
1876
def install_revisions(repository, iterable, num_revisions=None, pb=None):
2996.2.4 by Aaron Bentley
Rename function to add_signature_text
1877
    """Install all revision data into a repository.
1878
1879
    Accepts an iterable of revision, tree, signature tuples.  The signature
1880
    may be None.
1881
    """
2592.3.96 by Robert Collins
Merge index improvements (includes bzr.dev).
1882
    repository.start_write_group()
1883
    try:
3146.6.1 by Aaron Bentley
InterDifferingSerializer shows a progress bar
1884
        for n, (revision, revision_tree, signature) in enumerate(iterable):
2996.2.2 by Aaron Bentley
Create install_revisions function
1885
            _install_revision(repository, revision, revision_tree, signature)
3146.6.1 by Aaron Bentley
InterDifferingSerializer shows a progress bar
1886
            if pb is not None:
1887
                pb.update('Transferring revisions', n + 1, num_revisions)
2592.3.96 by Robert Collins
Merge index improvements (includes bzr.dev).
1888
    except:
1889
        repository.abort_write_group()
2592.3.101 by Robert Collins
Correctly propogate exceptions from repository.install_revisions.
1890
        raise
2592.3.96 by Robert Collins
Merge index improvements (includes bzr.dev).
1891
    else:
1892
        repository.commit_write_group()
1893
1894
2996.2.1 by Aaron Bentley
Add KnitRepositoryFormat4
1895
def _install_revision(repository, rev, revision_tree, signature):
2592.3.96 by Robert Collins
Merge index improvements (includes bzr.dev).
1896
    """Install all revision data into a repository."""
1185.82.84 by Aaron Bentley
Moved stuff around
1897
    present_parents = []
1898
    parent_trees = {}
1899
    for p_id in rev.parent_ids:
1900
        if repository.has_revision(p_id):
1901
            present_parents.append(p_id)
1902
            parent_trees[p_id] = repository.revision_tree(p_id)
1903
        else:
1852.5.1 by Robert Collins
Deprecate EmptyTree in favour of using Repository.revision_tree.
1904
            parent_trees[p_id] = repository.revision_tree(None)
1185.82.84 by Aaron Bentley
Moved stuff around
1905
1906
    inv = revision_tree.inventory
1910.2.51 by Aaron Bentley
Bundles now corrupt repositories
1907
    entries = inv.iter_entries()
2617.6.6 by Robert Collins
Some review feedback.
1908
    # backwards compatibility hack: skip the root id.
1910.2.63 by Aaron Bentley
Add supports_rich_root member to repository
1909
    if not repository.supports_rich_root():
1910.2.60 by Aaron Bentley
Ensure that new-model revisions aren't installed into old-model repos
1910
        path, root = entries.next()
1911
        if root.revision != rev.revision_id:
1910.2.63 by Aaron Bentley
Add supports_rich_root member to repository
1912
            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.
1913
    text_keys = {}
1914
    for path, ie in entries:
1915
        text_keys[(ie.file_id, ie.revision)] = ie
1916
    text_parent_map = repository.texts.get_parent_map(text_keys)
1917
    missing_texts = set(text_keys) - set(text_parent_map)
1185.82.84 by Aaron Bentley
Moved stuff around
1918
    # 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.
1919
    for text_key in missing_texts:
1920
        ie = text_keys[text_key]
1921
        text_parents = []
1922
        # FIXME: TODO: The following loop overlaps/duplicates that done by
1923
        # commit to determine parents. There is a latent/real bug here where
1924
        # the parents inserted are not those commit would do - in particular
1925
        # they are not filtered by heads(). RBC, AB
1926
        for revision, tree in parent_trees.iteritems():
1927
            if ie.file_id not in tree:
1928
                continue
1929
            parent_id = tree.inventory[ie.file_id].revision
1930
            if parent_id in text_parents:
1931
                continue
1932
            text_parents.append((ie.file_id, parent_id))
1933
        lines = revision_tree.get_file(ie.file_id).readlines()
1934
        repository.texts.add_lines(text_key, text_parents, lines)
1185.82.84 by Aaron Bentley
Moved stuff around
1935
    try:
1936
        # install the inventory
1937
        repository.add_inventory(rev.revision_id, inv, present_parents)
1938
    except errors.RevisionAlreadyPresent:
1939
        pass
2996.2.1 by Aaron Bentley
Add KnitRepositoryFormat4
1940
    if signature is not None:
2996.2.8 by Aaron Bentley
Fix add_signature discrepancies
1941
        repository.add_signature_text(rev.revision_id, signature)
1185.82.84 by Aaron Bentley
Moved stuff around
1942
    repository.add_revision(rev.revision_id, rev, inv)
1943
1944
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
1945
class MetaDirRepository(Repository):
3407.2.13 by Martin Pool
Remove indirection through control_files to get transports
1946
    """Repositories in the new meta-dir layout.
1947
    
1948
    :ivar _transport: Transport for access to repository control files,
1949
        typically pointing to .bzr/repository.
1950
    """
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
1951
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.
1952
    def __init__(self, _format, a_bzrdir, control_files):
1953
        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
1954
        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
1955
1596.2.12 by Robert Collins
Merge and make Knit Repository use the revision store for all possible queries.
1956
    @needs_read_lock
1957
    def is_shared(self):
1958
        """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
1959
        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.
1960
1961
    @needs_write_lock
1962
    def set_make_working_trees(self, new_value):
1963
        """Set the policy flag for making working trees when creating branches.
1964
1965
        This only applies to branches that use this repository.
1966
1967
        The default is 'True'.
1968
        :param new_value: True to restore the default, False to disable making
1969
                          working trees.
1970
        """
1971
        if new_value:
1972
            try:
3407.2.3 by Martin Pool
Branch and Repository use their own ._transport rather than going through .control_files
1973
                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.
1974
            except errors.NoSuchFile:
1975
                pass
1976
        else:
3407.2.5 by Martin Pool
Deprecate LockableFiles.put_utf8
1977
            self._transport.put_bytes('no-working-trees', '',
3468.1.1 by Martin Pool
Update more users of default file modes from control_files to bzrdir
1978
                mode=self.bzrdir._get_file_mode())
1596.2.12 by Robert Collins
Merge and make Knit Repository use the revision store for all possible queries.
1979
    
1980
    def make_working_trees(self):
1981
        """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
1982
        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.
1983
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
1984
3316.2.3 by Robert Collins
Remove manual notification of transaction finishing on versioned files.
1985
class MetaDirVersionedFileRepository(MetaDirRepository):
1986
    """Repositories in a meta-dir, that work via versioned file objects."""
1987
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.
1988
    def __init__(self, _format, a_bzrdir, control_files):
3316.2.5 by Robert Collins
Review feedback.
1989
        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.
1990
            control_files)
3316.2.3 by Robert Collins
Remove manual notification of transaction finishing on versioned files.
1991
1992
2241.1.2 by Martin Pool
change to using external Repository format registry
1993
class RepositoryFormatRegistry(registry.Registry):
2889.1.1 by Robert Collins
* The class ``bzrlib.repofmt.knitrepo.KnitRepository3`` has been folded into
1994
    """Registry of RepositoryFormats."""
2241.1.11 by Martin Pool
Get rid of RepositoryFormat*_instance objects. Instead the format
1995
1996
    def get(self, format_string):
1997
        r = registry.Registry.get(self, format_string)
1998
        if callable(r):
1999
            r = r()
2000
        return r
2241.1.2 by Martin Pool
change to using external Repository format registry
2001
    
2002
2003
format_registry = RepositoryFormatRegistry()
2241.1.11 by Martin Pool
Get rid of RepositoryFormat*_instance objects. Instead the format
2004
"""Registry of formats, indexed by their identifying format string.
2005
2006
This can contain either format instances themselves, or classes/factories that
2007
can be called to obtain one.
2008
"""
2241.1.2 by Martin Pool
change to using external Repository format registry
2009
2220.2.3 by Martin Pool
Add tag: revision namespace.
2010
2011
#####################################################################
2012
# Repository Formats
1910.2.46 by Aaron Bentley
Whitespace fix
2013
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
2014
class RepositoryFormat(object):
2015
    """A repository format.
2016
2017
    Formats provide three things:
2018
     * An initialization routine to construct repository data on disk.
2019
     * a format string which is used when the BzrDir supports versioned
2020
       children.
2021
     * an open routine which returns a Repository instance.
2022
2889.1.2 by Robert Collins
Review feedback.
2023
    There is one and only one Format subclass for each on-disk format. But
2024
    there can be one Repository subclass that is used for several different
2025
    formats. The _format attribute on a Repository instance can be used to
2026
    determine the disk format.
2889.1.1 by Robert Collins
* The class ``bzrlib.repofmt.knitrepo.KnitRepository3`` has been folded into
2027
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
2028
    Formats are placed in an dict by their format string for reference 
2029
    during opening. These should be subclasses of RepositoryFormat
2030
    for consistency.
2031
2032
    Once a format is deprecated, just deprecate the initialize and open
2033
    methods on the format class. Do not deprecate the object, as the 
2034
    object will be created every system load.
2035
2036
    Common instance attributes:
2037
    _matchingbzrdir - the bzrdir format that the repository format was
2038
    originally written to work with. This can be used if manually
2039
    constructing a bzrdir and repository, or more commonly for test suite
3128.1.3 by Vincent Ladeuil
Since we are there s/parameteris.*/parameteriz&/.
2040
    parameterization.
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
2041
    """
2042
2949.1.2 by Robert Collins
* Fetch with pack repositories will no longer read the entire history graph.
2043
    # Set to True or False in derived classes. True indicates that the format
2044
    # supports ghosts gracefully.
2045
    supports_ghosts = None
3221.3.1 by Robert Collins
* Repository formats have a new supported-feature attribute
2046
    # Can this repository be given external locations to lookup additional
2047
    # data. Set to True or False in derived classes.
2048
    supports_external_lookups = None
2949.1.2 by Robert Collins
* Fetch with pack repositories will no longer read the entire history graph.
2049
1904.2.3 by Martin Pool
Give a warning on access to old repository formats
2050
    def __str__(self):
2051
        return "<%s>" % self.__class__.__name__
2052
2241.1.11 by Martin Pool
Get rid of RepositoryFormat*_instance objects. Instead the format
2053
    def __eq__(self, other):
2054
        # format objects are generally stateless
2055
        return isinstance(other, self.__class__)
2056
2100.3.35 by Aaron Bentley
equality operations on bzrdir
2057
    def __ne__(self, other):
2100.3.31 by Aaron Bentley
Merged bzr.dev (17 tests failing)
2058
        return not self == other
2059
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
2060
    @classmethod
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
2061
    def find_format(klass, a_bzrdir):
2241.1.1 by Martin Pool
Change RepositoryFormat to use a Registry rather than ad-hoc dictionary
2062
        """Return the format for the repository object in a_bzrdir.
2063
        
2064
        This is used by bzr native formats that have a "format" file in
2065
        the repository.  Other methods may be used by different types of 
2066
        control directory.
2067
        """
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
2068
        try:
2069
            transport = a_bzrdir.get_repository_transport(None)
2070
            format_string = transport.get("format").read()
2241.1.2 by Martin Pool
change to using external Repository format registry
2071
            return format_registry.get(format_string)
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
2072
        except errors.NoSuchFile:
2073
            raise errors.NoRepositoryPresent(a_bzrdir)
2074
        except KeyError:
3246.3.2 by Daniel Watkins
Modified uses of errors.UnknownFormatError.
2075
            raise errors.UnknownFormatError(format=format_string,
2076
                                            kind='repository')
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
2077
2241.1.1 by Martin Pool
Change RepositoryFormat to use a Registry rather than ad-hoc dictionary
2078
    @classmethod
2241.1.2 by Martin Pool
change to using external Repository format registry
2079
    def register_format(klass, format):
2080
        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
2081
2082
    @classmethod
2083
    def unregister_format(klass, format):
2241.1.2 by Martin Pool
change to using external Repository format registry
2084
        format_registry.remove(format.get_format_string())
1563.2.23 by Robert Collins
Add add_revision and get_revision methods to RevisionStore
2085
    
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
2086
    @classmethod
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
2087
    def get_default_format(klass):
2088
        """Return the current default format."""
2204.5.3 by Aaron Bentley
zap old repository default handling
2089
        from bzrlib import bzrdir
2090
        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
2091
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
2092
    def get_format_string(self):
2093
        """Return the ASCII format string that identifies this format.
2094
        
2095
        Note that in pre format ?? repositories the format string is 
2096
        not permitted nor written to disk.
2097
        """
2098
        raise NotImplementedError(self.get_format_string)
2099
1624.3.19 by Olaf Conradi
New call get_format_description to give a user-friendly description of a
2100
    def get_format_description(self):
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
2101
        """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
2102
        raise NotImplementedError(self.get_format_description)
2103
2241.1.6 by Martin Pool
Move Knit repositories into the submodule bzrlib.repofmt.knitrepo and
2104
    # TODO: this shouldn't be in the base class, it's specific to things that
2105
    # 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.
2106
    def _get_versioned_file_store(self,
2107
                                  name,
2108
                                  transport,
2109
                                  control_files,
2110
                                  prefixed=True,
2241.1.10 by Martin Pool
Remove more references to weaves from the repository.py file
2111
                                  versionedfile_class=None,
1946.2.5 by John Arbash Meinel
Make knit stores delay creation, but not control stores
2112
                                  versionedfile_kwargs={},
1608.2.12 by Martin Pool
Store-escaping must quote uppercase characters too, so that they're safely
2113
                                  escaped=False):
2241.1.10 by Martin Pool
Remove more references to weaves from the repository.py file
2114
        if versionedfile_class is None:
2115
            versionedfile_class = self._versionedfile_class
1563.2.17 by Robert Collins
Change knits repositories to use a knit versioned file store for file texts.
2116
        weave_transport = control_files._transport.clone(name)
2117
        dir_mode = control_files._dir_mode
2118
        file_mode = control_files._file_mode
2119
        return VersionedFileStore(weave_transport, prefixed=prefixed,
1608.2.12 by Martin Pool
Store-escaping must quote uppercase characters too, so that they're safely
2120
                                  dir_mode=dir_mode,
2121
                                  file_mode=file_mode,
2122
                                  versionedfile_class=versionedfile_class,
1946.2.5 by John Arbash Meinel
Make knit stores delay creation, but not control stores
2123
                                  versionedfile_kwargs=versionedfile_kwargs,
1608.2.12 by Martin Pool
Store-escaping must quote uppercase characters too, so that they're safely
2124
                                  escaped=escaped)
1563.2.17 by Robert Collins
Change knits repositories to use a knit versioned file store for file texts.
2125
1534.6.1 by Robert Collins
allow API creation of shared repositories
2126
    def initialize(self, a_bzrdir, shared=False):
2127
        """Initialize a repository of this format in a_bzrdir.
2128
2129
        :param a_bzrdir: The bzrdir to put the new repository in it.
2130
        :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.
2131
        :returns: The new repository object.
2132
        
1534.6.1 by Robert Collins
allow API creation of shared repositories
2133
        This may raise UninitializableFormat if shared repository are not
2134
        compatible the a_bzrdir.
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
2135
        """
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
2136
        raise NotImplementedError(self.initialize)
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
2137
2138
    def is_supported(self):
2139
        """Is this format supported?
2140
2141
        Supported formats must be initializable and openable.
2142
        Unsupported formats may not support initialization or committing or 
2143
        some other features depending on the reason for not being supported.
2144
        """
2145
        return True
2146
1910.2.12 by Aaron Bentley
Implement knit repo format 2
2147
    def check_conversion_target(self, target_format):
2148
        raise NotImplementedError(self.check_conversion_target)
2149
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
2150
    def open(self, a_bzrdir, _found=False):
2151
        """Return an instance of this format for the bzrdir a_bzrdir.
2152
        
2153
        _found is a private parameter, do not use it.
2154
        """
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
2155
        raise NotImplementedError(self.open)
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
2156
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
2157
2158
class MetaDirRepositoryFormat(RepositoryFormat):
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
2159
    """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
2160
1910.2.14 by Aaron Bentley
Fail when trying to use interrepository on Knit2 and Knit1
2161
    rich_root_data = False
2323.5.17 by Martin Pool
Add supports_tree_reference to all repo formats (robert)
2162
    supports_tree_reference = False
3221.3.1 by Robert Collins
* Repository formats have a new supported-feature attribute
2163
    supports_external_lookups = False
2241.1.11 by Martin Pool
Get rid of RepositoryFormat*_instance objects. Instead the format
2164
    _matchingbzrdir = bzrdir.BzrDirMetaFormat1()
1910.2.14 by Aaron Bentley
Fail when trying to use interrepository on Knit2 and Knit1
2165
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.
2166
    def __init__(self):
2167
        super(MetaDirRepositoryFormat, self).__init__()
2168
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
2169
    def _create_control_files(self, a_bzrdir):
2170
        """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.
2171
        # FIXME: RBC 20060125 don't peek under the covers
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
2172
        # NB: no need to escape relative paths that are url safe.
2173
        repository_transport = a_bzrdir.get_repository_transport(self)
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
2174
        control_files = lockable_files.LockableFiles(repository_transport,
2175
                                'lock', lockdir.LockDir)
1553.5.61 by Martin Pool
Locks protecting LockableFiles must now be explicitly created before use.
2176
        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
2177
        return control_files
2178
2179
    def _upload_blank_content(self, a_bzrdir, dirs, files, utf8_files, shared):
2180
        """Upload the initial blank content."""
2181
        control_files = self._create_control_files(a_bzrdir)
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
2182
        control_files.lock_write()
3407.2.4 by Martin Pool
Small cleanups to initial creation of repository files
2183
        transport = control_files._transport
2184
        if shared == True:
2185
            utf8_files += [('shared-storage', '')]
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
2186
        try:
3446.1.1 by Martin Pool
merge further LockableFile deprecations
2187
            transport.mkdir_multi(dirs, mode=a_bzrdir._get_dir_mode())
3407.2.4 by Martin Pool
Small cleanups to initial creation of repository files
2188
            for (filename, content_stream) in files:
2189
                transport.put_file(filename, content_stream,
3446.1.1 by Martin Pool
merge further LockableFile deprecations
2190
                    mode=a_bzrdir._get_file_mode())
3407.2.4 by Martin Pool
Small cleanups to initial creation of repository files
2191
            for (filename, content_bytes) in utf8_files:
2192
                transport.put_bytes_non_atomic(filename, content_bytes,
3446.1.1 by Martin Pool
merge further LockableFile deprecations
2193
                    mode=a_bzrdir._get_file_mode())
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
2194
        finally:
2195
            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
2196
2197
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
2198
# formats which have no format string are not discoverable
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
2199
# and not independently creatable, so are not registered.  They're 
2241.1.11 by Martin Pool
Get rid of RepositoryFormat*_instance objects. Instead the format
2200
# all in bzrlib.repofmt.weaverepo now.  When an instance of one of these is
2201
# needed, it's constructed directly by the BzrDir.  Non-native formats where
2202
# the repository is not separately opened are similar.
2203
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
2204
format_registry.register_lazy(
2205
    'Bazaar-NG Repository format 7',
2206
    'bzrlib.repofmt.weaverepo',
2241.1.11 by Martin Pool
Get rid of RepositoryFormat*_instance objects. Instead the format
2207
    'RepositoryFormat7'
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
2208
    )
2592.3.22 by Robert Collins
Add new experimental repository formats.
2209
2241.1.6 by Martin Pool
Move Knit repositories into the submodule bzrlib.repofmt.knitrepo and
2210
format_registry.register_lazy(
2211
    'Bazaar-NG Knit Repository Format 1',
2212
    'bzrlib.repofmt.knitrepo',
2241.1.11 by Martin Pool
Get rid of RepositoryFormat*_instance objects. Instead the format
2213
    'RepositoryFormatKnit1',
2241.1.6 by Martin Pool
Move Knit repositories into the submodule bzrlib.repofmt.knitrepo and
2214
    )
2215
2241.1.5 by Martin Pool
Move KnitFormat2 into repofmt
2216
format_registry.register_lazy(
2255.2.230 by Robert Collins
Update tree format signatures to mention introducing bzr version.
2217
    'Bazaar Knit Repository Format 3 (bzr 0.15)\n',
2100.3.31 by Aaron Bentley
Merged bzr.dev (17 tests failing)
2218
    'bzrlib.repofmt.knitrepo',
2219
    'RepositoryFormatKnit3',
2220
    )
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
2221
2996.2.1 by Aaron Bentley
Add KnitRepositoryFormat4
2222
format_registry.register_lazy(
2223
    'Bazaar Knit Repository Format 4 (bzr 1.0)\n',
2224
    'bzrlib.repofmt.knitrepo',
2225
    'RepositoryFormatKnit4',
2226
    )
2227
2939.2.1 by Ian Clatworthy
use 'knitpack' naming instead of 'experimental' for pack formats
2228
# Pack-based formats. There is one format for pre-subtrees, and one for
2229
# post-subtrees to allow ease of testing.
3152.2.1 by Robert Collins
* A new repository format 'development' has been added. This format will
2230
# NOTE: These are experimental in 0.92. Stable in 1.0 and above
2592.3.22 by Robert Collins
Add new experimental repository formats.
2231
format_registry.register_lazy(
2939.2.6 by Ian Clatworthy
more review feedback from lifeless and poolie
2232
    '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.
2233
    'bzrlib.repofmt.pack_repo',
2592.3.224 by Martin Pool
Rename GraphKnitRepository etc to KnitPackRepository
2234
    'RepositoryFormatKnitPack1',
2592.3.22 by Robert Collins
Add new experimental repository formats.
2235
    )
2236
format_registry.register_lazy(
2939.2.6 by Ian Clatworthy
more review feedback from lifeless and poolie
2237
    '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.
2238
    'bzrlib.repofmt.pack_repo',
2592.3.224 by Martin Pool
Rename GraphKnitRepository etc to KnitPackRepository
2239
    'RepositoryFormatKnitPack3',
2592.3.22 by Robert Collins
Add new experimental repository formats.
2240
    )
2996.2.11 by Aaron Bentley
Implement rich-root-pack format ( #164639)
2241
format_registry.register_lazy(
2242
    'Bazaar pack repository format 1 with rich root (needs bzr 1.0)\n',
2243
    'bzrlib.repofmt.pack_repo',
2244
    'RepositoryFormatKnitPack4',
2245
    )
3152.2.1 by Robert Collins
* A new repository format 'development' has been added. This format will
2246
# Development formats. 
3152.2.3 by Robert Collins
Merge up with bzr.dev.
2247
# 1.2->1.3
3152.2.1 by Robert Collins
* A new repository format 'development' has been added. This format will
2248
# development 0 - stub to introduce development versioning scheme.
2249
format_registry.register_lazy(
3152.2.3 by Robert Collins
Merge up with bzr.dev.
2250
    "Bazaar development format 0 (needs bzr.dev from before 1.3)\n",
3152.2.1 by Robert Collins
* A new repository format 'development' has been added. This format will
2251
    'bzrlib.repofmt.pack_repo',
2252
    'RepositoryFormatPackDevelopment0',
2253
    )
2254
format_registry.register_lazy(
2255
    ("Bazaar development format 0 with subtree support "
3152.2.3 by Robert Collins
Merge up with bzr.dev.
2256
        "(needs bzr.dev from before 1.3)\n"),
3152.2.1 by Robert Collins
* A new repository format 'development' has been added. This format will
2257
    'bzrlib.repofmt.pack_repo',
2258
    'RepositoryFormatPackDevelopment0Subtree',
2259
    )
3152.2.3 by Robert Collins
Merge up with bzr.dev.
2260
# 1.3->1.4 go below here
2592.3.22 by Robert Collins
Add new experimental repository formats.
2261
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
2262
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.
2263
class InterRepository(InterObject):
1534.1.27 by Robert Collins
Start InterRepository with InterRepository.get.
2264
    """This class represents operations taking place between two repositories.
2265
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.
2266
    Its instances have methods like copy_content and fetch, and contain
1534.1.27 by Robert Collins
Start InterRepository with InterRepository.get.
2267
    references to the source and target repositories these operations can be 
2268
    carried out on.
2269
2270
    Often we will provide convenience methods on 'repository' which carry out
2271
    operations with another repository - they will always forward to
2272
    InterRepository.get(other).method_name(parameters).
2273
    """
2274
1910.2.15 by Aaron Bentley
Back out inter.get changes, make optimizers an ordered list
2275
    _optimisers = []
1534.1.28 by Robert Collins
Allow for optimised InterRepository selection.
2276
    """The available optimised InterRepository types."""
2277
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
2278
    def copy_content(self, revision_id=None):
1910.2.15 by Aaron Bentley
Back out inter.get changes, make optimizers an ordered list
2279
        raise NotImplementedError(self.copy_content)
2280
2949.1.2 by Robert Collins
* Fetch with pack repositories will no longer read the entire history graph.
2281
    def fetch(self, revision_id=None, pb=None, find_ghosts=False):
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.
2282
        """Fetch the content required to construct revision_id.
2283
1910.7.17 by Andrew Bennetts
Various cosmetic changes.
2284
        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.
2285
2286
        :param revision_id: if None all content is copied, if NULL_REVISION no
2287
                            content is copied.
2288
        :param pb: optional progress bar to use for progress reports. If not
2289
                   provided a default one will be created.
2290
2291
        Returns the copied revision count and the failed revisions in a tuple:
2292
        (copied, failures).
2293
        """
1910.2.15 by Aaron Bentley
Back out inter.get changes, make optimizers an ordered list
2294
        raise NotImplementedError(self.fetch)
3172.4.4 by Robert Collins
Review feedback.
2295
2296
    def _walk_to_common_revisions(self, revision_ids):
2297
        """Walk out from revision_ids in source to revisions target has.
2298
2299
        :param revision_ids: The start point for the search.
2300
        :return: A set of revision ids.
2301
        """
3366.1.1 by Robert Collins
* Severe performance degradation in fetching from knit repositories to
2302
        target_graph = self.target.get_graph()
1551.19.41 by Aaron Bentley
Accelerate no-op pull
2303
        revision_ids = frozenset(revision_ids)
2304
        if set(target_graph.get_parent_map(revision_ids)) == revision_ids:
2305
            return graph.SearchResult(revision_ids, set(), 0, set())
3172.4.4 by Robert Collins
Review feedback.
2306
        missing_revs = set()
1551.19.41 by Aaron Bentley
Accelerate no-op pull
2307
        source_graph = self.source.get_graph()
3172.4.4 by Robert Collins
Review feedback.
2308
        # ensure we don't pay silly lookup costs.
1551.19.41 by Aaron Bentley
Accelerate no-op pull
2309
        searcher = source_graph._make_breadth_first_searcher(revision_ids)
3172.4.4 by Robert Collins
Review feedback.
2310
        null_set = frozenset([_mod_revision.NULL_REVISION])
2311
        while True:
2312
            try:
2313
                next_revs, ghosts = searcher.next_with_ghosts()
2314
            except StopIteration:
2315
                break
2316
            if revision_ids.intersection(ghosts):
2317
                absent_ids = set(revision_ids.intersection(ghosts))
2318
                # If all absent_ids are present in target, no error is needed.
2319
                absent_ids.difference_update(
3366.1.1 by Robert Collins
* Severe performance degradation in fetching from knit repositories to
2320
                    set(target_graph.get_parent_map(absent_ids)))
3172.4.4 by Robert Collins
Review feedback.
2321
                if absent_ids:
2322
                    raise errors.NoSuchRevision(self.source, absent_ids.pop())
2323
            # we don't care about other ghosts as we can't fetch them and
2324
            # haven't been asked to.
2325
            next_revs = set(next_revs)
3184.1.8 by Robert Collins
* ``InterRepository.missing_revision_ids`` is now deprecated in favour of
2326
            # we always have NULL_REVISION present.
3366.1.1 by Robert Collins
* Severe performance degradation in fetching from knit repositories to
2327
            have_revs = set(target_graph.get_parent_map(next_revs)).union(null_set)
3172.4.4 by Robert Collins
Review feedback.
2328
            missing_revs.update(next_revs - have_revs)
2329
            searcher.stop_searching_any(have_revs)
3184.1.8 by Robert Collins
* ``InterRepository.missing_revision_ids`` is now deprecated in favour of
2330
        return searcher.get_result()
1910.2.15 by Aaron Bentley
Back out inter.get changes, make optimizers an ordered list
2331
   
3184.1.8 by Robert Collins
* ``InterRepository.missing_revision_ids`` is now deprecated in favour of
2332
    @deprecated_method(symbol_versioning.one_two)
1910.2.15 by Aaron Bentley
Back out inter.get changes, make optimizers an ordered list
2333
    @needs_read_lock
3010.1.5 by Robert Collins
Test that missing_revision_ids handles the case of the source not having the requested revision correctly with and without find_ghosts.
2334
    def missing_revision_ids(self, revision_id=None, find_ghosts=True):
1910.2.15 by Aaron Bentley
Back out inter.get changes, make optimizers an ordered list
2335
        """Return the revision ids that source has that target does not.
2336
        
2337
        These are returned in topological order.
2338
2339
        :param revision_id: only return revision ids included by this
2340
                            revision_id.
3172.4.1 by Robert Collins
* Fetching via bzr+ssh will no longer fill ghosts by default (this is
2341
        :param find_ghosts: If True find missing revisions in deep history
2342
            rather than just finding the surface difference.
1910.2.15 by Aaron Bentley
Back out inter.get changes, make optimizers an ordered list
2343
        """
3184.1.8 by Robert Collins
* ``InterRepository.missing_revision_ids`` is now deprecated in favour of
2344
        return list(self.search_missing_revision_ids(
2345
            revision_id, find_ghosts).get_keys())
2346
2347
    @needs_read_lock
2348
    def search_missing_revision_ids(self, revision_id=None, find_ghosts=True):
2349
        """Return the revision ids that source has that target does not.
2350
        
2351
        :param revision_id: only return revision ids included by this
2352
                            revision_id.
2353
        :param find_ghosts: If True find missing revisions in deep history
2354
            rather than just finding the surface difference.
2355
        :return: A bzrlib.graph.SearchResult.
2356
        """
3172.4.1 by Robert Collins
* Fetching via bzr+ssh will no longer fill ghosts by default (this is
2357
        # stop searching at found target revisions.
2358
        if not find_ghosts and revision_id is not None:
3172.4.4 by Robert Collins
Review feedback.
2359
            return self._walk_to_common_revisions([revision_id])
1910.2.15 by Aaron Bentley
Back out inter.get changes, make optimizers an ordered list
2360
        # generic, possibly worst case, slow code path.
2361
        target_ids = set(self.target.all_revision_ids())
2362
        if revision_id is not None:
2363
            source_ids = self.source.get_ancestry(revision_id)
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
2364
            if source_ids[0] is not None:
2365
                raise AssertionError()
1910.2.15 by Aaron Bentley
Back out inter.get changes, make optimizers an ordered list
2366
            source_ids.pop(0)
2367
        else:
2368
            source_ids = self.source.all_revision_ids()
2369
        result_set = set(source_ids).difference(target_ids)
3184.1.9 by Robert Collins
* ``Repository.get_data_stream`` is now deprecated in favour of
2370
        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
2371
2592.3.28 by Robert Collins
Make InterKnitOptimiser be used between any same-model knit repository.
2372
    @staticmethod
2373
    def _same_model(source, target):
2374
        """True if source and target have the same data representation."""
2375
        if source.supports_rich_root() != target.supports_rich_root():
2376
            return False
2377
        if source._serializer != target._serializer:
2378
            return False
2379
        return True
2380
1910.2.15 by Aaron Bentley
Back out inter.get changes, make optimizers an ordered list
2381
2382
class InterSameDataRepository(InterRepository):
2383
    """Code for converting between repositories that represent the same data.
2384
    
2385
    Data format and model must match for this to work.
2386
    """
2387
2241.1.6 by Martin Pool
Move Knit repositories into the submodule bzrlib.repofmt.knitrepo and
2388
    @classmethod
2241.1.7 by Martin Pool
rename method
2389
    def _get_repo_format_to_test(self):
2814.1.1 by Robert Collins
* Pushing, pulling and branching branches with subtree references was not
2390
        """Repository format for testing with.
2391
        
2392
        InterSameData can pull from subtree to subtree and from non-subtree to
2393
        non-subtree, so we test this with the richest repository format.
2394
        """
2395
        from bzrlib.repofmt import knitrepo
2396
        return knitrepo.RepositoryFormatKnit3()
1910.2.15 by Aaron Bentley
Back out inter.get changes, make optimizers an ordered list
2397
1910.2.14 by Aaron Bentley
Fail when trying to use interrepository on Knit2 and Knit1
2398
    @staticmethod
2399
    def is_compatible(source, target):
2592.3.28 by Robert Collins
Make InterKnitOptimiser be used between any same-model knit repository.
2400
        return InterRepository._same_model(source, target)
1910.2.14 by Aaron Bentley
Fail when trying to use interrepository on Knit2 and Knit1
2401
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.
2402
    @needs_write_lock
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
2403
    def copy_content(self, revision_id=None):
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.
2404
        """Make a complete copy of the content in self into destination.
2440.1.1 by Martin Pool
Add new Repository.sprout,
2405
2406
        This copies both the repository's revision data, and configuration information
2407
        such as the make_working_trees setting.
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.
2408
        
2409
        This is a destructive operation! Do not use it on existing 
2410
        repositories.
2411
2412
        :param revision_id: Only copy the content needed to construct
2413
                            revision_id and its parents.
2414
        """
2415
        try:
2416
            self.target.set_make_working_trees(self.source.make_working_trees())
2417
        except NotImplementedError:
2418
            pass
1759.2.2 by Jelmer Vernooij
Revert some of my spelling fixes and fix some typos after review by Aaron.
2419
        # but don't bother fetching if we have the needed data now.
1996.3.20 by John Arbash Meinel
[merge] bzr.dev 2063
2420
        if (revision_id not in (None, _mod_revision.NULL_REVISION) and 
1534.1.33 by Robert Collins
Move copy_content_into into InterRepository and InterWeaveRepo, and disable the default codepath test as we have optimised paths for all current combinations.
2421
            self.target.has_revision(revision_id)):
2422
            return
2423
        self.target.fetch(self.source, revision_id=revision_id)
2424
2425
    @needs_write_lock
2949.1.2 by Robert Collins
* Fetch with pack repositories will no longer read the entire history graph.
2426
    def fetch(self, revision_id=None, pb=None, find_ghosts=False):
1910.7.20 by Andrew Bennetts
Merge from bzr.dev
2427
        """See InterRepository.fetch()."""
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
2428
        from bzrlib.fetch import GenericRepoFetcher
1534.1.31 by Robert Collins
Deprecated fetch.fetch and fetch.greedy_fetch for branch.fetch, and move the Repository.fetch internals to InterRepo and InterWeaveRepo.
2429
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
2858.2.1 by Martin Pool
Remove most calls to safe_file_id and safe_revision_id.
2430
               self.source, self.source._format, self.target,
1910.2.15 by Aaron Bentley
Back out inter.get changes, make optimizers an ordered list
2431
               self.target._format)
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
2432
        f = GenericRepoFetcher(to_repository=self.target,
2433
                               from_repository=self.source,
2434
                               last_revision=revision_id,
3172.4.1 by Robert Collins
* Fetching via bzr+ssh will no longer fill ghosts by default (this is
2435
                               pb=pb, find_ghosts=find_ghosts)
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.
2436
        return f.count_copied, f.failed_revisions
1534.1.31 by Robert Collins
Deprecated fetch.fetch and fetch.greedy_fetch for branch.fetch, and move the Repository.fetch internals to InterRepo and InterWeaveRepo.
2437
1910.2.15 by Aaron Bentley
Back out inter.get changes, make optimizers an ordered list
2438
2241.1.12 by Martin Pool
Restore InterWeaveRepo
2439
class InterWeaveRepo(InterSameDataRepository):
2850.3.1 by Robert Collins
Move various weave specific code out of the base Repository class to weaverepo.py.
2440
    """Optimised code paths between Weave based repositories.
2441
    
2442
    This should be in bzrlib/repofmt/weaverepo.py but we have not yet
2443
    implemented lazy inter-object optimisation.
2444
    """
2241.1.12 by Martin Pool
Restore InterWeaveRepo
2445
2241.1.13 by Martin Pool
Re-register InterWeaveRepo, fix test integration, add test for it
2446
    @classmethod
2241.1.12 by Martin Pool
Restore InterWeaveRepo
2447
    def _get_repo_format_to_test(self):
2448
        from bzrlib.repofmt import weaverepo
2449
        return weaverepo.RepositoryFormat7()
2450
2451
    @staticmethod
2452
    def is_compatible(source, target):
2453
        """Be compatible with known Weave formats.
2454
        
2455
        We don't test for the stores being of specific types because that
2456
        could lead to confusing results, and there is no need to be 
2457
        overly general.
2458
        """
2459
        from bzrlib.repofmt.weaverepo import (
2460
                RepositoryFormat5,
2461
                RepositoryFormat6,
2462
                RepositoryFormat7,
2463
                )
2464
        try:
2465
            return (isinstance(source._format, (RepositoryFormat5,
2466
                                                RepositoryFormat6,
2467
                                                RepositoryFormat7)) and
2468
                    isinstance(target._format, (RepositoryFormat5,
2469
                                                RepositoryFormat6,
2470
                                                RepositoryFormat7)))
2471
        except AttributeError:
2472
            return False
2473
    
2474
    @needs_write_lock
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
2475
    def copy_content(self, revision_id=None):
2241.1.12 by Martin Pool
Restore InterWeaveRepo
2476
        """See InterRepository.copy_content()."""
2477
        # weave specific optimised path:
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
2478
        try:
2479
            self.target.set_make_working_trees(self.source.make_working_trees())
3349.1.2 by Aaron Bentley
Change ValueError to RepositoryUpgradeRequired
2480
        except (errors.RepositoryUpgradeRequired, NotImplemented):
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
2481
            pass
2482
        # FIXME do not peek!
3407.2.14 by Martin Pool
Remove more cases of getting transport via control_files
2483
        if self.source._transport.listable():
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
2484
            pb = ui.ui_factory.nested_progress_bar()
2241.1.12 by Martin Pool
Restore InterWeaveRepo
2485
            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.
2486
                self.target.texts.insert_record_stream(
2487
                    self.source.texts.get_record_stream(
2488
                        self.source.texts.keys(), 'topological', False))
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
2489
                pb.update('copying inventory', 0, 1)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2490
                self.target.inventories.insert_record_stream(
2491
                    self.source.inventories.get_record_stream(
2492
                        self.source.inventories.keys(), 'topological', False))
2493
                self.target.signatures.insert_record_stream(
2494
                    self.source.signatures.get_record_stream(
2495
                        self.source.signatures.keys(),
2496
                        'unordered', True))
2497
                self.target.revisions.insert_record_stream(
2498
                    self.source.revisions.get_record_stream(
2499
                        self.source.revisions.keys(),
2500
                        'topological', True))
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
2501
            finally:
2502
                pb.finished()
2503
        else:
2241.1.12 by Martin Pool
Restore InterWeaveRepo
2504
            self.target.fetch(self.source, revision_id=revision_id)
2505
2506
    @needs_write_lock
2949.1.2 by Robert Collins
* Fetch with pack repositories will no longer read the entire history graph.
2507
    def fetch(self, revision_id=None, pb=None, find_ghosts=False):
2241.1.12 by Martin Pool
Restore InterWeaveRepo
2508
        """See InterRepository.fetch()."""
2509
        from bzrlib.fetch import GenericRepoFetcher
2510
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
2511
               self.source, self.source._format, self.target, self.target._format)
2512
        f = GenericRepoFetcher(to_repository=self.target,
2513
                               from_repository=self.source,
2514
                               last_revision=revision_id,
3172.4.1 by Robert Collins
* Fetching via bzr+ssh will no longer fill ghosts by default (this is
2515
                               pb=pb, find_ghosts=find_ghosts)
2241.1.12 by Martin Pool
Restore InterWeaveRepo
2516
        return f.count_copied, f.failed_revisions
2517
2518
    @needs_read_lock
3184.1.8 by Robert Collins
* ``InterRepository.missing_revision_ids`` is now deprecated in favour of
2519
    def search_missing_revision_ids(self, revision_id=None, find_ghosts=True):
2241.1.12 by Martin Pool
Restore InterWeaveRepo
2520
        """See InterRepository.missing_revision_ids()."""
2521
        # we want all revisions to satisfy revision_id in source.
2522
        # but we don't want to stat every file here and there.
2523
        # we want then, all revisions other needs to satisfy revision_id 
2524
        # checked, but not those that we have locally.
2525
        # so the first thing is to get a subset of the revisions to 
2526
        # satisfy revision_id in source, and then eliminate those that
2527
        # we do already have. 
2528
        # this is slow on high latency connection to self, but as as this
2529
        # disk format scales terribly for push anyway due to rewriting 
2530
        # inventory.weave, this is considered acceptable.
2531
        # - RBC 20060209
2532
        if revision_id is not None:
2533
            source_ids = self.source.get_ancestry(revision_id)
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
2534
            if source_ids[0] is not None:
2535
                raise AssertionError()
2241.1.12 by Martin Pool
Restore InterWeaveRepo
2536
            source_ids.pop(0)
2537
        else:
2538
            source_ids = self.source._all_possible_ids()
2539
        source_ids_set = set(source_ids)
2540
        # source_ids is the worst possible case we may need to pull.
2541
        # now we want to filter source_ids against what we actually
2542
        # have in target, but don't try to check for existence where we know
2543
        # we do not have a revision as that would be pointless.
2544
        target_ids = set(self.target._all_possible_ids())
2545
        possibly_present_revisions = target_ids.intersection(source_ids_set)
3184.1.8 by Robert Collins
* ``InterRepository.missing_revision_ids`` is now deprecated in favour of
2546
        actually_present_revisions = set(
2547
            self.target._eliminate_revisions_not_present(possibly_present_revisions))
2241.1.12 by Martin Pool
Restore InterWeaveRepo
2548
        required_revisions = source_ids_set.difference(actually_present_revisions)
2549
        if revision_id is not None:
2550
            # we used get_ancestry to determine source_ids then we are assured all
2551
            # revisions referenced are present as they are installed in topological order.
2552
            # and the tip revision was validated by get_ancestry.
3184.1.8 by Robert Collins
* ``InterRepository.missing_revision_ids`` is now deprecated in favour of
2553
            result_set = required_revisions
2241.1.12 by Martin Pool
Restore InterWeaveRepo
2554
        else:
2555
            # if we just grabbed the possibly available ids, then 
2556
            # we only have an estimate of whats available and need to validate
2557
            # that against the revision records.
3184.1.8 by Robert Collins
* ``InterRepository.missing_revision_ids`` is now deprecated in favour of
2558
            result_set = set(
2559
                self.source._eliminate_revisions_not_present(required_revisions))
3184.1.9 by Robert Collins
* ``Repository.get_data_stream`` is now deprecated in favour of
2560
        return self.source.revision_ids_to_search_result(result_set)
2241.1.12 by Martin Pool
Restore InterWeaveRepo
2561
2562
1910.2.15 by Aaron Bentley
Back out inter.get changes, make optimizers an ordered list
2563
class InterKnitRepo(InterSameDataRepository):
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
2564
    """Optimised code paths between Knit based repositories."""
2565
2241.1.6 by Martin Pool
Move Knit repositories into the submodule bzrlib.repofmt.knitrepo and
2566
    @classmethod
2241.1.7 by Martin Pool
rename method
2567
    def _get_repo_format_to_test(self):
2241.1.6 by Martin Pool
Move Knit repositories into the submodule bzrlib.repofmt.knitrepo and
2568
        from bzrlib.repofmt import knitrepo
2569
        return knitrepo.RepositoryFormatKnit1()
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
2570
2571
    @staticmethod
2572
    def is_compatible(source, target):
2573
        """Be compatible with known Knit formats.
2574
        
1759.2.2 by Jelmer Vernooij
Revert some of my spelling fixes and fix some typos after review by Aaron.
2575
        We don't test for the stores being of specific types because that
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
2576
        could lead to confusing results, and there is no need to be 
2577
        overly general.
2578
        """
2592.3.28 by Robert Collins
Make InterKnitOptimiser be used between any same-model knit repository.
2579
        from bzrlib.repofmt.knitrepo import RepositoryFormatKnit
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
2580
        try:
2592.3.28 by Robert Collins
Make InterKnitOptimiser be used between any same-model knit repository.
2581
            are_knits = (isinstance(source._format, RepositoryFormatKnit) and
2582
                isinstance(target._format, RepositoryFormatKnit))
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
2583
        except AttributeError:
2584
            return False
2592.3.28 by Robert Collins
Make InterKnitOptimiser be used between any same-model knit repository.
2585
        return are_knits and InterRepository._same_model(source, target)
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
2586
2587
    @needs_write_lock
2949.1.2 by Robert Collins
* Fetch with pack repositories will no longer read the entire history graph.
2588
    def fetch(self, revision_id=None, pb=None, find_ghosts=False):
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
2589
        """See InterRepository.fetch()."""
2590
        from bzrlib.fetch import KnitRepoFetcher
2591
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
2592
               self.source, self.source._format, self.target, self.target._format)
2593
        f = KnitRepoFetcher(to_repository=self.target,
2594
                            from_repository=self.source,
2595
                            last_revision=revision_id,
3172.4.1 by Robert Collins
* Fetching via bzr+ssh will no longer fill ghosts by default (this is
2596
                            pb=pb, find_ghosts=find_ghosts)
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
2597
        return f.count_copied, f.failed_revisions
2598
2599
    @needs_read_lock
3184.1.8 by Robert Collins
* ``InterRepository.missing_revision_ids`` is now deprecated in favour of
2600
    def search_missing_revision_ids(self, revision_id=None, find_ghosts=True):
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
2601
        """See InterRepository.missing_revision_ids()."""
2602
        if revision_id is not None:
2603
            source_ids = self.source.get_ancestry(revision_id)
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
2604
            if source_ids[0] is not None:
2605
                raise AssertionError()
1668.1.14 by Martin Pool
merge olaf - InvalidRevisionId fixes
2606
            source_ids.pop(0)
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
2607
        else:
2850.3.1 by Robert Collins
Move various weave specific code out of the base Repository class to weaverepo.py.
2608
            source_ids = self.source.all_revision_ids()
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
2609
        source_ids_set = set(source_ids)
2610
        # source_ids is the worst possible case we may need to pull.
2611
        # now we want to filter source_ids against what we actually
1759.2.2 by Jelmer Vernooij
Revert some of my spelling fixes and fix some typos after review by Aaron.
2612
        # have in target, but don't try to check for existence where we know
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
2613
        # we do not have a revision as that would be pointless.
2850.3.1 by Robert Collins
Move various weave specific code out of the base Repository class to weaverepo.py.
2614
        target_ids = set(self.target.all_revision_ids())
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
2615
        possibly_present_revisions = target_ids.intersection(source_ids_set)
3184.1.8 by Robert Collins
* ``InterRepository.missing_revision_ids`` is now deprecated in favour of
2616
        actually_present_revisions = set(
2617
            self.target._eliminate_revisions_not_present(possibly_present_revisions))
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
2618
        required_revisions = source_ids_set.difference(actually_present_revisions)
2619
        if revision_id is not None:
2620
            # we used get_ancestry to determine source_ids then we are assured all
2621
            # revisions referenced are present as they are installed in topological order.
2622
            # and the tip revision was validated by get_ancestry.
3184.1.8 by Robert Collins
* ``InterRepository.missing_revision_ids`` is now deprecated in favour of
2623
            result_set = required_revisions
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
2624
        else:
2625
            # if we just grabbed the possibly available ids, then 
2626
            # we only have an estimate of whats available and need to validate
2627
            # that against the revision records.
3184.1.8 by Robert Collins
* ``InterRepository.missing_revision_ids`` is now deprecated in favour of
2628
            result_set = set(
2629
                self.source._eliminate_revisions_not_present(required_revisions))
3184.1.9 by Robert Collins
* ``Repository.get_data_stream`` is now deprecated in favour of
2630
        return self.source.revision_ids_to_search_result(result_set)
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
2631
1910.2.17 by Aaron Bentley
Get fetching from 1 to 2 under test
2632
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
2633
class InterPackRepo(InterSameDataRepository):
2634
    """Optimised code paths between Pack based repositories."""
2635
2636
    @classmethod
2637
    def _get_repo_format_to_test(self):
2638
        from bzrlib.repofmt import pack_repo
2592.3.224 by Martin Pool
Rename GraphKnitRepository etc to KnitPackRepository
2639
        return pack_repo.RepositoryFormatKnitPack1()
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
2640
2641
    @staticmethod
2642
    def is_compatible(source, target):
2643
        """Be compatible with known Pack formats.
2644
        
2645
        We don't test for the stores being of specific types because that
2646
        could lead to confusing results, and there is no need to be 
2647
        overly general.
2648
        """
2649
        from bzrlib.repofmt.pack_repo import RepositoryFormatPack
2650
        try:
2592.3.91 by Robert Collins
Incrementally closing in on a correct fetch for packs.
2651
            are_packs = (isinstance(source._format, RepositoryFormatPack) and
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
2652
                isinstance(target._format, RepositoryFormatPack))
2653
        except AttributeError:
2654
            return False
2592.3.91 by Robert Collins
Incrementally closing in on a correct fetch for packs.
2655
        return are_packs and InterRepository._same_model(source, target)
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
2656
2657
    @needs_write_lock
2949.1.2 by Robert Collins
* Fetch with pack repositories will no longer read the entire history graph.
2658
    def fetch(self, revision_id=None, pb=None, find_ghosts=False):
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
2659
        """See InterRepository.fetch()."""
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
2660
        from bzrlib.repofmt.pack_repo import Packer
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
2661
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
2662
               self.source, self.source._format, self.target, self.target._format)
2592.3.90 by Robert Collins
Slightly broken, but branch and fetch performance is now roughly on par (for bzr.dev) with knits - should be much faster for large repos.
2663
        self.count_copied = 0
2664
        if revision_id is None:
2665
            # TODO:
2666
            # everything to do - use pack logic
2667
            # to fetch from all packs to one without
2592.3.93 by Robert Collins
Steps toward filtering revisions/inventories/texts during fetch.
2668
            # inventory parsing etc, IFF nothing to be copied is in the target.
2592.3.90 by Robert Collins
Slightly broken, but branch and fetch performance is now roughly on par (for bzr.dev) with knits - should be much faster for large repos.
2669
            # till then:
2670
            revision_ids = self.source.all_revision_ids()
1551.19.36 by Aaron Bentley
Prevent fetch all from causing pack collisions
2671
            revision_keys = [(revid,) for revid in revision_ids]
2672
            index = self.target._pack_collection.revision_index.combined_index
2673
            present_revision_ids = set(item[1][0] for item in
2674
                index.iter_entries(revision_keys))
2675
            revision_ids = set(revision_ids) - present_revision_ids
2592.3.93 by Robert Collins
Steps toward filtering revisions/inventories/texts during fetch.
2676
            # implementing the TODO will involve:
2677
            # - detecting when all of a pack is selected
2678
            # - avoiding as much as possible pre-selection, so the
2679
            # more-core routines such as create_pack_from_packs can filter in
2680
            # a just-in-time fashion. (though having a HEADS list on a
2681
            # repository might make this a lot easier, because we could
2682
            # sensibly detect 'new revisions' without doing a full index scan.
2592.3.91 by Robert Collins
Incrementally closing in on a correct fetch for packs.
2683
        elif _mod_revision.is_null(revision_id):
2684
            # nothing to do:
3010.1.5 by Robert Collins
Test that missing_revision_ids handles the case of the source not having the requested revision correctly with and without find_ghosts.
2685
            return (0, [])
2592.3.90 by Robert Collins
Slightly broken, but branch and fetch performance is now roughly on par (for bzr.dev) with knits - should be much faster for large repos.
2686
        else:
2687
            try:
3184.1.8 by Robert Collins
* ``InterRepository.missing_revision_ids`` is now deprecated in favour of
2688
                revision_ids = self.search_missing_revision_ids(revision_id,
2689
                    find_ghosts=find_ghosts).get_keys()
2592.3.90 by Robert Collins
Slightly broken, but branch and fetch performance is now roughly on par (for bzr.dev) with knits - should be much faster for large repos.
2690
            except errors.NoSuchRevision:
2691
                raise errors.InstallFailed([revision_id])
1551.19.41 by Aaron Bentley
Accelerate no-op pull
2692
            if len(revision_ids) == 0:
2693
                return (0, [])
2592.3.232 by Martin Pool
Disambiguate two member variables called _packs into _packs_by_name and _pack_collection
2694
        packs = self.source._pack_collection.all_packs()
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
2695
        pack = Packer(self.target._pack_collection, packs, '.fetch',
2696
            revision_ids).pack()
2592.3.91 by Robert Collins
Incrementally closing in on a correct fetch for packs.
2697
        if pack is not None:
2592.3.232 by Martin Pool
Disambiguate two member variables called _packs into _packs_by_name and _pack_collection
2698
            self.target._pack_collection._save_pack_names()
2592.3.108 by Robert Collins
Autopack after pack to pack fetching too.
2699
            # Trigger an autopack. This may duplicate effort as we've just done
2700
            # a pack creation, but for now it is simpler to think about as
2701
            # 'upload data, then repack if needed'.
2592.3.232 by Martin Pool
Disambiguate two member variables called _packs into _packs_by_name and _pack_collection
2702
            self.target._pack_collection.autopack()
3010.1.5 by Robert Collins
Test that missing_revision_ids handles the case of the source not having the requested revision correctly with and without find_ghosts.
2703
            return (pack.get_revision_count(), [])
2592.3.91 by Robert Collins
Incrementally closing in on a correct fetch for packs.
2704
        else:
3010.1.5 by Robert Collins
Test that missing_revision_ids handles the case of the source not having the requested revision correctly with and without find_ghosts.
2705
            return (0, [])
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
2706
2707
    @needs_read_lock
3184.1.8 by Robert Collins
* ``InterRepository.missing_revision_ids`` is now deprecated in favour of
2708
    def search_missing_revision_ids(self, revision_id=None, find_ghosts=True):
2949.1.2 by Robert Collins
* Fetch with pack repositories will no longer read the entire history graph.
2709
        """See InterRepository.missing_revision_ids().
2710
        
3172.4.1 by Robert Collins
* Fetching via bzr+ssh will no longer fill ghosts by default (this is
2711
        :param find_ghosts: Find ghosts throughout the ancestry of
2949.1.2 by Robert Collins
* Fetch with pack repositories will no longer read the entire history graph.
2712
            revision_id.
2713
        """
2714
        if not find_ghosts and revision_id is not None:
3172.4.4 by Robert Collins
Review feedback.
2715
            return self._walk_to_common_revisions([revision_id])
2949.1.2 by Robert Collins
* Fetch with pack repositories will no longer read the entire history graph.
2716
        elif revision_id is not None:
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
2717
            source_ids = self.source.get_ancestry(revision_id)
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
2718
            if source_ids[0] is not None:
2719
                raise AssertionError()
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
2720
            source_ids.pop(0)
2721
        else:
2592.3.151 by Robert Collins
Use the revision index, not the inventory index, for missing and fetch operations.
2722
            source_ids = self.source.all_revision_ids()
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
2723
        # source_ids is the worst possible case we may need to pull.
2724
        # now we want to filter source_ids against what we actually
2725
        # have in target, but don't try to check for existence where we know
2726
        # we do not have a revision as that would be pointless.
2592.3.151 by Robert Collins
Use the revision index, not the inventory index, for missing and fetch operations.
2727
        target_ids = set(self.target.all_revision_ids())
3184.1.8 by Robert Collins
* ``InterRepository.missing_revision_ids`` is now deprecated in favour of
2728
        result_set = set(source_ids).difference(target_ids)
3184.1.9 by Robert Collins
* ``Repository.get_data_stream`` is now deprecated in favour of
2729
        return self.source.revision_ids_to_search_result(result_set)
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
2730
2731
1910.2.24 by Aaron Bentley
Got intra-repository fetch working between model1 and 2 for all types
2732
class InterModel1and2(InterRepository):
2733
2241.1.6 by Martin Pool
Move Knit repositories into the submodule bzrlib.repofmt.knitrepo and
2734
    @classmethod
2241.1.7 by Martin Pool
rename method
2735
    def _get_repo_format_to_test(self):
2241.1.6 by Martin Pool
Move Knit repositories into the submodule bzrlib.repofmt.knitrepo and
2736
        return None
1910.2.24 by Aaron Bentley
Got intra-repository fetch working between model1 and 2 for all types
2737
2738
    @staticmethod
2739
    def is_compatible(source, target):
2305.2.1 by Andrew Bennetts
Use repo.supports_rich_root() everywhere rather than
2740
        if not source.supports_rich_root() and target.supports_rich_root():
1910.2.24 by Aaron Bentley
Got intra-repository fetch working between model1 and 2 for all types
2741
            return True
2742
        else:
2743
            return False
2744
2745
    @needs_write_lock
2949.1.2 by Robert Collins
* Fetch with pack repositories will no longer read the entire history graph.
2746
    def fetch(self, revision_id=None, pb=None, find_ghosts=False):
1910.2.24 by Aaron Bentley
Got intra-repository fetch working between model1 and 2 for all types
2747
        """See InterRepository.fetch()."""
2748
        from bzrlib.fetch import Model1toKnit2Fetcher
2749
        f = Model1toKnit2Fetcher(to_repository=self.target,
2750
                                 from_repository=self.source,
2751
                                 last_revision=revision_id,
3172.4.1 by Robert Collins
* Fetching via bzr+ssh will no longer fill ghosts by default (this is
2752
                                 pb=pb, find_ghosts=find_ghosts)
1910.2.24 by Aaron Bentley
Got intra-repository fetch working between model1 and 2 for all types
2753
        return f.count_copied, f.failed_revisions
2754
1910.2.26 by Aaron Bentley
Fix up some test cases
2755
    @needs_write_lock
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
2756
    def copy_content(self, revision_id=None):
1910.2.26 by Aaron Bentley
Fix up some test cases
2757
        """Make a complete copy of the content in self into destination.
2758
        
2759
        This is a destructive operation! Do not use it on existing 
2760
        repositories.
2761
2762
        :param revision_id: Only copy the content needed to construct
2763
                            revision_id and its parents.
2764
        """
2765
        try:
2766
            self.target.set_make_working_trees(self.source.make_working_trees())
2767
        except NotImplementedError:
2768
            pass
2769
        # but don't bother fetching if we have the needed data now.
1996.3.20 by John Arbash Meinel
[merge] bzr.dev 2063
2770
        if (revision_id not in (None, _mod_revision.NULL_REVISION) and 
1910.2.26 by Aaron Bentley
Fix up some test cases
2771
            self.target.has_revision(revision_id)):
2772
            return
2773
        self.target.fetch(self.source, revision_id=revision_id)
2774
1910.2.24 by Aaron Bentley
Got intra-repository fetch working between model1 and 2 for all types
2775
1910.2.17 by Aaron Bentley
Get fetching from 1 to 2 under test
2776
class InterKnit1and2(InterKnitRepo):
2777
2241.1.6 by Martin Pool
Move Knit repositories into the submodule bzrlib.repofmt.knitrepo and
2778
    @classmethod
2241.1.7 by Martin Pool
rename method
2779
    def _get_repo_format_to_test(self):
2241.1.6 by Martin Pool
Move Knit repositories into the submodule bzrlib.repofmt.knitrepo and
2780
        return None
1910.2.24 by Aaron Bentley
Got intra-repository fetch working between model1 and 2 for all types
2781
1910.2.17 by Aaron Bentley
Get fetching from 1 to 2 under test
2782
    @staticmethod
2783
    def is_compatible(source, target):
2255.2.211 by Robert Collins
Remove knit2 repository format- it has never been supported.
2784
        """Be compatible with Knit1 source and Knit3 target"""
2785
        from bzrlib.repofmt.knitrepo import RepositoryFormatKnit3
1910.2.17 by Aaron Bentley
Get fetching from 1 to 2 under test
2786
        try:
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
2787
            from bzrlib.repofmt.knitrepo import (RepositoryFormatKnit1,
2788
                RepositoryFormatKnit3)
3152.2.1 by Robert Collins
* A new repository format 'development' has been added. This format will
2789
            from bzrlib.repofmt.pack_repo import (
2790
                RepositoryFormatKnitPack1,
2791
                RepositoryFormatKnitPack3,
2792
                RepositoryFormatPackDevelopment0,
2793
                RepositoryFormatPackDevelopment0Subtree,
2794
                )
2795
            nosubtrees = (
2796
                RepositoryFormatKnit1,
2797
                RepositoryFormatKnitPack1,
2798
                RepositoryFormatPackDevelopment0,
2799
                )
2800
            subtrees = (
2801
                RepositoryFormatKnit3,
2802
                RepositoryFormatKnitPack3,
2803
                RepositoryFormatPackDevelopment0Subtree,
2804
                )
2805
            return (isinstance(source._format, nosubtrees) and
2806
                isinstance(target._format, subtrees))
1910.2.17 by Aaron Bentley
Get fetching from 1 to 2 under test
2807
        except AttributeError:
2808
            return False
2809
2810
    @needs_write_lock
2949.1.2 by Robert Collins
* Fetch with pack repositories will no longer read the entire history graph.
2811
    def fetch(self, revision_id=None, pb=None, find_ghosts=False):
1910.2.17 by Aaron Bentley
Get fetching from 1 to 2 under test
2812
        """See InterRepository.fetch()."""
2813
        from bzrlib.fetch import Knit1to2Fetcher
2814
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
2815
               self.source, self.source._format, self.target, 
2816
               self.target._format)
2817
        f = Knit1to2Fetcher(to_repository=self.target,
2818
                            from_repository=self.source,
2819
                            last_revision=revision_id,
3172.4.1 by Robert Collins
* Fetching via bzr+ssh will no longer fill ghosts by default (this is
2820
                            pb=pb, find_ghosts=find_ghosts)
1910.2.17 by Aaron Bentley
Get fetching from 1 to 2 under test
2821
        return f.count_copied, f.failed_revisions
2822
2823
2996.2.1 by Aaron Bentley
Add KnitRepositoryFormat4
2824
class InterDifferingSerializer(InterKnitRepo):
2825
2826
    @classmethod
2827
    def _get_repo_format_to_test(self):
2828
        return None
2829
2830
    @staticmethod
2831
    def is_compatible(source, target):
2832
        """Be compatible with Knit2 source and Knit3 target"""
2833
        if source.supports_rich_root() != target.supports_rich_root():
2834
            return False
2835
        # Ideally, we'd support fetching if the source had no tree references
2836
        # even if it supported them...
2837
        if (getattr(source, '_format.supports_tree_reference', False) and
2838
            not getattr(target, '_format.supports_tree_reference', False)):
2839
            return False
2840
        return True
2841
2842
    @needs_write_lock
2843
    def fetch(self, revision_id=None, pb=None, find_ghosts=False):
2844
        """See InterRepository.fetch()."""
3184.1.9 by Robert Collins
* ``Repository.get_data_stream`` is now deprecated in favour of
2845
        revision_ids = self.target.search_missing_revision_ids(self.source,
3184.1.8 by Robert Collins
* ``InterRepository.missing_revision_ids`` is now deprecated in favour of
2846
            revision_id, find_ghosts=find_ghosts).get_keys()
2847
        revision_ids = tsort.topo_sort(
3184.1.9 by Robert Collins
* ``Repository.get_data_stream`` is now deprecated in favour of
2848
            self.source.get_graph().get_parent_map(revision_ids))
2996.2.2 by Aaron Bentley
Create install_revisions function
2849
        def revisions_iterator():
2850
            for current_revision_id in revision_ids:
2851
                revision = self.source.get_revision(current_revision_id)
2852
                tree = self.source.revision_tree(current_revision_id)
2853
                try:
2854
                    signature = self.source.get_signature_text(
2855
                        current_revision_id)
2856
                except errors.NoSuchRevision:
2857
                    signature = None
2858
                yield revision, tree, signature
3146.6.1 by Aaron Bentley
InterDifferingSerializer shows a progress bar
2859
        if pb is None:
2860
            my_pb = ui.ui_factory.nested_progress_bar()
2861
            pb = my_pb
2862
        else:
2863
            my_pb = None
2864
        try:
2865
            install_revisions(self.target, revisions_iterator(),
2866
                              len(revision_ids), pb)
2867
        finally:
2868
            if my_pb is not None:
2869
                my_pb.finished()
2996.2.1 by Aaron Bentley
Add KnitRepositoryFormat4
2870
        return len(revision_ids), 0
2871
2872
2535.3.12 by Andrew Bennetts
Add a first cut of a get_data_stream method to Repository.
2873
class InterOtherToRemote(InterRepository):
2874
2875
    def __init__(self, source, target):
2876
        InterRepository.__init__(self, source, target)
2877
        self._real_inter = None
2878
2879
    @staticmethod
2880
    def is_compatible(source, target):
2881
        if isinstance(target, remote.RemoteRepository):
2882
            return True
2883
        return False
2884
2885
    def _ensure_real_inter(self):
2886
        if self._real_inter is None:
2887
            self.target._ensure_real()
2888
            real_target = self.target._real_repository
2889
            self._real_inter = InterRepository.get(self.source, real_target)
2890
    
2891
    def copy_content(self, revision_id=None):
2892
        self._ensure_real_inter()
2893
        self._real_inter.copy_content(revision_id=revision_id)
2894
2949.1.2 by Robert Collins
* Fetch with pack repositories will no longer read the entire history graph.
2895
    def fetch(self, revision_id=None, pb=None, find_ghosts=False):
2535.3.12 by Andrew Bennetts
Add a first cut of a get_data_stream method to Repository.
2896
        self._ensure_real_inter()
3172.4.1 by Robert Collins
* Fetching via bzr+ssh will no longer fill ghosts by default (this is
2897
        self._real_inter.fetch(revision_id=revision_id, pb=pb,
2898
            find_ghosts=find_ghosts)
2535.3.12 by Andrew Bennetts
Add a first cut of a get_data_stream method to Repository.
2899
2900
    @classmethod
2901
    def _get_repo_format_to_test(self):
2902
        return None
2903
2904
2996.2.1 by Aaron Bentley
Add KnitRepositoryFormat4
2905
InterRepository.register_optimiser(InterDifferingSerializer)
1910.2.15 by Aaron Bentley
Back out inter.get changes, make optimizers an ordered list
2906
InterRepository.register_optimiser(InterSameDataRepository)
2241.1.13 by Martin Pool
Re-register InterWeaveRepo, fix test integration, add test for it
2907
InterRepository.register_optimiser(InterWeaveRepo)
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
2908
InterRepository.register_optimiser(InterKnitRepo)
1910.2.24 by Aaron Bentley
Got intra-repository fetch working between model1 and 2 for all types
2909
InterRepository.register_optimiser(InterModel1and2)
1910.2.17 by Aaron Bentley
Get fetching from 1 to 2 under test
2910
InterRepository.register_optimiser(InterKnit1and2)
2592.3.90 by Robert Collins
Slightly broken, but branch and fetch performance is now roughly on par (for bzr.dev) with knits - should be much faster for large repos.
2911
InterRepository.register_optimiser(InterPackRepo)
2535.3.12 by Andrew Bennetts
Add a first cut of a get_data_stream method to Repository.
2912
InterRepository.register_optimiser(InterOtherToRemote)
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.
2913
2914
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.
2915
class CopyConverter(object):
2916
    """A repository conversion tool which just performs a copy of the content.
2917
    
2918
    This is slow but quite reliable.
2919
    """
2920
2921
    def __init__(self, target_format):
2922
        """Create a CopyConverter.
2923
2924
        :param target_format: The format the resulting repository should be.
2925
        """
2926
        self.target_format = target_format
2927
        
2928
    def convert(self, repo, pb):
2929
        """Perform the conversion of to_convert, giving feedback via pb.
2930
2931
        :param to_convert: The disk object to convert.
2932
        :param pb: a progress bar to use for progress information.
2933
        """
2934
        self.pb = pb
2935
        self.count = 0
1596.2.22 by Robert Collins
Fetch changes to use new pb.
2936
        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.
2937
        # this is only useful with metadir layouts - separated repo content.
2938
        # trigger an assertion if not such
2939
        repo._format.get_format_string()
2940
        self.repo_dir = repo.bzrdir
2941
        self.step('Moving repository to repository.backup')
2942
        self.repo_dir.transport.move('repository', 'repository.backup')
2943
        backup_transport =  self.repo_dir.transport.clone('repository.backup')
1910.2.12 by Aaron Bentley
Implement knit repo format 2
2944
        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.
2945
        self.source_repo = repo._format.open(self.repo_dir,
2946
            _found=True,
2947
            _override_transport=backup_transport)
2948
        self.step('Creating new repository')
2949
        converted = self.target_format.initialize(self.repo_dir,
2950
                                                  self.source_repo.is_shared())
2951
        converted.lock_write()
2952
        try:
2953
            self.step('Copying content into repository.')
2954
            self.source_repo.copy_content_into(converted)
2955
        finally:
2956
            converted.unlock()
2957
        self.step('Deleting old repository content.')
2958
        self.repo_dir.transport.delete_tree('repository.backup')
2959
        self.pb.note('repository converted')
2960
2961
    def step(self, message):
2962
        """Update the pb by a step."""
2963
        self.count +=1
2964
        self.pb.update(message, self.count, self.total)
1596.1.1 by Martin Pool
Use simple xml unescaping rather than importing xml.sax
2965
2966
1843.2.4 by Aaron Bentley
Switch to John Meinel's _unescape_xml implementation
2967
_unescape_map = {
2968
    'apos':"'",
2969
    'quot':'"',
2970
    'amp':'&',
2971
    'lt':'<',
2972
    'gt':'>'
2973
}
2974
2975
2976
def _unescaper(match, _map=_unescape_map):
2294.1.2 by John Arbash Meinel
Track down and add tests that all tree.commit() can handle
2977
    code = match.group(1)
2978
    try:
2979
        return _map[code]
2980
    except KeyError:
2981
        if not code.startswith('#'):
2982
            raise
2294.1.10 by John Arbash Meinel
Switch all apis over to utf8 file ids. All tests pass
2983
        return unichr(int(code[1:])).encode('utf8')
1843.2.4 by Aaron Bentley
Switch to John Meinel's _unescape_xml implementation
2984
2985
2986
_unescape_re = None
2987
2988
1596.1.1 by Martin Pool
Use simple xml unescaping rather than importing xml.sax
2989
def _unescape_xml(data):
1843.2.4 by Aaron Bentley
Switch to John Meinel's _unescape_xml implementation
2990
    """Unescape predefined XML entities in a string of data."""
2991
    global _unescape_re
2992
    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.
2993
        _unescape_re = re.compile('\&([^;]*);')
1843.2.4 by Aaron Bentley
Switch to John Meinel's _unescape_xml implementation
2994
    return _unescape_re.sub(_unescaper, data)
2745.6.3 by Aaron Bentley
Implement versionedfile checking for bzr check
2995
2996
3036.1.3 by Robert Collins
Privatise VersionedFileChecker.
2997
class _VersionedFileChecker(object):
2745.6.47 by Andrew Bennetts
Move check_parents out of VersionedFile.
2998
2988.1.6 by Robert Collins
Change the contract for VersionedFileChecker to consolidate related parameters rather than splitting them across two api calls. This allows better reuse of a single checker object.
2999
    def __init__(self, repository):
2745.6.47 by Andrew Bennetts
Move check_parents out of VersionedFile.
3000
        self.repository = repository
2988.1.8 by Robert Collins
Change check and reconcile to use the new _generate_text_key_index rather
3001
        self.text_index = self.repository._generate_text_key_index()
2745.6.49 by Andrew Bennetts
Get rid of bzrlib.repository._RevisionParentsProvider.
3002
    
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.
3003
    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.
3004
        """Calculate the correct parents for a file version according to
3005
        the inventories.
3006
        """
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
        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
3008
        if parent_keys == [_mod_revision.NULL_REVISION]:
3009
            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.
3010
        return tuple(parent_keys)
2745.6.47 by Andrew Bennetts
Move check_parents out of VersionedFile.
3011
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.
3012
    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.
3013
        """Check the parents stored in a versioned file are correct.
3014
3015
        It also detects file versions that are not referenced by their
3016
        corresponding revision's inventory.
3017
2927.2.14 by Andrew Bennetts
Tweaks suggested by review.
3018
        :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.
3019
            wrong_parents is a dict mapping {revision_id: (stored_parents,
3020
            correct_parents)} for each revision_id where the stored parents
2927.2.14 by Andrew Bennetts
Tweaks suggested by review.
3021
            are not correct.  dangling_file_versions is a set of (file_id,
3022
            revision_id) tuples for versions that are present in this versioned
3023
            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.
3024
        """
2927.2.3 by Andrew Bennetts
Add fulltexts to avoid bug 155730.
3025
        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.
3026
        self.file_ids = set([file_id for file_id, _ in
3027
            self.text_index.iterkeys()])
3028
        # text keys is now grouped by file_id
3029
        n_weaves = len(self.file_ids)
3030
        files_in_revisions = {}
3031
        revisions_of_files = {}
3032
        n_versions = len(self.text_index)
3033
        progress_bar.update('loading text store', 0, n_versions)
3034
        parent_map = self.repository.texts.get_parent_map(self.text_index)
3035
        # On unlistable transports this could well be empty/error...
3036
        text_keys = self.repository.texts.keys()
3037
        unused_keys = frozenset(text_keys) - set(self.text_index)
3038
        for num, key in enumerate(self.text_index.iterkeys()):
3039
            if progress_bar is not None:
3040
                progress_bar.update('checking text graph', num, n_versions)
3041
            correct_parents = self.calculate_file_version_parents(key)
2927.2.6 by Andrew Bennetts
Make some more check tests pass.
3042
            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.
3043
                knit_parents = parent_map[key]
3044
            except errors.RevisionNotPresent:
3045
                # Missing text!
3046
                knit_parents = None
3047
            if correct_parents != knit_parents:
3048
                wrong_parents[key] = (knit_parents, correct_parents)
3049
        return wrong_parents, unused_keys
3287.6.8 by Robert Collins
Reduce code duplication as per review.
3050
3051
3052
def _old_get_graph(repository, revision_id):
3053
    """DO NOT USE. That is all. I'm serious."""
3054
    graph = repository.get_graph()
3055
    revision_graph = dict(((key, value) for key, value in
3056
        graph.iter_ancestry([revision_id]) if value is not None))
3057
    return _strip_NULL_ghosts(revision_graph)
3058
3059
3060
def _strip_NULL_ghosts(revision_graph):
3061
    """Also don't use this. more compatibility code for unmigrated clients."""
3062
    # Filter ghosts, and null:
3063
    if _mod_revision.NULL_REVISION in revision_graph:
3064
        del revision_graph[_mod_revision.NULL_REVISION]
3065
    for key, parents in revision_graph.items():
3066
        revision_graph[key] = tuple(parent for parent in parents if parent
3067
            in revision_graph)
3068
    return revision_graph