/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,
2490.2.21 by Aaron Bentley
Rename graph to deprecated_graph
28
    deprecated_graph,
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
29
    errors,
2116.4.1 by John Arbash Meinel
Update file and revision id generators.
30
    generate_ids,
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
31
    gpg,
32
    graph,
2163.2.1 by John Arbash Meinel
Speed up the fileids_altered_by_revision_ids processing
33
    lazy_regex,
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
34
    lockable_files,
35
    lockdir,
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,
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
42
    ui,
43
    )
2520.4.54 by Aaron Bentley
Hang a create_bundle method off repository
44
from bzrlib.bundle import serializer
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
45
from bzrlib.revisiontree import RevisionTree
46
from bzrlib.store.versioned import VersionedFileStore
47
from bzrlib.store.text import TextStore
48
from bzrlib.testament import Testament
49
""")
50
1534.4.28 by Robert Collins
first cut at merge from integration.
51
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.
52
from bzrlib.inter import InterObject
1910.2.3 by Aaron Bentley
All tests pass
53
from bzrlib.inventory import Inventory, InventoryDirectory, ROOT_ID
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
54
from bzrlib.symbol_versioning import (
55
        deprecated_method,
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
56
        )
2745.1.1 by Robert Collins
Add a number of -Devil checkpoints.
57
from bzrlib.trace import mutter, mutter_callsite, note, warning
1185.70.3 by Martin Pool
Various updates to make storage branch mergeable:
58
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
59
1904.2.5 by Martin Pool
Fix format warning inside test suite and add test
60
# Old formats display a warning, but only once
61
_deprecation_warning_done = False
62
63
2818.3.1 by Robert Collins
Change CommitBuilder factory delegation to allow simple declaration.
64
class CommitBuilder(object):
65
    """Provides an interface to build up a commit.
66
67
    This allows describing a tree to be committed without needing to 
68
    know the internals of the format of the repository.
69
    """
70
    
71
    # all clients should supply tree roots.
72
    record_root_entry = True
2825.5.2 by Robert Collins
Review feedback, and fix pointless commits with nested trees to raise PointlessCommit appropriately.
73
    # the default CommitBuilder does not manage trees whose root is versioned.
74
    _versioned_root = False
2818.3.1 by Robert Collins
Change CommitBuilder factory delegation to allow simple declaration.
75
76
    def __init__(self, repository, parents, config, timestamp=None, 
77
                 timezone=None, committer=None, revprops=None, 
78
                 revision_id=None):
79
        """Initiate a CommitBuilder.
80
81
        :param repository: Repository to commit to.
82
        :param parents: Revision ids of the parents of the new revision.
83
        :param config: Configuration to use.
84
        :param timestamp: Optional timestamp recorded for commit.
85
        :param timezone: Optional timezone for timestamp.
86
        :param committer: Optional committer to set for commit.
87
        :param revprops: Optional dictionary of revision properties.
88
        :param revision_id: Optional revision id.
89
        """
90
        self._config = config
91
92
        if committer is None:
93
            self._committer = self._config.username()
94
        else:
95
            assert isinstance(committer, basestring), type(committer)
96
            self._committer = committer
97
98
        self.new_inventory = Inventory(None)
99
        self._new_revision_id = osutils.safe_revision_id(revision_id)
100
        self.parents = parents
101
        self.repository = repository
102
103
        self._revprops = {}
104
        if revprops is not None:
105
            self._revprops.update(revprops)
106
107
        if timestamp is None:
108
            timestamp = time.time()
109
        # Restrict resolution to 1ms
110
        self._timestamp = round(timestamp, 3)
111
112
        if timezone is None:
113
            self._timezone = osutils.local_time_offset()
114
        else:
115
            self._timezone = int(timezone)
116
117
        self._generate_revision_if_needed()
2776.4.20 by Robert Collins
(robertc) Reduce object creation volume during commit by reusing the repository graph object. (Robert Collins)
118
        self._repo_graph = repository.get_graph()
2818.3.1 by Robert Collins
Change CommitBuilder factory delegation to allow simple declaration.
119
120
    def commit(self, message):
121
        """Make the actual commit.
122
123
        :return: The revision id of the recorded revision.
124
        """
125
        rev = _mod_revision.Revision(
126
                       timestamp=self._timestamp,
127
                       timezone=self._timezone,
128
                       committer=self._committer,
129
                       message=message,
130
                       inventory_sha1=self.inv_sha1,
131
                       revision_id=self._new_revision_id,
132
                       properties=self._revprops)
133
        rev.parent_ids = self.parents
134
        self.repository.add_revision(self._new_revision_id, rev,
135
            self.new_inventory, self._config)
136
        self.repository.commit_write_group()
137
        return self._new_revision_id
138
139
    def abort(self):
140
        """Abort the commit that is being built.
141
        """
142
        self.repository.abort_write_group()
143
144
    def revision_tree(self):
145
        """Return the tree that was just committed.
146
147
        After calling commit() this can be called to get a RevisionTree
148
        representing the newly committed tree. This is preferred to
149
        calling Repository.revision_tree() because that may require
150
        deserializing the inventory, while we already have a copy in
151
        memory.
152
        """
153
        return RevisionTree(self.repository, self.new_inventory,
154
                            self._new_revision_id)
155
156
    def finish_inventory(self):
157
        """Tell the builder that the inventory is finished."""
158
        if self.new_inventory.root is None:
159
            symbol_versioning.warn('Root entry should be supplied to'
160
                ' record_entry_contents, as of bzr 0.10.',
161
                 DeprecationWarning, stacklevel=2)
162
            self.new_inventory.add(InventoryDirectory(ROOT_ID, '', None))
163
        self.new_inventory.revision_id = self._new_revision_id
164
        self.inv_sha1 = self.repository.add_inventory(
165
            self._new_revision_id,
166
            self.new_inventory,
167
            self.parents
168
            )
169
170
    def _gen_revision_id(self):
171
        """Return new revision-id."""
172
        return generate_ids.gen_revision_id(self._config.username(),
173
                                            self._timestamp)
174
175
    def _generate_revision_if_needed(self):
176
        """Create a revision id if None was supplied.
177
        
178
        If the repository can not support user-specified revision ids
179
        they should override this function and raise CannotSetRevisionId
180
        if _new_revision_id is not None.
181
182
        :raises: CannotSetRevisionId
183
        """
184
        if self._new_revision_id is None:
185
            self._new_revision_id = self._gen_revision_id()
186
            self.random_revid = True
187
        else:
188
            self.random_revid = False
189
190
    def _check_root(self, ie, parent_invs, tree):
191
        """Helper for record_entry_contents.
192
193
        :param ie: An entry being added.
194
        :param parent_invs: The inventories of the parent revisions of the
195
            commit.
196
        :param tree: The tree that is being committed.
197
        """
2871.1.2 by Robert Collins
* ``CommitBuilder.record_entry_contents`` now requires the root entry of a
198
        # In this revision format, root entries have no knit or weave When
199
        # serializing out to disk and back in root.revision is always
200
        # _new_revision_id
201
        ie.revision = self._new_revision_id
2818.3.1 by Robert Collins
Change CommitBuilder factory delegation to allow simple declaration.
202
2871.1.4 by Robert Collins
Merge bzr.dev.
203
    def _get_delta(self, ie, basis_inv, path):
204
        """Get a delta against the basis inventory for ie."""
205
        if ie.file_id not in basis_inv:
206
            # add
207
            return (None, path, ie.file_id, ie)
208
        elif ie != basis_inv[ie.file_id]:
209
            # common but altered
210
            # TODO: avoid tis id2path call.
211
            return (basis_inv.id2path(ie.file_id), path, ie.file_id, ie)
2818.3.1 by Robert Collins
Change CommitBuilder factory delegation to allow simple declaration.
212
        else:
2871.1.4 by Robert Collins
Merge bzr.dev.
213
            # common, unaltered
214
            return None
2818.3.1 by Robert Collins
Change CommitBuilder factory delegation to allow simple declaration.
215
2776.4.11 by Robert Collins
Merge bzr.dev.
216
    def record_entry_contents(self, ie, parent_invs, path, tree,
217
        content_summary):
2818.3.1 by Robert Collins
Change CommitBuilder factory delegation to allow simple declaration.
218
        """Record the content of ie from tree into the commit if needed.
219
220
        Side effect: sets ie.revision when unchanged
221
222
        :param ie: An inventory entry present in the commit.
223
        :param parent_invs: The inventories of the parent revisions of the
224
            commit.
225
        :param path: The path the entry is at in the tree.
226
        :param tree: The tree which contains this entry and should be used to 
2776.4.11 by Robert Collins
Merge bzr.dev.
227
            obtain content.
228
        :param content_summary: Summary data from the tree about the paths
229
            content - stat, length, exec, sha/link target. This is only
230
            accessed when the entry has a revision of None - that is when it is
231
            a candidate to commit.
2871.1.3 by Robert Collins
* The CommitBuilder method ``record_entry_contents`` now returns summary
232
        :return: A tuple (change_delta, version_recorded). change_delta is 
233
            an inventory_delta change for this entry against the basis tree of
234
            the commit, or None if no change occured against the basis tree.
235
            version_recorded is True if a new version of the entry has been
236
            recorded. For instance, committing a merge where a file was only
237
            changed on the other side will return (delta, False).
2818.3.1 by Robert Collins
Change CommitBuilder factory delegation to allow simple declaration.
238
        """
239
        if self.new_inventory.root is None:
2871.1.2 by Robert Collins
* ``CommitBuilder.record_entry_contents`` now requires the root entry of a
240
            if ie.parent_id is not None:
241
                raise errors.RootMissing()
2825.5.2 by Robert Collins
Review feedback, and fix pointless commits with nested trees to raise PointlessCommit appropriately.
242
            self._check_root(ie, parent_invs, tree)
2776.4.11 by Robert Collins
Merge bzr.dev.
243
        if ie.revision is None:
244
            kind = content_summary[0]
245
        else:
246
            # ie is carried over from a prior commit
247
            kind = ie.kind
248
        # XXX: repository specific check for nested tree support goes here - if
249
        # the repo doesn't want nested trees we skip it ?
250
        if (kind == 'tree-reference' and
251
            not self.repository._format.supports_tree_reference):
252
            # mismatch between commit builder logic and repository:
253
            # this needs the entry creation pushed down into the builder.
2776.4.18 by Robert Collins
Review feedback.
254
            raise NotImplementedError('Missing repository subtree support.')
2776.4.11 by Robert Collins
Merge bzr.dev.
255
        # transitional assert only, will remove before release.
256
        assert ie.kind == kind
2818.3.1 by Robert Collins
Change CommitBuilder factory delegation to allow simple declaration.
257
        self.new_inventory.add(ie)
258
2871.1.3 by Robert Collins
* The CommitBuilder method ``record_entry_contents`` now returns summary
259
        # TODO: slow, take it out of the inner loop.
260
        try:
261
            basis_inv = parent_invs[0]
262
        except IndexError:
263
            basis_inv = Inventory(root_id=None)
264
2818.3.1 by Robert Collins
Change CommitBuilder factory delegation to allow simple declaration.
265
        # ie.revision is always None if the InventoryEntry is considered
2776.4.13 by Robert Collins
Merge bzr.dev.
266
        # for committing. We may record the previous parents revision if the
267
        # content is actually unchanged against a sole head.
2818.3.1 by Robert Collins
Change CommitBuilder factory delegation to allow simple declaration.
268
        if ie.revision is not None:
2871.1.3 by Robert Collins
* The CommitBuilder method ``record_entry_contents`` now returns summary
269
            if self._versioned_root or path != '':
270
                # not considered for commit
271
                delta = None
272
            else:
273
                # repositories that do not version the root set the root's
274
                # revision to the new commit even when no change occurs, and
275
                # this masks when a change may have occurred against the basis,
276
                # so calculate if one happened.
277
                if ie.file_id not in basis_inv:
278
                    # add
279
                    delta = (None, path, ie.file_id, ie)
280
                else:
281
                    basis_id = basis_inv[ie.file_id]
282
                    if basis_id.name != '':
283
                        # not the root
284
                        delta = (basis_inv.id2path(ie.file_id), path,
285
                            ie.file_id, ie)
286
                    else:
287
                        # common, unaltered
288
                        delta = None
289
            # not considered for commit, OR, for non-rich-root 
290
            return delta, ie.revision == self._new_revision_id and (path != '' or
2825.5.1 by Robert Collins
* Committing a change which is not a merge and does not change the number of
291
                self._versioned_root)
2818.3.1 by Robert Collins
Change CommitBuilder factory delegation to allow simple declaration.
292
2776.4.11 by Robert Collins
Merge bzr.dev.
293
        # XXX: Friction: parent_candidates should return a list not a dict
294
        #      so that we don't have to walk the inventories again.
2818.3.1 by Robert Collins
Change CommitBuilder factory delegation to allow simple declaration.
295
        parent_candiate_entries = ie.parent_candidates(parent_invs)
2776.4.20 by Robert Collins
(robertc) Reduce object creation volume during commit by reusing the repository graph object. (Robert Collins)
296
        head_set = self._repo_graph.heads(parent_candiate_entries.keys())
2776.4.11 by Robert Collins
Merge bzr.dev.
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':
329
            if not store:
330
                if (# if the file length changed we have to store:
331
                    parent_entry.text_size != content_summary[1] or
332
                    # if the exec bit has changed we have to store:
333
                    parent_entry.executable != content_summary[2]):
334
                    store = True
335
                elif parent_entry.text_sha1 == content_summary[3]:
336
                    # all meta and content is unchanged (using a hash cache
337
                    # hit to check the sha)
338
                    ie.revision = parent_entry.revision
339
                    ie.text_size = parent_entry.text_size
340
                    ie.text_sha1 = parent_entry.text_sha1
341
                    ie.executable = parent_entry.executable
2871.1.4 by Robert Collins
Merge bzr.dev.
342
                    return self._get_delta(ie, basis_inv, path), False
2776.4.11 by Robert Collins
Merge bzr.dev.
343
                else:
344
                    # Either there is only a hash change(no hash cache entry,
345
                    # or same size content change), or there is no change on
346
                    # this file at all.
2776.4.19 by Robert Collins
Final review tweaks.
347
                    # Provide the parent's hash to the store layer, so that the
348
                    # content is unchanged we will not store a new node.
2776.4.11 by Robert Collins
Merge bzr.dev.
349
                    nostore_sha = parent_entry.text_sha1
350
            if store:
2776.4.18 by Robert Collins
Review feedback.
351
                # We want to record a new node regardless of the presence or
352
                # absence of a content change in the file.
2776.4.11 by Robert Collins
Merge bzr.dev.
353
                nostore_sha = None
2776.4.18 by Robert Collins
Review feedback.
354
            ie.executable = content_summary[2]
355
            lines = tree.get_file(ie.file_id, path).readlines()
2776.4.11 by Robert Collins
Merge bzr.dev.
356
            try:
357
                ie.text_sha1, ie.text_size = self._add_text_to_weave(
358
                    ie.file_id, lines, heads, nostore_sha)
359
            except errors.ExistingContent:
2776.4.18 by Robert Collins
Review feedback.
360
                # Turns out that the file content was unchanged, and we were
361
                # only going to store a new node if it was changed. Carry over
362
                # the entry.
2776.4.11 by Robert Collins
Merge bzr.dev.
363
                ie.revision = parent_entry.revision
364
                ie.text_size = parent_entry.text_size
365
                ie.text_sha1 = parent_entry.text_sha1
366
                ie.executable = parent_entry.executable
2871.1.4 by Robert Collins
Merge bzr.dev.
367
                return self._get_delta(ie, basis_inv, path), False
2776.4.11 by Robert Collins
Merge bzr.dev.
368
        elif kind == 'directory':
369
            if not store:
370
                # all data is meta here, nothing specific to directory, so
371
                # carry over:
372
                ie.revision = parent_entry.revision
2871.1.4 by Robert Collins
Merge bzr.dev.
373
                return self._get_delta(ie, basis_inv, path), False
2776.4.11 by Robert Collins
Merge bzr.dev.
374
            lines = []
375
            self._add_text_to_weave(ie.file_id, lines, heads, None)
376
        elif kind == 'symlink':
377
            current_link_target = content_summary[3]
378
            if not store:
2776.4.18 by Robert Collins
Review feedback.
379
                # symlink target is not generic metadata, check if it has
2776.4.11 by Robert Collins
Merge bzr.dev.
380
                # changed.
381
                if current_link_target != parent_entry.symlink_target:
382
                    store = True
383
            if not store:
384
                # unchanged, carry over.
385
                ie.revision = parent_entry.revision
386
                ie.symlink_target = parent_entry.symlink_target
2871.1.4 by Robert Collins
Merge bzr.dev.
387
                return self._get_delta(ie, basis_inv, path), False
2776.4.11 by Robert Collins
Merge bzr.dev.
388
            ie.symlink_target = current_link_target
389
            lines = []
390
            self._add_text_to_weave(ie.file_id, lines, heads, None)
391
        elif kind == 'tree-reference':
392
            if not store:
393
                if content_summary[3] != parent_entry.reference_revision:
394
                    store = True
395
            if not store:
396
                # unchanged, carry over.
397
                ie.reference_revision = parent_entry.reference_revision
398
                ie.revision = parent_entry.revision
2871.1.4 by Robert Collins
Merge bzr.dev.
399
                return self._get_delta(ie, basis_inv, path), False
2776.4.11 by Robert Collins
Merge bzr.dev.
400
            ie.reference_revision = content_summary[3]
401
            lines = []
402
            self._add_text_to_weave(ie.file_id, lines, heads, None)
2818.3.1 by Robert Collins
Change CommitBuilder factory delegation to allow simple declaration.
403
        else:
2776.4.11 by Robert Collins
Merge bzr.dev.
404
            raise NotImplementedError('unknown kind')
405
        ie.revision = self._new_revision_id
2871.1.4 by Robert Collins
Merge bzr.dev.
406
        return self._get_delta(ie, basis_inv, path), True
2776.4.11 by Robert Collins
Merge bzr.dev.
407
408
    def _add_text_to_weave(self, file_id, new_lines, parents, nostore_sha):
2818.3.1 by Robert Collins
Change CommitBuilder factory delegation to allow simple declaration.
409
        versionedfile = self.repository.weave_store.get_weave_or_empty(
410
            file_id, self.repository.get_transaction())
411
        # Don't change this to add_lines - add_lines_with_ghosts is cheaper
412
        # than add_lines, and allows committing when a parent is ghosted for
413
        # some reason.
414
        # Note: as we read the content directly from the tree, we know its not
415
        # been turned into unicode or badly split - but a broken tree
416
        # implementation could give us bad output from readlines() so this is
417
        # not a guarantee of safety. What would be better is always checking
418
        # the content during test suite execution. RBC 20070912
2776.4.11 by Robert Collins
Merge bzr.dev.
419
        try:
420
            return versionedfile.add_lines_with_ghosts(
421
                self._new_revision_id, parents, new_lines,
422
                nostore_sha=nostore_sha, random_id=self.random_revid,
423
                check_content=False)[0:2]
424
        finally:
425
            versionedfile.clear_cache()
2818.3.1 by Robert Collins
Change CommitBuilder factory delegation to allow simple declaration.
426
427
428
class RootCommitBuilder(CommitBuilder):
429
    """This commitbuilder actually records the root id"""
430
    
2825.5.2 by Robert Collins
Review feedback, and fix pointless commits with nested trees to raise PointlessCommit appropriately.
431
    # the root entry gets versioned properly by this builder.
2840.1.1 by Ian Clatworthy
faster pointless commit detection (Robert Collins)
432
    _versioned_root = True
2825.5.2 by Robert Collins
Review feedback, and fix pointless commits with nested trees to raise PointlessCommit appropriately.
433
2818.3.1 by Robert Collins
Change CommitBuilder factory delegation to allow simple declaration.
434
    def _check_root(self, ie, parent_invs, tree):
435
        """Helper for record_entry_contents.
436
437
        :param ie: An entry being added.
438
        :param parent_invs: The inventories of the parent revisions of the
439
            commit.
440
        :param tree: The tree that is being committed.
441
        """
442
443
2220.2.3 by Martin Pool
Add tag: revision namespace.
444
######################################################################
445
# Repositories
446
1185.66.5 by Aaron Bentley
Renamed RevisionStorage to Repository
447
class Repository(object):
1185.70.3 by Martin Pool
Various updates to make storage branch mergeable:
448
    """Repository holding history for one or more branches.
449
450
    The repository holds and retrieves historical information including
451
    revisions and file history.  It's normally accessed only by the Branch,
452
    which views a particular line of development through that history.
453
454
    The Repository builds on top of Stores and a Transport, which respectively 
455
    describe the disk data format and the way of accessing the (possibly 
456
    remote) disk.
457
    """
1185.65.17 by Robert Collins
Merge from integration, mode-changes are broken.
458
2818.3.1 by Robert Collins
Change CommitBuilder factory delegation to allow simple declaration.
459
    # What class to use for a CommitBuilder. Often its simpler to change this
460
    # in a Repository class subclass rather than to override
461
    # get_commit_builder.
462
    _commit_builder_class = CommitBuilder
463
    # The search regex used by xml based repositories to determine what things
464
    # where changed in a single commit.
2163.2.1 by John Arbash Meinel
Speed up the fileids_altered_by_revision_ids processing
465
    _file_ids_altered_regex = lazy_regex.lazy_compile(
466
        r'file_id="(?P<file_id>[^"]+)"'
2776.4.6 by Robert Collins
Fixup various commit test failures falling out from the other commit changes.
467
        r'.* revision="(?P<revision_id>[^"]+)"'
2163.2.1 by John Arbash Meinel
Speed up the fileids_altered_by_revision_ids processing
468
        )
469
2617.6.2 by Robert Collins
Add abort_write_group and wire write_groups into fetch and commit.
470
    def abort_write_group(self):
471
        """Commit the contents accrued within the current write group.
472
473
        :seealso: start_write_group.
474
        """
475
        if self._write_group is not self.get_transaction():
476
            # has an unlock or relock occured ?
477
            raise errors.BzrError('mismatched lock context and write group.')
478
        self._abort_write_group()
479
        self._write_group = None
480
481
    def _abort_write_group(self):
482
        """Template method for per-repository write group cleanup.
483
        
484
        This is called during abort before the write group is considered to be 
485
        finished and should cleanup any internal state accrued during the write
486
        group. There is no requirement that data handed to the repository be
487
        *not* made available - this is not a rollback - but neither should any
488
        attempt be made to ensure that data added is fully commited. Abort is
489
        invoked when an error has occured so futher disk or network operations
490
        may not be possible or may error and if possible should not be
491
        attempted.
492
        """
493
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
494
    @needs_write_lock
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
495
    def add_inventory(self, revision_id, inv, parents):
496
        """Add the inventory inv to the repository as revision_id.
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
497
        
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
498
        :param parents: The revision ids of the parents that revision_id
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
499
                        is known to have and are in the repository already.
500
501
        returns the sha1 of the serialized inventory.
502
        """
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
503
        revision_id = osutils.safe_revision_id(revision_id)
504
        _mod_revision.check_not_reserved_id(revision_id)
505
        assert inv.revision_id is None or inv.revision_id == revision_id, \
1740.2.2 by Aaron Bentley
Add test for the basis inventory automatically adding the revision id.
506
            "Mismatch between inventory revision" \
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
507
            " id and insertion revid (%r, %r)" % (inv.revision_id, revision_id)
1910.2.6 by Aaron Bentley
Update for merge review, handle deprecations
508
        assert inv.root is not None
2817.2.1 by Robert Collins
* Inventory serialisation no longer double-sha's the content.
509
        inv_lines = self._serialise_inventory_to_lines(inv)
510
        inv_vf = self.get_inventory_weave()
511
        return self._inventory_add_lines(inv_vf, revision_id, parents,
512
            inv_lines, check_content=False)
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
513
2805.6.7 by Robert Collins
Review feedback.
514
    def _inventory_add_lines(self, inv_vf, revision_id, parents, lines,
515
        check_content=True):
2817.2.1 by Robert Collins
* Inventory serialisation no longer double-sha's the content.
516
        """Store lines in inv_vf and return the sha1 of the inventory."""
1740.3.6 by Jelmer Vernooij
Move inventory writing to the commit builder.
517
        final_parents = []
518
        for parent in parents:
519
            if parent in inv_vf:
520
                final_parents.append(parent)
2817.2.1 by Robert Collins
* Inventory serialisation no longer double-sha's the content.
521
        return inv_vf.add_lines(revision_id, final_parents, lines,
522
            check_content=check_content)[0]
1740.3.6 by Jelmer Vernooij
Move inventory writing to the commit builder.
523
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
524
    @needs_write_lock
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
525
    def add_revision(self, revision_id, rev, inv=None, config=None):
526
        """Add rev to the revision store as revision_id.
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
527
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
528
        :param revision_id: the revision id to use.
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
529
        :param rev: The revision object.
530
        :param inv: The inventory for the revision. if None, it will be looked
531
                    up in the inventory storer
532
        :param config: If None no digital signature will be created.
533
                       If supplied its signature_needed method will be used
534
                       to determine if a signature should be made.
535
        """
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
536
        revision_id = osutils.safe_revision_id(revision_id)
2249.5.13 by John Arbash Meinel
Finish auditing Repository, and fix generate_ids to always generate utf8 ids.
537
        # TODO: jam 20070210 Shouldn't we check rev.revision_id and
538
        #       rev.parent_ids?
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
539
        _mod_revision.check_not_reserved_id(revision_id)
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
540
        if config is not None and config.signature_needed():
541
            if inv is None:
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
542
                inv = self.get_inventory(revision_id)
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
543
            plaintext = Testament(rev, inv).as_short_text()
544
            self.store_revision_signature(
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
545
                gpg.GPGStrategy(config), plaintext, revision_id)
546
        if not revision_id in self.get_inventory_weave():
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
547
            if inv is None:
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
548
                raise errors.WeaveRevisionNotPresent(revision_id,
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
549
                                                     self.get_inventory_weave())
550
            else:
551
                # yes, this is not suitable for adding with ghosts.
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
552
                self.add_inventory(revision_id, inv, rev.parent_ids)
1608.2.1 by Martin Pool
[merge] Storage filename escaping
553
        self._revision_store.add_revision(rev, self.get_transaction())
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
554
2520.4.10 by Aaron Bentley
Enable installation of revisions
555
    def _add_revision_text(self, revision_id, text):
556
        revision = self._revision_store._serializer.read_revision_from_string(
557
            text)
558
        self._revision_store._add_revision(revision, StringIO(text),
559
                                           self.get_transaction())
560
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
561
    def all_revision_ids(self):
562
        """Returns a list of all the revision ids in the repository. 
563
564
        This is deprecated because code should generally work on the graph
565
        reachable from a particular revision, and ignore any other revisions
566
        that might be present.  There is no direct replacement method.
567
        """
2850.3.1 by Robert Collins
Move various weave specific code out of the base Repository class to weaverepo.py.
568
        if 'evil' in debug.debug_flags:
569
            mutter_callsite(2, "all_revision_ids is linear with history.")
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
570
        return self._all_revision_ids()
571
572
    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.
573
        """Returns a list of all the revision ids in the repository. 
574
575
        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.
576
        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.
577
        """
2850.3.1 by Robert Collins
Move various weave specific code out of the base Repository class to weaverepo.py.
578
        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.
579
1687.1.7 by Robert Collins
Teach Repository about break_lock.
580
    def break_lock(self):
581
        """Break a lock if one is present from another instance.
582
583
        Uses the ui factory to ask for confirmation if the lock may be from
584
        an active process.
585
        """
586
        self.control_files.break_lock()
587
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.
588
    @needs_read_lock
589
    def _eliminate_revisions_not_present(self, revision_ids):
590
        """Check every revision id in revision_ids to see if we have it.
591
592
        Returns a set of the present revisions.
593
        """
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
594
        result = []
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.
595
        for id in revision_ids:
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
596
            if self.has_revision(id):
597
               result.append(id)
598
        return result
599
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
600
    @staticmethod
601
    def create(a_bzrdir):
602
        """Construct the current default format repository in a_bzrdir."""
603
        return RepositoryFormat.get_default_format().initialize(a_bzrdir)
604
1563.2.29 by Robert Collins
Remove all but fetch references to repository.revision_store.
605
    def __init__(self, _format, a_bzrdir, control_files, _revision_store, control_store, text_store):
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
606
        """instantiate a Repository.
607
608
        :param _format: The format of the repository on disk.
609
        :param a_bzrdir: The BzrDir of the repository.
610
611
        In the future we will have a single api for all stores for
612
        getting file texts, inventories and revisions, then
613
        this construct will accept instances of those things.
614
        """
1608.2.1 by Martin Pool
[merge] Storage filename escaping
615
        super(Repository, self).__init__()
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
616
        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
617
        # 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.
618
        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
619
        self.control_files = control_files
1563.2.29 by Robert Collins
Remove all but fetch references to repository.revision_store.
620
        self._revision_store = _revision_store
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
621
        # backwards compatibility
1563.2.17 by Robert Collins
Change knits repositories to use a knit versioned file store for file texts.
622
        self.weave_store = text_store
2671.4.2 by Robert Collins
Review feedback.
623
        # for tests
624
        self._reconcile_does_inventory_gc = True
1563.2.23 by Robert Collins
Add add_revision and get_revision methods to RevisionStore
625
        # not right yet - should be more semantically clear ? 
626
        # 
627
        self.control_store = control_store
628
        self.control_weaves = control_store
1608.2.1 by Martin Pool
[merge] Storage filename escaping
629
        # TODO: make sure to construct the right store classes, etc, depending
630
        # on whether escaping is required.
1904.2.3 by Martin Pool
Give a warning on access to old repository formats
631
        self._warn_if_deprecated()
2617.6.1 by Robert Collins
* New method on Repository - ``start_write_group``, ``end_write_group``
632
        self._write_group = None
2881.4.1 by Robert Collins
Move responsibility for detecting same-repo fetching from the
633
        self.base = control_files._transport.base
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
634
1668.1.3 by Martin Pool
[patch] use the correct transaction when committing snapshot (Malone: #43959)
635
    def __repr__(self):
2881.4.1 by Robert Collins
Move responsibility for detecting same-repo fetching from the
636
        return '%s(%r)' % (self.__class__.__name__,
637
                           self.base)
1668.1.3 by Martin Pool
[patch] use the correct transaction when committing snapshot (Malone: #43959)
638
2671.1.4 by Andrew Bennetts
Rename is_same_repository to has_same_location, thanks Aaron!
639
    def has_same_location(self, other):
2671.1.3 by Andrew Bennetts
Remove Repository.__eq__/__ne__ methods, replace with is_same_repository method.
640
        """Returns a boolean indicating if this repository is at the same
641
        location as another repository.
642
643
        This might return False even when two repository objects are accessing
644
        the same physical repository via different URLs.
645
        """
2671.1.1 by Andrew Bennetts
Add support for comparing Repositories with == and != operators.
646
        if self.__class__ is not other.__class__:
647
            return False
648
        return (self.control_files._transport.base ==
649
                other.control_files._transport.base)
650
2617.6.1 by Robert Collins
* New method on Repository - ``start_write_group``, ``end_write_group``
651
    def is_in_write_group(self):
652
        """Return True if there is an open write group.
653
654
        :seealso: start_write_group.
655
        """
656
        return self._write_group is not None
657
1694.2.6 by Martin Pool
[merge] bzr.dev
658
    def is_locked(self):
659
        return self.control_files.is_locked()
660
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
661
    def lock_write(self, token=None):
662
        """Lock this repository for writing.
2617.6.8 by Robert Collins
Review feedback and documentation.
663
664
        This causes caching within the repository obejct to start accumlating
665
        data during reads, and allows a 'write_group' to be obtained. Write
666
        groups must be used for actual data insertion.
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
667
        
668
        :param token: if this is already locked, then lock_write will fail
669
            unless the token matches the existing lock.
670
        :returns: a token if this instance supports tokens, otherwise None.
671
        :raises TokenLockingNotSupported: when a token is given but this
672
            instance doesn't support using token locks.
673
        :raises MismatchedToken: if the specified token doesn't match the token
674
            of the existing lock.
2617.6.8 by Robert Collins
Review feedback and documentation.
675
        :seealso: start_write_group.
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
676
2018.5.145 by Andrew Bennetts
Add a brief explanation of what tokens are used for to lock_write docstrings.
677
        A token should be passed in if you know that you have locked the object
678
        some other way, and need to synchronise this object's state with that
679
        fact.
680
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
681
        XXX: this docstring is duplicated in many places, e.g. lockable_files.py
682
        """
2617.6.2 by Robert Collins
Add abort_write_group and wire write_groups into fetch and commit.
683
        result = self.control_files.lock_write(token=token)
684
        self._refresh_data()
685
        return result
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
686
687
    def lock_read(self):
1553.5.55 by Martin Pool
[revert] broken changes
688
        self.control_files.lock_read()
2617.6.2 by Robert Collins
Add abort_write_group and wire write_groups into fetch and commit.
689
        self._refresh_data()
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
690
1694.2.6 by Martin Pool
[merge] bzr.dev
691
    def get_physical_lock_status(self):
692
        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
693
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
694
    def leave_lock_in_place(self):
695
        """Tell this repository not to release the physical lock when this
696
        object is unlocked.
2018.5.76 by Andrew Bennetts
Testing that repository.{dont_,}leave_lock_in_place raises NotImplementedError if lock_write returns None.
697
        
698
        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.
699
        """
700
        self.control_files.leave_in_place()
701
702
    def dont_leave_lock_in_place(self):
703
        """Tell this repository to release the physical lock when this
704
        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.
705
706
        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.
707
        """
708
        self.control_files.dont_leave_in_place()
709
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.
710
    @needs_read_lock
2258.1.2 by Robert Collins
New version of gather_stats which gathers aggregate data too.
711
    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).
712
        """Gather statistics from a revision id.
713
2258.1.2 by Robert Collins
New version of gather_stats which gathers aggregate data too.
714
        :param revid: The revision id to gather statistics from, if None, then
715
            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).
716
        :param committers: Optional parameter controlling whether to grab
2258.1.2 by Robert Collins
New version of gather_stats which gathers aggregate data too.
717
            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).
718
        :return: A dictionary of statistics. Currently this contains:
719
            committers: The number of committers if requested.
720
            firstrev: A tuple with timestamp, timezone for the penultimate left
721
                most ancestor of revid, if revid is not the NULL_REVISION.
722
            latestrev: A tuple with timestamp, timezone for revid, if revid is
723
                not the NULL_REVISION.
2258.1.2 by Robert Collins
New version of gather_stats which gathers aggregate data too.
724
            revisions: The total revision count in the repository.
725
            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).
726
        """
727
        result = {}
2258.1.2 by Robert Collins
New version of gather_stats which gathers aggregate data too.
728
        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).
729
            result['committers'] = 0
2258.1.2 by Robert Collins
New version of gather_stats which gathers aggregate data too.
730
        if revid and revid != _mod_revision.NULL_REVISION:
731
            if committers:
732
                all_committers = set()
733
            revisions = self.get_ancestry(revid)
734
            # pop the leading None
735
            revisions.pop(0)
736
            first_revision = None
737
            if not committers:
738
                # ignore the revisions in the middle - just grab first and last
739
                revisions = revisions[0], revisions[-1]
740
            for revision in self.get_revisions(revisions):
741
                if not first_revision:
742
                    first_revision = revision
743
                if committers:
744
                    all_committers.add(revision.committer)
745
            last_revision = revision
746
            if committers:
747
                result['committers'] = len(all_committers)
748
            result['firstrev'] = (first_revision.timestamp,
749
                first_revision.timezone)
750
            result['latestrev'] = (last_revision.timestamp,
751
                last_revision.timezone)
752
753
        # now gather global repository information
754
        if self.bzrdir.root_transport.listable():
755
            c, t = self._revision_store.total_size(self.get_transaction())
756
            result['revisions'] = c
757
            result['size'] = t
2258.1.1 by Robert Collins
Move info branch statistics gathering into the repository to allow smart server optimisation (Robert Collins).
758
        return result
759
760
    @needs_read_lock
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.
761
    def missing_revision_ids(self, other, revision_id=None):
762
        """Return the revision ids that other has that this does not.
763
        
764
        These are returned in topological order.
765
766
        revision_id: only return revision ids included by revision_id.
767
        """
2249.5.13 by John Arbash Meinel
Finish auditing Repository, and fix generate_ids to always generate utf8 ids.
768
        revision_id = osutils.safe_revision_id(revision_id)
1534.1.34 by Robert Collins
Move missing_revision_ids from Repository to InterRepository, and eliminate the now unused Repository._compatible_formats method.
769
        return InterRepository.get(other, self).missing_revision_ids(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.
770
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
771
    @staticmethod
772
    def open(base):
773
        """Open the repository rooted at base.
774
775
        For instance, if the repository is at URL/.bzr/repository,
776
        Repository.open(URL) -> a Repository instance.
777
        """
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
778
        control = bzrdir.BzrDir.open(base)
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
779
        return control.open_repository()
780
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
781
    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.
782
        """Make a complete copy of the content in self into destination.
783
        
784
        This is a destructive operation! Do not use it on existing 
785
        repositories.
786
        """
2249.5.13 by John Arbash Meinel
Finish auditing Repository, and fix generate_ids to always generate utf8 ids.
787
        revision_id = osutils.safe_revision_id(revision_id)
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
788
        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.
789
2617.6.2 by Robert Collins
Add abort_write_group and wire write_groups into fetch and commit.
790
    def commit_write_group(self):
791
        """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``
792
793
        :seealso: start_write_group.
794
        """
795
        if self._write_group is not self.get_transaction():
796
            # has an unlock or relock occured ?
2881.4.1 by Robert Collins
Move responsibility for detecting same-repo fetching from the
797
            raise errors.BzrError('mismatched lock context %r and '
798
                'write group %r.' %
799
                (self.get_transaction(), self._write_group))
2617.6.2 by Robert Collins
Add abort_write_group and wire write_groups into fetch and commit.
800
        self._commit_write_group()
2617.6.1 by Robert Collins
* New method on Repository - ``start_write_group``, ``end_write_group``
801
        self._write_group = None
802
2617.6.2 by Robert Collins
Add abort_write_group and wire write_groups into fetch and commit.
803
    def _commit_write_group(self):
804
        """Template method for per-repository write group cleanup.
805
        
806
        This is called before the write group is considered to be 
807
        finished and should ensure that all data handed to the repository
808
        for writing during the write group is safely committed (to the 
809
        extent possible considering file system caching etc).
810
        """
811
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.
812
    def fetch(self, source, revision_id=None, pb=None):
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
813
        """Fetch the content required to construct revision_id from source.
814
815
        If revision_id is None all content is copied.
816
        """
2249.5.13 by John Arbash Meinel
Finish auditing Repository, and fix generate_ids to always generate utf8 ids.
817
        revision_id = osutils.safe_revision_id(revision_id)
2881.4.1 by Robert Collins
Move responsibility for detecting same-repo fetching from the
818
        # fast path same-url fetch operations
819
        if self.has_same_location(source):
820
            # check that last_revision is in 'from' and then return a
821
            # no-operation.
822
            if (revision_id is not None and
823
                not _mod_revision.is_null(revision_id)):
824
                self.get_revision(revision_id)
825
            return 0, []
2323.8.3 by Aaron Bentley
Reduce scope of try/except, update NEWS
826
        inter = InterRepository.get(source, self)
2323.8.2 by Aaron Bentley
Give a nicer error on fetch when repos are in incompatible formats
827
        try:
2323.8.3 by Aaron Bentley
Reduce scope of try/except, update NEWS
828
            return inter.fetch(revision_id=revision_id, pb=pb)
2323.8.2 by Aaron Bentley
Give a nicer error on fetch when repos are in incompatible formats
829
        except NotImplementedError:
830
            raise errors.IncompatibleRepositories(source, self)
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
831
2520.4.54 by Aaron Bentley
Hang a create_bundle method off repository
832
    def create_bundle(self, target, base, fileobj, format=None):
833
        return serializer.write_bundle(self, target, base, fileobj, format)
834
2803.2.1 by Robert Collins
* CommitBuilder now advertises itself as requiring the root entry to be
835
    def get_commit_builder(self, branch, parents, config, timestamp=None,
836
                           timezone=None, committer=None, revprops=None,
1740.3.7 by Jelmer Vernooij
Move committer, log, revprops, timestamp and timezone to CommitBuilder.
837
                           revision_id=None):
838
        """Obtain a CommitBuilder for this repository.
839
        
840
        :param branch: Branch to commit to.
841
        :param parents: Revision ids of the parents of the new revision.
842
        :param config: Configuration to use.
843
        :param timestamp: Optional timestamp recorded for commit.
844
        :param timezone: Optional timezone for timestamp.
845
        :param committer: Optional committer to set for commit.
846
        :param revprops: Optional dictionary of revision properties.
847
        :param revision_id: Optional revision id.
848
        """
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
849
        revision_id = osutils.safe_revision_id(revision_id)
2818.3.2 by Robert Collins
Review feedback.
850
        result = self._commit_builder_class(self, parents, config,
2818.3.1 by Robert Collins
Change CommitBuilder factory delegation to allow simple declaration.
851
            timestamp, timezone, committer, revprops, revision_id)
2617.6.2 by Robert Collins
Add abort_write_group and wire write_groups into fetch and commit.
852
        self.start_write_group()
853
        return result
1740.3.1 by Jelmer Vernooij
Introduce and use CommitBuilder objects.
854
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
855
    def unlock(self):
2617.6.1 by Robert Collins
* New method on Repository - ``start_write_group``, ``end_write_group``
856
        if (self.control_files._lock_count == 1 and
857
            self.control_files._lock_mode == 'w'):
858
            if self._write_group is not None:
859
                raise errors.BzrError(
860
                    'Must end write groups before releasing write locks.')
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
861
        self.control_files.unlock()
862
1185.65.27 by Robert Collins
Tweak storage towards mergability.
863
    @needs_read_lock
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
864
    def clone(self, a_bzrdir, revision_id=None):
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
865
        """Clone this repository into a_bzrdir using the current format.
866
867
        Currently no check is made that the format of this repository and
868
        the bzrdir format are compatible. FIXME RBC 20060201.
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
869
870
        :return: The newly created destination repository.
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
871
        """
2440.1.1 by Martin Pool
Add new Repository.sprout,
872
        # TODO: deprecate after 0.16; cloning this with all its settings is
873
        # probably not very useful -- mbp 20070423
874
        dest_repo = self._create_sprouting_repo(a_bzrdir, shared=self.is_shared())
875
        self.copy_content_into(dest_repo, revision_id)
876
        return dest_repo
877
2617.6.1 by Robert Collins
* New method on Repository - ``start_write_group``, ``end_write_group``
878
    def start_write_group(self):
879
        """Start a write group in the repository.
880
881
        Write groups are used by repositories which do not have a 1:1 mapping
882
        between file ids and backend store to manage the insertion of data from
883
        both fetch and commit operations.
884
2617.6.2 by Robert Collins
Add abort_write_group and wire write_groups into fetch and commit.
885
        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``
886
        for the support of lock-requiring repository formats.
2617.6.8 by Robert Collins
Review feedback and documentation.
887
888
        One can only insert data into a repository inside a write group.
889
2617.6.6 by Robert Collins
Some review feedback.
890
        :return: None.
2617.6.1 by Robert Collins
* New method on Repository - ``start_write_group``, ``end_write_group``
891
        """
892
        if not self.is_locked() or self.control_files._lock_mode != 'w':
893
            raise errors.NotWriteLocked(self)
894
        if self._write_group:
895
            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.
896
        self._start_write_group()
897
        # 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``
898
        self._write_group = self.get_transaction()
899
2617.6.2 by Robert Collins
Add abort_write_group and wire write_groups into fetch and commit.
900
    def _start_write_group(self):
901
        """Template method for per-repository write group startup.
902
        
903
        This is called before the write group is considered to be 
904
        entered.
905
        """
906
2440.1.1 by Martin Pool
Add new Repository.sprout,
907
    @needs_read_lock
908
    def sprout(self, to_bzrdir, revision_id=None):
909
        """Create a descendent repository for new development.
910
911
        Unlike clone, this does not copy the settings of the repository.
912
        """
913
        dest_repo = self._create_sprouting_repo(to_bzrdir, shared=False)
914
        dest_repo.fetch(self, revision_id=revision_id)
915
        return dest_repo
916
917
    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.
918
        if not isinstance(a_bzrdir._format, self.bzrdir._format.__class__):
919
            # use target default format.
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
920
            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.
921
        else:
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
922
            # Most control formats need the repository to be specifically
923
            # created, but on some old all-in-one formats it's not needed
924
            try:
2440.1.1 by Martin Pool
Add new Repository.sprout,
925
                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.
926
            except errors.UninitializableFormat:
927
                dest_repo = a_bzrdir.open_repository()
928
        return dest_repo
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
929
1563.2.22 by Robert Collins
Move responsibility for repository.has_revision into RevisionStore
930
    @needs_read_lock
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
931
    def has_revision(self, revision_id):
1563.2.22 by Robert Collins
Move responsibility for repository.has_revision into RevisionStore
932
        """True if this repository has a copy of the revision."""
2745.1.1 by Robert Collins
Add a number of -Devil checkpoints.
933
        if 'evil' in debug.debug_flags:
2881.4.1 by Robert Collins
Move responsibility for detecting same-repo fetching from the
934
            mutter_callsite(3, "has_revision is a LBYL symptom.")
2249.5.13 by John Arbash Meinel
Finish auditing Repository, and fix generate_ids to always generate utf8 ids.
935
        revision_id = osutils.safe_revision_id(revision_id)
1563.2.22 by Robert Collins
Move responsibility for repository.has_revision into RevisionStore
936
        return self._revision_store.has_revision_id(revision_id,
937
                                                    self.get_transaction())
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
938
1185.65.27 by Robert Collins
Tweak storage towards mergability.
939
    @needs_read_lock
2850.3.1 by Robert Collins
Move various weave specific code out of the base Repository class to weaverepo.py.
940
    def get_revision(self, revision_id):
941
        """Return the Revision object for a named revision."""
942
        return self.get_revisions([revision_id])[0]
943
944
    @needs_read_lock
1570.1.13 by Robert Collins
Check for incorrect revision parentage in the weave during revision access.
945
    def get_revision_reconcile(self, revision_id):
946
        """'reconcile' helper routine that allows access to a revision always.
947
        
948
        This variant of get_revision does not cross check the weave graph
949
        against the revision one as get_revision does: but it should only
950
        be used by reconcile, or reconcile-alike commands that are correcting
951
        or testing the revision graph.
952
        """
2850.3.1 by Robert Collins
Move various weave specific code out of the base Repository class to weaverepo.py.
953
        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.
954
1756.1.2 by Aaron Bentley
Show logs using get_revisions
955
    @needs_read_lock
956
    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.
957
        """Get many revisions at once."""
958
        return self._get_revisions(revision_ids)
959
960
    @needs_read_lock
961
    def _get_revisions(self, revision_ids):
962
        """Core work logic to get many revisions without sanity checks."""
2249.5.13 by John Arbash Meinel
Finish auditing Repository, and fix generate_ids to always generate utf8 ids.
963
        revision_ids = [osutils.safe_revision_id(r) for r in revision_ids]
2850.3.1 by Robert Collins
Move various weave specific code out of the base Repository class to weaverepo.py.
964
        for rev_id in revision_ids:
965
            if not rev_id or not isinstance(rev_id, basestring):
966
                raise errors.InvalidRevisionId(revision_id=rev_id, branch=self)
2249.5.13 by John Arbash Meinel
Finish auditing Repository, and fix generate_ids to always generate utf8 ids.
967
        revs = self._revision_store.get_revisions(revision_ids,
1756.1.2 by Aaron Bentley
Show logs using get_revisions
968
                                                  self.get_transaction())
2249.5.13 by John Arbash Meinel
Finish auditing Repository, and fix generate_ids to always generate utf8 ids.
969
        for rev in revs:
970
            assert not isinstance(rev.revision_id, unicode)
971
            for parent_id in rev.parent_ids:
972
                assert not isinstance(parent_id, unicode)
973
        return revs
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
974
1185.65.27 by Robert Collins
Tweak storage towards mergability.
975
    @needs_read_lock
1563.2.29 by Robert Collins
Remove all but fetch references to repository.revision_store.
976
    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.
977
        # TODO: jam 20070210 This shouldn't be necessary since get_revision
978
        #       would have already do it.
979
        # TODO: jam 20070210 Just use _serializer.write_revision_to_string()
980
        revision_id = osutils.safe_revision_id(revision_id)
981
        rev = self.get_revision(revision_id)
1563.2.29 by Robert Collins
Remove all but fetch references to repository.revision_store.
982
        rev_tmp = StringIO()
983
        # the current serializer..
984
        self._revision_store._serializer.write_revision(rev, rev_tmp)
985
        rev_tmp.seek(0)
986
        return rev_tmp.getvalue()
987
988
    @needs_read_lock
1756.3.22 by Aaron Bentley
Tweaks from review
989
    def get_deltas_for_revisions(self, revisions):
1756.3.19 by Aaron Bentley
Documentation and cleanups
990
        """Produce a generator of revision deltas.
991
        
992
        Note that the input is a sequence of REVISIONS, not revision_ids.
993
        Trees will be held in memory until the generator exits.
994
        Each delta is relative to the revision's lefthand predecessor.
995
        """
1756.3.3 by Aaron Bentley
More refactoring, introduce revision_trees.
996
        required_trees = set()
997
        for revision in revisions:
998
            required_trees.add(revision.revision_id)
999
            required_trees.update(revision.parent_ids[:1])
1000
        trees = dict((t.get_revision_id(), t) for 
1001
                     t in self.revision_trees(required_trees))
1002
        for revision in revisions:
1003
            if not revision.parent_ids:
1852.5.1 by Robert Collins
Deprecate EmptyTree in favour of using Repository.revision_tree.
1004
                old_tree = self.revision_tree(None)
1756.3.3 by Aaron Bentley
More refactoring, introduce revision_trees.
1005
            else:
1006
                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.
1007
            yield trees[revision.revision_id].changes_from(old_tree)
1756.3.3 by Aaron Bentley
More refactoring, introduce revision_trees.
1008
1756.3.19 by Aaron Bentley
Documentation and cleanups
1009
    @needs_read_lock
1744.2.2 by Johan Rydberg
Add get_revision_delta to Repository; and make Branch.get_revision_delta use it.
1010
    def get_revision_delta(self, revision_id):
1011
        """Return the delta for one revision.
1012
1013
        The delta is relative to the left-hand predecessor of the
1014
        revision.
1015
        """
1756.3.3 by Aaron Bentley
More refactoring, introduce revision_trees.
1016
        r = self.get_revision(revision_id)
1756.3.22 by Aaron Bentley
Tweaks from review
1017
        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.
1018
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
1019
    @needs_write_lock
1020
    def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
2249.5.13 by John Arbash Meinel
Finish auditing Repository, and fix generate_ids to always generate utf8 ids.
1021
        revision_id = osutils.safe_revision_id(revision_id)
1563.2.29 by Robert Collins
Remove all but fetch references to repository.revision_store.
1022
        signature = gpg_strategy.sign(plaintext)
1023
        self._revision_store.add_revision_signature_text(revision_id,
1024
                                                         signature,
1025
                                                         self.get_transaction())
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
1026
1694.2.6 by Martin Pool
[merge] bzr.dev
1027
    def fileids_altered_by_revision_ids(self, revision_ids):
1028
        """Find the file ids and versions affected by revisions.
1029
1030
        :param revisions: an iterable containing revision ids.
1031
        :return: a dictionary mapping altered file-ids to an iterable of
1032
        revision_ids. Each altered file-ids has the exact revision_ids that
1033
        altered it listed explicitly.
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1034
        """
1910.2.48 by Aaron Bentley
Update from review comments
1035
        assert self._serializer.support_altered_by_hack, \
1732.2.1 by Martin Pool
Remove obsolete fileid_involved from KnitRepository, fix error message.
1036
            ("fileids_altered_by_revision_ids only supported for branches " 
1037
             "which store inventory as unnested xml, not on %r" % self)
2249.5.13 by John Arbash Meinel
Finish auditing Repository, and fix generate_ids to always generate utf8 ids.
1038
        selected_revision_ids = set(osutils.safe_revision_id(r)
1039
                                    for r in revision_ids)
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1040
        w = self.get_inventory_weave()
1694.2.6 by Martin Pool
[merge] bzr.dev
1041
        result = {}
1563.2.35 by Robert Collins
cleanup deprecation warnings and finish conversion so the inventory is knit based too.
1042
1694.2.6 by Martin Pool
[merge] bzr.dev
1043
        # this code needs to read every new line in every inventory for the
1044
        # inventories [revision_ids]. Seeing a line twice is ok. Seeing a line
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
1045
        # 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.
1046
        # harmful because we are filtering by the revision id marker in the
1694.2.6 by Martin Pool
[merge] bzr.dev
1047
        # 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.
1048
        # 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.
1049
        # only those added in an inventory in rev X can contain a revision=X
1050
        # line.
2163.2.3 by John Arbash Meinel
Change to local variables to save another 300ms
1051
        unescape_revid_cache = {}
1052
        unescape_fileid_cache = {}
1053
2163.2.5 by John Arbash Meinel
Inline the cache lookup, and explain why
1054
        # jam 20061218 In a big fetch, this handles hundreds of thousands
1055
        # of lines, so it has had a lot of inlining and optimizing done.
1056
        # Sorry that it is a little bit messy.
2163.2.3 by John Arbash Meinel
Change to local variables to save another 300ms
1057
        # Move several functions to be local variables, since this is a long
1058
        # running loop.
1059
        search = self._file_ids_altered_regex.search
2163.2.5 by John Arbash Meinel
Inline the cache lookup, and explain why
1060
        unescape = _unescape_xml
2163.2.3 by John Arbash Meinel
Change to local variables to save another 300ms
1061
        setdefault = result.setdefault
2039.1.1 by Aaron Bentley
Clean up progress properly when interrupted during fetch (#54000)
1062
        pb = ui.ui_factory.nested_progress_bar()
1063
        try:
1064
            for line in w.iter_lines_added_or_present_in_versions(
2163.2.3 by John Arbash Meinel
Change to local variables to save another 300ms
1065
                                        selected_revision_ids, pb=pb):
1066
                match = search(line)
2163.2.1 by John Arbash Meinel
Speed up the fileids_altered_by_revision_ids processing
1067
                if match is None:
1068
                    continue
2163.2.5 by John Arbash Meinel
Inline the cache lookup, and explain why
1069
                # One call to match.group() returning multiple items is quite a
1070
                # bit faster than 2 calls to match.group() each returning 1
2163.2.1 by John Arbash Meinel
Speed up the fileids_altered_by_revision_ids processing
1071
                file_id, revision_id = match.group('file_id', 'revision_id')
2163.2.5 by John Arbash Meinel
Inline the cache lookup, and explain why
1072
1073
                # Inlining the cache lookups helps a lot when you make 170,000
1074
                # lines and 350k ids, versus 8.4 unique ids.
1075
                # Using a cache helps in 2 ways:
1076
                #   1) Avoids unnecessary decoding calls
1077
                #   2) Re-uses cached strings, which helps in future set and
1078
                #      equality checks.
1079
                # (2) is enough that removing encoding entirely along with
1080
                # the cache (so we are using plain strings) results in no
1081
                # performance improvement.
1082
                try:
1083
                    revision_id = unescape_revid_cache[revision_id]
1084
                except KeyError:
2294.1.10 by John Arbash Meinel
Switch all apis over to utf8 file ids. All tests pass
1085
                    unescaped = unescape(revision_id)
2163.2.5 by John Arbash Meinel
Inline the cache lookup, and explain why
1086
                    unescape_revid_cache[revision_id] = unescaped
1087
                    revision_id = unescaped
1088
2039.1.1 by Aaron Bentley
Clean up progress properly when interrupted during fetch (#54000)
1089
                if revision_id in selected_revision_ids:
2163.2.5 by John Arbash Meinel
Inline the cache lookup, and explain why
1090
                    try:
1091
                        file_id = unescape_fileid_cache[file_id]
1092
                    except KeyError:
1093
                        unescaped = unescape(file_id)
1094
                        unescape_fileid_cache[file_id] = unescaped
1095
                        file_id = unescaped
2163.2.3 by John Arbash Meinel
Change to local variables to save another 300ms
1096
                    setdefault(file_id, set()).add(revision_id)
2039.1.1 by Aaron Bentley
Clean up progress properly when interrupted during fetch (#54000)
1097
        finally:
1098
            pb.finished()
1694.2.6 by Martin Pool
[merge] bzr.dev
1099
        return result
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1100
2708.1.7 by Aaron Bentley
Rename extract_files_bytes to iter_files_bytes
1101
    def iter_files_bytes(self, desired_files):
2708.1.9 by Aaron Bentley
Clean-up docs and imports
1102
        """Iterate through file versions.
1103
2708.1.10 by Aaron Bentley
Update docstrings
1104
        Files will not necessarily be returned in the order they occur in
1105
        desired_files.  No specific order is guaranteed.
1106
2708.1.9 by Aaron Bentley
Clean-up docs and imports
1107
        Yields pairs of identifier, bytes_iterator.  identifier is an opaque
2708.1.10 by Aaron Bentley
Update docstrings
1108
        value supplied by the caller as part of desired_files.  It should
1109
        uniquely identify the file version in the caller's context.  (Examples:
1110
        an index number or a TreeTransform trans_id.)
1111
1112
        bytes_iterator is an iterable of bytestrings for the file.  The
1113
        kind of iterable and length of the bytestrings are unspecified, but for
1114
        this implementation, it is a list of lines produced by
1115
        VersionedFile.get_lines().
1116
2708.1.9 by Aaron Bentley
Clean-up docs and imports
1117
        :param desired_files: a list of (file_id, revision_id, identifier)
2708.1.10 by Aaron Bentley
Update docstrings
1118
            triples
2708.1.9 by Aaron Bentley
Clean-up docs and imports
1119
        """
2708.1.3 by Aaron Bentley
Implement extract_files_bytes on Repository
1120
        transaction = self.get_transaction()
1121
        for file_id, revision_id, callable_data in desired_files:
2708.1.11 by Aaron Bentley
Test and tweak error handling
1122
            try:
1123
                weave = self.weave_store.get_weave(file_id, transaction)
1124
            except errors.NoSuchFile:
1125
                raise errors.NoSuchIdInRepository(self, file_id)
2708.1.6 by Aaron Bentley
Turn extract_files_bytes into an iterator
1126
            yield callable_data, weave.get_lines(revision_id)
2708.1.3 by Aaron Bentley
Implement extract_files_bytes on Repository
1127
2668.2.8 by Andrew Bennetts
Rename get_data_to_fetch_for_revision_ids as item_keys_introduced_by.
1128
    def item_keys_introduced_by(self, revision_ids, _files_pb=None):
1129
        """Get an iterable listing the keys of all the data introduced by a set
1130
        of revision IDs.
1131
1132
        The keys will be ordered so that the corresponding items can be safely
1133
        fetched and inserted in that order.
1134
1135
        :returns: An iterable producing tuples of (knit-kind, file-id,
1136
            versions).  knit-kind is one of 'file', 'inventory', 'signatures',
1137
            'revisions'.  file-id is None unless knit-kind is 'file'.
2668.2.1 by Andrew Bennetts
Split out fetch refactoring from repo-refactor, adding Repository.get_data_about_revision_ids.
1138
        """
1139
        # XXX: it's a bit weird to control the inventory weave caching in this
1140
        # generator.  Ideally the caching would be done in fetch.py I think.  Or
1141
        # maybe this generator should explicitly have the contract that it
1142
        # should not be iterated until the previously yielded item has been
1143
        # processed?
1144
        inv_w = self.get_inventory_weave()
1145
        inv_w.enable_cache()
1146
1147
        # file ids that changed
1148
        file_ids = self.fileids_altered_by_revision_ids(revision_ids)
1149
        count = 0
1150
        num_file_ids = len(file_ids)
1151
        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.
1152
            if _files_pb is not None:
1153
                _files_pb.update("fetch texts", count, num_file_ids)
2668.2.1 by Andrew Bennetts
Split out fetch refactoring from repo-refactor, adding Repository.get_data_about_revision_ids.
1154
            count += 1
1155
            yield ("file", file_id, altered_versions)
1156
        # We're done with the files_pb.  Note that it finished by the caller,
1157
        # 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.
1158
        del _files_pb
2668.2.1 by Andrew Bennetts
Split out fetch refactoring from repo-refactor, adding Repository.get_data_about_revision_ids.
1159
1160
        # inventory
1161
        yield ("inventory", None, revision_ids)
1162
        inv_w.clear_cache()
1163
1164
        # signatures
1165
        revisions_with_signatures = set()
1166
        for rev_id in revision_ids:
1167
            try:
1168
                self.get_signature_text(rev_id)
1169
            except errors.NoSuchRevision:
1170
                # not signed.
1171
                pass
1172
            else:
1173
                revisions_with_signatures.add(rev_id)
1174
        yield ("signatures", None, revisions_with_signatures)
1175
1176
        # revisions
1177
        yield ("revisions", None, revision_ids)
1178
1185.65.27 by Robert Collins
Tweak storage towards mergability.
1179
    @needs_read_lock
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
1180
    def get_inventory_weave(self):
1181
        return self.control_weaves.get_weave('inventory',
1182
            self.get_transaction())
1183
1185.65.27 by Robert Collins
Tweak storage towards mergability.
1184
    @needs_read_lock
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
1185
    def get_inventory(self, revision_id):
1186
        """Get Inventory object by hash."""
2249.5.13 by John Arbash Meinel
Finish auditing Repository, and fix generate_ids to always generate utf8 ids.
1187
        # TODO: jam 20070210 Technically we don't need to sanitize, since all
1188
        #       called functions must sanitize.
1189
        revision_id = osutils.safe_revision_id(revision_id)
1740.2.3 by Aaron Bentley
Only reserialize the working tree basis inventory when needed.
1190
        return self.deserialise_inventory(
1191
            revision_id, self.get_inventory_xml(revision_id))
1192
1193
    def deserialise_inventory(self, revision_id, xml):
1194
        """Transform the xml into an inventory object. 
1195
1196
        :param revision_id: The expected revision id of the inventory.
1197
        :param xml: A serialised inventory.
1198
        """
2249.5.13 by John Arbash Meinel
Finish auditing Repository, and fix generate_ids to always generate utf8 ids.
1199
        revision_id = osutils.safe_revision_id(revision_id)
1910.2.48 by Aaron Bentley
Update from review comments
1200
        result = self._serializer.read_inventory_from_string(xml)
1910.2.1 by Aaron Bentley
Ensure root entry always has a revision
1201
        result.root.revision = revision_id
1202
        return result
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
1203
1910.2.22 by Aaron Bentley
Make commits preserve root entry data
1204
    def serialise_inventory(self, inv):
1910.2.48 by Aaron Bentley
Update from review comments
1205
        return self._serializer.write_inventory_to_string(inv)
1910.2.22 by Aaron Bentley
Make commits preserve root entry data
1206
2817.2.1 by Robert Collins
* Inventory serialisation no longer double-sha's the content.
1207
    def _serialise_inventory_to_lines(self, inv):
1208
        return self._serializer.write_inventory_to_lines(inv)
1209
2520.4.113 by Aaron Bentley
Avoid peeking at Repository._serializer
1210
    def get_serializer_format(self):
1211
        return self._serializer.format_num
1212
1185.65.27 by Robert Collins
Tweak storage towards mergability.
1213
    @needs_read_lock
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
1214
    def get_inventory_xml(self, revision_id):
1215
        """Get inventory XML as a file object."""
2249.5.13 by John Arbash Meinel
Finish auditing Repository, and fix generate_ids to always generate utf8 ids.
1216
        revision_id = osutils.safe_revision_id(revision_id)
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
1217
        try:
2249.5.13 by John Arbash Meinel
Finish auditing Repository, and fix generate_ids to always generate utf8 ids.
1218
            assert isinstance(revision_id, str), type(revision_id)
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
1219
            iw = self.get_inventory_weave()
1563.2.18 by Robert Collins
get knit repositories really using knits for text storage.
1220
            return iw.get_text(revision_id)
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
1221
        except IndexError:
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
1222
            raise errors.HistoryMissing(self, 'inventory', revision_id)
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
1223
1185.65.27 by Robert Collins
Tweak storage towards mergability.
1224
    @needs_read_lock
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
1225
    def get_inventory_sha1(self, revision_id):
1226
        """Return the sha1 hash of the inventory entry
1227
        """
2249.5.13 by John Arbash Meinel
Finish auditing Repository, and fix generate_ids to always generate utf8 ids.
1228
        # TODO: jam 20070210 Shouldn't this be deprecated / removed?
1229
        revision_id = osutils.safe_revision_id(revision_id)
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
1230
        return self.get_revision(revision_id).inventory_sha1
1231
1185.65.27 by Robert Collins
Tweak storage towards mergability.
1232
    @needs_read_lock
2850.3.2 by Robert Collins
Review feedback.
1233
    def get_revision_graph(self, revision_id=None):
1234
        """Return a dictionary containing the revision graph.
1235
1236
        NB: This method should not be used as it accesses the entire graph all
1237
        at once, which is much more data than most operations should require.
1238
1239
        :param revision_id: The revision_id to get a graph from. If None, then
1240
        the entire revision graph is returned. This is a deprecated mode of
1241
        operation and will be removed in the future.
1242
        :return: a dictionary of revision_id->revision_parents_list.
1243
        """
1244
        raise NotImplementedError(self.get_revision_graph)
1245
1246
    @needs_read_lock
1594.2.3 by Robert Collins
bugfix revision.MultipleRevisionSources.get_revision_graph to integrate ghosts between sources. [slow on weaves, fast on knits.
1247
    def get_revision_graph_with_ghosts(self, revision_ids=None):
1248
        """Return a graph of the revisions with ghosts marked as applicable.
1249
1250
        :param revision_ids: an iterable of revisions to graph or None for all.
1251
        :return: a Graph object with the graph reachable from revision_ids.
1252
        """
2745.1.1 by Robert Collins
Add a number of -Devil checkpoints.
1253
        if 'evil' in debug.debug_flags:
2881.4.1 by Robert Collins
Move responsibility for detecting same-repo fetching from the
1254
            mutter_callsite(3,
2745.1.1 by Robert Collins
Add a number of -Devil checkpoints.
1255
                "get_revision_graph_with_ghosts scales with size of history.")
2490.2.21 by Aaron Bentley
Rename graph to deprecated_graph
1256
        result = deprecated_graph.Graph()
1594.2.3 by Robert Collins
bugfix revision.MultipleRevisionSources.get_revision_graph to integrate ghosts between sources. [slow on weaves, fast on knits.
1257
        if not revision_ids:
1773.4.2 by Martin Pool
Cleanup of imports; undeprecate all_revision_ids()
1258
            pending = set(self.all_revision_ids())
1594.2.3 by Robert Collins
bugfix revision.MultipleRevisionSources.get_revision_graph to integrate ghosts between sources. [slow on weaves, fast on knits.
1259
            required = set([])
1260
        else:
2249.5.13 by John Arbash Meinel
Finish auditing Repository, and fix generate_ids to always generate utf8 ids.
1261
            pending = set(osutils.safe_revision_id(r) for r in revision_ids)
1836.3.1 by Robert Collins
(robertc) Teach repository.get_revision_graph, and revision.common_ancestor, about NULL_REVISION.
1262
            # special case NULL_REVISION
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
1263
            if _mod_revision.NULL_REVISION in pending:
1264
                pending.remove(_mod_revision.NULL_REVISION)
1836.3.1 by Robert Collins
(robertc) Teach repository.get_revision_graph, and revision.common_ancestor, about NULL_REVISION.
1265
            required = set(pending)
1594.2.3 by Robert Collins
bugfix revision.MultipleRevisionSources.get_revision_graph to integrate ghosts between sources. [slow on weaves, fast on knits.
1266
        done = set([])
1267
        while len(pending):
1268
            revision_id = pending.pop()
1269
            try:
1270
                rev = self.get_revision(revision_id)
1271
            except errors.NoSuchRevision:
1272
                if revision_id in required:
1273
                    raise
1274
                # a ghost
1275
                result.add_ghost(revision_id)
1276
                continue
1277
            for parent_id in rev.parent_ids:
1278
                # is this queued or done ?
1279
                if (parent_id not in pending and
1280
                    parent_id not in done):
1281
                    # no, queue it.
1282
                    pending.add(parent_id)
1283
            result.add_node(revision_id, rev.parent_ids)
1594.2.15 by Robert Collins
Unfuck performance.
1284
            done.add(revision_id)
1594.2.3 by Robert Collins
bugfix revision.MultipleRevisionSources.get_revision_graph to integrate ghosts between sources. [slow on weaves, fast on knits.
1285
        return result
1286
2230.3.54 by Aaron Bentley
Move reverse history iteration to repository
1287
    def _get_history_vf(self):
1288
        """Get a versionedfile whose history graph reflects all revisions.
1289
1290
        For weave repositories, this is the inventory weave.
1291
        """
1292
        return self.get_inventory_weave()
1293
1294
    def iter_reverse_revision_history(self, revision_id):
1295
        """Iterate backwards through revision ids in the lefthand history
1296
1297
        :param revision_id: The revision id to start with.  All its lefthand
1298
            ancestors will be traversed.
1299
        """
2249.5.17 by John Arbash Meinel
[merge] bzr.dev 2293 and resolve conflicts, but still broken
1300
        revision_id = osutils.safe_revision_id(revision_id)
2230.3.54 by Aaron Bentley
Move reverse history iteration to repository
1301
        if revision_id in (None, _mod_revision.NULL_REVISION):
1302
            return
1303
        next_id = revision_id
1304
        versionedfile = self._get_history_vf()
1305
        while True:
1306
            yield next_id
1307
            parents = versionedfile.get_parents(next_id)
1308
            if len(parents) == 0:
1309
                return
1310
            else:
1311
                next_id = parents[0]
1312
1594.2.3 by Robert Collins
bugfix revision.MultipleRevisionSources.get_revision_graph to integrate ghosts between sources. [slow on weaves, fast on knits.
1313
    @needs_read_lock
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
1314
    def get_revision_inventory(self, revision_id):
1315
        """Return inventory of a past revision."""
1316
        # TODO: Unify this with get_inventory()
1317
        # bzr 0.0.6 and later imposes the constraint that the inventory_id
1318
        # must be the same as its revision, so this is trivial.
1534.4.28 by Robert Collins
first cut at merge from integration.
1319
        if revision_id is None:
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
1320
            # This does not make sense: if there is no revision,
1321
            # then it is the current tree inventory surely ?!
1322
            # and thus get_root_id() is something that looks at the last
1323
            # commit on the branch, and the get_root_id is an inventory check.
1324
            raise NotImplementedError
1325
            # return Inventory(self.get_root_id())
1326
        else:
1327
            return self.get_inventory(revision_id)
1328
1185.65.27 by Robert Collins
Tweak storage towards mergability.
1329
    @needs_read_lock
1534.6.3 by Robert Collins
find_repository sufficiently robust.
1330
    def is_shared(self):
1331
        """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.
1332
        raise NotImplementedError(self.is_shared)
1534.6.3 by Robert Collins
find_repository sufficiently robust.
1333
1594.2.7 by Robert Collins
Add versionedfile.fix_parents api for correcting data post hoc.
1334
    @needs_write_lock
1692.1.1 by Robert Collins
* Repository.reconcile now takes a thorough keyword parameter to allow
1335
    def reconcile(self, other=None, thorough=False):
1594.2.7 by Robert Collins
Add versionedfile.fix_parents api for correcting data post hoc.
1336
        """Reconcile this repository."""
1337
        from bzrlib.reconcile import RepoReconciler
1692.1.1 by Robert Collins
* Repository.reconcile now takes a thorough keyword parameter to allow
1338
        reconciler = RepoReconciler(self, thorough=thorough)
1594.2.7 by Robert Collins
Add versionedfile.fix_parents api for correcting data post hoc.
1339
        reconciler.reconcile()
1340
        return reconciler
2440.1.1 by Martin Pool
Add new Repository.sprout,
1341
2617.6.2 by Robert Collins
Add abort_write_group and wire write_groups into fetch and commit.
1342
    def _refresh_data(self):
1343
        """Helper called from lock_* to ensure coherency with disk.
1344
1345
        The default implementation does nothing; it is however possible
1346
        for repositories to maintain loaded indices across multiple locks
1347
        by checking inside their implementation of this method to see
1348
        whether their indices are still valid. This depends of course on
1349
        the disk format being validatable in this manner.
1350
        """
1351
1534.6.3 by Robert Collins
find_repository sufficiently robust.
1352
    @needs_read_lock
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
1353
    def revision_tree(self, revision_id):
1354
        """Return Tree for a revision on this branch.
1355
1852.5.1 by Robert Collins
Deprecate EmptyTree in favour of using Repository.revision_tree.
1356
        `revision_id` may be None for the empty tree revision.
1357
        """
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
1358
        # TODO: refactor this to use an existing revision object
1359
        # so we don't need to read it in twice.
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
1360
        if revision_id is None or revision_id == _mod_revision.NULL_REVISION:
1731.1.61 by Aaron Bentley
Merge bzr.dev
1361
            return RevisionTree(self, Inventory(root_id=None), 
1362
                                _mod_revision.NULL_REVISION)
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
1363
        else:
2249.5.13 by John Arbash Meinel
Finish auditing Repository, and fix generate_ids to always generate utf8 ids.
1364
            revision_id = osutils.safe_revision_id(revision_id)
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
1365
            inv = self.get_revision_inventory(revision_id)
1185.65.17 by Robert Collins
Merge from integration, mode-changes are broken.
1366
            return RevisionTree(self, inv, revision_id)
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
1367
1185.65.27 by Robert Collins
Tweak storage towards mergability.
1368
    @needs_read_lock
1756.3.3 by Aaron Bentley
More refactoring, introduce revision_trees.
1369
    def revision_trees(self, revision_ids):
1370
        """Return Tree for a revision on this branch.
1371
1756.3.19 by Aaron Bentley
Documentation and cleanups
1372
        `revision_id` may not be None or 'null:'"""
1756.3.3 by Aaron Bentley
More refactoring, introduce revision_trees.
1373
        assert None not in revision_ids
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
1374
        assert _mod_revision.NULL_REVISION not in revision_ids
1756.3.5 by Aaron Bentley
Switch to get_texts, optimize get_texts
1375
        texts = self.get_inventory_weave().get_texts(revision_ids)
1756.3.3 by Aaron Bentley
More refactoring, introduce revision_trees.
1376
        for text, revision_id in zip(texts, revision_ids):
1377
            inv = self.deserialise_inventory(revision_id, text)
1378
            yield RevisionTree(self, inv, revision_id)
1379
1380
    @needs_read_lock
2530.1.1 by Aaron Bentley
Make topological sorting optional for get_ancestry
1381
    def get_ancestry(self, revision_id, topo_sorted=True):
1185.66.2 by Aaron Bentley
Moved get_ancestry to RevisionStorage
1382
        """Return a list of revision-ids integrated by a revision.
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
1383
1384
        The first element of the list is always None, indicating the origin 
1385
        revision.  This might change when we have history horizons, or 
1386
        perhaps we should have a new API.
1185.66.2 by Aaron Bentley
Moved get_ancestry to RevisionStorage
1387
        
1388
        This is topologically sorted.
1389
        """
2598.5.1 by Aaron Bentley
Start eliminating the use of None to indicate null revision
1390
        if _mod_revision.is_null(revision_id):
1185.66.2 by Aaron Bentley
Moved get_ancestry to RevisionStorage
1391
            return [None]
2249.5.13 by John Arbash Meinel
Finish auditing Repository, and fix generate_ids to always generate utf8 ids.
1392
        revision_id = osutils.safe_revision_id(revision_id)
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1393
        if not self.has_revision(revision_id):
1394
            raise errors.NoSuchRevision(self, revision_id)
1185.66.2 by Aaron Bentley
Moved get_ancestry to RevisionStorage
1395
        w = self.get_inventory_weave()
2490.2.33 by Aaron Bentley
Disable topological sorting of get_ancestry where sensible
1396
        candidates = w.get_ancestry(revision_id, topo_sorted)
1594.2.9 by Robert Collins
Teach Knit repositories how to handle ghosts without corrupting at all.
1397
        return [None] + candidates # self._eliminate_revisions_not_present(candidates)
1185.66.2 by Aaron Bentley
Moved get_ancestry to RevisionStorage
1398
2604.2.1 by Robert Collins
(robertc) Introduce a pack command.
1399
    def pack(self):
1400
        """Compress the data within the repository.
1401
1402
        This operation only makes sense for some repository types. For other
1403
        types it should be a no-op that just returns.
1404
1405
        This stub method does not require a lock, but subclasses should use
1406
        @needs_write_lock as this is a long running call its reasonable to 
1407
        implicitly lock for the user.
1408
        """
1409
1185.65.4 by Aaron Bentley
Fixed cat command
1410
    @needs_read_lock
1411
    def print_file(self, file, revision_id):
1185.65.29 by Robert Collins
Implement final review suggestions.
1412
        """Print `file` to stdout.
1413
        
1414
        FIXME RBC 20060125 as John Meinel points out this is a bad api
1415
        - it writes to stdout, it assumes that that is valid etc. Fix
1416
        by creating a new more flexible convenience function.
1417
        """
2249.5.13 by John Arbash Meinel
Finish auditing Repository, and fix generate_ids to always generate utf8 ids.
1418
        revision_id = osutils.safe_revision_id(revision_id)
1185.65.4 by Aaron Bentley
Fixed cat command
1419
        tree = self.revision_tree(revision_id)
1420
        # use inventory as it was in that revision
1421
        file_id = tree.inventory.path2id(file)
1422
        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
1423
            # TODO: jam 20060427 Write a test for this code path
1424
            #       it had a bug in it, and was raising the wrong
1425
            #       exception.
1426
            raise errors.BzrError("%r is not present in revision %s" % (file, revision_id))
1185.65.4 by Aaron Bentley
Fixed cat command
1427
        tree.print_file(file_id)
1428
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
1429
    def get_transaction(self):
1430
        return self.control_files.get_transaction()
1431
2249.5.13 by John Arbash Meinel
Finish auditing Repository, and fix generate_ids to always generate utf8 ids.
1432
    def revision_parents(self, revision_id):
1433
        revision_id = osutils.safe_revision_id(revision_id)
1434
        return self.get_inventory_weave().parent_names(revision_id)
1590.1.1 by Robert Collins
Improve common_ancestor performance.
1435
2490.2.13 by Aaron Bentley
Update distinct -> lowest, refactor, add ParentsProvider concept
1436
    def get_parents(self, revision_ids):
2490.2.22 by Aaron Bentley
Rename GraphWalker -> Graph, _AncestryWalker -> _BreadthFirstSearcher
1437
        """See StackedParentsProvider.get_parents"""
2490.2.13 by Aaron Bentley
Update distinct -> lowest, refactor, add ParentsProvider concept
1438
        parents_list = []
1439
        for revision_id in revision_ids:
1440
            if revision_id == _mod_revision.NULL_REVISION:
1441
                parents = []
1442
            else:
1443
                try:
1444
                    parents = self.get_revision(revision_id).parent_ids
1445
                except errors.NoSuchRevision:
1446
                    parents = None
1447
                else:
1448
                    if len(parents) == 0:
1449
                        parents = [_mod_revision.NULL_REVISION]
1450
            parents_list.append(parents)
1451
        return parents_list
1452
1453
    def _make_parents_provider(self):
1454
        return self
1455
2490.2.21 by Aaron Bentley
Rename graph to deprecated_graph
1456
    def get_graph(self, other_repository=None):
2490.2.13 by Aaron Bentley
Update distinct -> lowest, refactor, add ParentsProvider concept
1457
        """Return the graph walker for this repository format"""
1458
        parents_provider = self._make_parents_provider()
2490.2.14 by Aaron Bentley
Avoid StackedParentsProvider when underlying repos match
1459
        if (other_repository is not None and
1460
            other_repository.bzrdir.transport.base !=
1461
            self.bzrdir.transport.base):
2490.2.21 by Aaron Bentley
Rename graph to deprecated_graph
1462
            parents_provider = graph._StackedParentsProvider(
2490.2.13 by Aaron Bentley
Update distinct -> lowest, refactor, add ParentsProvider concept
1463
                [parents_provider, other_repository._make_parents_provider()])
2490.2.22 by Aaron Bentley
Rename GraphWalker -> Graph, _AncestryWalker -> _BreadthFirstSearcher
1464
        return graph.Graph(parents_provider)
2490.2.13 by Aaron Bentley
Update distinct -> lowest, refactor, add ParentsProvider concept
1465
1185.65.27 by Robert Collins
Tweak storage towards mergability.
1466
    @needs_write_lock
1534.6.5 by Robert Collins
Cloning of repos preserves shared and make-working-tree attributes.
1467
    def set_make_working_trees(self, new_value):
1468
        """Set the policy flag for making working trees when creating branches.
1469
1470
        This only applies to branches that use this repository.
1471
1472
        The default is 'True'.
1473
        :param new_value: True to restore the default, False to disable making
1474
                          working trees.
1475
        """
1596.2.12 by Robert Collins
Merge and make Knit Repository use the revision store for all possible queries.
1476
        raise NotImplementedError(self.set_make_working_trees)
1534.6.5 by Robert Collins
Cloning of repos preserves shared and make-working-tree attributes.
1477
    
1478
    def make_working_trees(self):
1479
        """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.
1480
        raise NotImplementedError(self.make_working_trees)
1534.6.5 by Robert Collins
Cloning of repos preserves shared and make-working-tree attributes.
1481
1482
    @needs_write_lock
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
1483
    def sign_revision(self, revision_id, gpg_strategy):
2249.5.13 by John Arbash Meinel
Finish auditing Repository, and fix generate_ids to always generate utf8 ids.
1484
        revision_id = osutils.safe_revision_id(revision_id)
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
1485
        plaintext = Testament.from_revision(self, revision_id).as_short_text()
1486
        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.
1487
1563.2.29 by Robert Collins
Remove all but fetch references to repository.revision_store.
1488
    @needs_read_lock
1489
    def has_signature_for_revision_id(self, revision_id):
1490
        """Query for a revision signature for revision_id in the repository."""
2249.5.13 by John Arbash Meinel
Finish auditing Repository, and fix generate_ids to always generate utf8 ids.
1491
        revision_id = osutils.safe_revision_id(revision_id)
1563.2.29 by Robert Collins
Remove all but fetch references to repository.revision_store.
1492
        return self._revision_store.has_signature(revision_id,
1493
                                                  self.get_transaction())
1494
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
1495
    @needs_read_lock
1496
    def get_signature_text(self, revision_id):
1497
        """Return the text for a signature."""
2249.5.13 by John Arbash Meinel
Finish auditing Repository, and fix generate_ids to always generate utf8 ids.
1498
        revision_id = osutils.safe_revision_id(revision_id)
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
1499
        return self._revision_store.get_signature_text(revision_id,
1500
                                                       self.get_transaction())
1501
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
1502
    @needs_read_lock
1503
    def check(self, revision_ids):
1504
        """Check consistency of all history of given revision_ids.
1505
1506
        Different repository implementations should override _check().
1507
1508
        :param revision_ids: A non-empty list of revision_ids whose ancestry
1509
             will be checked.  Typically the last revision_id of a branch.
1510
        """
1511
        if not revision_ids:
1512
            raise ValueError("revision_ids must be non-empty in %s.check" 
1513
                    % (self,))
2249.5.13 by John Arbash Meinel
Finish auditing Repository, and fix generate_ids to always generate utf8 ids.
1514
        revision_ids = [osutils.safe_revision_id(r) for r in revision_ids]
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
1515
        return self._check(revision_ids)
1516
1517
    def _check(self, revision_ids):
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
1518
        result = check.Check(self)
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
1519
        result.check()
1520
        return result
1521
1904.2.3 by Martin Pool
Give a warning on access to old repository formats
1522
    def _warn_if_deprecated(self):
1904.2.5 by Martin Pool
Fix format warning inside test suite and add test
1523
        global _deprecation_warning_done
1524
        if _deprecation_warning_done:
1525
            return
1526
        _deprecation_warning_done = True
1904.2.3 by Martin Pool
Give a warning on access to old repository formats
1527
        warning("Format %s for %s is deprecated - please use 'bzr upgrade' to get better performance"
1528
                % (self._format, self.bzrdir.transport.base))
1529
1910.2.63 by Aaron Bentley
Add supports_rich_root member to repository
1530
    def supports_rich_root(self):
1531
        return self._format.rich_root_data
1532
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.
1533
    def _check_ascii_revisionid(self, revision_id, method):
1534
        """Private helper for ascii-only repositories."""
1535
        # weave repositories refuse to store revisionids that are non-ascii.
1536
        if revision_id is not None:
1537
            # weaves require ascii revision ids.
1538
            if isinstance(revision_id, unicode):
1539
                try:
1540
                    revision_id.encode('ascii')
1541
                except UnicodeEncodeError:
1542
                    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
1543
            else:
1544
                try:
1545
                    revision_id.decode('ascii')
1546
                except UnicodeDecodeError:
1547
                    raise errors.NonAsciiRevisionId(method, self)
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.
1548
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1549
2241.1.14 by Martin Pool
Add deprecated forwarders for old formats from repository.py
1550
2241.1.18 by mbp at sourcefrog
Restore use of deprecating delegator for old formats in bzrlib.repository.
1551
# remove these delegates a while after bzr 0.15
1552
def __make_delegated(name, from_module):
1553
    def _deprecated_repository_forwarder():
1554
        symbol_versioning.warn('%s moved to %s in bzr 0.15'
1555
            % (name, from_module),
2241.1.20 by mbp at sourcefrog
update tests for new locations of weave repos
1556
            DeprecationWarning,
1557
            stacklevel=2)
2241.1.18 by mbp at sourcefrog
Restore use of deprecating delegator for old formats in bzrlib.repository.
1558
        m = __import__(from_module, globals(), locals(), [name])
1559
        try:
1560
            return getattr(m, name)
1561
        except AttributeError:
1562
            raise AttributeError('module %s has no name %s'
1563
                    % (m, name))
1564
    globals()[name] = _deprecated_repository_forwarder
1565
1566
for _name in [
1567
        'AllInOneRepository',
1568
        'WeaveMetaDirRepository',
1569
        'PreSplitOutRepositoryFormat',
1570
        'RepositoryFormat4',
1571
        'RepositoryFormat5',
1572
        'RepositoryFormat6',
1573
        'RepositoryFormat7',
1574
        ]:
1575
    __make_delegated(_name, 'bzrlib.repofmt.weaverepo')
1576
1577
for _name in [
1578
        'KnitRepository',
1579
        'RepositoryFormatKnit',
1580
        'RepositoryFormatKnit1',
1581
        ]:
1582
    __make_delegated(_name, 'bzrlib.repofmt.knitrepo')
1583
1584
1185.82.84 by Aaron Bentley
Moved stuff around
1585
def install_revision(repository, rev, revision_tree):
1586
    """Install all revision data into a repository."""
1587
    present_parents = []
1588
    parent_trees = {}
1589
    for p_id in rev.parent_ids:
1590
        if repository.has_revision(p_id):
1591
            present_parents.append(p_id)
1592
            parent_trees[p_id] = repository.revision_tree(p_id)
1593
        else:
1852.5.1 by Robert Collins
Deprecate EmptyTree in favour of using Repository.revision_tree.
1594
            parent_trees[p_id] = repository.revision_tree(None)
1185.82.84 by Aaron Bentley
Moved stuff around
1595
1596
    inv = revision_tree.inventory
1910.2.51 by Aaron Bentley
Bundles now corrupt repositories
1597
    entries = inv.iter_entries()
2617.6.6 by Robert Collins
Some review feedback.
1598
    # backwards compatibility hack: skip the root id.
1910.2.63 by Aaron Bentley
Add supports_rich_root member to repository
1599
    if not repository.supports_rich_root():
1910.2.60 by Aaron Bentley
Ensure that new-model revisions aren't installed into old-model repos
1600
        path, root = entries.next()
1601
        if root.revision != rev.revision_id:
1910.2.63 by Aaron Bentley
Add supports_rich_root member to repository
1602
            raise errors.IncompatibleRevision(repr(repository))
1185.82.84 by Aaron Bentley
Moved stuff around
1603
    # Add the texts that are not already present
1852.6.3 by Robert Collins
Make iter(Tree) consistent for all tree types.
1604
    for path, ie in entries:
1185.82.84 by Aaron Bentley
Moved stuff around
1605
        w = repository.weave_store.get_weave_or_empty(ie.file_id,
1606
                repository.get_transaction())
1607
        if ie.revision not in w:
1608
            text_parents = []
1740.2.2 by Aaron Bentley
Add test for the basis inventory automatically adding the revision id.
1609
            # FIXME: TODO: The following loop *may* be overlapping/duplicate
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
1610
            # with InventoryEntry.find_previous_heads(). if it is, then there
1740.2.2 by Aaron Bentley
Add test for the basis inventory automatically adding the revision id.
1611
            # is a latent bug here where the parents may have ancestors of each
1612
            # other. RBC, AB
1185.82.84 by Aaron Bentley
Moved stuff around
1613
            for revision, tree in parent_trees.iteritems():
1614
                if ie.file_id not in tree:
1615
                    continue
1616
                parent_id = tree.inventory[ie.file_id].revision
1617
                if parent_id in text_parents:
1618
                    continue
1619
                text_parents.append(parent_id)
1620
                    
1621
            vfile = repository.weave_store.get_weave_or_empty(ie.file_id, 
1622
                repository.get_transaction())
1623
            lines = revision_tree.get_file(ie.file_id).readlines()
1624
            vfile.add_lines(rev.revision_id, text_parents, lines)
1625
    try:
1626
        # install the inventory
1627
        repository.add_inventory(rev.revision_id, inv, present_parents)
1628
    except errors.RevisionAlreadyPresent:
1629
        pass
1630
    repository.add_revision(rev.revision_id, rev, inv)
1631
1632
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
1633
class MetaDirRepository(Repository):
1634
    """Repositories in the new meta-dir layout."""
1635
1563.2.29 by Robert Collins
Remove all but fetch references to repository.revision_store.
1636
    def __init__(self, _format, a_bzrdir, control_files, _revision_store, control_store, text_store):
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
1637
        super(MetaDirRepository, self).__init__(_format,
1638
                                                a_bzrdir,
1639
                                                control_files,
1563.2.29 by Robert Collins
Remove all but fetch references to repository.revision_store.
1640
                                                _revision_store,
1563.2.23 by Robert Collins
Add add_revision and get_revision methods to RevisionStore
1641
                                                control_store,
1563.2.17 by Robert Collins
Change knits repositories to use a knit versioned file store for file texts.
1642
                                                text_store)
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
1643
        dir_mode = self.control_files._dir_mode
1644
        file_mode = self.control_files._file_mode
1645
1596.2.12 by Robert Collins
Merge and make Knit Repository use the revision store for all possible queries.
1646
    @needs_read_lock
1647
    def is_shared(self):
1648
        """Return True if this repository is flagged as a shared repository."""
1649
        return self.control_files._transport.has('shared-storage')
1650
1651
    @needs_write_lock
1652
    def set_make_working_trees(self, new_value):
1653
        """Set the policy flag for making working trees when creating branches.
1654
1655
        This only applies to branches that use this repository.
1656
1657
        The default is 'True'.
1658
        :param new_value: True to restore the default, False to disable making
1659
                          working trees.
1660
        """
1661
        if new_value:
1662
            try:
1663
                self.control_files._transport.delete('no-working-trees')
1664
            except errors.NoSuchFile:
1665
                pass
1666
        else:
1667
            self.control_files.put_utf8('no-working-trees', '')
1668
    
1669
    def make_working_trees(self):
1670
        """Returns the policy for making working trees on new branches."""
1671
        return not self.control_files._transport.has('no-working-trees')
1672
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
1673
2241.1.2 by Martin Pool
change to using external Repository format registry
1674
class RepositoryFormatRegistry(registry.Registry):
1675
    """Registry of RepositoryFormats.
1676
    """
2241.1.11 by Martin Pool
Get rid of RepositoryFormat*_instance objects. Instead the format
1677
1678
    def get(self, format_string):
1679
        r = registry.Registry.get(self, format_string)
1680
        if callable(r):
1681
            r = r()
1682
        return r
2241.1.2 by Martin Pool
change to using external Repository format registry
1683
    
1684
1685
format_registry = RepositoryFormatRegistry()
2241.1.11 by Martin Pool
Get rid of RepositoryFormat*_instance objects. Instead the format
1686
"""Registry of formats, indexed by their identifying format string.
1687
1688
This can contain either format instances themselves, or classes/factories that
1689
can be called to obtain one.
1690
"""
2241.1.2 by Martin Pool
change to using external Repository format registry
1691
2220.2.3 by Martin Pool
Add tag: revision namespace.
1692
1693
#####################################################################
1694
# Repository Formats
1910.2.46 by Aaron Bentley
Whitespace fix
1695
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1696
class RepositoryFormat(object):
1697
    """A repository format.
1698
1699
    Formats provide three things:
1700
     * An initialization routine to construct repository data on disk.
1701
     * a format string which is used when the BzrDir supports versioned
1702
       children.
1703
     * an open routine which returns a Repository instance.
1704
1705
    Formats are placed in an dict by their format string for reference 
1706
    during opening. These should be subclasses of RepositoryFormat
1707
    for consistency.
1708
1709
    Once a format is deprecated, just deprecate the initialize and open
1710
    methods on the format class. Do not deprecate the object, as the 
1711
    object will be created every system load.
1712
1713
    Common instance attributes:
1714
    _matchingbzrdir - the bzrdir format that the repository format was
1715
    originally written to work with. This can be used if manually
1716
    constructing a bzrdir and repository, or more commonly for test suite
1717
    parameterisation.
1718
    """
1719
1904.2.3 by Martin Pool
Give a warning on access to old repository formats
1720
    def __str__(self):
1721
        return "<%s>" % self.__class__.__name__
1722
2241.1.11 by Martin Pool
Get rid of RepositoryFormat*_instance objects. Instead the format
1723
    def __eq__(self, other):
1724
        # format objects are generally stateless
1725
        return isinstance(other, self.__class__)
1726
2100.3.35 by Aaron Bentley
equality operations on bzrdir
1727
    def __ne__(self, other):
2100.3.31 by Aaron Bentley
Merged bzr.dev (17 tests failing)
1728
        return not self == other
1729
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1730
    @classmethod
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
1731
    def find_format(klass, a_bzrdir):
2241.1.1 by Martin Pool
Change RepositoryFormat to use a Registry rather than ad-hoc dictionary
1732
        """Return the format for the repository object in a_bzrdir.
1733
        
1734
        This is used by bzr native formats that have a "format" file in
1735
        the repository.  Other methods may be used by different types of 
1736
        control directory.
1737
        """
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
1738
        try:
1739
            transport = a_bzrdir.get_repository_transport(None)
1740
            format_string = transport.get("format").read()
2241.1.2 by Martin Pool
change to using external Repository format registry
1741
            return format_registry.get(format_string)
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
1742
        except errors.NoSuchFile:
1743
            raise errors.NoRepositoryPresent(a_bzrdir)
1744
        except KeyError:
1740.5.6 by Martin Pool
Clean up many exception classes.
1745
            raise errors.UnknownFormatError(format=format_string)
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
1746
2241.1.1 by Martin Pool
Change RepositoryFormat to use a Registry rather than ad-hoc dictionary
1747
    @classmethod
2241.1.2 by Martin Pool
change to using external Repository format registry
1748
    def register_format(klass, format):
1749
        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
1750
1751
    @classmethod
1752
    def unregister_format(klass, format):
2241.1.2 by Martin Pool
change to using external Repository format registry
1753
        format_registry.remove(format.get_format_string())
1563.2.23 by Robert Collins
Add add_revision and get_revision methods to RevisionStore
1754
    
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
1755
    @classmethod
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1756
    def get_default_format(klass):
1757
        """Return the current default format."""
2204.5.3 by Aaron Bentley
zap old repository default handling
1758
        from bzrlib import bzrdir
1759
        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
1760
1761
    def _get_control_store(self, repo_transport, control_files):
1762
        """Return the control store for this repository."""
1763
        raise NotImplementedError(self._get_control_store)
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1764
1765
    def get_format_string(self):
1766
        """Return the ASCII format string that identifies this format.
1767
        
1768
        Note that in pre format ?? repositories the format string is 
1769
        not permitted nor written to disk.
1770
        """
1771
        raise NotImplementedError(self.get_format_string)
1772
1624.3.19 by Olaf Conradi
New call get_format_description to give a user-friendly description of a
1773
    def get_format_description(self):
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
1774
        """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
1775
        raise NotImplementedError(self.get_format_description)
1776
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
1777
    def _get_revision_store(self, repo_transport, control_files):
1778
        """Return the revision store object for this a_bzrdir."""
1556.1.5 by Robert Collins
Review feedback.
1779
        raise NotImplementedError(self._get_revision_store)
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
1780
1563.2.22 by Robert Collins
Move responsibility for repository.has_revision into RevisionStore
1781
    def _get_text_rev_store(self,
1782
                            transport,
1783
                            control_files,
1784
                            name,
1785
                            compressed=True,
1563.2.28 by Robert Collins
Add total_size to the revision_store api.
1786
                            prefixed=False,
1787
                            serializer=None):
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
1788
        """Common logic for getting a revision store for a repository.
1789
        
1563.2.17 by Robert Collins
Change knits repositories to use a knit versioned file store for file texts.
1790
        see self._get_revision_store for the subclass-overridable method to 
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
1791
        get the store for a repository.
1792
        """
1563.2.22 by Robert Collins
Move responsibility for repository.has_revision into RevisionStore
1793
        from bzrlib.store.revision.text import TextRevisionStore
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
1794
        dir_mode = control_files._dir_mode
1795
        file_mode = control_files._file_mode
2220.2.2 by Martin Pool
Add tag command and basic implementation
1796
        text_store = TextStore(transport.clone(name),
1563.2.22 by Robert Collins
Move responsibility for repository.has_revision into RevisionStore
1797
                              prefixed=prefixed,
1798
                              compressed=compressed,
1799
                              dir_mode=dir_mode,
1800
                              file_mode=file_mode)
1563.2.29 by Robert Collins
Remove all but fetch references to repository.revision_store.
1801
        _revision_store = TextRevisionStore(text_store, serializer)
1802
        return _revision_store
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
1803
2241.1.6 by Martin Pool
Move Knit repositories into the submodule bzrlib.repofmt.knitrepo and
1804
    # TODO: this shouldn't be in the base class, it's specific to things that
1805
    # 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.
1806
    def _get_versioned_file_store(self,
1807
                                  name,
1808
                                  transport,
1809
                                  control_files,
1810
                                  prefixed=True,
2241.1.10 by Martin Pool
Remove more references to weaves from the repository.py file
1811
                                  versionedfile_class=None,
1946.2.5 by John Arbash Meinel
Make knit stores delay creation, but not control stores
1812
                                  versionedfile_kwargs={},
1608.2.12 by Martin Pool
Store-escaping must quote uppercase characters too, so that they're safely
1813
                                  escaped=False):
2241.1.10 by Martin Pool
Remove more references to weaves from the repository.py file
1814
        if versionedfile_class is None:
1815
            versionedfile_class = self._versionedfile_class
1563.2.17 by Robert Collins
Change knits repositories to use a knit versioned file store for file texts.
1816
        weave_transport = control_files._transport.clone(name)
1817
        dir_mode = control_files._dir_mode
1818
        file_mode = control_files._file_mode
1819
        return VersionedFileStore(weave_transport, prefixed=prefixed,
1608.2.12 by Martin Pool
Store-escaping must quote uppercase characters too, so that they're safely
1820
                                  dir_mode=dir_mode,
1821
                                  file_mode=file_mode,
1822
                                  versionedfile_class=versionedfile_class,
1946.2.5 by John Arbash Meinel
Make knit stores delay creation, but not control stores
1823
                                  versionedfile_kwargs=versionedfile_kwargs,
1608.2.12 by Martin Pool
Store-escaping must quote uppercase characters too, so that they're safely
1824
                                  escaped=escaped)
1563.2.17 by Robert Collins
Change knits repositories to use a knit versioned file store for file texts.
1825
1534.6.1 by Robert Collins
allow API creation of shared repositories
1826
    def initialize(self, a_bzrdir, shared=False):
1827
        """Initialize a repository of this format in a_bzrdir.
1828
1829
        :param a_bzrdir: The bzrdir to put the new repository in it.
1830
        :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.
1831
        :returns: The new repository object.
1832
        
1534.6.1 by Robert Collins
allow API creation of shared repositories
1833
        This may raise UninitializableFormat if shared repository are not
1834
        compatible the a_bzrdir.
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1835
        """
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
1836
        raise NotImplementedError(self.initialize)
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1837
1838
    def is_supported(self):
1839
        """Is this format supported?
1840
1841
        Supported formats must be initializable and openable.
1842
        Unsupported formats may not support initialization or committing or 
1843
        some other features depending on the reason for not being supported.
1844
        """
1845
        return True
1846
1910.2.12 by Aaron Bentley
Implement knit repo format 2
1847
    def check_conversion_target(self, target_format):
1848
        raise NotImplementedError(self.check_conversion_target)
1849
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1850
    def open(self, a_bzrdir, _found=False):
1851
        """Return an instance of this format for the bzrdir a_bzrdir.
1852
        
1853
        _found is a private parameter, do not use it.
1854
        """
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
1855
        raise NotImplementedError(self.open)
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1856
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
1857
1858
class MetaDirRepositoryFormat(RepositoryFormat):
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
1859
    """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
1860
1910.2.14 by Aaron Bentley
Fail when trying to use interrepository on Knit2 and Knit1
1861
    rich_root_data = False
2323.5.17 by Martin Pool
Add supports_tree_reference to all repo formats (robert)
1862
    supports_tree_reference = False
2241.1.11 by Martin Pool
Get rid of RepositoryFormat*_instance objects. Instead the format
1863
    _matchingbzrdir = bzrdir.BzrDirMetaFormat1()
1910.2.14 by Aaron Bentley
Fail when trying to use interrepository on Knit2 and Knit1
1864
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.
1865
    def __init__(self):
1866
        super(MetaDirRepositoryFormat, self).__init__()
1867
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
1868
    def _create_control_files(self, a_bzrdir):
1869
        """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.
1870
        # FIXME: RBC 20060125 don't peek under the covers
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
1871
        # NB: no need to escape relative paths that are url safe.
1872
        repository_transport = a_bzrdir.get_repository_transport(self)
1996.3.4 by John Arbash Meinel
lazy_import bzrlib/repository.py
1873
        control_files = lockable_files.LockableFiles(repository_transport,
1874
                                'lock', lockdir.LockDir)
1553.5.61 by Martin Pool
Locks protecting LockableFiles must now be explicitly created before use.
1875
        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
1876
        return control_files
1877
1878
    def _upload_blank_content(self, a_bzrdir, dirs, files, utf8_files, shared):
1879
        """Upload the initial blank content."""
1880
        control_files = self._create_control_files(a_bzrdir)
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
1881
        control_files.lock_write()
1882
        try:
1553.5.49 by Martin Pool
Use LockDirs for repo format 7
1883
            control_files._transport.mkdir_multi(dirs,
1884
                    mode=control_files._dir_mode)
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
1885
            for file, content in files:
1886
                control_files.put(file, content)
1887
            for file, content in utf8_files:
1888
                control_files.put_utf8(file, content)
1534.6.1 by Robert Collins
allow API creation of shared repositories
1889
            if shared == True:
1890
                control_files.put_utf8('shared-storage', '')
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
1891
        finally:
1892
            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
1893
1894
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1895
# 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.
1896
# 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
1897
# all in bzrlib.repofmt.weaverepo now.  When an instance of one of these is
1898
# needed, it's constructed directly by the BzrDir.  Non-native formats where
1899
# the repository is not separately opened are similar.
1900
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
1901
format_registry.register_lazy(
1902
    'Bazaar-NG Repository format 7',
1903
    'bzrlib.repofmt.weaverepo',
2241.1.11 by Martin Pool
Get rid of RepositoryFormat*_instance objects. Instead the format
1904
    'RepositoryFormat7'
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
1905
    )
2881.4.1 by Robert Collins
Move responsibility for detecting same-repo fetching from the
1906
2241.1.1 by Martin Pool
Change RepositoryFormat to use a Registry rather than ad-hoc dictionary
1907
# KEEP in sync with bzrdir.format_registry default, which controls the overall
1908
# default control directory format
2241.1.6 by Martin Pool
Move Knit repositories into the submodule bzrlib.repofmt.knitrepo and
1909
format_registry.register_lazy(
1910
    'Bazaar-NG Knit Repository Format 1',
1911
    'bzrlib.repofmt.knitrepo',
2241.1.11 by Martin Pool
Get rid of RepositoryFormat*_instance objects. Instead the format
1912
    'RepositoryFormatKnit1',
2241.1.6 by Martin Pool
Move Knit repositories into the submodule bzrlib.repofmt.knitrepo and
1913
    )
1914
format_registry.default_key = 'Bazaar-NG Knit Repository Format 1'
1915
2241.1.5 by Martin Pool
Move KnitFormat2 into repofmt
1916
format_registry.register_lazy(
2255.2.230 by Robert Collins
Update tree format signatures to mention introducing bzr version.
1917
    'Bazaar Knit Repository Format 3 (bzr 0.15)\n',
2100.3.31 by Aaron Bentley
Merged bzr.dev (17 tests failing)
1918
    'bzrlib.repofmt.knitrepo',
1919
    'RepositoryFormatKnit3',
1920
    )
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
1921
1922
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.
1923
class InterRepository(InterObject):
1534.1.27 by Robert Collins
Start InterRepository with InterRepository.get.
1924
    """This class represents operations taking place between two repositories.
1925
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.
1926
    Its instances have methods like copy_content and fetch, and contain
1534.1.27 by Robert Collins
Start InterRepository with InterRepository.get.
1927
    references to the source and target repositories these operations can be 
1928
    carried out on.
1929
1930
    Often we will provide convenience methods on 'repository' which carry out
1931
    operations with another repository - they will always forward to
1932
    InterRepository.get(other).method_name(parameters).
1933
    """
1934
1910.2.15 by Aaron Bentley
Back out inter.get changes, make optimizers an ordered list
1935
    _optimisers = []
1534.1.28 by Robert Collins
Allow for optimised InterRepository selection.
1936
    """The available optimised InterRepository types."""
1937
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
1938
    def copy_content(self, revision_id=None):
1910.2.15 by Aaron Bentley
Back out inter.get changes, make optimizers an ordered list
1939
        raise NotImplementedError(self.copy_content)
1940
1941
    def fetch(self, revision_id=None, pb=None):
1534.1.31 by Robert Collins
Deprecated fetch.fetch and fetch.greedy_fetch for branch.fetch, and move the Repository.fetch internals to InterRepo and InterWeaveRepo.
1942
        """Fetch the content required to construct revision_id.
1943
1910.7.17 by Andrew Bennetts
Various cosmetic changes.
1944
        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.
1945
1946
        :param revision_id: if None all content is copied, if NULL_REVISION no
1947
                            content is copied.
1948
        :param pb: optional progress bar to use for progress reports. If not
1949
                   provided a default one will be created.
1950
1951
        Returns the copied revision count and the failed revisions in a tuple:
1952
        (copied, failures).
1953
        """
1910.2.15 by Aaron Bentley
Back out inter.get changes, make optimizers an ordered list
1954
        raise NotImplementedError(self.fetch)
1955
   
1956
    @needs_read_lock
1957
    def missing_revision_ids(self, revision_id=None):
1958
        """Return the revision ids that source has that target does not.
1959
        
1960
        These are returned in topological order.
1961
1962
        :param revision_id: only return revision ids included by this
1963
                            revision_id.
1964
        """
1965
        # generic, possibly worst case, slow code path.
1966
        target_ids = set(self.target.all_revision_ids())
1967
        if revision_id is not None:
2249.5.13 by John Arbash Meinel
Finish auditing Repository, and fix generate_ids to always generate utf8 ids.
1968
            # TODO: jam 20070210 InterRepository is internal enough that it
1969
            #       should assume revision_ids are already utf-8
1970
            revision_id = osutils.safe_revision_id(revision_id)
1910.2.15 by Aaron Bentley
Back out inter.get changes, make optimizers an ordered list
1971
            source_ids = self.source.get_ancestry(revision_id)
1963.2.6 by Robey Pointer
pychecker is on crack; go back to using 'is None'.
1972
            assert source_ids[0] is None
1910.2.15 by Aaron Bentley
Back out inter.get changes, make optimizers an ordered list
1973
            source_ids.pop(0)
1974
        else:
1975
            source_ids = self.source.all_revision_ids()
1976
        result_set = set(source_ids).difference(target_ids)
1977
        # this may look like a no-op: its not. It preserves the ordering
1978
        # other_ids had while only returning the members from other_ids
1979
        # that we've decided we need.
1980
        return [rev_id for rev_id in source_ids if rev_id in result_set]
1981
2881.4.1 by Robert Collins
Move responsibility for detecting same-repo fetching from the
1982
    @staticmethod
1983
    def _same_model(source, target):
1984
        """True if source and target have the same data representation."""
1985
        if source.supports_rich_root() != target.supports_rich_root():
1986
            return False
1987
        if source._serializer != target._serializer:
1988
            return False
1989
        return True
1990
1910.2.15 by Aaron Bentley
Back out inter.get changes, make optimizers an ordered list
1991
1992
class InterSameDataRepository(InterRepository):
1993
    """Code for converting between repositories that represent the same data.
1994
    
1995
    Data format and model must match for this to work.
1996
    """
1997
2241.1.6 by Martin Pool
Move Knit repositories into the submodule bzrlib.repofmt.knitrepo and
1998
    @classmethod
2241.1.7 by Martin Pool
rename method
1999
    def _get_repo_format_to_test(self):
2814.1.1 by Robert Collins
* Pushing, pulling and branching branches with subtree references was not
2000
        """Repository format for testing with.
2001
        
2002
        InterSameData can pull from subtree to subtree and from non-subtree to
2003
        non-subtree, so we test this with the richest repository format.
2004
        """
2005
        from bzrlib.repofmt import knitrepo
2006
        return knitrepo.RepositoryFormatKnit3()
1910.2.15 by Aaron Bentley
Back out inter.get changes, make optimizers an ordered list
2007
1910.2.14 by Aaron Bentley
Fail when trying to use interrepository on Knit2 and Knit1
2008
    @staticmethod
2009
    def is_compatible(source, target):
2881.4.1 by Robert Collins
Move responsibility for detecting same-repo fetching from the
2010
        return InterRepository._same_model(source, target)
1910.2.14 by Aaron Bentley
Fail when trying to use interrepository on Knit2 and Knit1
2011
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.
2012
    @needs_write_lock
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
2013
    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.
2014
        """Make a complete copy of the content in self into destination.
2440.1.1 by Martin Pool
Add new Repository.sprout,
2015
2016
        This copies both the repository's revision data, and configuration information
2017
        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.
2018
        
2019
        This is a destructive operation! Do not use it on existing 
2020
        repositories.
2021
2022
        :param revision_id: Only copy the content needed to construct
2023
                            revision_id and its parents.
2024
        """
2025
        try:
2026
            self.target.set_make_working_trees(self.source.make_working_trees())
2027
        except NotImplementedError:
2028
            pass
2249.5.13 by John Arbash Meinel
Finish auditing Repository, and fix generate_ids to always generate utf8 ids.
2029
        # TODO: jam 20070210 This is fairly internal, so we should probably
2030
        #       just assert that revision_id is not unicode.
2031
        revision_id = osutils.safe_revision_id(revision_id)
1759.2.2 by Jelmer Vernooij
Revert some of my spelling fixes and fix some typos after review by Aaron.
2032
        # but don't bother fetching if we have the needed data now.
1996.3.20 by John Arbash Meinel
[merge] bzr.dev 2063
2033
        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.
2034
            self.target.has_revision(revision_id)):
2035
            return
2036
        self.target.fetch(self.source, revision_id=revision_id)
2037
2038
    @needs_write_lock
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.
2039
    def fetch(self, revision_id=None, pb=None):
1910.7.20 by Andrew Bennetts
Merge from bzr.dev
2040
        """See InterRepository.fetch()."""
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
2041
        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.
2042
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
1910.2.15 by Aaron Bentley
Back out inter.get changes, make optimizers an ordered list
2043
               self.source, self.source._format, self.target, 
2044
               self.target._format)
2249.5.13 by John Arbash Meinel
Finish auditing Repository, and fix generate_ids to always generate utf8 ids.
2045
        # TODO: jam 20070210 This should be an assert, not a translate
2046
        revision_id = osutils.safe_revision_id(revision_id)
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
2047
        f = GenericRepoFetcher(to_repository=self.target,
2048
                               from_repository=self.source,
2049
                               last_revision=revision_id,
2050
                               pb=pb)
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.
2051
        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.
2052
1910.2.15 by Aaron Bentley
Back out inter.get changes, make optimizers an ordered list
2053
2241.1.12 by Martin Pool
Restore InterWeaveRepo
2054
class InterWeaveRepo(InterSameDataRepository):
2850.3.1 by Robert Collins
Move various weave specific code out of the base Repository class to weaverepo.py.
2055
    """Optimised code paths between Weave based repositories.
2056
    
2057
    This should be in bzrlib/repofmt/weaverepo.py but we have not yet
2058
    implemented lazy inter-object optimisation.
2059
    """
2241.1.12 by Martin Pool
Restore InterWeaveRepo
2060
2241.1.13 by Martin Pool
Re-register InterWeaveRepo, fix test integration, add test for it
2061
    @classmethod
2241.1.12 by Martin Pool
Restore InterWeaveRepo
2062
    def _get_repo_format_to_test(self):
2063
        from bzrlib.repofmt import weaverepo
2064
        return weaverepo.RepositoryFormat7()
2065
2066
    @staticmethod
2067
    def is_compatible(source, target):
2068
        """Be compatible with known Weave formats.
2069
        
2070
        We don't test for the stores being of specific types because that
2071
        could lead to confusing results, and there is no need to be 
2072
        overly general.
2073
        """
2074
        from bzrlib.repofmt.weaverepo import (
2075
                RepositoryFormat5,
2076
                RepositoryFormat6,
2077
                RepositoryFormat7,
2078
                )
2079
        try:
2080
            return (isinstance(source._format, (RepositoryFormat5,
2081
                                                RepositoryFormat6,
2082
                                                RepositoryFormat7)) and
2083
                    isinstance(target._format, (RepositoryFormat5,
2084
                                                RepositoryFormat6,
2085
                                                RepositoryFormat7)))
2086
        except AttributeError:
2087
            return False
2088
    
2089
    @needs_write_lock
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
2090
    def copy_content(self, revision_id=None):
2241.1.12 by Martin Pool
Restore InterWeaveRepo
2091
        """See InterRepository.copy_content()."""
2092
        # weave specific optimised path:
2249.5.13 by John Arbash Meinel
Finish auditing Repository, and fix generate_ids to always generate utf8 ids.
2093
        # TODO: jam 20070210 Internal, should be an assert, not translate
2094
        revision_id = osutils.safe_revision_id(revision_id)
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
2095
        try:
2096
            self.target.set_make_working_trees(self.source.make_working_trees())
2097
        except NotImplementedError:
2098
            pass
2099
        # FIXME do not peek!
2100
        if self.source.control_files._transport.listable():
2101
            pb = ui.ui_factory.nested_progress_bar()
2241.1.12 by Martin Pool
Restore InterWeaveRepo
2102
            try:
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
2103
                self.target.weave_store.copy_all_ids(
2104
                    self.source.weave_store,
2105
                    pb=pb,
2106
                    from_transaction=self.source.get_transaction(),
2107
                    to_transaction=self.target.get_transaction())
2108
                pb.update('copying inventory', 0, 1)
2109
                self.target.control_weaves.copy_multi(
2110
                    self.source.control_weaves, ['inventory'],
2111
                    from_transaction=self.source.get_transaction(),
2112
                    to_transaction=self.target.get_transaction())
2113
                self.target._revision_store.text_store.copy_all_ids(
2114
                    self.source._revision_store.text_store,
2115
                    pb=pb)
2116
            finally:
2117
                pb.finished()
2118
        else:
2241.1.12 by Martin Pool
Restore InterWeaveRepo
2119
            self.target.fetch(self.source, revision_id=revision_id)
2120
2121
    @needs_write_lock
2122
    def fetch(self, revision_id=None, pb=None):
2123
        """See InterRepository.fetch()."""
2124
        from bzrlib.fetch import GenericRepoFetcher
2125
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
2126
               self.source, self.source._format, self.target, self.target._format)
2249.5.13 by John Arbash Meinel
Finish auditing Repository, and fix generate_ids to always generate utf8 ids.
2127
        # TODO: jam 20070210 This should be an assert, not a translate
2128
        revision_id = osutils.safe_revision_id(revision_id)
2241.1.12 by Martin Pool
Restore InterWeaveRepo
2129
        f = GenericRepoFetcher(to_repository=self.target,
2130
                               from_repository=self.source,
2131
                               last_revision=revision_id,
2132
                               pb=pb)
2133
        return f.count_copied, f.failed_revisions
2134
2135
    @needs_read_lock
2136
    def missing_revision_ids(self, revision_id=None):
2137
        """See InterRepository.missing_revision_ids()."""
2138
        # we want all revisions to satisfy revision_id in source.
2139
        # but we don't want to stat every file here and there.
2140
        # we want then, all revisions other needs to satisfy revision_id 
2141
        # checked, but not those that we have locally.
2142
        # so the first thing is to get a subset of the revisions to 
2143
        # satisfy revision_id in source, and then eliminate those that
2144
        # we do already have. 
2145
        # this is slow on high latency connection to self, but as as this
2146
        # disk format scales terribly for push anyway due to rewriting 
2147
        # inventory.weave, this is considered acceptable.
2148
        # - RBC 20060209
2149
        if revision_id is not None:
2150
            source_ids = self.source.get_ancestry(revision_id)
2151
            assert source_ids[0] is None
2152
            source_ids.pop(0)
2153
        else:
2154
            source_ids = self.source._all_possible_ids()
2155
        source_ids_set = set(source_ids)
2156
        # source_ids is the worst possible case we may need to pull.
2157
        # now we want to filter source_ids against what we actually
2158
        # have in target, but don't try to check for existence where we know
2159
        # we do not have a revision as that would be pointless.
2160
        target_ids = set(self.target._all_possible_ids())
2161
        possibly_present_revisions = target_ids.intersection(source_ids_set)
2162
        actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
2163
        required_revisions = source_ids_set.difference(actually_present_revisions)
2164
        required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
2165
        if revision_id is not None:
2166
            # we used get_ancestry to determine source_ids then we are assured all
2167
            # revisions referenced are present as they are installed in topological order.
2168
            # and the tip revision was validated by get_ancestry.
2169
            return required_topo_revisions
2170
        else:
2171
            # if we just grabbed the possibly available ids, then 
2172
            # we only have an estimate of whats available and need to validate
2173
            # that against the revision records.
2174
            return self.source._eliminate_revisions_not_present(required_topo_revisions)
2175
2176
1910.2.15 by Aaron Bentley
Back out inter.get changes, make optimizers an ordered list
2177
class InterKnitRepo(InterSameDataRepository):
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
2178
    """Optimised code paths between Knit based repositories."""
2179
2241.1.6 by Martin Pool
Move Knit repositories into the submodule bzrlib.repofmt.knitrepo and
2180
    @classmethod
2241.1.7 by Martin Pool
rename method
2181
    def _get_repo_format_to_test(self):
2241.1.6 by Martin Pool
Move Knit repositories into the submodule bzrlib.repofmt.knitrepo and
2182
        from bzrlib.repofmt import knitrepo
2183
        return knitrepo.RepositoryFormatKnit1()
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
2184
2185
    @staticmethod
2186
    def is_compatible(source, target):
2187
        """Be compatible with known Knit formats.
2188
        
1759.2.2 by Jelmer Vernooij
Revert some of my spelling fixes and fix some typos after review by Aaron.
2189
        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.
2190
        could lead to confusing results, and there is no need to be 
2191
        overly general.
2192
        """
2881.4.1 by Robert Collins
Move responsibility for detecting same-repo fetching from the
2193
        from bzrlib.repofmt.knitrepo import RepositoryFormatKnit
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
2194
        try:
2881.4.1 by Robert Collins
Move responsibility for detecting same-repo fetching from the
2195
            are_knits = (isinstance(source._format, RepositoryFormatKnit) and
2196
                isinstance(target._format, RepositoryFormatKnit))
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
2197
        except AttributeError:
2198
            return False
2881.4.1 by Robert Collins
Move responsibility for detecting same-repo fetching from the
2199
        return are_knits and InterRepository._same_model(source, target)
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
2200
2201
    @needs_write_lock
2202
    def fetch(self, revision_id=None, pb=None):
2203
        """See InterRepository.fetch()."""
2204
        from bzrlib.fetch import KnitRepoFetcher
2205
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
2206
               self.source, self.source._format, self.target, self.target._format)
2249.5.13 by John Arbash Meinel
Finish auditing Repository, and fix generate_ids to always generate utf8 ids.
2207
        # TODO: jam 20070210 This should be an assert, not a translate
2208
        revision_id = osutils.safe_revision_id(revision_id)
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
2209
        f = KnitRepoFetcher(to_repository=self.target,
2210
                            from_repository=self.source,
2211
                            last_revision=revision_id,
2212
                            pb=pb)
2213
        return f.count_copied, f.failed_revisions
2214
2215
    @needs_read_lock
2216
    def missing_revision_ids(self, revision_id=None):
2217
        """See InterRepository.missing_revision_ids()."""
2218
        if revision_id is not None:
2219
            source_ids = self.source.get_ancestry(revision_id)
1963.2.6 by Robey Pointer
pychecker is on crack; go back to using 'is None'.
2220
            assert source_ids[0] is None
1668.1.14 by Martin Pool
merge olaf - InvalidRevisionId fixes
2221
            source_ids.pop(0)
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
2222
        else:
2850.3.1 by Robert Collins
Move various weave specific code out of the base Repository class to weaverepo.py.
2223
            source_ids = self.source.all_revision_ids()
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
2224
        source_ids_set = set(source_ids)
2225
        # source_ids is the worst possible case we may need to pull.
2226
        # 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.
2227
        # 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.
2228
        # 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.
2229
        target_ids = set(self.target.all_revision_ids())
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
2230
        possibly_present_revisions = target_ids.intersection(source_ids_set)
2231
        actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
2232
        required_revisions = source_ids_set.difference(actually_present_revisions)
2233
        required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
2234
        if revision_id is not None:
2235
            # we used get_ancestry to determine source_ids then we are assured all
2236
            # revisions referenced are present as they are installed in topological order.
2237
            # and the tip revision was validated by get_ancestry.
2238
            return required_topo_revisions
2239
        else:
2240
            # if we just grabbed the possibly available ids, then 
2241
            # we only have an estimate of whats available and need to validate
2242
            # that against the revision records.
2243
            return self.source._eliminate_revisions_not_present(required_topo_revisions)
2244
1910.2.17 by Aaron Bentley
Get fetching from 1 to 2 under test
2245
1910.2.24 by Aaron Bentley
Got intra-repository fetch working between model1 and 2 for all types
2246
class InterModel1and2(InterRepository):
2247
2241.1.6 by Martin Pool
Move Knit repositories into the submodule bzrlib.repofmt.knitrepo and
2248
    @classmethod
2241.1.7 by Martin Pool
rename method
2249
    def _get_repo_format_to_test(self):
2241.1.6 by Martin Pool
Move Knit repositories into the submodule bzrlib.repofmt.knitrepo and
2250
        return None
1910.2.24 by Aaron Bentley
Got intra-repository fetch working between model1 and 2 for all types
2251
2252
    @staticmethod
2253
    def is_compatible(source, target):
2305.2.1 by Andrew Bennetts
Use repo.supports_rich_root() everywhere rather than
2254
        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
2255
            return True
2256
        else:
2257
            return False
2258
2259
    @needs_write_lock
2260
    def fetch(self, revision_id=None, pb=None):
2261
        """See InterRepository.fetch()."""
2262
        from bzrlib.fetch import Model1toKnit2Fetcher
2249.5.13 by John Arbash Meinel
Finish auditing Repository, and fix generate_ids to always generate utf8 ids.
2263
        # TODO: jam 20070210 This should be an assert, not a translate
2264
        revision_id = osutils.safe_revision_id(revision_id)
1910.2.24 by Aaron Bentley
Got intra-repository fetch working between model1 and 2 for all types
2265
        f = Model1toKnit2Fetcher(to_repository=self.target,
2266
                                 from_repository=self.source,
2267
                                 last_revision=revision_id,
2268
                                 pb=pb)
2269
        return f.count_copied, f.failed_revisions
2270
1910.2.26 by Aaron Bentley
Fix up some test cases
2271
    @needs_write_lock
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
2272
    def copy_content(self, revision_id=None):
1910.2.26 by Aaron Bentley
Fix up some test cases
2273
        """Make a complete copy of the content in self into destination.
2274
        
2275
        This is a destructive operation! Do not use it on existing 
2276
        repositories.
2277
2278
        :param revision_id: Only copy the content needed to construct
2279
                            revision_id and its parents.
2280
        """
2281
        try:
2282
            self.target.set_make_working_trees(self.source.make_working_trees())
2283
        except NotImplementedError:
2284
            pass
2249.5.13 by John Arbash Meinel
Finish auditing Repository, and fix generate_ids to always generate utf8 ids.
2285
        # TODO: jam 20070210 Internal, assert, don't translate
2286
        revision_id = osutils.safe_revision_id(revision_id)
1910.2.26 by Aaron Bentley
Fix up some test cases
2287
        # but don't bother fetching if we have the needed data now.
1996.3.20 by John Arbash Meinel
[merge] bzr.dev 2063
2288
        if (revision_id not in (None, _mod_revision.NULL_REVISION) and 
1910.2.26 by Aaron Bentley
Fix up some test cases
2289
            self.target.has_revision(revision_id)):
2290
            return
2291
        self.target.fetch(self.source, revision_id=revision_id)
2292
1910.2.24 by Aaron Bentley
Got intra-repository fetch working between model1 and 2 for all types
2293
1910.2.17 by Aaron Bentley
Get fetching from 1 to 2 under test
2294
class InterKnit1and2(InterKnitRepo):
2295
2241.1.6 by Martin Pool
Move Knit repositories into the submodule bzrlib.repofmt.knitrepo and
2296
    @classmethod
2241.1.7 by Martin Pool
rename method
2297
    def _get_repo_format_to_test(self):
2241.1.6 by Martin Pool
Move Knit repositories into the submodule bzrlib.repofmt.knitrepo and
2298
        return None
1910.2.24 by Aaron Bentley
Got intra-repository fetch working between model1 and 2 for all types
2299
1910.2.17 by Aaron Bentley
Get fetching from 1 to 2 under test
2300
    @staticmethod
2301
    def is_compatible(source, target):
2255.2.211 by Robert Collins
Remove knit2 repository format- it has never been supported.
2302
        """Be compatible with Knit1 source and Knit3 target"""
2303
        from bzrlib.repofmt.knitrepo import RepositoryFormatKnit3
1910.2.17 by Aaron Bentley
Get fetching from 1 to 2 under test
2304
        try:
2241.1.6 by Martin Pool
Move Knit repositories into the submodule bzrlib.repofmt.knitrepo and
2305
            from bzrlib.repofmt.knitrepo import RepositoryFormatKnit1, \
2255.2.211 by Robert Collins
Remove knit2 repository format- it has never been supported.
2306
                    RepositoryFormatKnit3
1910.2.17 by Aaron Bentley
Get fetching from 1 to 2 under test
2307
            return (isinstance(source._format, (RepositoryFormatKnit1)) and
2255.2.211 by Robert Collins
Remove knit2 repository format- it has never been supported.
2308
                    isinstance(target._format, (RepositoryFormatKnit3)))
1910.2.17 by Aaron Bentley
Get fetching from 1 to 2 under test
2309
        except AttributeError:
2310
            return False
2311
2312
    @needs_write_lock
2313
    def fetch(self, revision_id=None, pb=None):
2314
        """See InterRepository.fetch()."""
2315
        from bzrlib.fetch import Knit1to2Fetcher
2316
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
2317
               self.source, self.source._format, self.target, 
2318
               self.target._format)
2249.5.13 by John Arbash Meinel
Finish auditing Repository, and fix generate_ids to always generate utf8 ids.
2319
        # TODO: jam 20070210 This should be an assert, not a translate
2320
        revision_id = osutils.safe_revision_id(revision_id)
1910.2.17 by Aaron Bentley
Get fetching from 1 to 2 under test
2321
        f = Knit1to2Fetcher(to_repository=self.target,
2322
                            from_repository=self.source,
2323
                            last_revision=revision_id,
2324
                            pb=pb)
2325
        return f.count_copied, f.failed_revisions
2326
2327
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
2328
class InterRemoteRepository(InterRepository):
2329
    """Code for converting between RemoteRepository objects.
2330
2331
    This just gets an non-remote repository from the RemoteRepository, and calls
2332
    InterRepository.get again.
2333
    """
2334
2335
    def __init__(self, source, target):
2336
        if isinstance(source, remote.RemoteRepository):
2337
            source._ensure_real()
2338
            real_source = source._real_repository
2339
        else:
2340
            real_source = source
2341
        if isinstance(target, remote.RemoteRepository):
2342
            target._ensure_real()
2343
            real_target = target._real_repository
2344
        else:
2345
            real_target = target
2346
        self.real_inter = InterRepository.get(real_source, real_target)
2347
2348
    @staticmethod
2349
    def is_compatible(source, target):
2350
        if isinstance(source, remote.RemoteRepository):
2351
            return True
2352
        if isinstance(target, remote.RemoteRepository):
2353
            return True
2354
        return False
2355
2356
    def copy_content(self, revision_id=None):
2357
        self.real_inter.copy_content(revision_id=revision_id)
2358
2359
    def fetch(self, revision_id=None, pb=None):
2360
        self.real_inter.fetch(revision_id=revision_id, pb=pb)
2361
2362
    @classmethod
2363
    def _get_repo_format_to_test(self):
2364
        return None
2365
2366
1910.2.15 by Aaron Bentley
Back out inter.get changes, make optimizers an ordered list
2367
InterRepository.register_optimiser(InterSameDataRepository)
2241.1.13 by Martin Pool
Re-register InterWeaveRepo, fix test integration, add test for it
2368
InterRepository.register_optimiser(InterWeaveRepo)
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
2369
InterRepository.register_optimiser(InterKnitRepo)
1910.2.24 by Aaron Bentley
Got intra-repository fetch working between model1 and 2 for all types
2370
InterRepository.register_optimiser(InterModel1and2)
1910.2.17 by Aaron Bentley
Get fetching from 1 to 2 under test
2371
InterRepository.register_optimiser(InterKnit1and2)
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
2372
InterRepository.register_optimiser(InterRemoteRepository)
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.
2373
2374
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.
2375
class CopyConverter(object):
2376
    """A repository conversion tool which just performs a copy of the content.
2377
    
2378
    This is slow but quite reliable.
2379
    """
2380
2381
    def __init__(self, target_format):
2382
        """Create a CopyConverter.
2383
2384
        :param target_format: The format the resulting repository should be.
2385
        """
2386
        self.target_format = target_format
2387
        
2388
    def convert(self, repo, pb):
2389
        """Perform the conversion of to_convert, giving feedback via pb.
2390
2391
        :param to_convert: The disk object to convert.
2392
        :param pb: a progress bar to use for progress information.
2393
        """
2394
        self.pb = pb
2395
        self.count = 0
1596.2.22 by Robert Collins
Fetch changes to use new pb.
2396
        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.
2397
        # this is only useful with metadir layouts - separated repo content.
2398
        # trigger an assertion if not such
2399
        repo._format.get_format_string()
2400
        self.repo_dir = repo.bzrdir
2401
        self.step('Moving repository to repository.backup')
2402
        self.repo_dir.transport.move('repository', 'repository.backup')
2403
        backup_transport =  self.repo_dir.transport.clone('repository.backup')
1910.2.12 by Aaron Bentley
Implement knit repo format 2
2404
        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.
2405
        self.source_repo = repo._format.open(self.repo_dir,
2406
            _found=True,
2407
            _override_transport=backup_transport)
2408
        self.step('Creating new repository')
2409
        converted = self.target_format.initialize(self.repo_dir,
2410
                                                  self.source_repo.is_shared())
2411
        converted.lock_write()
2412
        try:
2413
            self.step('Copying content into repository.')
2414
            self.source_repo.copy_content_into(converted)
2415
        finally:
2416
            converted.unlock()
2417
        self.step('Deleting old repository content.')
2418
        self.repo_dir.transport.delete_tree('repository.backup')
2419
        self.pb.note('repository converted')
2420
2421
    def step(self, message):
2422
        """Update the pb by a step."""
2423
        self.count +=1
2424
        self.pb.update(message, self.count, self.total)
1596.1.1 by Martin Pool
Use simple xml unescaping rather than importing xml.sax
2425
2426
1843.2.4 by Aaron Bentley
Switch to John Meinel's _unescape_xml implementation
2427
_unescape_map = {
2428
    'apos':"'",
2429
    'quot':'"',
2430
    'amp':'&',
2431
    'lt':'<',
2432
    'gt':'>'
2433
}
2434
2435
2436
def _unescaper(match, _map=_unescape_map):
2294.1.2 by John Arbash Meinel
Track down and add tests that all tree.commit() can handle
2437
    code = match.group(1)
2438
    try:
2439
        return _map[code]
2440
    except KeyError:
2441
        if not code.startswith('#'):
2442
            raise
2294.1.10 by John Arbash Meinel
Switch all apis over to utf8 file ids. All tests pass
2443
        return unichr(int(code[1:])).encode('utf8')
1843.2.4 by Aaron Bentley
Switch to John Meinel's _unescape_xml implementation
2444
2445
2446
_unescape_re = None
2447
2448
1596.1.1 by Martin Pool
Use simple xml unescaping rather than importing xml.sax
2449
def _unescape_xml(data):
1843.2.4 by Aaron Bentley
Switch to John Meinel's _unescape_xml implementation
2450
    """Unescape predefined XML entities in a string of data."""
2451
    global _unescape_re
2452
    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.
2453
        _unescape_re = re.compile('\&([^;]*);')
1843.2.4 by Aaron Bentley
Switch to John Meinel's _unescape_xml implementation
2454
    return _unescape_re.sub(_unescaper, data)