/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/repository.py

  • Committer: Robert Collins
  • Date: 2007-10-08 04:53:50 UTC
  • mfrom: (2890.1.2 readv)
  • mto: This revision was merged to the branch mainline in revision 2933.
  • Revision ID: robertc@robertcollins.net-20071008045350-qwh1gb3r9vy3c8kk
Readv fixes.

Show diffs side-by-side

added added

removed removed

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