~bzr-pqm/bzr/bzr.dev

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