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