/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-11 04:54:04 UTC
  • mfrom: (2904 +trunk)
  • mto: This revision was merged to the branch mainline in revision 2933.
  • Revision ID: robertc@robertcollins.net-20071011045404-lj5a81n4ripi01mt
Merge bzr.dev.

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