/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: Martin Pool
  • Date: 2007-02-20 07:50:00 UTC
  • mto: This revision was merged to the branch mainline in revision 2309.
  • Revision ID: mbp@sourcefrog.net-20070220075000-2hz26ddu1hm28jrl
Tag methods now available through Branch.tags.add_tag, etc

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