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