/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: Aaron Bentley
  • Date: 2007-02-13 18:58:39 UTC
  • mfrom: (2283 +trunk)
  • mto: (2230.3.47 branch6)
  • mto: This revision was merged to the branch mainline in revision 2290.
  • Revision ID: abentley@panoramicfeedback.com-20070213185839-9cc540a30gtrgq1g
merge bzr.dev

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
 
2
#
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
 
 
17
from cStringIO import StringIO
 
18
 
 
19
from bzrlib.lazy_import import lazy_import
 
20
lazy_import(globals(), """
 
21
import re
 
22
import time
 
23
import unittest
 
24
 
 
25
from bzrlib import (
 
26
    bzrdir,
 
27
    check,
 
28
    errors,
 
29
    generate_ids,
 
30
    gpg,
 
31
    graph,
 
32
    lazy_regex,
 
33
    lockable_files,
 
34
    lockdir,
 
35
    osutils,
 
36
    registry,
 
37
    revision as _mod_revision,
 
38
    symbol_versioning,
 
39
    transactions,
 
40
    ui,
 
41
    )
 
42
from bzrlib.revisiontree import RevisionTree
 
43
from bzrlib.store.versioned import VersionedFileStore
 
44
from bzrlib.store.text import TextStore
 
45
from bzrlib.testament import Testament
 
46
 
 
47
""")
 
48
 
 
49
from bzrlib.decorators import needs_read_lock, needs_write_lock
 
50
from bzrlib.inter import InterObject
 
51
from bzrlib.inventory import Inventory, InventoryDirectory, ROOT_ID
 
52
from bzrlib.symbol_versioning import (
 
53
        deprecated_method,
 
54
        zero_nine,
 
55
        )
 
56
from bzrlib.trace import mutter, note, warning
 
57
 
 
58
 
 
59
# Old formats display a warning, but only once
 
60
_deprecation_warning_done = False
 
61
 
 
62
 
 
63
class Repository(object):
 
64
    """Repository holding history for one or more branches.
 
65
 
 
66
    The repository holds and retrieves historical information including
 
67
    revisions and file history.  It's normally accessed only by the Branch,
 
68
    which views a particular line of development through that history.
 
69
 
 
70
    The Repository builds on top of Stores and a Transport, which respectively 
 
71
    describe the disk data format and the way of accessing the (possibly 
 
72
    remote) disk.
 
73
    """
 
74
 
 
75
    _file_ids_altered_regex = lazy_regex.lazy_compile(
 
76
        r'file_id="(?P<file_id>[^"]+)"'
 
77
        r'.*revision="(?P<revision_id>[^"]+)"'
 
78
        )
 
79
 
 
80
    @needs_write_lock
 
81
    def add_inventory(self, revid, inv, parents):
 
82
        """Add the inventory inv to the repository as revid.
 
83
        
 
84
        :param parents: The revision ids of the parents that revid
 
85
                        is known to have and are in the repository already.
 
86
 
 
87
        returns the sha1 of the serialized inventory.
 
88
        """
 
89
        _mod_revision.check_not_reserved_id(revid)
 
90
        assert inv.revision_id is None or inv.revision_id == revid, \
 
91
            "Mismatch between inventory revision" \
 
92
            " id and insertion revid (%r, %r)" % (inv.revision_id, revid)
 
93
        assert inv.root is not None
 
94
        inv_text = self.serialise_inventory(inv)
 
95
        inv_sha1 = osutils.sha_string(inv_text)
 
96
        inv_vf = self.control_weaves.get_weave('inventory',
 
97
                                               self.get_transaction())
 
98
        self._inventory_add_lines(inv_vf, revid, parents, osutils.split_lines(inv_text))
 
99
        return inv_sha1
 
100
 
 
101
    def _inventory_add_lines(self, inv_vf, revid, parents, lines):
 
102
        final_parents = []
 
103
        for parent in parents:
 
104
            if parent in inv_vf:
 
105
                final_parents.append(parent)
 
106
 
 
107
        inv_vf.add_lines(revid, final_parents, lines)
 
108
 
 
109
    @needs_write_lock
 
110
    def add_revision(self, rev_id, rev, inv=None, config=None):
 
111
        """Add rev to the revision store as rev_id.
 
112
 
 
113
        :param rev_id: the revision id to use.
 
114
        :param rev: The revision object.
 
115
        :param inv: The inventory for the revision. if None, it will be looked
 
116
                    up in the inventory storer
 
117
        :param config: If None no digital signature will be created.
 
118
                       If supplied its signature_needed method will be used
 
119
                       to determine if a signature should be made.
 
120
        """
 
121
        _mod_revision.check_not_reserved_id(rev_id)
 
122
        if config is not None and config.signature_needed():
 
123
            if inv is None:
 
124
                inv = self.get_inventory(rev_id)
 
125
            plaintext = Testament(rev, inv).as_short_text()
 
126
            self.store_revision_signature(
 
127
                gpg.GPGStrategy(config), plaintext, rev_id)
 
128
        if not rev_id in self.get_inventory_weave():
 
129
            if inv is None:
 
130
                raise errors.WeaveRevisionNotPresent(rev_id,
 
131
                                                     self.get_inventory_weave())
 
132
            else:
 
133
                # yes, this is not suitable for adding with ghosts.
 
134
                self.add_inventory(rev_id, inv, rev.parent_ids)
 
135
        self._revision_store.add_revision(rev, self.get_transaction())
 
136
 
 
137
    @needs_read_lock
 
138
    def _all_possible_ids(self):
 
139
        """Return all the possible revisions that we could find."""
 
140
        return self.get_inventory_weave().versions()
 
141
 
 
142
    def all_revision_ids(self):
 
143
        """Returns a list of all the revision ids in the repository. 
 
144
 
 
145
        This is deprecated because code should generally work on the graph
 
146
        reachable from a particular revision, and ignore any other revisions
 
147
        that might be present.  There is no direct replacement method.
 
148
        """
 
149
        return self._all_revision_ids()
 
150
 
 
151
    @needs_read_lock
 
152
    def _all_revision_ids(self):
 
153
        """Returns a list of all the revision ids in the repository. 
 
154
 
 
155
        These are in as much topological order as the underlying store can 
 
156
        present: for weaves ghosts may lead to a lack of correctness until
 
157
        the reweave updates the parents list.
 
158
        """
 
159
        if self._revision_store.text_store.listable():
 
160
            return self._revision_store.all_revision_ids(self.get_transaction())
 
161
        result = self._all_possible_ids()
 
162
        return self._eliminate_revisions_not_present(result)
 
163
 
 
164
    def break_lock(self):
 
165
        """Break a lock if one is present from another instance.
 
166
 
 
167
        Uses the ui factory to ask for confirmation if the lock may be from
 
168
        an active process.
 
169
        """
 
170
        self.control_files.break_lock()
 
171
 
 
172
    @needs_read_lock
 
173
    def _eliminate_revisions_not_present(self, revision_ids):
 
174
        """Check every revision id in revision_ids to see if we have it.
 
175
 
 
176
        Returns a set of the present revisions.
 
177
        """
 
178
        result = []
 
179
        for id in revision_ids:
 
180
            if self.has_revision(id):
 
181
               result.append(id)
 
182
        return result
 
183
 
 
184
    @staticmethod
 
185
    def create(a_bzrdir):
 
186
        """Construct the current default format repository in a_bzrdir."""
 
187
        return RepositoryFormat.get_default_format().initialize(a_bzrdir)
 
188
 
 
189
    def __init__(self, _format, a_bzrdir, control_files, _revision_store, control_store, text_store):
 
190
        """instantiate a Repository.
 
191
 
 
192
        :param _format: The format of the repository on disk.
 
193
        :param a_bzrdir: The BzrDir of the repository.
 
194
 
 
195
        In the future we will have a single api for all stores for
 
196
        getting file texts, inventories and revisions, then
 
197
        this construct will accept instances of those things.
 
198
        """
 
199
        super(Repository, self).__init__()
 
200
        self._format = _format
 
201
        # the following are part of the public API for Repository:
 
202
        self.bzrdir = a_bzrdir
 
203
        self.control_files = control_files
 
204
        self._revision_store = _revision_store
 
205
        self.text_store = text_store
 
206
        # backwards compatibility
 
207
        self.weave_store = text_store
 
208
        # not right yet - should be more semantically clear ? 
 
209
        # 
 
210
        self.control_store = control_store
 
211
        self.control_weaves = control_store
 
212
        # TODO: make sure to construct the right store classes, etc, depending
 
213
        # on whether escaping is required.
 
214
        self._warn_if_deprecated()
 
215
 
 
216
    def __repr__(self):
 
217
        return '%s(%r)' % (self.__class__.__name__, 
 
218
                           self.bzrdir.transport.base)
 
219
 
 
220
    def is_locked(self):
 
221
        return self.control_files.is_locked()
 
222
 
 
223
    def lock_write(self):
 
224
        self.control_files.lock_write()
 
225
 
 
226
    def lock_read(self):
 
227
        self.control_files.lock_read()
 
228
 
 
229
    def get_physical_lock_status(self):
 
230
        return self.control_files.get_physical_lock_status()
 
231
 
 
232
    @needs_read_lock
 
233
    def gather_stats(self, revid=None, committers=None):
 
234
        """Gather statistics from a revision id.
 
235
 
 
236
        :param revid: The revision id to gather statistics from, if None, then
 
237
            no revision specific statistics are gathered.
 
238
        :param committers: Optional parameter controlling whether to grab
 
239
            a count of committers from the revision specific statistics.
 
240
        :return: A dictionary of statistics. Currently this contains:
 
241
            committers: The number of committers if requested.
 
242
            firstrev: A tuple with timestamp, timezone for the penultimate left
 
243
                most ancestor of revid, if revid is not the NULL_REVISION.
 
244
            latestrev: A tuple with timestamp, timezone for revid, if revid is
 
245
                not the NULL_REVISION.
 
246
            revisions: The total revision count in the repository.
 
247
            size: An estimate disk size of the repository in bytes.
 
248
        """
 
249
        result = {}
 
250
        if revid and committers:
 
251
            result['committers'] = 0
 
252
        if revid and revid != _mod_revision.NULL_REVISION:
 
253
            if committers:
 
254
                all_committers = set()
 
255
            revisions = self.get_ancestry(revid)
 
256
            # pop the leading None
 
257
            revisions.pop(0)
 
258
            first_revision = None
 
259
            if not committers:
 
260
                # ignore the revisions in the middle - just grab first and last
 
261
                revisions = revisions[0], revisions[-1]
 
262
            for revision in self.get_revisions(revisions):
 
263
                if not first_revision:
 
264
                    first_revision = revision
 
265
                if committers:
 
266
                    all_committers.add(revision.committer)
 
267
            last_revision = revision
 
268
            if committers:
 
269
                result['committers'] = len(all_committers)
 
270
            result['firstrev'] = (first_revision.timestamp,
 
271
                first_revision.timezone)
 
272
            result['latestrev'] = (last_revision.timestamp,
 
273
                last_revision.timezone)
 
274
 
 
275
        # now gather global repository information
 
276
        if self.bzrdir.root_transport.listable():
 
277
            c, t = self._revision_store.total_size(self.get_transaction())
 
278
            result['revisions'] = c
 
279
            result['size'] = t
 
280
        return result
 
281
 
 
282
    @needs_read_lock
 
283
    def missing_revision_ids(self, other, revision_id=None):
 
284
        """Return the revision ids that other has that this does not.
 
285
        
 
286
        These are returned in topological order.
 
287
 
 
288
        revision_id: only return revision ids included by revision_id.
 
289
        """
 
290
        return InterRepository.get(other, self).missing_revision_ids(revision_id)
 
291
 
 
292
    @staticmethod
 
293
    def open(base):
 
294
        """Open the repository rooted at base.
 
295
 
 
296
        For instance, if the repository is at URL/.bzr/repository,
 
297
        Repository.open(URL) -> a Repository instance.
 
298
        """
 
299
        control = bzrdir.BzrDir.open(base)
 
300
        return control.open_repository()
 
301
 
 
302
    def copy_content_into(self, destination, revision_id=None, basis=None):
 
303
        """Make a complete copy of the content in self into destination.
 
304
        
 
305
        This is a destructive operation! Do not use it on existing 
 
306
        repositories.
 
307
        """
 
308
        return InterRepository.get(self, destination).copy_content(revision_id, basis)
 
309
 
 
310
    def fetch(self, source, revision_id=None, pb=None):
 
311
        """Fetch the content required to construct revision_id from source.
 
312
 
 
313
        If revision_id is None all content is copied.
 
314
        """
 
315
        return InterRepository.get(source, self).fetch(revision_id=revision_id,
 
316
                                                       pb=pb)
 
317
 
 
318
    def get_commit_builder(self, branch, parents, config, timestamp=None, 
 
319
                           timezone=None, committer=None, revprops=None, 
 
320
                           revision_id=None):
 
321
        """Obtain a CommitBuilder for this repository.
 
322
        
 
323
        :param branch: Branch to commit to.
 
324
        :param parents: Revision ids of the parents of the new revision.
 
325
        :param config: Configuration to use.
 
326
        :param timestamp: Optional timestamp recorded for commit.
 
327
        :param timezone: Optional timezone for timestamp.
 
328
        :param committer: Optional committer to set for commit.
 
329
        :param revprops: Optional dictionary of revision properties.
 
330
        :param revision_id: Optional revision id.
 
331
        """
 
332
        return _CommitBuilder(self, parents, config, timestamp, timezone,
 
333
                              committer, revprops, revision_id)
 
334
 
 
335
    def unlock(self):
 
336
        self.control_files.unlock()
 
337
 
 
338
    @needs_read_lock
 
339
    def clone(self, a_bzrdir, revision_id=None, basis=None):
 
340
        """Clone this repository into a_bzrdir using the current format.
 
341
 
 
342
        Currently no check is made that the format of this repository and
 
343
        the bzrdir format are compatible. FIXME RBC 20060201.
 
344
 
 
345
        :return: The newly created destination repository.
 
346
        """
 
347
        if not isinstance(a_bzrdir._format, self.bzrdir._format.__class__):
 
348
            # use target default format.
 
349
            dest_repo = a_bzrdir.create_repository()
 
350
        else:
 
351
            # Most control formats need the repository to be specifically
 
352
            # created, but on some old all-in-one formats it's not needed
 
353
            try:
 
354
                dest_repo = self._format.initialize(a_bzrdir, shared=self.is_shared())
 
355
            except errors.UninitializableFormat:
 
356
                dest_repo = a_bzrdir.open_repository()
 
357
        self.copy_content_into(dest_repo, revision_id, basis)
 
358
        return dest_repo
 
359
 
 
360
    @needs_read_lock
 
361
    def has_revision(self, revision_id):
 
362
        """True if this repository has a copy of the revision."""
 
363
        return self._revision_store.has_revision_id(revision_id,
 
364
                                                    self.get_transaction())
 
365
 
 
366
    @needs_read_lock
 
367
    def get_revision_reconcile(self, revision_id):
 
368
        """'reconcile' helper routine that allows access to a revision always.
 
369
        
 
370
        This variant of get_revision does not cross check the weave graph
 
371
        against the revision one as get_revision does: but it should only
 
372
        be used by reconcile, or reconcile-alike commands that are correcting
 
373
        or testing the revision graph.
 
374
        """
 
375
        if not revision_id or not isinstance(revision_id, basestring):
 
376
            raise errors.InvalidRevisionId(revision_id=revision_id,
 
377
                                           branch=self)
 
378
        return self._revision_store.get_revisions([revision_id],
 
379
                                                  self.get_transaction())[0]
 
380
    @needs_read_lock
 
381
    def get_revisions(self, revision_ids):
 
382
        return self._revision_store.get_revisions(revision_ids,
 
383
                                                  self.get_transaction())
 
384
 
 
385
    @needs_read_lock
 
386
    def get_revision_xml(self, revision_id):
 
387
        rev = self.get_revision(revision_id) 
 
388
        rev_tmp = StringIO()
 
389
        # the current serializer..
 
390
        self._revision_store._serializer.write_revision(rev, rev_tmp)
 
391
        rev_tmp.seek(0)
 
392
        return rev_tmp.getvalue()
 
393
 
 
394
    @needs_read_lock
 
395
    def get_revision(self, revision_id):
 
396
        """Return the Revision object for a named revision"""
 
397
        r = self.get_revision_reconcile(revision_id)
 
398
        # weave corruption can lead to absent revision markers that should be
 
399
        # present.
 
400
        # the following test is reasonably cheap (it needs a single weave read)
 
401
        # and the weave is cached in read transactions. In write transactions
 
402
        # it is not cached but typically we only read a small number of
 
403
        # revisions. For knits when they are introduced we will probably want
 
404
        # to ensure that caching write transactions are in use.
 
405
        inv = self.get_inventory_weave()
 
406
        self._check_revision_parents(r, inv)
 
407
        return r
 
408
 
 
409
    @needs_read_lock
 
410
    def get_deltas_for_revisions(self, revisions):
 
411
        """Produce a generator of revision deltas.
 
412
        
 
413
        Note that the input is a sequence of REVISIONS, not revision_ids.
 
414
        Trees will be held in memory until the generator exits.
 
415
        Each delta is relative to the revision's lefthand predecessor.
 
416
        """
 
417
        required_trees = set()
 
418
        for revision in revisions:
 
419
            required_trees.add(revision.revision_id)
 
420
            required_trees.update(revision.parent_ids[:1])
 
421
        trees = dict((t.get_revision_id(), t) for 
 
422
                     t in self.revision_trees(required_trees))
 
423
        for revision in revisions:
 
424
            if not revision.parent_ids:
 
425
                old_tree = self.revision_tree(None)
 
426
            else:
 
427
                old_tree = trees[revision.parent_ids[0]]
 
428
            yield trees[revision.revision_id].changes_from(old_tree)
 
429
 
 
430
    @needs_read_lock
 
431
    def get_revision_delta(self, revision_id):
 
432
        """Return the delta for one revision.
 
433
 
 
434
        The delta is relative to the left-hand predecessor of the
 
435
        revision.
 
436
        """
 
437
        r = self.get_revision(revision_id)
 
438
        return list(self.get_deltas_for_revisions([r]))[0]
 
439
 
 
440
    def _check_revision_parents(self, revision, inventory):
 
441
        """Private to Repository and Fetch.
 
442
        
 
443
        This checks the parentage of revision in an inventory weave for 
 
444
        consistency and is only applicable to inventory-weave-for-ancestry
 
445
        using repository formats & fetchers.
 
446
        """
 
447
        weave_parents = inventory.get_parents(revision.revision_id)
 
448
        weave_names = inventory.versions()
 
449
        for parent_id in revision.parent_ids:
 
450
            if parent_id in weave_names:
 
451
                # this parent must not be a ghost.
 
452
                if not parent_id in weave_parents:
 
453
                    # but it is a ghost
 
454
                    raise errors.CorruptRepository(self)
 
455
 
 
456
    @needs_write_lock
 
457
    def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
 
458
        signature = gpg_strategy.sign(plaintext)
 
459
        self._revision_store.add_revision_signature_text(revision_id,
 
460
                                                         signature,
 
461
                                                         self.get_transaction())
 
462
 
 
463
    def fileids_altered_by_revision_ids(self, revision_ids):
 
464
        """Find the file ids and versions affected by revisions.
 
465
 
 
466
        :param revisions: an iterable containing revision ids.
 
467
        :return: a dictionary mapping altered file-ids to an iterable of
 
468
        revision_ids. Each altered file-ids has the exact revision_ids that
 
469
        altered it listed explicitly.
 
470
        """
 
471
        assert self._serializer.support_altered_by_hack, \
 
472
            ("fileids_altered_by_revision_ids only supported for branches " 
 
473
             "which store inventory as unnested xml, not on %r" % self)
 
474
        selected_revision_ids = set(revision_ids)
 
475
        w = self.get_inventory_weave()
 
476
        result = {}
 
477
 
 
478
        # this code needs to read every new line in every inventory for the
 
479
        # inventories [revision_ids]. Seeing a line twice is ok. Seeing a line
 
480
        # not present in one of those inventories is unnecessary but not 
 
481
        # harmful because we are filtering by the revision id marker in the
 
482
        # inventory lines : we only select file ids altered in one of those  
 
483
        # revisions. We don't need to see all lines in the inventory because
 
484
        # only those added in an inventory in rev X can contain a revision=X
 
485
        # line.
 
486
        unescape_revid_cache = {}
 
487
        unescape_fileid_cache = {}
 
488
 
 
489
        # jam 20061218 In a big fetch, this handles hundreds of thousands
 
490
        # of lines, so it has had a lot of inlining and optimizing done.
 
491
        # Sorry that it is a little bit messy.
 
492
        # Move several functions to be local variables, since this is a long
 
493
        # running loop.
 
494
        search = self._file_ids_altered_regex.search
 
495
        unescape = _unescape_xml
 
496
        setdefault = result.setdefault
 
497
        pb = ui.ui_factory.nested_progress_bar()
 
498
        try:
 
499
            for line in w.iter_lines_added_or_present_in_versions(
 
500
                                        selected_revision_ids, pb=pb):
 
501
                match = search(line)
 
502
                if match is None:
 
503
                    continue
 
504
                # One call to match.group() returning multiple items is quite a
 
505
                # bit faster than 2 calls to match.group() each returning 1
 
506
                file_id, revision_id = match.group('file_id', 'revision_id')
 
507
 
 
508
                # Inlining the cache lookups helps a lot when you make 170,000
 
509
                # lines and 350k ids, versus 8.4 unique ids.
 
510
                # Using a cache helps in 2 ways:
 
511
                #   1) Avoids unnecessary decoding calls
 
512
                #   2) Re-uses cached strings, which helps in future set and
 
513
                #      equality checks.
 
514
                # (2) is enough that removing encoding entirely along with
 
515
                # the cache (so we are using plain strings) results in no
 
516
                # performance improvement.
 
517
                try:
 
518
                    revision_id = unescape_revid_cache[revision_id]
 
519
                except KeyError:
 
520
                    unescaped = unescape(revision_id)
 
521
                    unescape_revid_cache[revision_id] = unescaped
 
522
                    revision_id = unescaped
 
523
 
 
524
                if revision_id in selected_revision_ids:
 
525
                    try:
 
526
                        file_id = unescape_fileid_cache[file_id]
 
527
                    except KeyError:
 
528
                        unescaped = unescape(file_id)
 
529
                        unescape_fileid_cache[file_id] = unescaped
 
530
                        file_id = unescaped
 
531
                    setdefault(file_id, set()).add(revision_id)
 
532
        finally:
 
533
            pb.finished()
 
534
        return result
 
535
 
 
536
    @needs_read_lock
 
537
    def get_inventory_weave(self):
 
538
        return self.control_weaves.get_weave('inventory',
 
539
            self.get_transaction())
 
540
 
 
541
    @needs_read_lock
 
542
    def get_inventory(self, revision_id):
 
543
        """Get Inventory object by hash."""
 
544
        return self.deserialise_inventory(
 
545
            revision_id, self.get_inventory_xml(revision_id))
 
546
 
 
547
    def deserialise_inventory(self, revision_id, xml):
 
548
        """Transform the xml into an inventory object. 
 
549
 
 
550
        :param revision_id: The expected revision id of the inventory.
 
551
        :param xml: A serialised inventory.
 
552
        """
 
553
        result = self._serializer.read_inventory_from_string(xml)
 
554
        result.root.revision = revision_id
 
555
        return result
 
556
 
 
557
    def serialise_inventory(self, inv):
 
558
        return self._serializer.write_inventory_to_string(inv)
 
559
 
 
560
    @needs_read_lock
 
561
    def get_inventory_xml(self, revision_id):
 
562
        """Get inventory XML as a file object."""
 
563
        try:
 
564
            assert isinstance(revision_id, basestring), type(revision_id)
 
565
            iw = self.get_inventory_weave()
 
566
            return iw.get_text(revision_id)
 
567
        except IndexError:
 
568
            raise errors.HistoryMissing(self, 'inventory', revision_id)
 
569
 
 
570
    @needs_read_lock
 
571
    def get_inventory_sha1(self, revision_id):
 
572
        """Return the sha1 hash of the inventory entry
 
573
        """
 
574
        return self.get_revision(revision_id).inventory_sha1
 
575
 
 
576
    @needs_read_lock
 
577
    def get_revision_graph(self, revision_id=None):
 
578
        """Return a dictionary containing the revision graph.
 
579
        
 
580
        :param revision_id: The revision_id to get a graph from. If None, then
 
581
        the entire revision graph is returned. This is a deprecated mode of
 
582
        operation and will be removed in the future.
 
583
        :return: a dictionary of revision_id->revision_parents_list.
 
584
        """
 
585
        # special case NULL_REVISION
 
586
        if revision_id == _mod_revision.NULL_REVISION:
 
587
            return {}
 
588
        a_weave = self.get_inventory_weave()
 
589
        all_revisions = self._eliminate_revisions_not_present(
 
590
                                a_weave.versions())
 
591
        entire_graph = dict([(node, a_weave.get_parents(node)) for 
 
592
                             node in all_revisions])
 
593
        if revision_id is None:
 
594
            return entire_graph
 
595
        elif revision_id not in entire_graph:
 
596
            raise errors.NoSuchRevision(self, revision_id)
 
597
        else:
 
598
            # add what can be reached from revision_id
 
599
            result = {}
 
600
            pending = set([revision_id])
 
601
            while len(pending) > 0:
 
602
                node = pending.pop()
 
603
                result[node] = entire_graph[node]
 
604
                for revision_id in result[node]:
 
605
                    if revision_id not in result:
 
606
                        pending.add(revision_id)
 
607
            return result
 
608
 
 
609
    @needs_read_lock
 
610
    def get_revision_graph_with_ghosts(self, revision_ids=None):
 
611
        """Return a graph of the revisions with ghosts marked as applicable.
 
612
 
 
613
        :param revision_ids: an iterable of revisions to graph or None for all.
 
614
        :return: a Graph object with the graph reachable from revision_ids.
 
615
        """
 
616
        result = graph.Graph()
 
617
        if not revision_ids:
 
618
            pending = set(self.all_revision_ids())
 
619
            required = set([])
 
620
        else:
 
621
            pending = set(revision_ids)
 
622
            # special case NULL_REVISION
 
623
            if _mod_revision.NULL_REVISION in pending:
 
624
                pending.remove(_mod_revision.NULL_REVISION)
 
625
            required = set(pending)
 
626
        done = set([])
 
627
        while len(pending):
 
628
            revision_id = pending.pop()
 
629
            try:
 
630
                rev = self.get_revision(revision_id)
 
631
            except errors.NoSuchRevision:
 
632
                if revision_id in required:
 
633
                    raise
 
634
                # a ghost
 
635
                result.add_ghost(revision_id)
 
636
                continue
 
637
            for parent_id in rev.parent_ids:
 
638
                # is this queued or done ?
 
639
                if (parent_id not in pending and
 
640
                    parent_id not in done):
 
641
                    # no, queue it.
 
642
                    pending.add(parent_id)
 
643
            result.add_node(revision_id, rev.parent_ids)
 
644
            done.add(revision_id)
 
645
        return result
 
646
 
 
647
    @needs_read_lock
 
648
    def get_revision_inventory(self, revision_id):
 
649
        """Return inventory of a past revision."""
 
650
        # TODO: Unify this with get_inventory()
 
651
        # bzr 0.0.6 and later imposes the constraint that the inventory_id
 
652
        # must be the same as its revision, so this is trivial.
 
653
        if revision_id is None:
 
654
            # This does not make sense: if there is no revision,
 
655
            # then it is the current tree inventory surely ?!
 
656
            # and thus get_root_id() is something that looks at the last
 
657
            # commit on the branch, and the get_root_id is an inventory check.
 
658
            raise NotImplementedError
 
659
            # return Inventory(self.get_root_id())
 
660
        else:
 
661
            return self.get_inventory(revision_id)
 
662
 
 
663
    @needs_read_lock
 
664
    def is_shared(self):
 
665
        """Return True if this repository is flagged as a shared repository."""
 
666
        raise NotImplementedError(self.is_shared)
 
667
 
 
668
    @needs_write_lock
 
669
    def reconcile(self, other=None, thorough=False):
 
670
        """Reconcile this repository."""
 
671
        from bzrlib.reconcile import RepoReconciler
 
672
        reconciler = RepoReconciler(self, thorough=thorough)
 
673
        reconciler.reconcile()
 
674
        return reconciler
 
675
    
 
676
    @needs_read_lock
 
677
    def revision_tree(self, revision_id):
 
678
        """Return Tree for a revision on this branch.
 
679
 
 
680
        `revision_id` may be None for the empty tree revision.
 
681
        """
 
682
        # TODO: refactor this to use an existing revision object
 
683
        # so we don't need to read it in twice.
 
684
        if revision_id is None or revision_id == _mod_revision.NULL_REVISION:
 
685
            return RevisionTree(self, Inventory(root_id=None), 
 
686
                                _mod_revision.NULL_REVISION)
 
687
        else:
 
688
            inv = self.get_revision_inventory(revision_id)
 
689
            return RevisionTree(self, inv, revision_id)
 
690
 
 
691
    @needs_read_lock
 
692
    def revision_trees(self, revision_ids):
 
693
        """Return Tree for a revision on this branch.
 
694
 
 
695
        `revision_id` may not be None or 'null:'"""
 
696
        assert None not in revision_ids
 
697
        assert _mod_revision.NULL_REVISION not in revision_ids
 
698
        texts = self.get_inventory_weave().get_texts(revision_ids)
 
699
        for text, revision_id in zip(texts, revision_ids):
 
700
            inv = self.deserialise_inventory(revision_id, text)
 
701
            yield RevisionTree(self, inv, revision_id)
 
702
 
 
703
    @needs_read_lock
 
704
    def get_ancestry(self, revision_id):
 
705
        """Return a list of revision-ids integrated by a revision.
 
706
 
 
707
        The first element of the list is always None, indicating the origin 
 
708
        revision.  This might change when we have history horizons, or 
 
709
        perhaps we should have a new API.
 
710
        
 
711
        This is topologically sorted.
 
712
        """
 
713
        if revision_id is None:
 
714
            return [None]
 
715
        if not self.has_revision(revision_id):
 
716
            raise errors.NoSuchRevision(self, revision_id)
 
717
        w = self.get_inventory_weave()
 
718
        candidates = w.get_ancestry(revision_id)
 
719
        return [None] + candidates # self._eliminate_revisions_not_present(candidates)
 
720
 
 
721
    @needs_read_lock
 
722
    def print_file(self, file, revision_id):
 
723
        """Print `file` to stdout.
 
724
        
 
725
        FIXME RBC 20060125 as John Meinel points out this is a bad api
 
726
        - it writes to stdout, it assumes that that is valid etc. Fix
 
727
        by creating a new more flexible convenience function.
 
728
        """
 
729
        tree = self.revision_tree(revision_id)
 
730
        # use inventory as it was in that revision
 
731
        file_id = tree.inventory.path2id(file)
 
732
        if not file_id:
 
733
            # TODO: jam 20060427 Write a test for this code path
 
734
            #       it had a bug in it, and was raising the wrong
 
735
            #       exception.
 
736
            raise errors.BzrError("%r is not present in revision %s" % (file, revision_id))
 
737
        tree.print_file(file_id)
 
738
 
 
739
    def get_transaction(self):
 
740
        return self.control_files.get_transaction()
 
741
 
 
742
    def revision_parents(self, revid):
 
743
        return self.get_inventory_weave().parent_names(revid)
 
744
 
 
745
    @needs_write_lock
 
746
    def set_make_working_trees(self, new_value):
 
747
        """Set the policy flag for making working trees when creating branches.
 
748
 
 
749
        This only applies to branches that use this repository.
 
750
 
 
751
        The default is 'True'.
 
752
        :param new_value: True to restore the default, False to disable making
 
753
                          working trees.
 
754
        """
 
755
        raise NotImplementedError(self.set_make_working_trees)
 
756
    
 
757
    def make_working_trees(self):
 
758
        """Returns the policy for making working trees on new branches."""
 
759
        raise NotImplementedError(self.make_working_trees)
 
760
 
 
761
    @needs_write_lock
 
762
    def sign_revision(self, revision_id, gpg_strategy):
 
763
        plaintext = Testament.from_revision(self, revision_id).as_short_text()
 
764
        self.store_revision_signature(gpg_strategy, plaintext, revision_id)
 
765
 
 
766
    @needs_read_lock
 
767
    def has_signature_for_revision_id(self, revision_id):
 
768
        """Query for a revision signature for revision_id in the repository."""
 
769
        return self._revision_store.has_signature(revision_id,
 
770
                                                  self.get_transaction())
 
771
 
 
772
    @needs_read_lock
 
773
    def get_signature_text(self, revision_id):
 
774
        """Return the text for a signature."""
 
775
        return self._revision_store.get_signature_text(revision_id,
 
776
                                                       self.get_transaction())
 
777
 
 
778
    @needs_read_lock
 
779
    def check(self, revision_ids):
 
780
        """Check consistency of all history of given revision_ids.
 
781
 
 
782
        Different repository implementations should override _check().
 
783
 
 
784
        :param revision_ids: A non-empty list of revision_ids whose ancestry
 
785
             will be checked.  Typically the last revision_id of a branch.
 
786
        """
 
787
        if not revision_ids:
 
788
            raise ValueError("revision_ids must be non-empty in %s.check" 
 
789
                    % (self,))
 
790
        return self._check(revision_ids)
 
791
 
 
792
    def _check(self, revision_ids):
 
793
        result = check.Check(self)
 
794
        result.check()
 
795
        return result
 
796
 
 
797
    def _warn_if_deprecated(self):
 
798
        global _deprecation_warning_done
 
799
        if _deprecation_warning_done:
 
800
            return
 
801
        _deprecation_warning_done = True
 
802
        warning("Format %s for %s is deprecated - please use 'bzr upgrade' to get better performance"
 
803
                % (self._format, self.bzrdir.transport.base))
 
804
 
 
805
    def supports_rich_root(self):
 
806
        return self._format.rich_root_data
 
807
 
 
808
    def _check_ascii_revisionid(self, revision_id, method):
 
809
        """Private helper for ascii-only repositories."""
 
810
        # weave repositories refuse to store revisionids that are non-ascii.
 
811
        if revision_id is not None:
 
812
            # weaves require ascii revision ids.
 
813
            if isinstance(revision_id, unicode):
 
814
                try:
 
815
                    revision_id.encode('ascii')
 
816
                except UnicodeEncodeError:
 
817
                    raise errors.NonAsciiRevisionId(method, self)
 
818
 
 
819
 
 
820
 
 
821
# remove these delegates a while after bzr 0.15
 
822
def __make_delegated(name, from_module):
 
823
    def _deprecated_repository_forwarder():
 
824
        symbol_versioning.warn('%s moved to %s in bzr 0.15'
 
825
            % (name, from_module),
 
826
            DeprecationWarning,
 
827
            stacklevel=2)
 
828
        m = __import__(from_module, globals(), locals(), [name])
 
829
        try:
 
830
            return getattr(m, name)
 
831
        except AttributeError:
 
832
            raise AttributeError('module %s has no name %s'
 
833
                    % (m, name))
 
834
    globals()[name] = _deprecated_repository_forwarder
 
835
 
 
836
for _name in [
 
837
        'AllInOneRepository',
 
838
        'WeaveMetaDirRepository',
 
839
        'PreSplitOutRepositoryFormat',
 
840
        'RepositoryFormat4',
 
841
        'RepositoryFormat5',
 
842
        'RepositoryFormat6',
 
843
        'RepositoryFormat7',
 
844
        ]:
 
845
    __make_delegated(_name, 'bzrlib.repofmt.weaverepo')
 
846
 
 
847
for _name in [
 
848
        'KnitRepository',
 
849
        'KnitRepository2',
 
850
        'RepositoryFormatKnit',
 
851
        'RepositoryFormatKnit1',
 
852
        'RepositoryFormatKnit2',
 
853
        ]:
 
854
    __make_delegated(_name, 'bzrlib.repofmt.knitrepo')
 
855
 
 
856
 
 
857
def install_revision(repository, rev, revision_tree):
 
858
    """Install all revision data into a repository."""
 
859
    present_parents = []
 
860
    parent_trees = {}
 
861
    for p_id in rev.parent_ids:
 
862
        if repository.has_revision(p_id):
 
863
            present_parents.append(p_id)
 
864
            parent_trees[p_id] = repository.revision_tree(p_id)
 
865
        else:
 
866
            parent_trees[p_id] = repository.revision_tree(None)
 
867
 
 
868
    inv = revision_tree.inventory
 
869
    entries = inv.iter_entries()
 
870
    # backwards compatability hack: skip the root id.
 
871
    if not repository.supports_rich_root():
 
872
        path, root = entries.next()
 
873
        if root.revision != rev.revision_id:
 
874
            raise errors.IncompatibleRevision(repr(repository))
 
875
    # Add the texts that are not already present
 
876
    for path, ie in entries:
 
877
        w = repository.weave_store.get_weave_or_empty(ie.file_id,
 
878
                repository.get_transaction())
 
879
        if ie.revision not in w:
 
880
            text_parents = []
 
881
            # FIXME: TODO: The following loop *may* be overlapping/duplicate
 
882
            # with InventoryEntry.find_previous_heads(). if it is, then there
 
883
            # is a latent bug here where the parents may have ancestors of each
 
884
            # other. RBC, AB
 
885
            for revision, tree in parent_trees.iteritems():
 
886
                if ie.file_id not in tree:
 
887
                    continue
 
888
                parent_id = tree.inventory[ie.file_id].revision
 
889
                if parent_id in text_parents:
 
890
                    continue
 
891
                text_parents.append(parent_id)
 
892
                    
 
893
            vfile = repository.weave_store.get_weave_or_empty(ie.file_id, 
 
894
                repository.get_transaction())
 
895
            lines = revision_tree.get_file(ie.file_id).readlines()
 
896
            vfile.add_lines(rev.revision_id, text_parents, lines)
 
897
    try:
 
898
        # install the inventory
 
899
        repository.add_inventory(rev.revision_id, inv, present_parents)
 
900
    except errors.RevisionAlreadyPresent:
 
901
        pass
 
902
    repository.add_revision(rev.revision_id, rev, inv)
 
903
 
 
904
 
 
905
class MetaDirRepository(Repository):
 
906
    """Repositories in the new meta-dir layout."""
 
907
 
 
908
    def __init__(self, _format, a_bzrdir, control_files, _revision_store, control_store, text_store):
 
909
        super(MetaDirRepository, self).__init__(_format,
 
910
                                                a_bzrdir,
 
911
                                                control_files,
 
912
                                                _revision_store,
 
913
                                                control_store,
 
914
                                                text_store)
 
915
        dir_mode = self.control_files._dir_mode
 
916
        file_mode = self.control_files._file_mode
 
917
 
 
918
    @needs_read_lock
 
919
    def is_shared(self):
 
920
        """Return True if this repository is flagged as a shared repository."""
 
921
        return self.control_files._transport.has('shared-storage')
 
922
 
 
923
    @needs_write_lock
 
924
    def set_make_working_trees(self, new_value):
 
925
        """Set the policy flag for making working trees when creating branches.
 
926
 
 
927
        This only applies to branches that use this repository.
 
928
 
 
929
        The default is 'True'.
 
930
        :param new_value: True to restore the default, False to disable making
 
931
                          working trees.
 
932
        """
 
933
        if new_value:
 
934
            try:
 
935
                self.control_files._transport.delete('no-working-trees')
 
936
            except errors.NoSuchFile:
 
937
                pass
 
938
        else:
 
939
            self.control_files.put_utf8('no-working-trees', '')
 
940
    
 
941
    def make_working_trees(self):
 
942
        """Returns the policy for making working trees on new branches."""
 
943
        return not self.control_files._transport.has('no-working-trees')
 
944
 
 
945
 
 
946
class RepositoryFormatRegistry(registry.Registry):
 
947
    """Registry of RepositoryFormats.
 
948
    """
 
949
 
 
950
    def get(self, format_string):
 
951
        r = registry.Registry.get(self, format_string)
 
952
        if callable(r):
 
953
            r = r()
 
954
        return r
 
955
    
 
956
 
 
957
format_registry = RepositoryFormatRegistry()
 
958
"""Registry of formats, indexed by their identifying format string.
 
959
 
 
960
This can contain either format instances themselves, or classes/factories that
 
961
can be called to obtain one.
 
962
"""
 
963
 
 
964
 
 
965
class RepositoryFormat(object):
 
966
    """A repository format.
 
967
 
 
968
    Formats provide three things:
 
969
     * An initialization routine to construct repository data on disk.
 
970
     * a format string which is used when the BzrDir supports versioned
 
971
       children.
 
972
     * an open routine which returns a Repository instance.
 
973
 
 
974
    Formats are placed in an dict by their format string for reference 
 
975
    during opening. These should be subclasses of RepositoryFormat
 
976
    for consistency.
 
977
 
 
978
    Once a format is deprecated, just deprecate the initialize and open
 
979
    methods on the format class. Do not deprecate the object, as the 
 
980
    object will be created every system load.
 
981
 
 
982
    Common instance attributes:
 
983
    _matchingbzrdir - the bzrdir format that the repository format was
 
984
    originally written to work with. This can be used if manually
 
985
    constructing a bzrdir and repository, or more commonly for test suite
 
986
    parameterisation.
 
987
    """
 
988
 
 
989
    def __str__(self):
 
990
        return "<%s>" % self.__class__.__name__
 
991
 
 
992
    def __eq__(self, other):
 
993
        # format objects are generally stateless
 
994
        return isinstance(other, self.__class__)
 
995
 
 
996
    @classmethod
 
997
    def find_format(klass, a_bzrdir):
 
998
        """Return the format for the repository object in a_bzrdir.
 
999
        
 
1000
        This is used by bzr native formats that have a "format" file in
 
1001
        the repository.  Other methods may be used by different types of 
 
1002
        control directory.
 
1003
        """
 
1004
        try:
 
1005
            transport = a_bzrdir.get_repository_transport(None)
 
1006
            format_string = transport.get("format").read()
 
1007
            return format_registry.get(format_string)
 
1008
        except errors.NoSuchFile:
 
1009
            raise errors.NoRepositoryPresent(a_bzrdir)
 
1010
        except KeyError:
 
1011
            raise errors.UnknownFormatError(format=format_string)
 
1012
 
 
1013
    @classmethod
 
1014
    def register_format(klass, format):
 
1015
        format_registry.register(format.get_format_string(), format)
 
1016
 
 
1017
    @classmethod
 
1018
    def unregister_format(klass, format):
 
1019
        format_registry.remove(format.get_format_string())
 
1020
    
 
1021
    @classmethod
 
1022
    def get_default_format(klass):
 
1023
        """Return the current default format."""
 
1024
        from bzrlib import bzrdir
 
1025
        return bzrdir.format_registry.make_bzrdir('default').repository_format
 
1026
 
 
1027
    def _get_control_store(self, repo_transport, control_files):
 
1028
        """Return the control store for this repository."""
 
1029
        raise NotImplementedError(self._get_control_store)
 
1030
 
 
1031
    def get_format_string(self):
 
1032
        """Return the ASCII format string that identifies this format.
 
1033
        
 
1034
        Note that in pre format ?? repositories the format string is 
 
1035
        not permitted nor written to disk.
 
1036
        """
 
1037
        raise NotImplementedError(self.get_format_string)
 
1038
 
 
1039
    def get_format_description(self):
 
1040
        """Return the short description for this format."""
 
1041
        raise NotImplementedError(self.get_format_description)
 
1042
 
 
1043
    def _get_revision_store(self, repo_transport, control_files):
 
1044
        """Return the revision store object for this a_bzrdir."""
 
1045
        raise NotImplementedError(self._get_revision_store)
 
1046
 
 
1047
    def _get_text_rev_store(self,
 
1048
                            transport,
 
1049
                            control_files,
 
1050
                            name,
 
1051
                            compressed=True,
 
1052
                            prefixed=False,
 
1053
                            serializer=None):
 
1054
        """Common logic for getting a revision store for a repository.
 
1055
        
 
1056
        see self._get_revision_store for the subclass-overridable method to 
 
1057
        get the store for a repository.
 
1058
        """
 
1059
        from bzrlib.store.revision.text import TextRevisionStore
 
1060
        dir_mode = control_files._dir_mode
 
1061
        file_mode = control_files._file_mode
 
1062
        text_store =TextStore(transport.clone(name),
 
1063
                              prefixed=prefixed,
 
1064
                              compressed=compressed,
 
1065
                              dir_mode=dir_mode,
 
1066
                              file_mode=file_mode)
 
1067
        _revision_store = TextRevisionStore(text_store, serializer)
 
1068
        return _revision_store
 
1069
 
 
1070
    # TODO: this shouldn't be in the base class, it's specific to things that
 
1071
    # use weaves or knits -- mbp 20070207
 
1072
    def _get_versioned_file_store(self,
 
1073
                                  name,
 
1074
                                  transport,
 
1075
                                  control_files,
 
1076
                                  prefixed=True,
 
1077
                                  versionedfile_class=None,
 
1078
                                  versionedfile_kwargs={},
 
1079
                                  escaped=False):
 
1080
        if versionedfile_class is None:
 
1081
            versionedfile_class = self._versionedfile_class
 
1082
        weave_transport = control_files._transport.clone(name)
 
1083
        dir_mode = control_files._dir_mode
 
1084
        file_mode = control_files._file_mode
 
1085
        return VersionedFileStore(weave_transport, prefixed=prefixed,
 
1086
                                  dir_mode=dir_mode,
 
1087
                                  file_mode=file_mode,
 
1088
                                  versionedfile_class=versionedfile_class,
 
1089
                                  versionedfile_kwargs=versionedfile_kwargs,
 
1090
                                  escaped=escaped)
 
1091
 
 
1092
    def initialize(self, a_bzrdir, shared=False):
 
1093
        """Initialize a repository of this format in a_bzrdir.
 
1094
 
 
1095
        :param a_bzrdir: The bzrdir to put the new repository in it.
 
1096
        :param shared: The repository should be initialized as a sharable one.
 
1097
 
 
1098
        This may raise UninitializableFormat if shared repository are not
 
1099
        compatible the a_bzrdir.
 
1100
        """
 
1101
 
 
1102
    def is_supported(self):
 
1103
        """Is this format supported?
 
1104
 
 
1105
        Supported formats must be initializable and openable.
 
1106
        Unsupported formats may not support initialization or committing or 
 
1107
        some other features depending on the reason for not being supported.
 
1108
        """
 
1109
        return True
 
1110
 
 
1111
    def check_conversion_target(self, target_format):
 
1112
        raise NotImplementedError(self.check_conversion_target)
 
1113
 
 
1114
    def open(self, a_bzrdir, _found=False):
 
1115
        """Return an instance of this format for the bzrdir a_bzrdir.
 
1116
        
 
1117
        _found is a private parameter, do not use it.
 
1118
        """
 
1119
        raise NotImplementedError(self.open)
 
1120
 
 
1121
 
 
1122
class MetaDirRepositoryFormat(RepositoryFormat):
 
1123
    """Common base class for the new repositories using the metadir layout."""
 
1124
 
 
1125
    rich_root_data = False
 
1126
    _matchingbzrdir = bzrdir.BzrDirMetaFormat1()
 
1127
 
 
1128
    def __init__(self):
 
1129
        super(MetaDirRepositoryFormat, self).__init__()
 
1130
 
 
1131
    def _create_control_files(self, a_bzrdir):
 
1132
        """Create the required files and the initial control_files object."""
 
1133
        # FIXME: RBC 20060125 don't peek under the covers
 
1134
        # NB: no need to escape relative paths that are url safe.
 
1135
        repository_transport = a_bzrdir.get_repository_transport(self)
 
1136
        control_files = lockable_files.LockableFiles(repository_transport,
 
1137
                                'lock', lockdir.LockDir)
 
1138
        control_files.create_lock()
 
1139
        return control_files
 
1140
 
 
1141
    def _upload_blank_content(self, a_bzrdir, dirs, files, utf8_files, shared):
 
1142
        """Upload the initial blank content."""
 
1143
        control_files = self._create_control_files(a_bzrdir)
 
1144
        control_files.lock_write()
 
1145
        try:
 
1146
            control_files._transport.mkdir_multi(dirs,
 
1147
                    mode=control_files._dir_mode)
 
1148
            for file, content in files:
 
1149
                control_files.put(file, content)
 
1150
            for file, content in utf8_files:
 
1151
                control_files.put_utf8(file, content)
 
1152
            if shared == True:
 
1153
                control_files.put_utf8('shared-storage', '')
 
1154
        finally:
 
1155
            control_files.unlock()
 
1156
 
 
1157
 
 
1158
# formats which have no format string are not discoverable
 
1159
# and not independently creatable, so are not registered.  They're 
 
1160
# all in bzrlib.repofmt.weaverepo now.  When an instance of one of these is
 
1161
# needed, it's constructed directly by the BzrDir.  Non-native formats where
 
1162
# the repository is not separately opened are similar.
 
1163
 
 
1164
format_registry.register_lazy(
 
1165
    'Bazaar-NG Repository format 7',
 
1166
    'bzrlib.repofmt.weaverepo',
 
1167
    'RepositoryFormat7'
 
1168
    )
 
1169
# KEEP in sync with bzrdir.format_registry default, which controls the overall
 
1170
# default control directory format
 
1171
 
 
1172
format_registry.register_lazy(
 
1173
    'Bazaar-NG Knit Repository Format 1',
 
1174
    'bzrlib.repofmt.knitrepo',
 
1175
    'RepositoryFormatKnit1',
 
1176
    )
 
1177
format_registry.default_key = 'Bazaar-NG Knit Repository Format 1'
 
1178
 
 
1179
format_registry.register_lazy(
 
1180
    'Bazaar Knit Repository Format 2\n',
 
1181
    'bzrlib.repofmt.knitrepo',
 
1182
    'RepositoryFormatKnit2',
 
1183
    )
 
1184
 
 
1185
 
 
1186
class InterRepository(InterObject):
 
1187
    """This class represents operations taking place between two repositories.
 
1188
 
 
1189
    Its instances have methods like copy_content and fetch, and contain
 
1190
    references to the source and target repositories these operations can be 
 
1191
    carried out on.
 
1192
 
 
1193
    Often we will provide convenience methods on 'repository' which carry out
 
1194
    operations with another repository - they will always forward to
 
1195
    InterRepository.get(other).method_name(parameters).
 
1196
    """
 
1197
 
 
1198
    _optimisers = []
 
1199
    """The available optimised InterRepository types."""
 
1200
 
 
1201
    def copy_content(self, revision_id=None, basis=None):
 
1202
        raise NotImplementedError(self.copy_content)
 
1203
 
 
1204
    def fetch(self, revision_id=None, pb=None):
 
1205
        """Fetch the content required to construct revision_id.
 
1206
 
 
1207
        The content is copied from self.source to self.target.
 
1208
 
 
1209
        :param revision_id: if None all content is copied, if NULL_REVISION no
 
1210
                            content is copied.
 
1211
        :param pb: optional progress bar to use for progress reports. If not
 
1212
                   provided a default one will be created.
 
1213
 
 
1214
        Returns the copied revision count and the failed revisions in a tuple:
 
1215
        (copied, failures).
 
1216
        """
 
1217
        raise NotImplementedError(self.fetch)
 
1218
   
 
1219
    @needs_read_lock
 
1220
    def missing_revision_ids(self, revision_id=None):
 
1221
        """Return the revision ids that source has that target does not.
 
1222
        
 
1223
        These are returned in topological order.
 
1224
 
 
1225
        :param revision_id: only return revision ids included by this
 
1226
                            revision_id.
 
1227
        """
 
1228
        # generic, possibly worst case, slow code path.
 
1229
        target_ids = set(self.target.all_revision_ids())
 
1230
        if revision_id is not None:
 
1231
            source_ids = self.source.get_ancestry(revision_id)
 
1232
            assert source_ids[0] is None
 
1233
            source_ids.pop(0)
 
1234
        else:
 
1235
            source_ids = self.source.all_revision_ids()
 
1236
        result_set = set(source_ids).difference(target_ids)
 
1237
        # this may look like a no-op: its not. It preserves the ordering
 
1238
        # other_ids had while only returning the members from other_ids
 
1239
        # that we've decided we need.
 
1240
        return [rev_id for rev_id in source_ids if rev_id in result_set]
 
1241
 
 
1242
 
 
1243
class InterSameDataRepository(InterRepository):
 
1244
    """Code for converting between repositories that represent the same data.
 
1245
    
 
1246
    Data format and model must match for this to work.
 
1247
    """
 
1248
 
 
1249
    @classmethod
 
1250
    def _get_repo_format_to_test(self):
 
1251
        """Repository format for testing with."""
 
1252
        return RepositoryFormat.get_default_format()
 
1253
 
 
1254
    @staticmethod
 
1255
    def is_compatible(source, target):
 
1256
        if not isinstance(source, Repository):
 
1257
            return False
 
1258
        if not isinstance(target, Repository):
 
1259
            return False
 
1260
        if source._format.rich_root_data == target._format.rich_root_data:
 
1261
            return True
 
1262
        else:
 
1263
            return False
 
1264
 
 
1265
    @needs_write_lock
 
1266
    def copy_content(self, revision_id=None, basis=None):
 
1267
        """Make a complete copy of the content in self into destination.
 
1268
        
 
1269
        This is a destructive operation! Do not use it on existing 
 
1270
        repositories.
 
1271
 
 
1272
        :param revision_id: Only copy the content needed to construct
 
1273
                            revision_id and its parents.
 
1274
        :param basis: Copy the needed data preferentially from basis.
 
1275
        """
 
1276
        try:
 
1277
            self.target.set_make_working_trees(self.source.make_working_trees())
 
1278
        except NotImplementedError:
 
1279
            pass
 
1280
        # grab the basis available data
 
1281
        if basis is not None:
 
1282
            self.target.fetch(basis, revision_id=revision_id)
 
1283
        # but don't bother fetching if we have the needed data now.
 
1284
        if (revision_id not in (None, _mod_revision.NULL_REVISION) and 
 
1285
            self.target.has_revision(revision_id)):
 
1286
            return
 
1287
        self.target.fetch(self.source, revision_id=revision_id)
 
1288
 
 
1289
    @needs_write_lock
 
1290
    def fetch(self, revision_id=None, pb=None):
 
1291
        """See InterRepository.fetch()."""
 
1292
        from bzrlib.fetch import GenericRepoFetcher
 
1293
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
 
1294
               self.source, self.source._format, self.target, 
 
1295
               self.target._format)
 
1296
        f = GenericRepoFetcher(to_repository=self.target,
 
1297
                               from_repository=self.source,
 
1298
                               last_revision=revision_id,
 
1299
                               pb=pb)
 
1300
        return f.count_copied, f.failed_revisions
 
1301
 
 
1302
 
 
1303
class InterWeaveRepo(InterSameDataRepository):
 
1304
    """Optimised code paths between Weave based repositories."""
 
1305
 
 
1306
    @classmethod
 
1307
    def _get_repo_format_to_test(self):
 
1308
        from bzrlib.repofmt import weaverepo
 
1309
        return weaverepo.RepositoryFormat7()
 
1310
 
 
1311
    @staticmethod
 
1312
    def is_compatible(source, target):
 
1313
        """Be compatible with known Weave formats.
 
1314
        
 
1315
        We don't test for the stores being of specific types because that
 
1316
        could lead to confusing results, and there is no need to be 
 
1317
        overly general.
 
1318
        """
 
1319
        from bzrlib.repofmt.weaverepo import (
 
1320
                RepositoryFormat5,
 
1321
                RepositoryFormat6,
 
1322
                RepositoryFormat7,
 
1323
                )
 
1324
        try:
 
1325
            return (isinstance(source._format, (RepositoryFormat5,
 
1326
                                                RepositoryFormat6,
 
1327
                                                RepositoryFormat7)) and
 
1328
                    isinstance(target._format, (RepositoryFormat5,
 
1329
                                                RepositoryFormat6,
 
1330
                                                RepositoryFormat7)))
 
1331
        except AttributeError:
 
1332
            return False
 
1333
    
 
1334
    @needs_write_lock
 
1335
    def copy_content(self, revision_id=None, basis=None):
 
1336
        """See InterRepository.copy_content()."""
 
1337
        # weave specific optimised path:
 
1338
        if basis is not None:
 
1339
            # copy the basis in, then fetch remaining data.
 
1340
            basis.copy_content_into(self.target, revision_id)
 
1341
            # the basis copy_content_into could miss-set this.
 
1342
            try:
 
1343
                self.target.set_make_working_trees(self.source.make_working_trees())
 
1344
            except NotImplementedError:
 
1345
                pass
 
1346
            self.target.fetch(self.source, revision_id=revision_id)
 
1347
        else:
 
1348
            try:
 
1349
                self.target.set_make_working_trees(self.source.make_working_trees())
 
1350
            except NotImplementedError:
 
1351
                pass
 
1352
            # FIXME do not peek!
 
1353
            if self.source.control_files._transport.listable():
 
1354
                pb = ui.ui_factory.nested_progress_bar()
 
1355
                try:
 
1356
                    self.target.weave_store.copy_all_ids(
 
1357
                        self.source.weave_store,
 
1358
                        pb=pb,
 
1359
                        from_transaction=self.source.get_transaction(),
 
1360
                        to_transaction=self.target.get_transaction())
 
1361
                    pb.update('copying inventory', 0, 1)
 
1362
                    self.target.control_weaves.copy_multi(
 
1363
                        self.source.control_weaves, ['inventory'],
 
1364
                        from_transaction=self.source.get_transaction(),
 
1365
                        to_transaction=self.target.get_transaction())
 
1366
                    self.target._revision_store.text_store.copy_all_ids(
 
1367
                        self.source._revision_store.text_store,
 
1368
                        pb=pb)
 
1369
                finally:
 
1370
                    pb.finished()
 
1371
            else:
 
1372
                self.target.fetch(self.source, revision_id=revision_id)
 
1373
 
 
1374
    @needs_write_lock
 
1375
    def fetch(self, revision_id=None, pb=None):
 
1376
        """See InterRepository.fetch()."""
 
1377
        from bzrlib.fetch import GenericRepoFetcher
 
1378
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
 
1379
               self.source, self.source._format, self.target, self.target._format)
 
1380
        f = GenericRepoFetcher(to_repository=self.target,
 
1381
                               from_repository=self.source,
 
1382
                               last_revision=revision_id,
 
1383
                               pb=pb)
 
1384
        return f.count_copied, f.failed_revisions
 
1385
 
 
1386
    @needs_read_lock
 
1387
    def missing_revision_ids(self, revision_id=None):
 
1388
        """See InterRepository.missing_revision_ids()."""
 
1389
        # we want all revisions to satisfy revision_id in source.
 
1390
        # but we don't want to stat every file here and there.
 
1391
        # we want then, all revisions other needs to satisfy revision_id 
 
1392
        # checked, but not those that we have locally.
 
1393
        # so the first thing is to get a subset of the revisions to 
 
1394
        # satisfy revision_id in source, and then eliminate those that
 
1395
        # we do already have. 
 
1396
        # this is slow on high latency connection to self, but as as this
 
1397
        # disk format scales terribly for push anyway due to rewriting 
 
1398
        # inventory.weave, this is considered acceptable.
 
1399
        # - RBC 20060209
 
1400
        if revision_id is not None:
 
1401
            source_ids = self.source.get_ancestry(revision_id)
 
1402
            assert source_ids[0] is None
 
1403
            source_ids.pop(0)
 
1404
        else:
 
1405
            source_ids = self.source._all_possible_ids()
 
1406
        source_ids_set = set(source_ids)
 
1407
        # source_ids is the worst possible case we may need to pull.
 
1408
        # now we want to filter source_ids against what we actually
 
1409
        # have in target, but don't try to check for existence where we know
 
1410
        # we do not have a revision as that would be pointless.
 
1411
        target_ids = set(self.target._all_possible_ids())
 
1412
        possibly_present_revisions = target_ids.intersection(source_ids_set)
 
1413
        actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
 
1414
        required_revisions = source_ids_set.difference(actually_present_revisions)
 
1415
        required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
 
1416
        if revision_id is not None:
 
1417
            # we used get_ancestry to determine source_ids then we are assured all
 
1418
            # revisions referenced are present as they are installed in topological order.
 
1419
            # and the tip revision was validated by get_ancestry.
 
1420
            return required_topo_revisions
 
1421
        else:
 
1422
            # if we just grabbed the possibly available ids, then 
 
1423
            # we only have an estimate of whats available and need to validate
 
1424
            # that against the revision records.
 
1425
            return self.source._eliminate_revisions_not_present(required_topo_revisions)
 
1426
 
 
1427
 
 
1428
class InterKnitRepo(InterSameDataRepository):
 
1429
    """Optimised code paths between Knit based repositories."""
 
1430
 
 
1431
    @classmethod
 
1432
    def _get_repo_format_to_test(self):
 
1433
        from bzrlib.repofmt import knitrepo
 
1434
        return knitrepo.RepositoryFormatKnit1()
 
1435
 
 
1436
    @staticmethod
 
1437
    def is_compatible(source, target):
 
1438
        """Be compatible with known Knit formats.
 
1439
        
 
1440
        We don't test for the stores being of specific types because that
 
1441
        could lead to confusing results, and there is no need to be 
 
1442
        overly general.
 
1443
        """
 
1444
        from bzrlib.repofmt.knitrepo import RepositoryFormatKnit1
 
1445
        try:
 
1446
            return (isinstance(source._format, (RepositoryFormatKnit1)) and
 
1447
                    isinstance(target._format, (RepositoryFormatKnit1)))
 
1448
        except AttributeError:
 
1449
            return False
 
1450
 
 
1451
    @needs_write_lock
 
1452
    def fetch(self, revision_id=None, pb=None):
 
1453
        """See InterRepository.fetch()."""
 
1454
        from bzrlib.fetch import KnitRepoFetcher
 
1455
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
 
1456
               self.source, self.source._format, self.target, self.target._format)
 
1457
        f = KnitRepoFetcher(to_repository=self.target,
 
1458
                            from_repository=self.source,
 
1459
                            last_revision=revision_id,
 
1460
                            pb=pb)
 
1461
        return f.count_copied, f.failed_revisions
 
1462
 
 
1463
    @needs_read_lock
 
1464
    def missing_revision_ids(self, revision_id=None):
 
1465
        """See InterRepository.missing_revision_ids()."""
 
1466
        if revision_id is not None:
 
1467
            source_ids = self.source.get_ancestry(revision_id)
 
1468
            assert source_ids[0] is None
 
1469
            source_ids.pop(0)
 
1470
        else:
 
1471
            source_ids = self.source._all_possible_ids()
 
1472
        source_ids_set = set(source_ids)
 
1473
        # source_ids is the worst possible case we may need to pull.
 
1474
        # now we want to filter source_ids against what we actually
 
1475
        # have in target, but don't try to check for existence where we know
 
1476
        # we do not have a revision as that would be pointless.
 
1477
        target_ids = set(self.target._all_possible_ids())
 
1478
        possibly_present_revisions = target_ids.intersection(source_ids_set)
 
1479
        actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
 
1480
        required_revisions = source_ids_set.difference(actually_present_revisions)
 
1481
        required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
 
1482
        if revision_id is not None:
 
1483
            # we used get_ancestry to determine source_ids then we are assured all
 
1484
            # revisions referenced are present as they are installed in topological order.
 
1485
            # and the tip revision was validated by get_ancestry.
 
1486
            return required_topo_revisions
 
1487
        else:
 
1488
            # if we just grabbed the possibly available ids, then 
 
1489
            # we only have an estimate of whats available and need to validate
 
1490
            # that against the revision records.
 
1491
            return self.source._eliminate_revisions_not_present(required_topo_revisions)
 
1492
 
 
1493
 
 
1494
class InterModel1and2(InterRepository):
 
1495
 
 
1496
    @classmethod
 
1497
    def _get_repo_format_to_test(self):
 
1498
        return None
 
1499
 
 
1500
    @staticmethod
 
1501
    def is_compatible(source, target):
 
1502
        if not isinstance(source, Repository):
 
1503
            return False
 
1504
        if not isinstance(target, Repository):
 
1505
            return False
 
1506
        if not source._format.rich_root_data and target._format.rich_root_data:
 
1507
            return True
 
1508
        else:
 
1509
            return False
 
1510
 
 
1511
    @needs_write_lock
 
1512
    def fetch(self, revision_id=None, pb=None):
 
1513
        """See InterRepository.fetch()."""
 
1514
        from bzrlib.fetch import Model1toKnit2Fetcher
 
1515
        f = Model1toKnit2Fetcher(to_repository=self.target,
 
1516
                                 from_repository=self.source,
 
1517
                                 last_revision=revision_id,
 
1518
                                 pb=pb)
 
1519
        return f.count_copied, f.failed_revisions
 
1520
 
 
1521
    @needs_write_lock
 
1522
    def copy_content(self, revision_id=None, basis=None):
 
1523
        """Make a complete copy of the content in self into destination.
 
1524
        
 
1525
        This is a destructive operation! Do not use it on existing 
 
1526
        repositories.
 
1527
 
 
1528
        :param revision_id: Only copy the content needed to construct
 
1529
                            revision_id and its parents.
 
1530
        :param basis: Copy the needed data preferentially from basis.
 
1531
        """
 
1532
        try:
 
1533
            self.target.set_make_working_trees(self.source.make_working_trees())
 
1534
        except NotImplementedError:
 
1535
            pass
 
1536
        # grab the basis available data
 
1537
        if basis is not None:
 
1538
            self.target.fetch(basis, revision_id=revision_id)
 
1539
        # but don't bother fetching if we have the needed data now.
 
1540
        if (revision_id not in (None, _mod_revision.NULL_REVISION) and 
 
1541
            self.target.has_revision(revision_id)):
 
1542
            return
 
1543
        self.target.fetch(self.source, revision_id=revision_id)
 
1544
 
 
1545
 
 
1546
class InterKnit1and2(InterKnitRepo):
 
1547
 
 
1548
    @classmethod
 
1549
    def _get_repo_format_to_test(self):
 
1550
        return None
 
1551
 
 
1552
    @staticmethod
 
1553
    def is_compatible(source, target):
 
1554
        """Be compatible with Knit1 source and Knit2 target"""
 
1555
        from bzrlib.repofmt.knitrepo import RepositoryFormatKnit2
 
1556
        try:
 
1557
            from bzrlib.repofmt.knitrepo import RepositoryFormatKnit1, \
 
1558
                    RepositoryFormatKnit2
 
1559
            return (isinstance(source._format, (RepositoryFormatKnit1)) and
 
1560
                    isinstance(target._format, (RepositoryFormatKnit2)))
 
1561
        except AttributeError:
 
1562
            return False
 
1563
 
 
1564
    @needs_write_lock
 
1565
    def fetch(self, revision_id=None, pb=None):
 
1566
        """See InterRepository.fetch()."""
 
1567
        from bzrlib.fetch import Knit1to2Fetcher
 
1568
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
 
1569
               self.source, self.source._format, self.target, 
 
1570
               self.target._format)
 
1571
        f = Knit1to2Fetcher(to_repository=self.target,
 
1572
                            from_repository=self.source,
 
1573
                            last_revision=revision_id,
 
1574
                            pb=pb)
 
1575
        return f.count_copied, f.failed_revisions
 
1576
 
 
1577
 
 
1578
InterRepository.register_optimiser(InterSameDataRepository)
 
1579
InterRepository.register_optimiser(InterWeaveRepo)
 
1580
InterRepository.register_optimiser(InterKnitRepo)
 
1581
InterRepository.register_optimiser(InterModel1and2)
 
1582
InterRepository.register_optimiser(InterKnit1and2)
 
1583
 
 
1584
 
 
1585
class RepositoryTestProviderAdapter(object):
 
1586
    """A tool to generate a suite testing multiple repository formats at once.
 
1587
 
 
1588
    This is done by copying the test once for each transport and injecting
 
1589
    the transport_server, transport_readonly_server, and bzrdir_format and
 
1590
    repository_format classes into each copy. Each copy is also given a new id()
 
1591
    to make it easy to identify.
 
1592
    """
 
1593
 
 
1594
    def __init__(self, transport_server, transport_readonly_server, formats):
 
1595
        self._transport_server = transport_server
 
1596
        self._transport_readonly_server = transport_readonly_server
 
1597
        self._formats = formats
 
1598
    
 
1599
    def adapt(self, test):
 
1600
        result = unittest.TestSuite()
 
1601
        for repository_format, bzrdir_format in self._formats:
 
1602
            from copy import deepcopy
 
1603
            new_test = deepcopy(test)
 
1604
            new_test.transport_server = self._transport_server
 
1605
            new_test.transport_readonly_server = self._transport_readonly_server
 
1606
            new_test.bzrdir_format = bzrdir_format
 
1607
            new_test.repository_format = repository_format
 
1608
            def make_new_test_id():
 
1609
                new_id = "%s(%s)" % (new_test.id(), repository_format.__class__.__name__)
 
1610
                return lambda: new_id
 
1611
            new_test.id = make_new_test_id()
 
1612
            result.addTest(new_test)
 
1613
        return result
 
1614
 
 
1615
 
 
1616
class InterRepositoryTestProviderAdapter(object):
 
1617
    """A tool to generate a suite testing multiple inter repository formats.
 
1618
 
 
1619
    This is done by copying the test once for each interrepo provider and injecting
 
1620
    the transport_server, transport_readonly_server, repository_format and 
 
1621
    repository_to_format classes into each copy.
 
1622
    Each copy is also given a new id() to make it easy to identify.
 
1623
    """
 
1624
 
 
1625
    def __init__(self, transport_server, transport_readonly_server, formats):
 
1626
        self._transport_server = transport_server
 
1627
        self._transport_readonly_server = transport_readonly_server
 
1628
        self._formats = formats
 
1629
    
 
1630
    def adapt(self, test):
 
1631
        result = unittest.TestSuite()
 
1632
        for interrepo_class, repository_format, repository_format_to in self._formats:
 
1633
            from copy import deepcopy
 
1634
            new_test = deepcopy(test)
 
1635
            new_test.transport_server = self._transport_server
 
1636
            new_test.transport_readonly_server = self._transport_readonly_server
 
1637
            new_test.interrepo_class = interrepo_class
 
1638
            new_test.repository_format = repository_format
 
1639
            new_test.repository_format_to = repository_format_to
 
1640
            def make_new_test_id():
 
1641
                new_id = "%s(%s)" % (new_test.id(), interrepo_class.__name__)
 
1642
                return lambda: new_id
 
1643
            new_test.id = make_new_test_id()
 
1644
            result.addTest(new_test)
 
1645
        return result
 
1646
 
 
1647
    @staticmethod
 
1648
    def default_test_list():
 
1649
        """Generate the default list of interrepo permutations to test."""
 
1650
        from bzrlib.repofmt import knitrepo, weaverepo
 
1651
        result = []
 
1652
        # test the default InterRepository between format 6 and the current 
 
1653
        # default format.
 
1654
        # XXX: robertc 20060220 reinstate this when there are two supported
 
1655
        # formats which do not have an optimal code path between them.
 
1656
        #result.append((InterRepository,
 
1657
        #               RepositoryFormat6(),
 
1658
        #               RepositoryFormatKnit1()))
 
1659
        for optimiser_class in InterRepository._optimisers:
 
1660
            format_to_test = optimiser_class._get_repo_format_to_test()
 
1661
            if format_to_test is not None:
 
1662
                result.append((optimiser_class,
 
1663
                               format_to_test, format_to_test))
 
1664
        # if there are specific combinations we want to use, we can add them 
 
1665
        # here.
 
1666
        result.append((InterModel1and2,
 
1667
                       weaverepo.RepositoryFormat5(),
 
1668
                       knitrepo.RepositoryFormatKnit2()))
 
1669
        result.append((InterKnit1and2,
 
1670
                       knitrepo.RepositoryFormatKnit1(),
 
1671
                       knitrepo.RepositoryFormatKnit2()))
 
1672
        return result
 
1673
 
 
1674
 
 
1675
class CopyConverter(object):
 
1676
    """A repository conversion tool which just performs a copy of the content.
 
1677
    
 
1678
    This is slow but quite reliable.
 
1679
    """
 
1680
 
 
1681
    def __init__(self, target_format):
 
1682
        """Create a CopyConverter.
 
1683
 
 
1684
        :param target_format: The format the resulting repository should be.
 
1685
        """
 
1686
        self.target_format = target_format
 
1687
        
 
1688
    def convert(self, repo, pb):
 
1689
        """Perform the conversion of to_convert, giving feedback via pb.
 
1690
 
 
1691
        :param to_convert: The disk object to convert.
 
1692
        :param pb: a progress bar to use for progress information.
 
1693
        """
 
1694
        self.pb = pb
 
1695
        self.count = 0
 
1696
        self.total = 4
 
1697
        # this is only useful with metadir layouts - separated repo content.
 
1698
        # trigger an assertion if not such
 
1699
        repo._format.get_format_string()
 
1700
        self.repo_dir = repo.bzrdir
 
1701
        self.step('Moving repository to repository.backup')
 
1702
        self.repo_dir.transport.move('repository', 'repository.backup')
 
1703
        backup_transport =  self.repo_dir.transport.clone('repository.backup')
 
1704
        repo._format.check_conversion_target(self.target_format)
 
1705
        self.source_repo = repo._format.open(self.repo_dir,
 
1706
            _found=True,
 
1707
            _override_transport=backup_transport)
 
1708
        self.step('Creating new repository')
 
1709
        converted = self.target_format.initialize(self.repo_dir,
 
1710
                                                  self.source_repo.is_shared())
 
1711
        converted.lock_write()
 
1712
        try:
 
1713
            self.step('Copying content into repository.')
 
1714
            self.source_repo.copy_content_into(converted)
 
1715
        finally:
 
1716
            converted.unlock()
 
1717
        self.step('Deleting old repository content.')
 
1718
        self.repo_dir.transport.delete_tree('repository.backup')
 
1719
        self.pb.note('repository converted')
 
1720
 
 
1721
    def step(self, message):
 
1722
        """Update the pb by a step."""
 
1723
        self.count +=1
 
1724
        self.pb.update(message, self.count, self.total)
 
1725
 
 
1726
 
 
1727
class CommitBuilder(object):
 
1728
    """Provides an interface to build up a commit.
 
1729
 
 
1730
    This allows describing a tree to be committed without needing to 
 
1731
    know the internals of the format of the repository.
 
1732
    """
 
1733
    
 
1734
    record_root_entry = False
 
1735
    def __init__(self, repository, parents, config, timestamp=None, 
 
1736
                 timezone=None, committer=None, revprops=None, 
 
1737
                 revision_id=None):
 
1738
        """Initiate a CommitBuilder.
 
1739
 
 
1740
        :param repository: Repository to commit to.
 
1741
        :param parents: Revision ids of the parents of the new revision.
 
1742
        :param config: Configuration to use.
 
1743
        :param timestamp: Optional timestamp recorded for commit.
 
1744
        :param timezone: Optional timezone for timestamp.
 
1745
        :param committer: Optional committer to set for commit.
 
1746
        :param revprops: Optional dictionary of revision properties.
 
1747
        :param revision_id: Optional revision id.
 
1748
        """
 
1749
        self._config = config
 
1750
 
 
1751
        if committer is None:
 
1752
            self._committer = self._config.username()
 
1753
        else:
 
1754
            assert isinstance(committer, basestring), type(committer)
 
1755
            self._committer = committer
 
1756
 
 
1757
        self.new_inventory = Inventory(None)
 
1758
        self._new_revision_id = revision_id
 
1759
        self.parents = parents
 
1760
        self.repository = repository
 
1761
 
 
1762
        self._revprops = {}
 
1763
        if revprops is not None:
 
1764
            self._revprops.update(revprops)
 
1765
 
 
1766
        if timestamp is None:
 
1767
            timestamp = time.time()
 
1768
        # Restrict resolution to 1ms
 
1769
        self._timestamp = round(timestamp, 3)
 
1770
 
 
1771
        if timezone is None:
 
1772
            self._timezone = osutils.local_time_offset()
 
1773
        else:
 
1774
            self._timezone = int(timezone)
 
1775
 
 
1776
        self._generate_revision_if_needed()
 
1777
 
 
1778
    def commit(self, message):
 
1779
        """Make the actual commit.
 
1780
 
 
1781
        :return: The revision id of the recorded revision.
 
1782
        """
 
1783
        rev = _mod_revision.Revision(
 
1784
                       timestamp=self._timestamp,
 
1785
                       timezone=self._timezone,
 
1786
                       committer=self._committer,
 
1787
                       message=message,
 
1788
                       inventory_sha1=self.inv_sha1,
 
1789
                       revision_id=self._new_revision_id,
 
1790
                       properties=self._revprops)
 
1791
        rev.parent_ids = self.parents
 
1792
        self.repository.add_revision(self._new_revision_id, rev, 
 
1793
            self.new_inventory, self._config)
 
1794
        return self._new_revision_id
 
1795
 
 
1796
    def revision_tree(self):
 
1797
        """Return the tree that was just committed.
 
1798
 
 
1799
        After calling commit() this can be called to get a RevisionTree
 
1800
        representing the newly committed tree. This is preferred to
 
1801
        calling Repository.revision_tree() because that may require
 
1802
        deserializing the inventory, while we already have a copy in
 
1803
        memory.
 
1804
        """
 
1805
        return RevisionTree(self.repository, self.new_inventory,
 
1806
                            self._new_revision_id)
 
1807
 
 
1808
    def finish_inventory(self):
 
1809
        """Tell the builder that the inventory is finished."""
 
1810
        if self.new_inventory.root is None:
 
1811
            symbol_versioning.warn('Root entry should be supplied to'
 
1812
                ' record_entry_contents, as of bzr 0.10.',
 
1813
                 DeprecationWarning, stacklevel=2)
 
1814
            self.new_inventory.add(InventoryDirectory(ROOT_ID, '', None))
 
1815
        self.new_inventory.revision_id = self._new_revision_id
 
1816
        self.inv_sha1 = self.repository.add_inventory(
 
1817
            self._new_revision_id,
 
1818
            self.new_inventory,
 
1819
            self.parents
 
1820
            )
 
1821
 
 
1822
    def _gen_revision_id(self):
 
1823
        """Return new revision-id."""
 
1824
        return generate_ids.gen_revision_id(self._config.username(),
 
1825
                                            self._timestamp)
 
1826
 
 
1827
    def _generate_revision_if_needed(self):
 
1828
        """Create a revision id if None was supplied.
 
1829
        
 
1830
        If the repository can not support user-specified revision ids
 
1831
        they should override this function and raise CannotSetRevisionId
 
1832
        if _new_revision_id is not None.
 
1833
 
 
1834
        :raises: CannotSetRevisionId
 
1835
        """
 
1836
        if self._new_revision_id is None:
 
1837
            self._new_revision_id = self._gen_revision_id()
 
1838
 
 
1839
    def record_entry_contents(self, ie, parent_invs, path, tree):
 
1840
        """Record the content of ie from tree into the commit if needed.
 
1841
 
 
1842
        Side effect: sets ie.revision when unchanged
 
1843
 
 
1844
        :param ie: An inventory entry present in the commit.
 
1845
        :param parent_invs: The inventories of the parent revisions of the
 
1846
            commit.
 
1847
        :param path: The path the entry is at in the tree.
 
1848
        :param tree: The tree which contains this entry and should be used to 
 
1849
        obtain content.
 
1850
        """
 
1851
        if self.new_inventory.root is None and ie.parent_id is not None:
 
1852
            symbol_versioning.warn('Root entry should be supplied to'
 
1853
                ' record_entry_contents, as of bzr 0.10.',
 
1854
                 DeprecationWarning, stacklevel=2)
 
1855
            self.record_entry_contents(tree.inventory.root.copy(), parent_invs,
 
1856
                                       '', tree)
 
1857
        self.new_inventory.add(ie)
 
1858
 
 
1859
        # ie.revision is always None if the InventoryEntry is considered
 
1860
        # for committing. ie.snapshot will record the correct revision 
 
1861
        # which may be the sole parent if it is untouched.
 
1862
        if ie.revision is not None:
 
1863
            return
 
1864
 
 
1865
        # In this revision format, root entries have no knit or weave
 
1866
        if ie is self.new_inventory.root:
 
1867
            # When serializing out to disk and back in
 
1868
            # root.revision is always _new_revision_id
 
1869
            ie.revision = self._new_revision_id
 
1870
            return
 
1871
        previous_entries = ie.find_previous_heads(
 
1872
            parent_invs,
 
1873
            self.repository.weave_store,
 
1874
            self.repository.get_transaction())
 
1875
        # we are creating a new revision for ie in the history store
 
1876
        # and inventory.
 
1877
        ie.snapshot(self._new_revision_id, path, previous_entries, tree, self)
 
1878
 
 
1879
    def modified_directory(self, file_id, file_parents):
 
1880
        """Record the presence of a symbolic link.
 
1881
 
 
1882
        :param file_id: The file_id of the link to record.
 
1883
        :param file_parents: The per-file parent revision ids.
 
1884
        """
 
1885
        self._add_text_to_weave(file_id, [], file_parents.keys())
 
1886
    
 
1887
    def modified_file_text(self, file_id, file_parents,
 
1888
                           get_content_byte_lines, text_sha1=None,
 
1889
                           text_size=None):
 
1890
        """Record the text of file file_id
 
1891
 
 
1892
        :param file_id: The file_id of the file to record the text of.
 
1893
        :param file_parents: The per-file parent revision ids.
 
1894
        :param get_content_byte_lines: A callable which will return the byte
 
1895
            lines for the file.
 
1896
        :param text_sha1: Optional SHA1 of the file contents.
 
1897
        :param text_size: Optional size of the file contents.
 
1898
        """
 
1899
        # mutter('storing text of file {%s} in revision {%s} into %r',
 
1900
        #        file_id, self._new_revision_id, self.repository.weave_store)
 
1901
        # special case to avoid diffing on renames or 
 
1902
        # reparenting
 
1903
        if (len(file_parents) == 1
 
1904
            and text_sha1 == file_parents.values()[0].text_sha1
 
1905
            and text_size == file_parents.values()[0].text_size):
 
1906
            previous_ie = file_parents.values()[0]
 
1907
            versionedfile = self.repository.weave_store.get_weave(file_id, 
 
1908
                self.repository.get_transaction())
 
1909
            versionedfile.clone_text(self._new_revision_id, 
 
1910
                previous_ie.revision, file_parents.keys())
 
1911
            return text_sha1, text_size
 
1912
        else:
 
1913
            new_lines = get_content_byte_lines()
 
1914
            # TODO: Rather than invoking sha_strings here, _add_text_to_weave
 
1915
            # should return the SHA1 and size
 
1916
            self._add_text_to_weave(file_id, new_lines, file_parents.keys())
 
1917
            return osutils.sha_strings(new_lines), \
 
1918
                sum(map(len, new_lines))
 
1919
 
 
1920
    def modified_link(self, file_id, file_parents, link_target):
 
1921
        """Record the presence of a symbolic link.
 
1922
 
 
1923
        :param file_id: The file_id of the link to record.
 
1924
        :param file_parents: The per-file parent revision ids.
 
1925
        :param link_target: Target location of this link.
 
1926
        """
 
1927
        self._add_text_to_weave(file_id, [], file_parents.keys())
 
1928
 
 
1929
    def _add_text_to_weave(self, file_id, new_lines, parents):
 
1930
        versionedfile = self.repository.weave_store.get_weave_or_empty(
 
1931
            file_id, self.repository.get_transaction())
 
1932
        versionedfile.add_lines(self._new_revision_id, parents, new_lines)
 
1933
        versionedfile.clear_cache()
 
1934
 
 
1935
 
 
1936
class _CommitBuilder(CommitBuilder):
 
1937
    """Temporary class so old CommitBuilders are detected properly
 
1938
    
 
1939
    Note: CommitBuilder works whether or not root entry is recorded.
 
1940
    """
 
1941
 
 
1942
    record_root_entry = True
 
1943
 
 
1944
 
 
1945
class RootCommitBuilder(CommitBuilder):
 
1946
    """This commitbuilder actually records the root id"""
 
1947
    
 
1948
    record_root_entry = True
 
1949
 
 
1950
    def record_entry_contents(self, ie, parent_invs, path, tree):
 
1951
        """Record the content of ie from tree into the commit if needed.
 
1952
 
 
1953
        Side effect: sets ie.revision when unchanged
 
1954
 
 
1955
        :param ie: An inventory entry present in the commit.
 
1956
        :param parent_invs: The inventories of the parent revisions of the
 
1957
            commit.
 
1958
        :param path: The path the entry is at in the tree.
 
1959
        :param tree: The tree which contains this entry and should be used to 
 
1960
        obtain content.
 
1961
        """
 
1962
        assert self.new_inventory.root is not None or ie.parent_id is None
 
1963
        self.new_inventory.add(ie)
 
1964
 
 
1965
        # ie.revision is always None if the InventoryEntry is considered
 
1966
        # for committing. ie.snapshot will record the correct revision 
 
1967
        # which may be the sole parent if it is untouched.
 
1968
        if ie.revision is not None:
 
1969
            return
 
1970
 
 
1971
        previous_entries = ie.find_previous_heads(
 
1972
            parent_invs,
 
1973
            self.repository.weave_store,
 
1974
            self.repository.get_transaction())
 
1975
        # we are creating a new revision for ie in the history store
 
1976
        # and inventory.
 
1977
        ie.snapshot(self._new_revision_id, path, previous_entries, tree, self)
 
1978
 
 
1979
 
 
1980
_unescape_map = {
 
1981
    'apos':"'",
 
1982
    'quot':'"',
 
1983
    'amp':'&',
 
1984
    'lt':'<',
 
1985
    'gt':'>'
 
1986
}
 
1987
 
 
1988
 
 
1989
def _unescaper(match, _map=_unescape_map):
 
1990
    return _map[match.group(1)]
 
1991
 
 
1992
 
 
1993
_unescape_re = None
 
1994
 
 
1995
 
 
1996
def _unescape_xml(data):
 
1997
    """Unescape predefined XML entities in a string of data."""
 
1998
    global _unescape_re
 
1999
    if _unescape_re is None:
 
2000
        _unescape_re = re.compile('\&([^;]*);')
 
2001
    return _unescape_re.sub(_unescaper, data)