/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: Canonical.com Patch Queue Manager
  • Date: 2007-10-03 05:04:42 UTC
  • mfrom: (2776.4.19 commit)
  • Revision ID: pqm@pqm.ubuntu.com-20071003050442-e0x9ofdfo0hwxnal
(robertc) Move serialisation of inventory entries into CommitBuilder. (Robert Collins)

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