/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: Andrew Bennetts
  • Date: 2007-02-05 05:16:09 UTC
  • mto: (2018.5.72 hpss)
  • mto: This revision was merged to the branch mainline in revision 2435.
  • Revision ID: andrew.bennetts@canonical.com-20070205051609-1oxwbeg70yzruqjt
Fix test_wsgi.TestWSGI.test_chrooting to work with the new chroot semantics.

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
from binascii import hexlify
 
22
from copy import deepcopy
 
23
import re
 
24
import time
 
25
import unittest
 
26
 
 
27
from bzrlib import (
 
28
    bzrdir,
 
29
    check,
 
30
    delta,
 
31
    errors,
 
32
    generate_ids,
 
33
    gpg,
 
34
    graph,
 
35
    knit,
 
36
    lazy_regex,
 
37
    lockable_files,
 
38
    lockdir,
 
39
    osutils,
 
40
    registry,
 
41
    revision as _mod_revision,
 
42
    symbol_versioning,
 
43
    transactions,
 
44
    ui,
 
45
    weave,
 
46
    weavefile,
 
47
    xml5,
 
48
    xml6,
 
49
    )
 
50
from bzrlib.osutils import (
 
51
    rand_bytes,
 
52
    compact_date, 
 
53
    local_time_offset,
 
54
    )
 
55
from bzrlib.revisiontree import RevisionTree
 
56
from bzrlib.store.versioned import VersionedFileStore
 
57
from bzrlib.store.text import TextStore
 
58
from bzrlib.testament import Testament
 
59
""")
 
60
 
 
61
from bzrlib.decorators import needs_read_lock, needs_write_lock
 
62
from bzrlib.inter import InterObject
 
63
from bzrlib.inventory import Inventory, InventoryDirectory, ROOT_ID
 
64
from bzrlib.symbol_versioning import (
 
65
        deprecated_method,
 
66
        zero_nine,
 
67
        )
 
68
from bzrlib.trace import mutter, note, warning
 
69
 
 
70
 
 
71
# Old formats display a warning, but only once
 
72
_deprecation_warning_done = False
 
73
 
 
74
 
 
75
class Repository(object):
 
76
    """Repository holding history for one or more branches.
 
77
 
 
78
    The repository holds and retrieves historical information including
 
79
    revisions and file history.  It's normally accessed only by the Branch,
 
80
    which views a particular line of development through that history.
 
81
 
 
82
    The Repository builds on top of Stores and a Transport, which respectively 
 
83
    describe the disk data format and the way of accessing the (possibly 
 
84
    remote) disk.
 
85
    """
 
86
 
 
87
    _file_ids_altered_regex = lazy_regex.lazy_compile(
 
88
        r'file_id="(?P<file_id>[^"]+)"'
 
89
        r'.*revision="(?P<revision_id>[^"]+)"'
 
90
        )
 
91
 
 
92
    @needs_write_lock
 
93
    def add_inventory(self, revid, inv, parents):
 
94
        """Add the inventory inv to the repository as revid.
 
95
        
 
96
        :param parents: The revision ids of the parents that revid
 
97
                        is known to have and are in the repository already.
 
98
 
 
99
        returns the sha1 of the serialized inventory.
 
100
        """
 
101
        _mod_revision.check_not_reserved_id(revid)
 
102
        assert inv.revision_id is None or inv.revision_id == revid, \
 
103
            "Mismatch between inventory revision" \
 
104
            " id and insertion revid (%r, %r)" % (inv.revision_id, revid)
 
105
        assert inv.root is not None
 
106
        inv_text = self.serialise_inventory(inv)
 
107
        inv_sha1 = osutils.sha_string(inv_text)
 
108
        inv_vf = self.control_weaves.get_weave('inventory',
 
109
                                               self.get_transaction())
 
110
        self._inventory_add_lines(inv_vf, revid, parents, osutils.split_lines(inv_text))
 
111
        return inv_sha1
 
112
 
 
113
    def _inventory_add_lines(self, inv_vf, revid, parents, lines):
 
114
        final_parents = []
 
115
        for parent in parents:
 
116
            if parent in inv_vf:
 
117
                final_parents.append(parent)
 
118
 
 
119
        inv_vf.add_lines(revid, final_parents, lines)
 
120
 
 
121
    @needs_write_lock
 
122
    def add_revision(self, rev_id, rev, inv=None, config=None):
 
123
        """Add rev to the revision store as rev_id.
 
124
 
 
125
        :param rev_id: the revision id to use.
 
126
        :param rev: The revision object.
 
127
        :param inv: The inventory for the revision. if None, it will be looked
 
128
                    up in the inventory storer
 
129
        :param config: If None no digital signature will be created.
 
130
                       If supplied its signature_needed method will be used
 
131
                       to determine if a signature should be made.
 
132
        """
 
133
        _mod_revision.check_not_reserved_id(rev_id)
 
134
        if config is not None and config.signature_needed():
 
135
            if inv is None:
 
136
                inv = self.get_inventory(rev_id)
 
137
            plaintext = Testament(rev, inv).as_short_text()
 
138
            self.store_revision_signature(
 
139
                gpg.GPGStrategy(config), plaintext, rev_id)
 
140
        if not rev_id in self.get_inventory_weave():
 
141
            if inv is None:
 
142
                raise errors.WeaveRevisionNotPresent(rev_id,
 
143
                                                     self.get_inventory_weave())
 
144
            else:
 
145
                # yes, this is not suitable for adding with ghosts.
 
146
                self.add_inventory(rev_id, inv, rev.parent_ids)
 
147
        self._revision_store.add_revision(rev, self.get_transaction())
 
148
 
 
149
    @needs_read_lock
 
150
    def _all_possible_ids(self):
 
151
        """Return all the possible revisions that we could find."""
 
152
        return self.get_inventory_weave().versions()
 
153
 
 
154
    def all_revision_ids(self):
 
155
        """Returns a list of all the revision ids in the repository. 
 
156
 
 
157
        This is deprecated because code should generally work on the graph
 
158
        reachable from a particular revision, and ignore any other revisions
 
159
        that might be present.  There is no direct replacement method.
 
160
        """
 
161
        return self._all_revision_ids()
 
162
 
 
163
    @needs_read_lock
 
164
    def _all_revision_ids(self):
 
165
        """Returns a list of all the revision ids in the repository. 
 
166
 
 
167
        These are in as much topological order as the underlying store can 
 
168
        present: for weaves ghosts may lead to a lack of correctness until
 
169
        the reweave updates the parents list.
 
170
        """
 
171
        if self._revision_store.text_store.listable():
 
172
            return self._revision_store.all_revision_ids(self.get_transaction())
 
173
        result = self._all_possible_ids()
 
174
        return self._eliminate_revisions_not_present(result)
 
175
 
 
176
    def break_lock(self):
 
177
        """Break a lock if one is present from another instance.
 
178
 
 
179
        Uses the ui factory to ask for confirmation if the lock may be from
 
180
        an active process.
 
181
        """
 
182
        self.control_files.break_lock()
 
183
 
 
184
    @needs_read_lock
 
185
    def _eliminate_revisions_not_present(self, revision_ids):
 
186
        """Check every revision id in revision_ids to see if we have it.
 
187
 
 
188
        Returns a set of the present revisions.
 
189
        """
 
190
        result = []
 
191
        for id in revision_ids:
 
192
            if self.has_revision(id):
 
193
               result.append(id)
 
194
        return result
 
195
 
 
196
    @staticmethod
 
197
    def create(a_bzrdir):
 
198
        """Construct the current default format repository in a_bzrdir."""
 
199
        return RepositoryFormat.get_default_format().initialize(a_bzrdir)
 
200
 
 
201
    def __init__(self, _format, a_bzrdir, control_files, _revision_store, control_store, text_store):
 
202
        """instantiate a Repository.
 
203
 
 
204
        :param _format: The format of the repository on disk.
 
205
        :param a_bzrdir: The BzrDir of the repository.
 
206
 
 
207
        In the future we will have a single api for all stores for
 
208
        getting file texts, inventories and revisions, then
 
209
        this construct will accept instances of those things.
 
210
        """
 
211
        super(Repository, self).__init__()
 
212
        self._format = _format
 
213
        # the following are part of the public API for Repository:
 
214
        self.bzrdir = a_bzrdir
 
215
        self.control_files = control_files
 
216
        self._revision_store = _revision_store
 
217
        self.text_store = text_store
 
218
        # backwards compatibility
 
219
        self.weave_store = text_store
 
220
        # not right yet - should be more semantically clear ? 
 
221
        # 
 
222
        self.control_store = control_store
 
223
        self.control_weaves = control_store
 
224
        # TODO: make sure to construct the right store classes, etc, depending
 
225
        # on whether escaping is required.
 
226
        self._warn_if_deprecated()
 
227
        self._serializer = xml5.serializer_v5
 
228
 
 
229
    def __repr__(self):
 
230
        return '%s(%r)' % (self.__class__.__name__, 
 
231
                           self.bzrdir.transport.base)
 
232
 
 
233
    def is_locked(self):
 
234
        return self.control_files.is_locked()
 
235
 
 
236
    def lock_write(self):
 
237
        self.control_files.lock_write()
 
238
 
 
239
    def lock_read(self):
 
240
        self.control_files.lock_read()
 
241
 
 
242
    def get_physical_lock_status(self):
 
243
        return self.control_files.get_physical_lock_status()
 
244
 
 
245
    @needs_read_lock
 
246
    def gather_stats(self, revid=None, committers=None):
 
247
        """Gather statistics from a revision id.
 
248
 
 
249
        :param revid: The revision id to gather statistics from, if None, then
 
250
            no revision specific statistics are gathered.
 
251
        :param committers: Optional parameter controlling whether to grab
 
252
            a count of committers from the revision specific statistics.
 
253
        :return: A dictionary of statistics. Currently this contains:
 
254
            committers: The number of committers if requested.
 
255
            firstrev: A tuple with timestamp, timezone for the penultimate left
 
256
                most ancestor of revid, if revid is not the NULL_REVISION.
 
257
            latestrev: A tuple with timestamp, timezone for revid, if revid is
 
258
                not the NULL_REVISION.
 
259
            revisions: The total revision count in the repository.
 
260
            size: An estimate disk size of the repository in bytes.
 
261
        """
 
262
        result = {}
 
263
        if revid and committers:
 
264
            result['committers'] = 0
 
265
        if revid and revid != _mod_revision.NULL_REVISION:
 
266
            if committers:
 
267
                all_committers = set()
 
268
            revisions = self.get_ancestry(revid)
 
269
            # pop the leading None
 
270
            revisions.pop(0)
 
271
            first_revision = None
 
272
            if not committers:
 
273
                # ignore the revisions in the middle - just grab first and last
 
274
                revisions = revisions[0], revisions[-1]
 
275
            for revision in self.get_revisions(revisions):
 
276
                if not first_revision:
 
277
                    first_revision = revision
 
278
                if committers:
 
279
                    all_committers.add(revision.committer)
 
280
            last_revision = revision
 
281
            if committers:
 
282
                result['committers'] = len(all_committers)
 
283
            result['firstrev'] = (first_revision.timestamp,
 
284
                first_revision.timezone)
 
285
            result['latestrev'] = (last_revision.timestamp,
 
286
                last_revision.timezone)
 
287
 
 
288
        # now gather global repository information
 
289
        if self.bzrdir.root_transport.listable():
 
290
            c, t = self._revision_store.total_size(self.get_transaction())
 
291
            result['revisions'] = c
 
292
            result['size'] = t
 
293
        return result
 
294
 
 
295
    @needs_read_lock
 
296
    def missing_revision_ids(self, other, revision_id=None):
 
297
        """Return the revision ids that other has that this does not.
 
298
        
 
299
        These are returned in topological order.
 
300
 
 
301
        revision_id: only return revision ids included by revision_id.
 
302
        """
 
303
        return InterRepository.get(other, self).missing_revision_ids(revision_id)
 
304
 
 
305
    @staticmethod
 
306
    def open(base):
 
307
        """Open the repository rooted at base.
 
308
 
 
309
        For instance, if the repository is at URL/.bzr/repository,
 
310
        Repository.open(URL) -> a Repository instance.
 
311
        """
 
312
        control = bzrdir.BzrDir.open(base)
 
313
        return control.open_repository()
 
314
 
 
315
    def copy_content_into(self, destination, revision_id=None, basis=None):
 
316
        """Make a complete copy of the content in self into destination.
 
317
        
 
318
        This is a destructive operation! Do not use it on existing 
 
319
        repositories.
 
320
        """
 
321
        return InterRepository.get(self, destination).copy_content(revision_id, basis)
 
322
 
 
323
    def fetch(self, source, revision_id=None, pb=None):
 
324
        """Fetch the content required to construct revision_id from source.
 
325
 
 
326
        If revision_id is None all content is copied.
 
327
        """
 
328
        return InterRepository.get(source, self).fetch(revision_id=revision_id,
 
329
                                                       pb=pb)
 
330
 
 
331
    def get_commit_builder(self, branch, parents, config, timestamp=None, 
 
332
                           timezone=None, committer=None, revprops=None, 
 
333
                           revision_id=None):
 
334
        """Obtain a CommitBuilder for this repository.
 
335
        
 
336
        :param branch: Branch to commit to.
 
337
        :param parents: Revision ids of the parents of the new revision.
 
338
        :param config: Configuration to use.
 
339
        :param timestamp: Optional timestamp recorded for commit.
 
340
        :param timezone: Optional timezone for timestamp.
 
341
        :param committer: Optional committer to set for commit.
 
342
        :param revprops: Optional dictionary of revision properties.
 
343
        :param revision_id: Optional revision id.
 
344
        """
 
345
        return _CommitBuilder(self, parents, config, timestamp, timezone,
 
346
                              committer, revprops, revision_id)
 
347
 
 
348
    def unlock(self):
 
349
        self.control_files.unlock()
 
350
 
 
351
    @needs_read_lock
 
352
    def clone(self, a_bzrdir, revision_id=None, basis=None):
 
353
        """Clone this repository into a_bzrdir using the current format.
 
354
 
 
355
        Currently no check is made that the format of this repository and
 
356
        the bzrdir format are compatible. FIXME RBC 20060201.
 
357
        """
 
358
        if not isinstance(a_bzrdir._format, self.bzrdir._format.__class__):
 
359
            # use target default format.
 
360
            result = a_bzrdir.create_repository()
 
361
        # FIXME RBC 20060209 split out the repository type to avoid this check ?
 
362
        elif isinstance(a_bzrdir._format,
 
363
                      (bzrdir.BzrDirFormat4,
 
364
                       bzrdir.BzrDirFormat5,
 
365
                       bzrdir.BzrDirFormat6)):
 
366
            result = a_bzrdir.open_repository()
 
367
        else:
 
368
            result = self._format.initialize(a_bzrdir, shared=self.is_shared())
 
369
        self.copy_content_into(result, revision_id, basis)
 
370
        return result
 
371
 
 
372
    @needs_read_lock
 
373
    def has_revision(self, revision_id):
 
374
        """True if this repository has a copy of the revision."""
 
375
        return self._revision_store.has_revision_id(revision_id,
 
376
                                                    self.get_transaction())
 
377
 
 
378
    @needs_read_lock
 
379
    def get_revision_reconcile(self, revision_id):
 
380
        """'reconcile' helper routine that allows access to a revision always.
 
381
        
 
382
        This variant of get_revision does not cross check the weave graph
 
383
        against the revision one as get_revision does: but it should only
 
384
        be used by reconcile, or reconcile-alike commands that are correcting
 
385
        or testing the revision graph.
 
386
        """
 
387
        if not revision_id or not isinstance(revision_id, basestring):
 
388
            raise errors.InvalidRevisionId(revision_id=revision_id,
 
389
                                           branch=self)
 
390
        return self._revision_store.get_revisions([revision_id],
 
391
                                                  self.get_transaction())[0]
 
392
    @needs_read_lock
 
393
    def get_revisions(self, revision_ids):
 
394
        return self._revision_store.get_revisions(revision_ids,
 
395
                                                  self.get_transaction())
 
396
 
 
397
    @needs_read_lock
 
398
    def get_revision_xml(self, revision_id):
 
399
        rev = self.get_revision(revision_id) 
 
400
        rev_tmp = StringIO()
 
401
        # the current serializer..
 
402
        self._revision_store._serializer.write_revision(rev, rev_tmp)
 
403
        rev_tmp.seek(0)
 
404
        return rev_tmp.getvalue()
 
405
 
 
406
    @needs_read_lock
 
407
    def get_revision(self, revision_id):
 
408
        """Return the Revision object for a named revision"""
 
409
        r = self.get_revision_reconcile(revision_id)
 
410
        # weave corruption can lead to absent revision markers that should be
 
411
        # present.
 
412
        # the following test is reasonably cheap (it needs a single weave read)
 
413
        # and the weave is cached in read transactions. In write transactions
 
414
        # it is not cached but typically we only read a small number of
 
415
        # revisions. For knits when they are introduced we will probably want
 
416
        # to ensure that caching write transactions are in use.
 
417
        inv = self.get_inventory_weave()
 
418
        self._check_revision_parents(r, inv)
 
419
        return r
 
420
 
 
421
    @needs_read_lock
 
422
    def get_deltas_for_revisions(self, revisions):
 
423
        """Produce a generator of revision deltas.
 
424
        
 
425
        Note that the input is a sequence of REVISIONS, not revision_ids.
 
426
        Trees will be held in memory until the generator exits.
 
427
        Each delta is relative to the revision's lefthand predecessor.
 
428
        """
 
429
        required_trees = set()
 
430
        for revision in revisions:
 
431
            required_trees.add(revision.revision_id)
 
432
            required_trees.update(revision.parent_ids[:1])
 
433
        trees = dict((t.get_revision_id(), t) for 
 
434
                     t in self.revision_trees(required_trees))
 
435
        for revision in revisions:
 
436
            if not revision.parent_ids:
 
437
                old_tree = self.revision_tree(None)
 
438
            else:
 
439
                old_tree = trees[revision.parent_ids[0]]
 
440
            yield trees[revision.revision_id].changes_from(old_tree)
 
441
 
 
442
    @needs_read_lock
 
443
    def get_revision_delta(self, revision_id):
 
444
        """Return the delta for one revision.
 
445
 
 
446
        The delta is relative to the left-hand predecessor of the
 
447
        revision.
 
448
        """
 
449
        r = self.get_revision(revision_id)
 
450
        return list(self.get_deltas_for_revisions([r]))[0]
 
451
 
 
452
    def _check_revision_parents(self, revision, inventory):
 
453
        """Private to Repository and Fetch.
 
454
        
 
455
        This checks the parentage of revision in an inventory weave for 
 
456
        consistency and is only applicable to inventory-weave-for-ancestry
 
457
        using repository formats & fetchers.
 
458
        """
 
459
        weave_parents = inventory.get_parents(revision.revision_id)
 
460
        weave_names = inventory.versions()
 
461
        for parent_id in revision.parent_ids:
 
462
            if parent_id in weave_names:
 
463
                # this parent must not be a ghost.
 
464
                if not parent_id in weave_parents:
 
465
                    # but it is a ghost
 
466
                    raise errors.CorruptRepository(self)
 
467
 
 
468
    @needs_write_lock
 
469
    def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
 
470
        signature = gpg_strategy.sign(plaintext)
 
471
        self._revision_store.add_revision_signature_text(revision_id,
 
472
                                                         signature,
 
473
                                                         self.get_transaction())
 
474
 
 
475
    def fileids_altered_by_revision_ids(self, revision_ids):
 
476
        """Find the file ids and versions affected by revisions.
 
477
 
 
478
        :param revisions: an iterable containing revision ids.
 
479
        :return: a dictionary mapping altered file-ids to an iterable of
 
480
        revision_ids. Each altered file-ids has the exact revision_ids that
 
481
        altered it listed explicitly.
 
482
        """
 
483
        assert self._serializer.support_altered_by_hack, \
 
484
            ("fileids_altered_by_revision_ids only supported for branches " 
 
485
             "which store inventory as unnested xml, not on %r" % self)
 
486
        selected_revision_ids = set(revision_ids)
 
487
        w = self.get_inventory_weave()
 
488
        result = {}
 
489
 
 
490
        # this code needs to read every new line in every inventory for the
 
491
        # inventories [revision_ids]. Seeing a line twice is ok. Seeing a line
 
492
        # not present in one of those inventories is unnecessary but not 
 
493
        # harmful because we are filtering by the revision id marker in the
 
494
        # inventory lines : we only select file ids altered in one of those  
 
495
        # revisions. We don't need to see all lines in the inventory because
 
496
        # only those added in an inventory in rev X can contain a revision=X
 
497
        # line.
 
498
        unescape_revid_cache = {}
 
499
        unescape_fileid_cache = {}
 
500
 
 
501
        # jam 20061218 In a big fetch, this handles hundreds of thousands
 
502
        # of lines, so it has had a lot of inlining and optimizing done.
 
503
        # Sorry that it is a little bit messy.
 
504
        # Move several functions to be local variables, since this is a long
 
505
        # running loop.
 
506
        search = self._file_ids_altered_regex.search
 
507
        unescape = _unescape_xml
 
508
        setdefault = result.setdefault
 
509
        pb = ui.ui_factory.nested_progress_bar()
 
510
        try:
 
511
            for line in w.iter_lines_added_or_present_in_versions(
 
512
                                        selected_revision_ids, pb=pb):
 
513
                match = search(line)
 
514
                if match is None:
 
515
                    continue
 
516
                # One call to match.group() returning multiple items is quite a
 
517
                # bit faster than 2 calls to match.group() each returning 1
 
518
                file_id, revision_id = match.group('file_id', 'revision_id')
 
519
 
 
520
                # Inlining the cache lookups helps a lot when you make 170,000
 
521
                # lines and 350k ids, versus 8.4 unique ids.
 
522
                # Using a cache helps in 2 ways:
 
523
                #   1) Avoids unnecessary decoding calls
 
524
                #   2) Re-uses cached strings, which helps in future set and
 
525
                #      equality checks.
 
526
                # (2) is enough that removing encoding entirely along with
 
527
                # the cache (so we are using plain strings) results in no
 
528
                # performance improvement.
 
529
                try:
 
530
                    revision_id = unescape_revid_cache[revision_id]
 
531
                except KeyError:
 
532
                    unescaped = unescape(revision_id)
 
533
                    unescape_revid_cache[revision_id] = unescaped
 
534
                    revision_id = unescaped
 
535
 
 
536
                if revision_id in selected_revision_ids:
 
537
                    try:
 
538
                        file_id = unescape_fileid_cache[file_id]
 
539
                    except KeyError:
 
540
                        unescaped = unescape(file_id)
 
541
                        unescape_fileid_cache[file_id] = unescaped
 
542
                        file_id = unescaped
 
543
                    setdefault(file_id, set()).add(revision_id)
 
544
        finally:
 
545
            pb.finished()
 
546
        return result
 
547
 
 
548
    @needs_read_lock
 
549
    def get_inventory_weave(self):
 
550
        return self.control_weaves.get_weave('inventory',
 
551
            self.get_transaction())
 
552
 
 
553
    @needs_read_lock
 
554
    def get_inventory(self, revision_id):
 
555
        """Get Inventory object by hash."""
 
556
        return self.deserialise_inventory(
 
557
            revision_id, self.get_inventory_xml(revision_id))
 
558
 
 
559
    def deserialise_inventory(self, revision_id, xml):
 
560
        """Transform the xml into an inventory object. 
 
561
 
 
562
        :param revision_id: The expected revision id of the inventory.
 
563
        :param xml: A serialised inventory.
 
564
        """
 
565
        result = self._serializer.read_inventory_from_string(xml)
 
566
        result.root.revision = revision_id
 
567
        return result
 
568
 
 
569
    def serialise_inventory(self, inv):
 
570
        return self._serializer.write_inventory_to_string(inv)
 
571
 
 
572
    @needs_read_lock
 
573
    def get_inventory_xml(self, revision_id):
 
574
        """Get inventory XML as a file object."""
 
575
        try:
 
576
            assert isinstance(revision_id, basestring), type(revision_id)
 
577
            iw = self.get_inventory_weave()
 
578
            return iw.get_text(revision_id)
 
579
        except IndexError:
 
580
            raise errors.HistoryMissing(self, 'inventory', revision_id)
 
581
 
 
582
    @needs_read_lock
 
583
    def get_inventory_sha1(self, revision_id):
 
584
        """Return the sha1 hash of the inventory entry
 
585
        """
 
586
        return self.get_revision(revision_id).inventory_sha1
 
587
 
 
588
    @needs_read_lock
 
589
    def get_revision_graph(self, revision_id=None):
 
590
        """Return a dictionary containing the revision graph.
 
591
        
 
592
        :param revision_id: The revision_id to get a graph from. If None, then
 
593
        the entire revision graph is returned. This is a deprecated mode of
 
594
        operation and will be removed in the future.
 
595
        :return: a dictionary of revision_id->revision_parents_list.
 
596
        """
 
597
        # special case NULL_REVISION
 
598
        if revision_id == _mod_revision.NULL_REVISION:
 
599
            return {}
 
600
        a_weave = self.get_inventory_weave()
 
601
        all_revisions = self._eliminate_revisions_not_present(
 
602
                                a_weave.versions())
 
603
        entire_graph = dict([(node, a_weave.get_parents(node)) for 
 
604
                             node in all_revisions])
 
605
        if revision_id is None:
 
606
            return entire_graph
 
607
        elif revision_id not in entire_graph:
 
608
            raise errors.NoSuchRevision(self, revision_id)
 
609
        else:
 
610
            # add what can be reached from revision_id
 
611
            result = {}
 
612
            pending = set([revision_id])
 
613
            while len(pending) > 0:
 
614
                node = pending.pop()
 
615
                result[node] = entire_graph[node]
 
616
                for revision_id in result[node]:
 
617
                    if revision_id not in result:
 
618
                        pending.add(revision_id)
 
619
            return result
 
620
 
 
621
    @needs_read_lock
 
622
    def get_revision_graph_with_ghosts(self, revision_ids=None):
 
623
        """Return a graph of the revisions with ghosts marked as applicable.
 
624
 
 
625
        :param revision_ids: an iterable of revisions to graph or None for all.
 
626
        :return: a Graph object with the graph reachable from revision_ids.
 
627
        """
 
628
        result = graph.Graph()
 
629
        if not revision_ids:
 
630
            pending = set(self.all_revision_ids())
 
631
            required = set([])
 
632
        else:
 
633
            pending = set(revision_ids)
 
634
            # special case NULL_REVISION
 
635
            if _mod_revision.NULL_REVISION in pending:
 
636
                pending.remove(_mod_revision.NULL_REVISION)
 
637
            required = set(pending)
 
638
        done = set([])
 
639
        while len(pending):
 
640
            revision_id = pending.pop()
 
641
            try:
 
642
                rev = self.get_revision(revision_id)
 
643
            except errors.NoSuchRevision:
 
644
                if revision_id in required:
 
645
                    raise
 
646
                # a ghost
 
647
                result.add_ghost(revision_id)
 
648
                continue
 
649
            for parent_id in rev.parent_ids:
 
650
                # is this queued or done ?
 
651
                if (parent_id not in pending and
 
652
                    parent_id not in done):
 
653
                    # no, queue it.
 
654
                    pending.add(parent_id)
 
655
            result.add_node(revision_id, rev.parent_ids)
 
656
            done.add(revision_id)
 
657
        return result
 
658
 
 
659
    @needs_read_lock
 
660
    def get_revision_inventory(self, revision_id):
 
661
        """Return inventory of a past revision."""
 
662
        # TODO: Unify this with get_inventory()
 
663
        # bzr 0.0.6 and later imposes the constraint that the inventory_id
 
664
        # must be the same as its revision, so this is trivial.
 
665
        if revision_id is None:
 
666
            # This does not make sense: if there is no revision,
 
667
            # then it is the current tree inventory surely ?!
 
668
            # and thus get_root_id() is something that looks at the last
 
669
            # commit on the branch, and the get_root_id is an inventory check.
 
670
            raise NotImplementedError
 
671
            # return Inventory(self.get_root_id())
 
672
        else:
 
673
            return self.get_inventory(revision_id)
 
674
 
 
675
    @needs_read_lock
 
676
    def is_shared(self):
 
677
        """Return True if this repository is flagged as a shared repository."""
 
678
        raise NotImplementedError(self.is_shared)
 
679
 
 
680
    @needs_write_lock
 
681
    def reconcile(self, other=None, thorough=False):
 
682
        """Reconcile this repository."""
 
683
        from bzrlib.reconcile import RepoReconciler
 
684
        reconciler = RepoReconciler(self, thorough=thorough)
 
685
        reconciler.reconcile()
 
686
        return reconciler
 
687
    
 
688
    @needs_read_lock
 
689
    def revision_tree(self, revision_id):
 
690
        """Return Tree for a revision on this branch.
 
691
 
 
692
        `revision_id` may be None for the empty tree revision.
 
693
        """
 
694
        # TODO: refactor this to use an existing revision object
 
695
        # so we don't need to read it in twice.
 
696
        if revision_id is None or revision_id == _mod_revision.NULL_REVISION:
 
697
            return RevisionTree(self, Inventory(root_id=None), 
 
698
                                _mod_revision.NULL_REVISION)
 
699
        else:
 
700
            inv = self.get_revision_inventory(revision_id)
 
701
            return RevisionTree(self, inv, revision_id)
 
702
 
 
703
    @needs_read_lock
 
704
    def revision_trees(self, revision_ids):
 
705
        """Return Tree for a revision on this branch.
 
706
 
 
707
        `revision_id` may not be None or 'null:'"""
 
708
        assert None not in revision_ids
 
709
        assert _mod_revision.NULL_REVISION not in revision_ids
 
710
        texts = self.get_inventory_weave().get_texts(revision_ids)
 
711
        for text, revision_id in zip(texts, revision_ids):
 
712
            inv = self.deserialise_inventory(revision_id, text)
 
713
            yield RevisionTree(self, inv, revision_id)
 
714
 
 
715
    @needs_read_lock
 
716
    def get_ancestry(self, revision_id):
 
717
        """Return a list of revision-ids integrated by a revision.
 
718
 
 
719
        The first element of the list is always None, indicating the origin 
 
720
        revision.  This might change when we have history horizons, or 
 
721
        perhaps we should have a new API.
 
722
        
 
723
        This is topologically sorted.
 
724
        """
 
725
        if revision_id is None:
 
726
            return [None]
 
727
        if not self.has_revision(revision_id):
 
728
            raise errors.NoSuchRevision(self, revision_id)
 
729
        w = self.get_inventory_weave()
 
730
        candidates = w.get_ancestry(revision_id)
 
731
        return [None] + candidates # self._eliminate_revisions_not_present(candidates)
 
732
 
 
733
    @needs_read_lock
 
734
    def print_file(self, file, revision_id):
 
735
        """Print `file` to stdout.
 
736
        
 
737
        FIXME RBC 20060125 as John Meinel points out this is a bad api
 
738
        - it writes to stdout, it assumes that that is valid etc. Fix
 
739
        by creating a new more flexible convenience function.
 
740
        """
 
741
        tree = self.revision_tree(revision_id)
 
742
        # use inventory as it was in that revision
 
743
        file_id = tree.inventory.path2id(file)
 
744
        if not file_id:
 
745
            # TODO: jam 20060427 Write a test for this code path
 
746
            #       it had a bug in it, and was raising the wrong
 
747
            #       exception.
 
748
            raise errors.BzrError("%r is not present in revision %s" % (file, revision_id))
 
749
        tree.print_file(file_id)
 
750
 
 
751
    def get_transaction(self):
 
752
        return self.control_files.get_transaction()
 
753
 
 
754
    def revision_parents(self, revid):
 
755
        return self.get_inventory_weave().parent_names(revid)
 
756
 
 
757
    @needs_write_lock
 
758
    def set_make_working_trees(self, new_value):
 
759
        """Set the policy flag for making working trees when creating branches.
 
760
 
 
761
        This only applies to branches that use this repository.
 
762
 
 
763
        The default is 'True'.
 
764
        :param new_value: True to restore the default, False to disable making
 
765
                          working trees.
 
766
        """
 
767
        raise NotImplementedError(self.set_make_working_trees)
 
768
    
 
769
    def make_working_trees(self):
 
770
        """Returns the policy for making working trees on new branches."""
 
771
        raise NotImplementedError(self.make_working_trees)
 
772
 
 
773
    @needs_write_lock
 
774
    def sign_revision(self, revision_id, gpg_strategy):
 
775
        plaintext = Testament.from_revision(self, revision_id).as_short_text()
 
776
        self.store_revision_signature(gpg_strategy, plaintext, revision_id)
 
777
 
 
778
    @needs_read_lock
 
779
    def has_signature_for_revision_id(self, revision_id):
 
780
        """Query for a revision signature for revision_id in the repository."""
 
781
        return self._revision_store.has_signature(revision_id,
 
782
                                                  self.get_transaction())
 
783
 
 
784
    @needs_read_lock
 
785
    def get_signature_text(self, revision_id):
 
786
        """Return the text for a signature."""
 
787
        return self._revision_store.get_signature_text(revision_id,
 
788
                                                       self.get_transaction())
 
789
 
 
790
    @needs_read_lock
 
791
    def check(self, revision_ids):
 
792
        """Check consistency of all history of given revision_ids.
 
793
 
 
794
        Different repository implementations should override _check().
 
795
 
 
796
        :param revision_ids: A non-empty list of revision_ids whose ancestry
 
797
             will be checked.  Typically the last revision_id of a branch.
 
798
        """
 
799
        if not revision_ids:
 
800
            raise ValueError("revision_ids must be non-empty in %s.check" 
 
801
                    % (self,))
 
802
        return self._check(revision_ids)
 
803
 
 
804
    def _check(self, revision_ids):
 
805
        result = check.Check(self)
 
806
        result.check()
 
807
        return result
 
808
 
 
809
    def _warn_if_deprecated(self):
 
810
        global _deprecation_warning_done
 
811
        if _deprecation_warning_done:
 
812
            return
 
813
        _deprecation_warning_done = True
 
814
        warning("Format %s for %s is deprecated - please use 'bzr upgrade' to get better performance"
 
815
                % (self._format, self.bzrdir.transport.base))
 
816
 
 
817
    def supports_rich_root(self):
 
818
        return self._format.rich_root_data
 
819
 
 
820
    def _check_ascii_revisionid(self, revision_id, method):
 
821
        """Private helper for ascii-only repositories."""
 
822
        # weave repositories refuse to store revisionids that are non-ascii.
 
823
        if revision_id is not None:
 
824
            # weaves require ascii revision ids.
 
825
            if isinstance(revision_id, unicode):
 
826
                try:
 
827
                    revision_id.encode('ascii')
 
828
                except UnicodeEncodeError:
 
829
                    raise errors.NonAsciiRevisionId(method, self)
 
830
 
 
831
 
 
832
class AllInOneRepository(Repository):
 
833
    """Legacy support - the repository behaviour for all-in-one branches."""
 
834
 
 
835
    def __init__(self, _format, a_bzrdir, _revision_store, control_store, text_store):
 
836
        # we reuse one control files instance.
 
837
        dir_mode = a_bzrdir._control_files._dir_mode
 
838
        file_mode = a_bzrdir._control_files._file_mode
 
839
 
 
840
        def get_store(name, compressed=True, prefixed=False):
 
841
            # FIXME: This approach of assuming stores are all entirely compressed
 
842
            # or entirely uncompressed is tidy, but breaks upgrade from 
 
843
            # some existing branches where there's a mixture; we probably 
 
844
            # still want the option to look for both.
 
845
            relpath = a_bzrdir._control_files._escape(name)
 
846
            store = TextStore(a_bzrdir._control_files._transport.clone(relpath),
 
847
                              prefixed=prefixed, compressed=compressed,
 
848
                              dir_mode=dir_mode,
 
849
                              file_mode=file_mode)
 
850
            #if self._transport.should_cache():
 
851
            #    cache_path = os.path.join(self.cache_root, name)
 
852
            #    os.mkdir(cache_path)
 
853
            #    store = bzrlib.store.CachedStore(store, cache_path)
 
854
            return store
 
855
 
 
856
        # not broken out yet because the controlweaves|inventory_store
 
857
        # and text_store | weave_store bits are still different.
 
858
        if isinstance(_format, RepositoryFormat4):
 
859
            # cannot remove these - there is still no consistent api 
 
860
            # which allows access to this old info.
 
861
            self.inventory_store = get_store('inventory-store')
 
862
            text_store = get_store('text-store')
 
863
        super(AllInOneRepository, self).__init__(_format, a_bzrdir, a_bzrdir._control_files, _revision_store, control_store, text_store)
 
864
 
 
865
    def get_commit_builder(self, branch, parents, config, timestamp=None,
 
866
                           timezone=None, committer=None, revprops=None,
 
867
                           revision_id=None):
 
868
        self._check_ascii_revisionid(revision_id, self.get_commit_builder)
 
869
        return Repository.get_commit_builder(self, branch, parents, config,
 
870
            timestamp, timezone, committer, revprops, revision_id)
 
871
 
 
872
    @needs_read_lock
 
873
    def is_shared(self):
 
874
        """AllInOne repositories cannot be shared."""
 
875
        return False
 
876
 
 
877
    @needs_write_lock
 
878
    def set_make_working_trees(self, new_value):
 
879
        """Set the policy flag for making working trees when creating branches.
 
880
 
 
881
        This only applies to branches that use this repository.
 
882
 
 
883
        The default is 'True'.
 
884
        :param new_value: True to restore the default, False to disable making
 
885
                          working trees.
 
886
        """
 
887
        raise NotImplementedError(self.set_make_working_trees)
 
888
    
 
889
    def make_working_trees(self):
 
890
        """Returns the policy for making working trees on new branches."""
 
891
        return True
 
892
 
 
893
 
 
894
def install_revision(repository, rev, revision_tree):
 
895
    """Install all revision data into a repository."""
 
896
    present_parents = []
 
897
    parent_trees = {}
 
898
    for p_id in rev.parent_ids:
 
899
        if repository.has_revision(p_id):
 
900
            present_parents.append(p_id)
 
901
            parent_trees[p_id] = repository.revision_tree(p_id)
 
902
        else:
 
903
            parent_trees[p_id] = repository.revision_tree(None)
 
904
 
 
905
    inv = revision_tree.inventory
 
906
    entries = inv.iter_entries()
 
907
    # backwards compatability hack: skip the root id.
 
908
    if not repository.supports_rich_root():
 
909
        path, root = entries.next()
 
910
        if root.revision != rev.revision_id:
 
911
            raise errors.IncompatibleRevision(repr(repository))
 
912
    # Add the texts that are not already present
 
913
    for path, ie in entries:
 
914
        w = repository.weave_store.get_weave_or_empty(ie.file_id,
 
915
                repository.get_transaction())
 
916
        if ie.revision not in w:
 
917
            text_parents = []
 
918
            # FIXME: TODO: The following loop *may* be overlapping/duplicate
 
919
            # with InventoryEntry.find_previous_heads(). if it is, then there
 
920
            # is a latent bug here where the parents may have ancestors of each
 
921
            # other. RBC, AB
 
922
            for revision, tree in parent_trees.iteritems():
 
923
                if ie.file_id not in tree:
 
924
                    continue
 
925
                parent_id = tree.inventory[ie.file_id].revision
 
926
                if parent_id in text_parents:
 
927
                    continue
 
928
                text_parents.append(parent_id)
 
929
                    
 
930
            vfile = repository.weave_store.get_weave_or_empty(ie.file_id, 
 
931
                repository.get_transaction())
 
932
            lines = revision_tree.get_file(ie.file_id).readlines()
 
933
            vfile.add_lines(rev.revision_id, text_parents, lines)
 
934
    try:
 
935
        # install the inventory
 
936
        repository.add_inventory(rev.revision_id, inv, present_parents)
 
937
    except errors.RevisionAlreadyPresent:
 
938
        pass
 
939
    repository.add_revision(rev.revision_id, rev, inv)
 
940
 
 
941
 
 
942
class MetaDirRepository(Repository):
 
943
    """Repositories in the new meta-dir layout."""
 
944
 
 
945
    def __init__(self, _format, a_bzrdir, control_files, _revision_store, control_store, text_store):
 
946
        super(MetaDirRepository, self).__init__(_format,
 
947
                                                a_bzrdir,
 
948
                                                control_files,
 
949
                                                _revision_store,
 
950
                                                control_store,
 
951
                                                text_store)
 
952
        dir_mode = self.control_files._dir_mode
 
953
        file_mode = self.control_files._file_mode
 
954
 
 
955
    @needs_read_lock
 
956
    def is_shared(self):
 
957
        """Return True if this repository is flagged as a shared repository."""
 
958
        return self.control_files._transport.has('shared-storage')
 
959
 
 
960
    @needs_write_lock
 
961
    def set_make_working_trees(self, new_value):
 
962
        """Set the policy flag for making working trees when creating branches.
 
963
 
 
964
        This only applies to branches that use this repository.
 
965
 
 
966
        The default is 'True'.
 
967
        :param new_value: True to restore the default, False to disable making
 
968
                          working trees.
 
969
        """
 
970
        if new_value:
 
971
            try:
 
972
                self.control_files._transport.delete('no-working-trees')
 
973
            except errors.NoSuchFile:
 
974
                pass
 
975
        else:
 
976
            self.control_files.put_utf8('no-working-trees', '')
 
977
    
 
978
    def make_working_trees(self):
 
979
        """Returns the policy for making working trees on new branches."""
 
980
        return not self.control_files._transport.has('no-working-trees')
 
981
 
 
982
 
 
983
class WeaveMetaDirRepository(MetaDirRepository):
 
984
    """A subclass of MetaDirRepository to set weave specific policy."""
 
985
 
 
986
    def get_commit_builder(self, branch, parents, config, timestamp=None,
 
987
                           timezone=None, committer=None, revprops=None,
 
988
                           revision_id=None):
 
989
        self._check_ascii_revisionid(revision_id, self.get_commit_builder)
 
990
        return MetaDirRepository.get_commit_builder(self, branch, parents,
 
991
            config, timestamp, timezone, committer, revprops, revision_id)
 
992
 
 
993
 
 
994
class KnitRepository(MetaDirRepository):
 
995
    """Knit format repository."""
 
996
 
 
997
    def _warn_if_deprecated(self):
 
998
        # This class isn't deprecated
 
999
        pass
 
1000
 
 
1001
    def _inventory_add_lines(self, inv_vf, revid, parents, lines):
 
1002
        inv_vf.add_lines_with_ghosts(revid, parents, lines)
 
1003
 
 
1004
    @needs_read_lock
 
1005
    def _all_revision_ids(self):
 
1006
        """See Repository.all_revision_ids()."""
 
1007
        # Knits get the revision graph from the index of the revision knit, so
 
1008
        # it's always possible even if they're on an unlistable transport.
 
1009
        return self._revision_store.all_revision_ids(self.get_transaction())
 
1010
 
 
1011
    def fileid_involved_between_revs(self, from_revid, to_revid):
 
1012
        """Find file_id(s) which are involved in the changes between revisions.
 
1013
 
 
1014
        This determines the set of revisions which are involved, and then
 
1015
        finds all file ids affected by those revisions.
 
1016
        """
 
1017
        vf = self._get_revision_vf()
 
1018
        from_set = set(vf.get_ancestry(from_revid))
 
1019
        to_set = set(vf.get_ancestry(to_revid))
 
1020
        changed = to_set.difference(from_set)
 
1021
        return self._fileid_involved_by_set(changed)
 
1022
 
 
1023
    def fileid_involved(self, last_revid=None):
 
1024
        """Find all file_ids modified in the ancestry of last_revid.
 
1025
 
 
1026
        :param last_revid: If None, last_revision() will be used.
 
1027
        """
 
1028
        if not last_revid:
 
1029
            changed = set(self.all_revision_ids())
 
1030
        else:
 
1031
            changed = set(self.get_ancestry(last_revid))
 
1032
        if None in changed:
 
1033
            changed.remove(None)
 
1034
        return self._fileid_involved_by_set(changed)
 
1035
 
 
1036
    @needs_read_lock
 
1037
    def get_ancestry(self, revision_id):
 
1038
        """Return a list of revision-ids integrated by a revision.
 
1039
        
 
1040
        This is topologically sorted.
 
1041
        """
 
1042
        if revision_id is None:
 
1043
            return [None]
 
1044
        vf = self._get_revision_vf()
 
1045
        try:
 
1046
            return [None] + vf.get_ancestry(revision_id)
 
1047
        except errors.RevisionNotPresent:
 
1048
            raise errors.NoSuchRevision(self, revision_id)
 
1049
 
 
1050
    @needs_read_lock
 
1051
    def get_revision(self, revision_id):
 
1052
        """Return the Revision object for a named revision"""
 
1053
        return self.get_revision_reconcile(revision_id)
 
1054
 
 
1055
    @needs_read_lock
 
1056
    def get_revision_graph(self, revision_id=None):
 
1057
        """Return a dictionary containing the revision graph.
 
1058
 
 
1059
        :param revision_id: The revision_id to get a graph from. If None, then
 
1060
        the entire revision graph is returned. This is a deprecated mode of
 
1061
        operation and will be removed in the future.
 
1062
        :return: a dictionary of revision_id->revision_parents_list.
 
1063
        """
 
1064
        # special case NULL_REVISION
 
1065
        if revision_id == _mod_revision.NULL_REVISION:
 
1066
            return {}
 
1067
        a_weave = self._get_revision_vf()
 
1068
        entire_graph = a_weave.get_graph()
 
1069
        if revision_id is None:
 
1070
            return a_weave.get_graph()
 
1071
        elif revision_id not in a_weave:
 
1072
            raise errors.NoSuchRevision(self, revision_id)
 
1073
        else:
 
1074
            # add what can be reached from revision_id
 
1075
            result = {}
 
1076
            pending = set([revision_id])
 
1077
            while len(pending) > 0:
 
1078
                node = pending.pop()
 
1079
                result[node] = a_weave.get_parents(node)
 
1080
                for revision_id in result[node]:
 
1081
                    if revision_id not in result:
 
1082
                        pending.add(revision_id)
 
1083
            return result
 
1084
 
 
1085
    @needs_read_lock
 
1086
    def get_revision_graph_with_ghosts(self, revision_ids=None):
 
1087
        """Return a graph of the revisions with ghosts marked as applicable.
 
1088
 
 
1089
        :param revision_ids: an iterable of revisions to graph or None for all.
 
1090
        :return: a Graph object with the graph reachable from revision_ids.
 
1091
        """
 
1092
        result = graph.Graph()
 
1093
        vf = self._get_revision_vf()
 
1094
        versions = set(vf.versions())
 
1095
        if not revision_ids:
 
1096
            pending = set(self.all_revision_ids())
 
1097
            required = set([])
 
1098
        else:
 
1099
            pending = set(revision_ids)
 
1100
            # special case NULL_REVISION
 
1101
            if _mod_revision.NULL_REVISION in pending:
 
1102
                pending.remove(_mod_revision.NULL_REVISION)
 
1103
            required = set(pending)
 
1104
        done = set([])
 
1105
        while len(pending):
 
1106
            revision_id = pending.pop()
 
1107
            if not revision_id in versions:
 
1108
                if revision_id in required:
 
1109
                    raise errors.NoSuchRevision(self, revision_id)
 
1110
                # a ghost
 
1111
                result.add_ghost(revision_id)
 
1112
                # mark it as done so we don't try for it again.
 
1113
                done.add(revision_id)
 
1114
                continue
 
1115
            parent_ids = vf.get_parents_with_ghosts(revision_id)
 
1116
            for parent_id in parent_ids:
 
1117
                # is this queued or done ?
 
1118
                if (parent_id not in pending and
 
1119
                    parent_id not in done):
 
1120
                    # no, queue it.
 
1121
                    pending.add(parent_id)
 
1122
            result.add_node(revision_id, parent_ids)
 
1123
            done.add(revision_id)
 
1124
        return result
 
1125
 
 
1126
    def _get_revision_vf(self):
 
1127
        """:return: a versioned file containing the revisions."""
 
1128
        vf = self._revision_store.get_revision_file(self.get_transaction())
 
1129
        return vf
 
1130
 
 
1131
    @needs_write_lock
 
1132
    def reconcile(self, other=None, thorough=False):
 
1133
        """Reconcile this repository."""
 
1134
        from bzrlib.reconcile import KnitReconciler
 
1135
        reconciler = KnitReconciler(self, thorough=thorough)
 
1136
        reconciler.reconcile()
 
1137
        return reconciler
 
1138
    
 
1139
    def revision_parents(self, revision_id):
 
1140
        return self._get_revision_vf().get_parents(revision_id)
 
1141
 
 
1142
 
 
1143
class KnitRepository2(KnitRepository):
 
1144
    """"""
 
1145
    def __init__(self, _format, a_bzrdir, control_files, _revision_store,
 
1146
                 control_store, text_store):
 
1147
        KnitRepository.__init__(self, _format, a_bzrdir, control_files,
 
1148
                              _revision_store, control_store, text_store)
 
1149
        self._serializer = xml6.serializer_v6
 
1150
 
 
1151
    def deserialise_inventory(self, revision_id, xml):
 
1152
        """Transform the xml into an inventory object. 
 
1153
 
 
1154
        :param revision_id: The expected revision id of the inventory.
 
1155
        :param xml: A serialised inventory.
 
1156
        """
 
1157
        result = self._serializer.read_inventory_from_string(xml)
 
1158
        assert result.root.revision is not None
 
1159
        return result
 
1160
 
 
1161
    def serialise_inventory(self, inv):
 
1162
        """Transform the inventory object into XML text.
 
1163
 
 
1164
        :param revision_id: The expected revision id of the inventory.
 
1165
        :param xml: A serialised inventory.
 
1166
        """
 
1167
        assert inv.revision_id is not None
 
1168
        assert inv.root.revision is not None
 
1169
        return KnitRepository.serialise_inventory(self, inv)
 
1170
 
 
1171
    def get_commit_builder(self, branch, parents, config, timestamp=None, 
 
1172
                           timezone=None, committer=None, revprops=None, 
 
1173
                           revision_id=None):
 
1174
        """Obtain a CommitBuilder for this repository.
 
1175
        
 
1176
        :param branch: Branch to commit to.
 
1177
        :param parents: Revision ids of the parents of the new revision.
 
1178
        :param config: Configuration to use.
 
1179
        :param timestamp: Optional timestamp recorded for commit.
 
1180
        :param timezone: Optional timezone for timestamp.
 
1181
        :param committer: Optional committer to set for commit.
 
1182
        :param revprops: Optional dictionary of revision properties.
 
1183
        :param revision_id: Optional revision id.
 
1184
        """
 
1185
        return RootCommitBuilder(self, parents, config, timestamp, timezone,
 
1186
                                 committer, revprops, revision_id)
 
1187
 
 
1188
 
 
1189
class RepositoryFormatRegistry(registry.Registry):
 
1190
    """Registry of RepositoryFormats.
 
1191
    """
 
1192
    
 
1193
 
 
1194
format_registry = RepositoryFormatRegistry()
 
1195
"""Registry of formats, indexed by their identifying format string."""
 
1196
 
 
1197
 
 
1198
class RepositoryFormat(object):
 
1199
    """A repository format.
 
1200
 
 
1201
    Formats provide three things:
 
1202
     * An initialization routine to construct repository data on disk.
 
1203
     * a format string which is used when the BzrDir supports versioned
 
1204
       children.
 
1205
     * an open routine which returns a Repository instance.
 
1206
 
 
1207
    Formats are placed in an dict by their format string for reference 
 
1208
    during opening. These should be subclasses of RepositoryFormat
 
1209
    for consistency.
 
1210
 
 
1211
    Once a format is deprecated, just deprecate the initialize and open
 
1212
    methods on the format class. Do not deprecate the object, as the 
 
1213
    object will be created every system load.
 
1214
 
 
1215
    Common instance attributes:
 
1216
    _matchingbzrdir - the bzrdir format that the repository format was
 
1217
    originally written to work with. This can be used if manually
 
1218
    constructing a bzrdir and repository, or more commonly for test suite
 
1219
    parameterisation.
 
1220
    """
 
1221
 
 
1222
    def __str__(self):
 
1223
        return "<%s>" % self.__class__.__name__
 
1224
 
 
1225
    @classmethod
 
1226
    def find_format(klass, a_bzrdir):
 
1227
        """Return the format for the repository object in a_bzrdir.
 
1228
        
 
1229
        This is used by bzr native formats that have a "format" file in
 
1230
        the repository.  Other methods may be used by different types of 
 
1231
        control directory.
 
1232
        """
 
1233
        try:
 
1234
            transport = a_bzrdir.get_repository_transport(None)
 
1235
            format_string = transport.get("format").read()
 
1236
            return format_registry.get(format_string)
 
1237
        except errors.NoSuchFile:
 
1238
            raise errors.NoRepositoryPresent(a_bzrdir)
 
1239
        except KeyError:
 
1240
            raise errors.UnknownFormatError(format=format_string)
 
1241
 
 
1242
    @classmethod
 
1243
    def register_format(klass, format):
 
1244
        format_registry.register(format.get_format_string(), format)
 
1245
 
 
1246
    @classmethod
 
1247
    def unregister_format(klass, format):
 
1248
        format_registry.remove(format.get_format_string())
 
1249
    
 
1250
    @classmethod
 
1251
    def get_default_format(klass):
 
1252
        """Return the current default format."""
 
1253
        from bzrlib import bzrdir
 
1254
        return bzrdir.format_registry.make_bzrdir('default').repository_format
 
1255
 
 
1256
    def _get_control_store(self, repo_transport, control_files):
 
1257
        """Return the control store for this repository."""
 
1258
        raise NotImplementedError(self._get_control_store)
 
1259
 
 
1260
    def get_format_string(self):
 
1261
        """Return the ASCII format string that identifies this format.
 
1262
        
 
1263
        Note that in pre format ?? repositories the format string is 
 
1264
        not permitted nor written to disk.
 
1265
        """
 
1266
        raise NotImplementedError(self.get_format_string)
 
1267
 
 
1268
    def get_format_description(self):
 
1269
        """Return the short description for this format."""
 
1270
        raise NotImplementedError(self.get_format_description)
 
1271
 
 
1272
    def _get_revision_store(self, repo_transport, control_files):
 
1273
        """Return the revision store object for this a_bzrdir."""
 
1274
        raise NotImplementedError(self._get_revision_store)
 
1275
 
 
1276
    def _get_text_rev_store(self,
 
1277
                            transport,
 
1278
                            control_files,
 
1279
                            name,
 
1280
                            compressed=True,
 
1281
                            prefixed=False,
 
1282
                            serializer=None):
 
1283
        """Common logic for getting a revision store for a repository.
 
1284
        
 
1285
        see self._get_revision_store for the subclass-overridable method to 
 
1286
        get the store for a repository.
 
1287
        """
 
1288
        from bzrlib.store.revision.text import TextRevisionStore
 
1289
        dir_mode = control_files._dir_mode
 
1290
        file_mode = control_files._file_mode
 
1291
        text_store =TextStore(transport.clone(name),
 
1292
                              prefixed=prefixed,
 
1293
                              compressed=compressed,
 
1294
                              dir_mode=dir_mode,
 
1295
                              file_mode=file_mode)
 
1296
        _revision_store = TextRevisionStore(text_store, serializer)
 
1297
        return _revision_store
 
1298
 
 
1299
    def _get_versioned_file_store(self,
 
1300
                                  name,
 
1301
                                  transport,
 
1302
                                  control_files,
 
1303
                                  prefixed=True,
 
1304
                                  versionedfile_class=weave.WeaveFile,
 
1305
                                  versionedfile_kwargs={},
 
1306
                                  escaped=False):
 
1307
        weave_transport = control_files._transport.clone(name)
 
1308
        dir_mode = control_files._dir_mode
 
1309
        file_mode = control_files._file_mode
 
1310
        return VersionedFileStore(weave_transport, prefixed=prefixed,
 
1311
                                  dir_mode=dir_mode,
 
1312
                                  file_mode=file_mode,
 
1313
                                  versionedfile_class=versionedfile_class,
 
1314
                                  versionedfile_kwargs=versionedfile_kwargs,
 
1315
                                  escaped=escaped)
 
1316
 
 
1317
    def initialize(self, a_bzrdir, shared=False):
 
1318
        """Initialize a repository of this format in a_bzrdir.
 
1319
 
 
1320
        :param a_bzrdir: The bzrdir to put the new repository in it.
 
1321
        :param shared: The repository should be initialized as a sharable one.
 
1322
        :returns: The new repository object.
 
1323
        
 
1324
        This may raise UninitializableFormat if shared repository are not
 
1325
        compatible the a_bzrdir.
 
1326
        """
 
1327
        raise NotImplementedError(self.initialize)
 
1328
 
 
1329
    def is_supported(self):
 
1330
        """Is this format supported?
 
1331
 
 
1332
        Supported formats must be initializable and openable.
 
1333
        Unsupported formats may not support initialization or committing or 
 
1334
        some other features depending on the reason for not being supported.
 
1335
        """
 
1336
        return True
 
1337
 
 
1338
    def check_conversion_target(self, target_format):
 
1339
        raise NotImplementedError(self.check_conversion_target)
 
1340
 
 
1341
    def open(self, a_bzrdir, _found=False):
 
1342
        """Return an instance of this format for the bzrdir a_bzrdir.
 
1343
        
 
1344
        _found is a private parameter, do not use it.
 
1345
        """
 
1346
        raise NotImplementedError(self.open)
 
1347
 
 
1348
 
 
1349
class PreSplitOutRepositoryFormat(RepositoryFormat):
 
1350
    """Base class for the pre split out repository formats."""
 
1351
 
 
1352
    rich_root_data = False
 
1353
 
 
1354
    def initialize(self, a_bzrdir, shared=False, _internal=False):
 
1355
        """Create a weave repository.
 
1356
        
 
1357
        TODO: when creating split out bzr branch formats, move this to a common
 
1358
        base for Format5, Format6. or something like that.
 
1359
        """
 
1360
        if shared:
 
1361
            raise errors.IncompatibleFormat(self, a_bzrdir._format)
 
1362
 
 
1363
        if not _internal:
 
1364
            # always initialized when the bzrdir is.
 
1365
            return self.open(a_bzrdir, _found=True)
 
1366
        
 
1367
        # Create an empty weave
 
1368
        sio = StringIO()
 
1369
        weavefile.write_weave_v5(weave.Weave(), sio)
 
1370
        empty_weave = sio.getvalue()
 
1371
 
 
1372
        mutter('creating repository in %s.', a_bzrdir.transport.base)
 
1373
        dirs = ['revision-store', 'weaves']
 
1374
        files = [('inventory.weave', StringIO(empty_weave)),
 
1375
                 ]
 
1376
        
 
1377
        # FIXME: RBC 20060125 don't peek under the covers
 
1378
        # NB: no need to escape relative paths that are url safe.
 
1379
        control_files = lockable_files.LockableFiles(a_bzrdir.transport,
 
1380
                                'branch-lock', lockable_files.TransportLock)
 
1381
        control_files.create_lock()
 
1382
        control_files.lock_write()
 
1383
        control_files._transport.mkdir_multi(dirs,
 
1384
                mode=control_files._dir_mode)
 
1385
        try:
 
1386
            for file, content in files:
 
1387
                control_files.put(file, content)
 
1388
        finally:
 
1389
            control_files.unlock()
 
1390
        return self.open(a_bzrdir, _found=True)
 
1391
 
 
1392
    def _get_control_store(self, repo_transport, control_files):
 
1393
        """Return the control store for this repository."""
 
1394
        return self._get_versioned_file_store('',
 
1395
                                              repo_transport,
 
1396
                                              control_files,
 
1397
                                              prefixed=False)
 
1398
 
 
1399
    def _get_text_store(self, transport, control_files):
 
1400
        """Get a store for file texts for this format."""
 
1401
        raise NotImplementedError(self._get_text_store)
 
1402
 
 
1403
    def open(self, a_bzrdir, _found=False):
 
1404
        """See RepositoryFormat.open()."""
 
1405
        if not _found:
 
1406
            # we are being called directly and must probe.
 
1407
            raise NotImplementedError
 
1408
 
 
1409
        repo_transport = a_bzrdir.get_repository_transport(None)
 
1410
        control_files = a_bzrdir._control_files
 
1411
        text_store = self._get_text_store(repo_transport, control_files)
 
1412
        control_store = self._get_control_store(repo_transport, control_files)
 
1413
        _revision_store = self._get_revision_store(repo_transport, control_files)
 
1414
        return AllInOneRepository(_format=self,
 
1415
                                  a_bzrdir=a_bzrdir,
 
1416
                                  _revision_store=_revision_store,
 
1417
                                  control_store=control_store,
 
1418
                                  text_store=text_store)
 
1419
 
 
1420
    def check_conversion_target(self, target_format):
 
1421
        pass
 
1422
 
 
1423
 
 
1424
class RepositoryFormat4(PreSplitOutRepositoryFormat):
 
1425
    """Bzr repository format 4.
 
1426
 
 
1427
    This repository format has:
 
1428
     - flat stores
 
1429
     - TextStores for texts, inventories,revisions.
 
1430
 
 
1431
    This format is deprecated: it indexes texts using a text id which is
 
1432
    removed in format 5; initialization and write support for this format
 
1433
    has been removed.
 
1434
    """
 
1435
 
 
1436
    def __init__(self):
 
1437
        super(RepositoryFormat4, self).__init__()
 
1438
        self._matchingbzrdir = bzrdir.BzrDirFormat4()
 
1439
 
 
1440
    def get_format_description(self):
 
1441
        """See RepositoryFormat.get_format_description()."""
 
1442
        return "Repository format 4"
 
1443
 
 
1444
    def initialize(self, url, shared=False, _internal=False):
 
1445
        """Format 4 branches cannot be created."""
 
1446
        raise errors.UninitializableFormat(self)
 
1447
 
 
1448
    def is_supported(self):
 
1449
        """Format 4 is not supported.
 
1450
 
 
1451
        It is not supported because the model changed from 4 to 5 and the
 
1452
        conversion logic is expensive - so doing it on the fly was not 
 
1453
        feasible.
 
1454
        """
 
1455
        return False
 
1456
 
 
1457
    def _get_control_store(self, repo_transport, control_files):
 
1458
        """Format 4 repositories have no formal control store at this point.
 
1459
        
 
1460
        This will cause any control-file-needing apis to fail - this is desired.
 
1461
        """
 
1462
        return None
 
1463
    
 
1464
    def _get_revision_store(self, repo_transport, control_files):
 
1465
        """See RepositoryFormat._get_revision_store()."""
 
1466
        from bzrlib.xml4 import serializer_v4
 
1467
        return self._get_text_rev_store(repo_transport,
 
1468
                                        control_files,
 
1469
                                        'revision-store',
 
1470
                                        serializer=serializer_v4)
 
1471
 
 
1472
    def _get_text_store(self, transport, control_files):
 
1473
        """See RepositoryFormat._get_text_store()."""
 
1474
 
 
1475
 
 
1476
class RepositoryFormat5(PreSplitOutRepositoryFormat):
 
1477
    """Bzr control format 5.
 
1478
 
 
1479
    This repository format has:
 
1480
     - weaves for file texts and inventory
 
1481
     - flat stores
 
1482
     - TextStores for revisions and signatures.
 
1483
    """
 
1484
 
 
1485
    def __init__(self):
 
1486
        super(RepositoryFormat5, self).__init__()
 
1487
        self._matchingbzrdir = bzrdir.BzrDirFormat5()
 
1488
 
 
1489
    def get_format_description(self):
 
1490
        """See RepositoryFormat.get_format_description()."""
 
1491
        return "Weave repository format 5"
 
1492
 
 
1493
    def _get_revision_store(self, repo_transport, control_files):
 
1494
        """See RepositoryFormat._get_revision_store()."""
 
1495
        """Return the revision store object for this a_bzrdir."""
 
1496
        return self._get_text_rev_store(repo_transport,
 
1497
                                        control_files,
 
1498
                                        'revision-store',
 
1499
                                        compressed=False)
 
1500
 
 
1501
    def _get_text_store(self, transport, control_files):
 
1502
        """See RepositoryFormat._get_text_store()."""
 
1503
        return self._get_versioned_file_store('weaves', transport, control_files, prefixed=False)
 
1504
 
 
1505
 
 
1506
class RepositoryFormat6(PreSplitOutRepositoryFormat):
 
1507
    """Bzr control format 6.
 
1508
 
 
1509
    This repository format has:
 
1510
     - weaves for file texts and inventory
 
1511
     - hash subdirectory based stores.
 
1512
     - TextStores for revisions and signatures.
 
1513
    """
 
1514
 
 
1515
    def __init__(self):
 
1516
        super(RepositoryFormat6, self).__init__()
 
1517
        self._matchingbzrdir = bzrdir.BzrDirFormat6()
 
1518
 
 
1519
    def get_format_description(self):
 
1520
        """See RepositoryFormat.get_format_description()."""
 
1521
        return "Weave repository format 6"
 
1522
 
 
1523
    def _get_revision_store(self, repo_transport, control_files):
 
1524
        """See RepositoryFormat._get_revision_store()."""
 
1525
        return self._get_text_rev_store(repo_transport,
 
1526
                                        control_files,
 
1527
                                        'revision-store',
 
1528
                                        compressed=False,
 
1529
                                        prefixed=True)
 
1530
 
 
1531
    def _get_text_store(self, transport, control_files):
 
1532
        """See RepositoryFormat._get_text_store()."""
 
1533
        return self._get_versioned_file_store('weaves', transport, control_files)
 
1534
 
 
1535
 
 
1536
class MetaDirRepositoryFormat(RepositoryFormat):
 
1537
    """Common base class for the new repositories using the metadir layout."""
 
1538
 
 
1539
    rich_root_data = False
 
1540
 
 
1541
    def __init__(self):
 
1542
        super(MetaDirRepositoryFormat, self).__init__()
 
1543
        self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
 
1544
 
 
1545
    def _create_control_files(self, a_bzrdir):
 
1546
        """Create the required files and the initial control_files object."""
 
1547
        # FIXME: RBC 20060125 don't peek under the covers
 
1548
        # NB: no need to escape relative paths that are url safe.
 
1549
        repository_transport = a_bzrdir.get_repository_transport(self)
 
1550
        control_files = lockable_files.LockableFiles(repository_transport,
 
1551
                                'lock', lockdir.LockDir)
 
1552
        control_files.create_lock()
 
1553
        return control_files
 
1554
 
 
1555
    def _upload_blank_content(self, a_bzrdir, dirs, files, utf8_files, shared):
 
1556
        """Upload the initial blank content."""
 
1557
        control_files = self._create_control_files(a_bzrdir)
 
1558
        control_files.lock_write()
 
1559
        try:
 
1560
            control_files._transport.mkdir_multi(dirs,
 
1561
                    mode=control_files._dir_mode)
 
1562
            for file, content in files:
 
1563
                control_files.put(file, content)
 
1564
            for file, content in utf8_files:
 
1565
                control_files.put_utf8(file, content)
 
1566
            if shared == True:
 
1567
                control_files.put_utf8('shared-storage', '')
 
1568
        finally:
 
1569
            control_files.unlock()
 
1570
 
 
1571
 
 
1572
class RepositoryFormat7(MetaDirRepositoryFormat):
 
1573
    """Bzr repository 7.
 
1574
 
 
1575
    This repository format has:
 
1576
     - weaves for file texts and inventory
 
1577
     - hash subdirectory based stores.
 
1578
     - TextStores for revisions and signatures.
 
1579
     - a format marker of its own
 
1580
     - an optional 'shared-storage' flag
 
1581
     - an optional 'no-working-trees' flag
 
1582
    """
 
1583
 
 
1584
    def _get_control_store(self, repo_transport, control_files):
 
1585
        """Return the control store for this repository."""
 
1586
        return self._get_versioned_file_store('',
 
1587
                                              repo_transport,
 
1588
                                              control_files,
 
1589
                                              prefixed=False)
 
1590
 
 
1591
    def get_format_string(self):
 
1592
        """See RepositoryFormat.get_format_string()."""
 
1593
        return "Bazaar-NG Repository format 7"
 
1594
 
 
1595
    def get_format_description(self):
 
1596
        """See RepositoryFormat.get_format_description()."""
 
1597
        return "Weave repository format 7"
 
1598
 
 
1599
    def check_conversion_target(self, target_format):
 
1600
        pass
 
1601
 
 
1602
    def _get_revision_store(self, repo_transport, control_files):
 
1603
        """See RepositoryFormat._get_revision_store()."""
 
1604
        return self._get_text_rev_store(repo_transport,
 
1605
                                        control_files,
 
1606
                                        'revision-store',
 
1607
                                        compressed=False,
 
1608
                                        prefixed=True,
 
1609
                                        )
 
1610
 
 
1611
    def _get_text_store(self, transport, control_files):
 
1612
        """See RepositoryFormat._get_text_store()."""
 
1613
        return self._get_versioned_file_store('weaves',
 
1614
                                              transport,
 
1615
                                              control_files)
 
1616
 
 
1617
    def initialize(self, a_bzrdir, shared=False):
 
1618
        """Create a weave repository.
 
1619
 
 
1620
        :param shared: If true the repository will be initialized as a shared
 
1621
                       repository.
 
1622
        """
 
1623
        # Create an empty weave
 
1624
        sio = StringIO()
 
1625
        weavefile.write_weave_v5(weave.Weave(), sio)
 
1626
        empty_weave = sio.getvalue()
 
1627
 
 
1628
        mutter('creating repository in %s.', a_bzrdir.transport.base)
 
1629
        dirs = ['revision-store', 'weaves']
 
1630
        files = [('inventory.weave', StringIO(empty_weave)), 
 
1631
                 ]
 
1632
        utf8_files = [('format', self.get_format_string())]
 
1633
 
 
1634
        self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
 
1635
        return self.open(a_bzrdir=a_bzrdir, _found=True)
 
1636
 
 
1637
    def open(self, a_bzrdir, _found=False, _override_transport=None):
 
1638
        """See RepositoryFormat.open().
 
1639
        
 
1640
        :param _override_transport: INTERNAL USE ONLY. Allows opening the
 
1641
                                    repository at a slightly different url
 
1642
                                    than normal. I.e. during 'upgrade'.
 
1643
        """
 
1644
        if not _found:
 
1645
            format = RepositoryFormat.find_format(a_bzrdir)
 
1646
            assert format.__class__ ==  self.__class__
 
1647
        if _override_transport is not None:
 
1648
            repo_transport = _override_transport
 
1649
        else:
 
1650
            repo_transport = a_bzrdir.get_repository_transport(None)
 
1651
        control_files = lockable_files.LockableFiles(repo_transport,
 
1652
                                'lock', lockdir.LockDir)
 
1653
        text_store = self._get_text_store(repo_transport, control_files)
 
1654
        control_store = self._get_control_store(repo_transport, control_files)
 
1655
        _revision_store = self._get_revision_store(repo_transport, control_files)
 
1656
        return WeaveMetaDirRepository(_format=self,
 
1657
            a_bzrdir=a_bzrdir,
 
1658
            control_files=control_files,
 
1659
            _revision_store=_revision_store,
 
1660
            control_store=control_store,
 
1661
            text_store=text_store)
 
1662
 
 
1663
 
 
1664
class RepositoryFormatKnit(MetaDirRepositoryFormat):
 
1665
    """Bzr repository knit format (generalized). 
 
1666
 
 
1667
    This repository format has:
 
1668
     - knits for file texts and inventory
 
1669
     - hash subdirectory based stores.
 
1670
     - knits for revisions and signatures
 
1671
     - TextStores for revisions and signatures.
 
1672
     - a format marker of its own
 
1673
     - an optional 'shared-storage' flag
 
1674
     - an optional 'no-working-trees' flag
 
1675
     - a LockDir lock
 
1676
    """
 
1677
 
 
1678
    def _get_control_store(self, repo_transport, control_files):
 
1679
        """Return the control store for this repository."""
 
1680
        return VersionedFileStore(
 
1681
            repo_transport,
 
1682
            prefixed=False,
 
1683
            file_mode=control_files._file_mode,
 
1684
            versionedfile_class=knit.KnitVersionedFile,
 
1685
            versionedfile_kwargs={'factory':knit.KnitPlainFactory()},
 
1686
            )
 
1687
 
 
1688
    def _get_revision_store(self, repo_transport, control_files):
 
1689
        """See RepositoryFormat._get_revision_store()."""
 
1690
        from bzrlib.store.revision.knit import KnitRevisionStore
 
1691
        versioned_file_store = VersionedFileStore(
 
1692
            repo_transport,
 
1693
            file_mode=control_files._file_mode,
 
1694
            prefixed=False,
 
1695
            precious=True,
 
1696
            versionedfile_class=knit.KnitVersionedFile,
 
1697
            versionedfile_kwargs={'delta':False,
 
1698
                                  'factory':knit.KnitPlainFactory(),
 
1699
                                 },
 
1700
            escaped=True,
 
1701
            )
 
1702
        return KnitRevisionStore(versioned_file_store)
 
1703
 
 
1704
    def _get_text_store(self, transport, control_files):
 
1705
        """See RepositoryFormat._get_text_store()."""
 
1706
        return self._get_versioned_file_store('knits',
 
1707
                                  transport,
 
1708
                                  control_files,
 
1709
                                  versionedfile_class=knit.KnitVersionedFile,
 
1710
                                  versionedfile_kwargs={
 
1711
                                      'create_parent_dir':True,
 
1712
                                      'delay_create':True,
 
1713
                                      'dir_mode':control_files._dir_mode,
 
1714
                                  },
 
1715
                                  escaped=True)
 
1716
 
 
1717
    def initialize(self, a_bzrdir, shared=False):
 
1718
        """Create a knit format 1 repository.
 
1719
 
 
1720
        :param a_bzrdir: bzrdir to contain the new repository; must already
 
1721
            be initialized.
 
1722
        :param shared: If true the repository will be initialized as a shared
 
1723
                       repository.
 
1724
        """
 
1725
        mutter('creating repository in %s.', a_bzrdir.transport.base)
 
1726
        dirs = ['revision-store', 'knits']
 
1727
        files = []
 
1728
        utf8_files = [('format', self.get_format_string())]
 
1729
        
 
1730
        self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
 
1731
        repo_transport = a_bzrdir.get_repository_transport(None)
 
1732
        control_files = lockable_files.LockableFiles(repo_transport,
 
1733
                                'lock', lockdir.LockDir)
 
1734
        control_store = self._get_control_store(repo_transport, control_files)
 
1735
        transaction = transactions.WriteTransaction()
 
1736
        # trigger a write of the inventory store.
 
1737
        control_store.get_weave_or_empty('inventory', transaction)
 
1738
        _revision_store = self._get_revision_store(repo_transport, control_files)
 
1739
        # the revision id here is irrelevant: it will not be stored, and cannot
 
1740
        # already exist.
 
1741
        _revision_store.has_revision_id('A', transaction)
 
1742
        _revision_store.get_signature_file(transaction)
 
1743
        return self.open(a_bzrdir=a_bzrdir, _found=True)
 
1744
 
 
1745
    def open(self, a_bzrdir, _found=False, _override_transport=None):
 
1746
        """See RepositoryFormat.open().
 
1747
        
 
1748
        :param _override_transport: INTERNAL USE ONLY. Allows opening the
 
1749
                                    repository at a slightly different url
 
1750
                                    than normal. I.e. during 'upgrade'.
 
1751
        """
 
1752
        if not _found:
 
1753
            format = RepositoryFormat.find_format(a_bzrdir)
 
1754
            assert format.__class__ ==  self.__class__
 
1755
        if _override_transport is not None:
 
1756
            repo_transport = _override_transport
 
1757
        else:
 
1758
            repo_transport = a_bzrdir.get_repository_transport(None)
 
1759
        control_files = lockable_files.LockableFiles(repo_transport,
 
1760
                                'lock', lockdir.LockDir)
 
1761
        text_store = self._get_text_store(repo_transport, control_files)
 
1762
        control_store = self._get_control_store(repo_transport, control_files)
 
1763
        _revision_store = self._get_revision_store(repo_transport, control_files)
 
1764
        return KnitRepository(_format=self,
 
1765
                              a_bzrdir=a_bzrdir,
 
1766
                              control_files=control_files,
 
1767
                              _revision_store=_revision_store,
 
1768
                              control_store=control_store,
 
1769
                              text_store=text_store)
 
1770
 
 
1771
 
 
1772
class RepositoryFormatKnit1(RepositoryFormatKnit):
 
1773
    """Bzr repository knit format 1.
 
1774
 
 
1775
    This repository format has:
 
1776
     - knits for file texts and inventory
 
1777
     - hash subdirectory based stores.
 
1778
     - knits for revisions and signatures
 
1779
     - TextStores for revisions and signatures.
 
1780
     - a format marker of its own
 
1781
     - an optional 'shared-storage' flag
 
1782
     - an optional 'no-working-trees' flag
 
1783
     - a LockDir lock
 
1784
 
 
1785
    This format was introduced in bzr 0.8.
 
1786
    """
 
1787
    def get_format_string(self):
 
1788
        """See RepositoryFormat.get_format_string()."""
 
1789
        return "Bazaar-NG Knit Repository Format 1"
 
1790
 
 
1791
    def get_format_description(self):
 
1792
        """See RepositoryFormat.get_format_description()."""
 
1793
        return "Knit repository format 1"
 
1794
 
 
1795
    def check_conversion_target(self, target_format):
 
1796
        pass
 
1797
 
 
1798
 
 
1799
class RepositoryFormatKnit2(RepositoryFormatKnit):
 
1800
    """Bzr repository knit format 2.
 
1801
 
 
1802
    THIS FORMAT IS EXPERIMENTAL
 
1803
    This repository format has:
 
1804
     - knits for file texts and inventory
 
1805
     - hash subdirectory based stores.
 
1806
     - knits for revisions and signatures
 
1807
     - TextStores for revisions and signatures.
 
1808
     - a format marker of its own
 
1809
     - an optional 'shared-storage' flag
 
1810
     - an optional 'no-working-trees' flag
 
1811
     - a LockDir lock
 
1812
     - Support for recording full info about the tree root
 
1813
 
 
1814
    """
 
1815
    
 
1816
    rich_root_data = True
 
1817
 
 
1818
    def get_format_string(self):
 
1819
        """See RepositoryFormat.get_format_string()."""
 
1820
        return "Bazaar Knit Repository Format 2\n"
 
1821
 
 
1822
    def get_format_description(self):
 
1823
        """See RepositoryFormat.get_format_description()."""
 
1824
        return "Knit repository format 2"
 
1825
 
 
1826
    def check_conversion_target(self, target_format):
 
1827
        if not target_format.rich_root_data:
 
1828
            raise errors.BadConversionTarget(
 
1829
                'Does not support rich root data.', target_format)
 
1830
 
 
1831
    def open(self, a_bzrdir, _found=False, _override_transport=None):
 
1832
        """See RepositoryFormat.open().
 
1833
        
 
1834
        :param _override_transport: INTERNAL USE ONLY. Allows opening the
 
1835
                                    repository at a slightly different url
 
1836
                                    than normal. I.e. during 'upgrade'.
 
1837
        """
 
1838
        if not _found:
 
1839
            format = RepositoryFormat.find_format(a_bzrdir)
 
1840
            assert format.__class__ ==  self.__class__
 
1841
        if _override_transport is not None:
 
1842
            repo_transport = _override_transport
 
1843
        else:
 
1844
            repo_transport = a_bzrdir.get_repository_transport(None)
 
1845
        control_files = lockable_files.LockableFiles(repo_transport, 'lock',
 
1846
                                                     lockdir.LockDir)
 
1847
        text_store = self._get_text_store(repo_transport, control_files)
 
1848
        control_store = self._get_control_store(repo_transport, control_files)
 
1849
        _revision_store = self._get_revision_store(repo_transport, control_files)
 
1850
        return KnitRepository2(_format=self,
 
1851
                               a_bzrdir=a_bzrdir,
 
1852
                               control_files=control_files,
 
1853
                               _revision_store=_revision_store,
 
1854
                               control_store=control_store,
 
1855
                               text_store=text_store)
 
1856
 
 
1857
 
 
1858
 
 
1859
# formats which have no format string are not discoverable
 
1860
# and not independently creatable, so are not registered.
 
1861
RepositoryFormat.register_format(RepositoryFormat7())
 
1862
# KEEP in sync with bzrdir.format_registry default
 
1863
RepositoryFormat.register_format(RepositoryFormatKnit1())
 
1864
RepositoryFormat.register_format(RepositoryFormatKnit2())
 
1865
_legacy_formats = [RepositoryFormat4(),
 
1866
                   RepositoryFormat5(),
 
1867
                   RepositoryFormat6()]
 
1868
 
 
1869
 
 
1870
class InterRepository(InterObject):
 
1871
    """This class represents operations taking place between two repositories.
 
1872
 
 
1873
    Its instances have methods like copy_content and fetch, and contain
 
1874
    references to the source and target repositories these operations can be 
 
1875
    carried out on.
 
1876
 
 
1877
    Often we will provide convenience methods on 'repository' which carry out
 
1878
    operations with another repository - they will always forward to
 
1879
    InterRepository.get(other).method_name(parameters).
 
1880
    """
 
1881
 
 
1882
    _optimisers = []
 
1883
    """The available optimised InterRepository types."""
 
1884
 
 
1885
    def copy_content(self, revision_id=None, basis=None):
 
1886
        raise NotImplementedError(self.copy_content)
 
1887
 
 
1888
    def fetch(self, revision_id=None, pb=None):
 
1889
        """Fetch the content required to construct revision_id.
 
1890
 
 
1891
        The content is copied from self.source to self.target.
 
1892
 
 
1893
        :param revision_id: if None all content is copied, if NULL_REVISION no
 
1894
                            content is copied.
 
1895
        :param pb: optional progress bar to use for progress reports. If not
 
1896
                   provided a default one will be created.
 
1897
 
 
1898
        Returns the copied revision count and the failed revisions in a tuple:
 
1899
        (copied, failures).
 
1900
        """
 
1901
        raise NotImplementedError(self.fetch)
 
1902
   
 
1903
    @needs_read_lock
 
1904
    def missing_revision_ids(self, revision_id=None):
 
1905
        """Return the revision ids that source has that target does not.
 
1906
        
 
1907
        These are returned in topological order.
 
1908
 
 
1909
        :param revision_id: only return revision ids included by this
 
1910
                            revision_id.
 
1911
        """
 
1912
        # generic, possibly worst case, slow code path.
 
1913
        target_ids = set(self.target.all_revision_ids())
 
1914
        if revision_id is not None:
 
1915
            source_ids = self.source.get_ancestry(revision_id)
 
1916
            assert source_ids[0] is None
 
1917
            source_ids.pop(0)
 
1918
        else:
 
1919
            source_ids = self.source.all_revision_ids()
 
1920
        result_set = set(source_ids).difference(target_ids)
 
1921
        # this may look like a no-op: its not. It preserves the ordering
 
1922
        # other_ids had while only returning the members from other_ids
 
1923
        # that we've decided we need.
 
1924
        return [rev_id for rev_id in source_ids if rev_id in result_set]
 
1925
 
 
1926
 
 
1927
class InterSameDataRepository(InterRepository):
 
1928
    """Code for converting between repositories that represent the same data.
 
1929
    
 
1930
    Data format and model must match for this to work.
 
1931
    """
 
1932
 
 
1933
    _matching_repo_format = RepositoryFormat4()
 
1934
    """Repository format for testing with."""
 
1935
 
 
1936
    @staticmethod
 
1937
    def is_compatible(source, target):
 
1938
        if source._format.rich_root_data == target._format.rich_root_data:
 
1939
            return True
 
1940
        else:
 
1941
            return False
 
1942
 
 
1943
    @needs_write_lock
 
1944
    def copy_content(self, revision_id=None, basis=None):
 
1945
        """Make a complete copy of the content in self into destination.
 
1946
        
 
1947
        This is a destructive operation! Do not use it on existing 
 
1948
        repositories.
 
1949
 
 
1950
        :param revision_id: Only copy the content needed to construct
 
1951
                            revision_id and its parents.
 
1952
        :param basis: Copy the needed data preferentially from basis.
 
1953
        """
 
1954
        try:
 
1955
            self.target.set_make_working_trees(self.source.make_working_trees())
 
1956
        except NotImplementedError:
 
1957
            pass
 
1958
        # grab the basis available data
 
1959
        if basis is not None:
 
1960
            self.target.fetch(basis, revision_id=revision_id)
 
1961
        # but don't bother fetching if we have the needed data now.
 
1962
        if (revision_id not in (None, _mod_revision.NULL_REVISION) and 
 
1963
            self.target.has_revision(revision_id)):
 
1964
            return
 
1965
        self.target.fetch(self.source, revision_id=revision_id)
 
1966
 
 
1967
    @needs_write_lock
 
1968
    def fetch(self, revision_id=None, pb=None):
 
1969
        """See InterRepository.fetch()."""
 
1970
        from bzrlib.fetch import GenericRepoFetcher
 
1971
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
 
1972
               self.source, self.source._format, self.target, 
 
1973
               self.target._format)
 
1974
        f = GenericRepoFetcher(to_repository=self.target,
 
1975
                               from_repository=self.source,
 
1976
                               last_revision=revision_id,
 
1977
                               pb=pb)
 
1978
        return f.count_copied, f.failed_revisions
 
1979
 
 
1980
 
 
1981
class InterWeaveRepo(InterSameDataRepository):
 
1982
    """Optimised code paths between Weave based repositories."""
 
1983
 
 
1984
    _matching_repo_format = RepositoryFormat7()
 
1985
    """Repository format for testing with."""
 
1986
 
 
1987
    @staticmethod
 
1988
    def is_compatible(source, target):
 
1989
        """Be compatible with known Weave formats.
 
1990
        
 
1991
        We don't test for the stores being of specific types because that
 
1992
        could lead to confusing results, and there is no need to be 
 
1993
        overly general.
 
1994
        """
 
1995
        try:
 
1996
            return (isinstance(source._format, (RepositoryFormat5,
 
1997
                                                RepositoryFormat6,
 
1998
                                                RepositoryFormat7)) and
 
1999
                    isinstance(target._format, (RepositoryFormat5,
 
2000
                                                RepositoryFormat6,
 
2001
                                                RepositoryFormat7)))
 
2002
        except AttributeError:
 
2003
            return False
 
2004
    
 
2005
    @needs_write_lock
 
2006
    def copy_content(self, revision_id=None, basis=None):
 
2007
        """See InterRepository.copy_content()."""
 
2008
        # weave specific optimised path:
 
2009
        if basis is not None:
 
2010
            # copy the basis in, then fetch remaining data.
 
2011
            basis.copy_content_into(self.target, revision_id)
 
2012
            # the basis copy_content_into could miss-set this.
 
2013
            try:
 
2014
                self.target.set_make_working_trees(self.source.make_working_trees())
 
2015
            except NotImplementedError:
 
2016
                pass
 
2017
            self.target.fetch(self.source, revision_id=revision_id)
 
2018
        else:
 
2019
            try:
 
2020
                self.target.set_make_working_trees(self.source.make_working_trees())
 
2021
            except NotImplementedError:
 
2022
                pass
 
2023
            # FIXME do not peek!
 
2024
            if self.source.control_files._transport.listable():
 
2025
                pb = ui.ui_factory.nested_progress_bar()
 
2026
                try:
 
2027
                    self.target.weave_store.copy_all_ids(
 
2028
                        self.source.weave_store,
 
2029
                        pb=pb,
 
2030
                        from_transaction=self.source.get_transaction(),
 
2031
                        to_transaction=self.target.get_transaction())
 
2032
                    pb.update('copying inventory', 0, 1)
 
2033
                    self.target.control_weaves.copy_multi(
 
2034
                        self.source.control_weaves, ['inventory'],
 
2035
                        from_transaction=self.source.get_transaction(),
 
2036
                        to_transaction=self.target.get_transaction())
 
2037
                    self.target._revision_store.text_store.copy_all_ids(
 
2038
                        self.source._revision_store.text_store,
 
2039
                        pb=pb)
 
2040
                finally:
 
2041
                    pb.finished()
 
2042
            else:
 
2043
                self.target.fetch(self.source, revision_id=revision_id)
 
2044
 
 
2045
    @needs_write_lock
 
2046
    def fetch(self, revision_id=None, pb=None):
 
2047
        """See InterRepository.fetch()."""
 
2048
        from bzrlib.fetch import GenericRepoFetcher
 
2049
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
 
2050
               self.source, self.source._format, self.target, self.target._format)
 
2051
        f = GenericRepoFetcher(to_repository=self.target,
 
2052
                               from_repository=self.source,
 
2053
                               last_revision=revision_id,
 
2054
                               pb=pb)
 
2055
        return f.count_copied, f.failed_revisions
 
2056
 
 
2057
    @needs_read_lock
 
2058
    def missing_revision_ids(self, revision_id=None):
 
2059
        """See InterRepository.missing_revision_ids()."""
 
2060
        # we want all revisions to satisfy revision_id in source.
 
2061
        # but we don't want to stat every file here and there.
 
2062
        # we want then, all revisions other needs to satisfy revision_id 
 
2063
        # checked, but not those that we have locally.
 
2064
        # so the first thing is to get a subset of the revisions to 
 
2065
        # satisfy revision_id in source, and then eliminate those that
 
2066
        # we do already have. 
 
2067
        # this is slow on high latency connection to self, but as as this
 
2068
        # disk format scales terribly for push anyway due to rewriting 
 
2069
        # inventory.weave, this is considered acceptable.
 
2070
        # - RBC 20060209
 
2071
        if revision_id is not None:
 
2072
            source_ids = self.source.get_ancestry(revision_id)
 
2073
            assert source_ids[0] is None
 
2074
            source_ids.pop(0)
 
2075
        else:
 
2076
            source_ids = self.source._all_possible_ids()
 
2077
        source_ids_set = set(source_ids)
 
2078
        # source_ids is the worst possible case we may need to pull.
 
2079
        # now we want to filter source_ids against what we actually
 
2080
        # have in target, but don't try to check for existence where we know
 
2081
        # we do not have a revision as that would be pointless.
 
2082
        target_ids = set(self.target._all_possible_ids())
 
2083
        possibly_present_revisions = target_ids.intersection(source_ids_set)
 
2084
        actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
 
2085
        required_revisions = source_ids_set.difference(actually_present_revisions)
 
2086
        required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
 
2087
        if revision_id is not None:
 
2088
            # we used get_ancestry to determine source_ids then we are assured all
 
2089
            # revisions referenced are present as they are installed in topological order.
 
2090
            # and the tip revision was validated by get_ancestry.
 
2091
            return required_topo_revisions
 
2092
        else:
 
2093
            # if we just grabbed the possibly available ids, then 
 
2094
            # we only have an estimate of whats available and need to validate
 
2095
            # that against the revision records.
 
2096
            return self.source._eliminate_revisions_not_present(required_topo_revisions)
 
2097
 
 
2098
 
 
2099
class InterKnitRepo(InterSameDataRepository):
 
2100
    """Optimised code paths between Knit based repositories."""
 
2101
 
 
2102
    _matching_repo_format = RepositoryFormatKnit1()
 
2103
    """Repository format for testing with."""
 
2104
 
 
2105
    @staticmethod
 
2106
    def is_compatible(source, target):
 
2107
        """Be compatible with known Knit formats.
 
2108
        
 
2109
        We don't test for the stores being of specific types because that
 
2110
        could lead to confusing results, and there is no need to be 
 
2111
        overly general.
 
2112
        """
 
2113
        try:
 
2114
            return (isinstance(source._format, (RepositoryFormatKnit1)) and
 
2115
                    isinstance(target._format, (RepositoryFormatKnit1)))
 
2116
        except AttributeError:
 
2117
            return False
 
2118
 
 
2119
    @needs_write_lock
 
2120
    def fetch(self, revision_id=None, pb=None):
 
2121
        """See InterRepository.fetch()."""
 
2122
        from bzrlib.fetch import KnitRepoFetcher
 
2123
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
 
2124
               self.source, self.source._format, self.target, self.target._format)
 
2125
        f = KnitRepoFetcher(to_repository=self.target,
 
2126
                            from_repository=self.source,
 
2127
                            last_revision=revision_id,
 
2128
                            pb=pb)
 
2129
        return f.count_copied, f.failed_revisions
 
2130
 
 
2131
    @needs_read_lock
 
2132
    def missing_revision_ids(self, revision_id=None):
 
2133
        """See InterRepository.missing_revision_ids()."""
 
2134
        if revision_id is not None:
 
2135
            source_ids = self.source.get_ancestry(revision_id)
 
2136
            assert source_ids[0] is None
 
2137
            source_ids.pop(0)
 
2138
        else:
 
2139
            source_ids = self.source._all_possible_ids()
 
2140
        source_ids_set = set(source_ids)
 
2141
        # source_ids is the worst possible case we may need to pull.
 
2142
        # now we want to filter source_ids against what we actually
 
2143
        # have in target, but don't try to check for existence where we know
 
2144
        # we do not have a revision as that would be pointless.
 
2145
        target_ids = set(self.target._all_possible_ids())
 
2146
        possibly_present_revisions = target_ids.intersection(source_ids_set)
 
2147
        actually_present_revisions = set(self.target._eliminate_revisions_not_present(possibly_present_revisions))
 
2148
        required_revisions = source_ids_set.difference(actually_present_revisions)
 
2149
        required_topo_revisions = [rev_id for rev_id in source_ids if rev_id in required_revisions]
 
2150
        if revision_id is not None:
 
2151
            # we used get_ancestry to determine source_ids then we are assured all
 
2152
            # revisions referenced are present as they are installed in topological order.
 
2153
            # and the tip revision was validated by get_ancestry.
 
2154
            return required_topo_revisions
 
2155
        else:
 
2156
            # if we just grabbed the possibly available ids, then 
 
2157
            # we only have an estimate of whats available and need to validate
 
2158
            # that against the revision records.
 
2159
            return self.source._eliminate_revisions_not_present(required_topo_revisions)
 
2160
 
 
2161
 
 
2162
class InterModel1and2(InterRepository):
 
2163
 
 
2164
    _matching_repo_format = None
 
2165
 
 
2166
    @staticmethod
 
2167
    def is_compatible(source, target):
 
2168
        if not isinstance(source, Repository):
 
2169
            return False
 
2170
        if not isinstance(target, Repository):
 
2171
            return False
 
2172
        if not source._format.rich_root_data and target._format.rich_root_data:
 
2173
            return True
 
2174
        else:
 
2175
            return False
 
2176
 
 
2177
    @needs_write_lock
 
2178
    def fetch(self, revision_id=None, pb=None):
 
2179
        """See InterRepository.fetch()."""
 
2180
        from bzrlib.fetch import Model1toKnit2Fetcher
 
2181
        f = Model1toKnit2Fetcher(to_repository=self.target,
 
2182
                                 from_repository=self.source,
 
2183
                                 last_revision=revision_id,
 
2184
                                 pb=pb)
 
2185
        return f.count_copied, f.failed_revisions
 
2186
 
 
2187
    @needs_write_lock
 
2188
    def copy_content(self, revision_id=None, basis=None):
 
2189
        """Make a complete copy of the content in self into destination.
 
2190
        
 
2191
        This is a destructive operation! Do not use it on existing 
 
2192
        repositories.
 
2193
 
 
2194
        :param revision_id: Only copy the content needed to construct
 
2195
                            revision_id and its parents.
 
2196
        :param basis: Copy the needed data preferentially from basis.
 
2197
        """
 
2198
        try:
 
2199
            self.target.set_make_working_trees(self.source.make_working_trees())
 
2200
        except NotImplementedError:
 
2201
            pass
 
2202
        # grab the basis available data
 
2203
        if basis is not None:
 
2204
            self.target.fetch(basis, revision_id=revision_id)
 
2205
        # but don't bother fetching if we have the needed data now.
 
2206
        if (revision_id not in (None, _mod_revision.NULL_REVISION) and 
 
2207
            self.target.has_revision(revision_id)):
 
2208
            return
 
2209
        self.target.fetch(self.source, revision_id=revision_id)
 
2210
 
 
2211
 
 
2212
class InterKnit1and2(InterKnitRepo):
 
2213
 
 
2214
    _matching_repo_format = None
 
2215
 
 
2216
    @staticmethod
 
2217
    def is_compatible(source, target):
 
2218
        """Be compatible with Knit1 source and Knit2 target"""
 
2219
        try:
 
2220
            return (isinstance(source._format, (RepositoryFormatKnit1)) and
 
2221
                    isinstance(target._format, (RepositoryFormatKnit2)))
 
2222
        except AttributeError:
 
2223
            return False
 
2224
 
 
2225
    @needs_write_lock
 
2226
    def fetch(self, revision_id=None, pb=None):
 
2227
        """See InterRepository.fetch()."""
 
2228
        from bzrlib.fetch import Knit1to2Fetcher
 
2229
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
 
2230
               self.source, self.source._format, self.target, 
 
2231
               self.target._format)
 
2232
        f = Knit1to2Fetcher(to_repository=self.target,
 
2233
                            from_repository=self.source,
 
2234
                            last_revision=revision_id,
 
2235
                            pb=pb)
 
2236
        return f.count_copied, f.failed_revisions
 
2237
 
 
2238
 
 
2239
InterRepository.register_optimiser(InterSameDataRepository)
 
2240
InterRepository.register_optimiser(InterWeaveRepo)
 
2241
InterRepository.register_optimiser(InterKnitRepo)
 
2242
InterRepository.register_optimiser(InterModel1and2)
 
2243
InterRepository.register_optimiser(InterKnit1and2)
 
2244
 
 
2245
 
 
2246
class RepositoryTestProviderAdapter(object):
 
2247
    """A tool to generate a suite testing multiple repository formats at once.
 
2248
 
 
2249
    This is done by copying the test once for each transport and injecting
 
2250
    the transport_server, transport_readonly_server, and bzrdir_format and
 
2251
    repository_format classes into each copy. Each copy is also given a new id()
 
2252
    to make it easy to identify.
 
2253
    """
 
2254
 
 
2255
    def __init__(self, transport_server, transport_readonly_server, formats,
 
2256
        vfs_transport_factory=None):
 
2257
        self._transport_server = transport_server
 
2258
        self._transport_readonly_server = transport_readonly_server
 
2259
        self._vfs_transport_factory = vfs_transport_factory
 
2260
        self._formats = formats
 
2261
    
 
2262
    def adapt(self, test):
 
2263
        result = unittest.TestSuite()
 
2264
        for repository_format, bzrdir_format in self._formats:
 
2265
            new_test = deepcopy(test)
 
2266
            new_test.transport_server = self._transport_server
 
2267
            new_test.transport_readonly_server = self._transport_readonly_server
 
2268
            if self._vfs_transport_factory:
 
2269
                new_test.vfs_transport_factory = self._vfs_transport_factory
 
2270
            new_test.bzrdir_format = bzrdir_format
 
2271
            new_test.repository_format = repository_format
 
2272
            def make_new_test_id():
 
2273
                new_id = "%s(%s)" % (new_test.id(), repository_format.__class__.__name__)
 
2274
                return lambda: new_id
 
2275
            new_test.id = make_new_test_id()
 
2276
            result.addTest(new_test)
 
2277
        return result
 
2278
 
 
2279
 
 
2280
class InterRepositoryTestProviderAdapter(object):
 
2281
    """A tool to generate a suite testing multiple inter repository formats.
 
2282
 
 
2283
    This is done by copying the test once for each interrepo provider and injecting
 
2284
    the transport_server, transport_readonly_server, repository_format and 
 
2285
    repository_to_format classes into each copy.
 
2286
    Each copy is also given a new id() to make it easy to identify.
 
2287
    """
 
2288
 
 
2289
    def __init__(self, transport_server, transport_readonly_server, formats):
 
2290
        self._transport_server = transport_server
 
2291
        self._transport_readonly_server = transport_readonly_server
 
2292
        self._formats = formats
 
2293
    
 
2294
    def adapt(self, test):
 
2295
        result = unittest.TestSuite()
 
2296
        for interrepo_class, repository_format, repository_format_to in self._formats:
 
2297
            new_test = deepcopy(test)
 
2298
            new_test.transport_server = self._transport_server
 
2299
            new_test.transport_readonly_server = self._transport_readonly_server
 
2300
            new_test.interrepo_class = interrepo_class
 
2301
            new_test.repository_format = repository_format
 
2302
            new_test.repository_format_to = repository_format_to
 
2303
            def make_new_test_id():
 
2304
                new_id = "%s(%s)" % (new_test.id(), interrepo_class.__name__)
 
2305
                return lambda: new_id
 
2306
            new_test.id = make_new_test_id()
 
2307
            result.addTest(new_test)
 
2308
        return result
 
2309
 
 
2310
    @staticmethod
 
2311
    def default_test_list():
 
2312
        """Generate the default list of interrepo permutations to test."""
 
2313
        result = []
 
2314
        # test the default InterRepository between format 6 and the current 
 
2315
        # default format.
 
2316
        # XXX: robertc 20060220 reinstate this when there are two supported
 
2317
        # formats which do not have an optimal code path between them.
 
2318
        #result.append((InterRepository,
 
2319
        #               RepositoryFormat6(),
 
2320
        #               RepositoryFormatKnit1()))
 
2321
        for optimiser in InterRepository._optimisers:
 
2322
            if optimiser._matching_repo_format is not None:
 
2323
                result.append((optimiser,
 
2324
                               optimiser._matching_repo_format,
 
2325
                               optimiser._matching_repo_format
 
2326
                               ))
 
2327
        # if there are specific combinations we want to use, we can add them 
 
2328
        # here.
 
2329
        result.append((InterModel1and2, RepositoryFormat5(),
 
2330
                       RepositoryFormatKnit2()))
 
2331
        result.append((InterKnit1and2, RepositoryFormatKnit1(),
 
2332
                       RepositoryFormatKnit2()))
 
2333
        return result
 
2334
 
 
2335
 
 
2336
class CopyConverter(object):
 
2337
    """A repository conversion tool which just performs a copy of the content.
 
2338
    
 
2339
    This is slow but quite reliable.
 
2340
    """
 
2341
 
 
2342
    def __init__(self, target_format):
 
2343
        """Create a CopyConverter.
 
2344
 
 
2345
        :param target_format: The format the resulting repository should be.
 
2346
        """
 
2347
        self.target_format = target_format
 
2348
        
 
2349
    def convert(self, repo, pb):
 
2350
        """Perform the conversion of to_convert, giving feedback via pb.
 
2351
 
 
2352
        :param to_convert: The disk object to convert.
 
2353
        :param pb: a progress bar to use for progress information.
 
2354
        """
 
2355
        self.pb = pb
 
2356
        self.count = 0
 
2357
        self.total = 4
 
2358
        # this is only useful with metadir layouts - separated repo content.
 
2359
        # trigger an assertion if not such
 
2360
        repo._format.get_format_string()
 
2361
        self.repo_dir = repo.bzrdir
 
2362
        self.step('Moving repository to repository.backup')
 
2363
        self.repo_dir.transport.move('repository', 'repository.backup')
 
2364
        backup_transport =  self.repo_dir.transport.clone('repository.backup')
 
2365
        repo._format.check_conversion_target(self.target_format)
 
2366
        self.source_repo = repo._format.open(self.repo_dir,
 
2367
            _found=True,
 
2368
            _override_transport=backup_transport)
 
2369
        self.step('Creating new repository')
 
2370
        converted = self.target_format.initialize(self.repo_dir,
 
2371
                                                  self.source_repo.is_shared())
 
2372
        converted.lock_write()
 
2373
        try:
 
2374
            self.step('Copying content into repository.')
 
2375
            self.source_repo.copy_content_into(converted)
 
2376
        finally:
 
2377
            converted.unlock()
 
2378
        self.step('Deleting old repository content.')
 
2379
        self.repo_dir.transport.delete_tree('repository.backup')
 
2380
        self.pb.note('repository converted')
 
2381
 
 
2382
    def step(self, message):
 
2383
        """Update the pb by a step."""
 
2384
        self.count +=1
 
2385
        self.pb.update(message, self.count, self.total)
 
2386
 
 
2387
 
 
2388
class CommitBuilder(object):
 
2389
    """Provides an interface to build up a commit.
 
2390
 
 
2391
    This allows describing a tree to be committed without needing to 
 
2392
    know the internals of the format of the repository.
 
2393
    """
 
2394
    
 
2395
    record_root_entry = False
 
2396
    def __init__(self, repository, parents, config, timestamp=None, 
 
2397
                 timezone=None, committer=None, revprops=None, 
 
2398
                 revision_id=None):
 
2399
        """Initiate a CommitBuilder.
 
2400
 
 
2401
        :param repository: Repository to commit to.
 
2402
        :param parents: Revision ids of the parents of the new revision.
 
2403
        :param config: Configuration to use.
 
2404
        :param timestamp: Optional timestamp recorded for commit.
 
2405
        :param timezone: Optional timezone for timestamp.
 
2406
        :param committer: Optional committer to set for commit.
 
2407
        :param revprops: Optional dictionary of revision properties.
 
2408
        :param revision_id: Optional revision id.
 
2409
        """
 
2410
        self._config = config
 
2411
 
 
2412
        if committer is None:
 
2413
            self._committer = self._config.username()
 
2414
        else:
 
2415
            assert isinstance(committer, basestring), type(committer)
 
2416
            self._committer = committer
 
2417
 
 
2418
        self.new_inventory = Inventory(None)
 
2419
        self._new_revision_id = revision_id
 
2420
        self.parents = parents
 
2421
        self.repository = repository
 
2422
 
 
2423
        self._revprops = {}
 
2424
        if revprops is not None:
 
2425
            self._revprops.update(revprops)
 
2426
 
 
2427
        if timestamp is None:
 
2428
            timestamp = time.time()
 
2429
        # Restrict resolution to 1ms
 
2430
        self._timestamp = round(timestamp, 3)
 
2431
 
 
2432
        if timezone is None:
 
2433
            self._timezone = local_time_offset()
 
2434
        else:
 
2435
            self._timezone = int(timezone)
 
2436
 
 
2437
        self._generate_revision_if_needed()
 
2438
 
 
2439
    def commit(self, message):
 
2440
        """Make the actual commit.
 
2441
 
 
2442
        :return: The revision id of the recorded revision.
 
2443
        """
 
2444
        rev = _mod_revision.Revision(
 
2445
                       timestamp=self._timestamp,
 
2446
                       timezone=self._timezone,
 
2447
                       committer=self._committer,
 
2448
                       message=message,
 
2449
                       inventory_sha1=self.inv_sha1,
 
2450
                       revision_id=self._new_revision_id,
 
2451
                       properties=self._revprops)
 
2452
        rev.parent_ids = self.parents
 
2453
        self.repository.add_revision(self._new_revision_id, rev, 
 
2454
            self.new_inventory, self._config)
 
2455
        return self._new_revision_id
 
2456
 
 
2457
    def revision_tree(self):
 
2458
        """Return the tree that was just committed.
 
2459
 
 
2460
        After calling commit() this can be called to get a RevisionTree
 
2461
        representing the newly committed tree. This is preferred to
 
2462
        calling Repository.revision_tree() because that may require
 
2463
        deserializing the inventory, while we already have a copy in
 
2464
        memory.
 
2465
        """
 
2466
        return RevisionTree(self.repository, self.new_inventory,
 
2467
                            self._new_revision_id)
 
2468
 
 
2469
    def finish_inventory(self):
 
2470
        """Tell the builder that the inventory is finished."""
 
2471
        if self.new_inventory.root is None:
 
2472
            symbol_versioning.warn('Root entry should be supplied to'
 
2473
                ' record_entry_contents, as of bzr 0.10.',
 
2474
                 DeprecationWarning, stacklevel=2)
 
2475
            self.new_inventory.add(InventoryDirectory(ROOT_ID, '', None))
 
2476
        self.new_inventory.revision_id = self._new_revision_id
 
2477
        self.inv_sha1 = self.repository.add_inventory(
 
2478
            self._new_revision_id,
 
2479
            self.new_inventory,
 
2480
            self.parents
 
2481
            )
 
2482
 
 
2483
    def _gen_revision_id(self):
 
2484
        """Return new revision-id."""
 
2485
        return generate_ids.gen_revision_id(self._config.username(),
 
2486
                                            self._timestamp)
 
2487
 
 
2488
    def _generate_revision_if_needed(self):
 
2489
        """Create a revision id if None was supplied.
 
2490
        
 
2491
        If the repository can not support user-specified revision ids
 
2492
        they should override this function and raise CannotSetRevisionId
 
2493
        if _new_revision_id is not None.
 
2494
 
 
2495
        :raises: CannotSetRevisionId
 
2496
        """
 
2497
        if self._new_revision_id is None:
 
2498
            self._new_revision_id = self._gen_revision_id()
 
2499
 
 
2500
    def record_entry_contents(self, ie, parent_invs, path, tree):
 
2501
        """Record the content of ie from tree into the commit if needed.
 
2502
 
 
2503
        Side effect: sets ie.revision when unchanged
 
2504
 
 
2505
        :param ie: An inventory entry present in the commit.
 
2506
        :param parent_invs: The inventories of the parent revisions of the
 
2507
            commit.
 
2508
        :param path: The path the entry is at in the tree.
 
2509
        :param tree: The tree which contains this entry and should be used to 
 
2510
        obtain content.
 
2511
        """
 
2512
        if self.new_inventory.root is None and ie.parent_id is not None:
 
2513
            symbol_versioning.warn('Root entry should be supplied to'
 
2514
                ' record_entry_contents, as of bzr 0.10.',
 
2515
                 DeprecationWarning, stacklevel=2)
 
2516
            self.record_entry_contents(tree.inventory.root.copy(), parent_invs,
 
2517
                                       '', tree)
 
2518
        self.new_inventory.add(ie)
 
2519
 
 
2520
        # ie.revision is always None if the InventoryEntry is considered
 
2521
        # for committing. ie.snapshot will record the correct revision 
 
2522
        # which may be the sole parent if it is untouched.
 
2523
        if ie.revision is not None:
 
2524
            return
 
2525
 
 
2526
        # In this revision format, root entries have no knit or weave
 
2527
        if ie is self.new_inventory.root:
 
2528
            # When serializing out to disk and back in
 
2529
            # root.revision is always _new_revision_id
 
2530
            ie.revision = self._new_revision_id
 
2531
            return
 
2532
        previous_entries = ie.find_previous_heads(
 
2533
            parent_invs,
 
2534
            self.repository.weave_store,
 
2535
            self.repository.get_transaction())
 
2536
        # we are creating a new revision for ie in the history store
 
2537
        # and inventory.
 
2538
        ie.snapshot(self._new_revision_id, path, previous_entries, tree, self)
 
2539
 
 
2540
    def modified_directory(self, file_id, file_parents):
 
2541
        """Record the presence of a symbolic link.
 
2542
 
 
2543
        :param file_id: The file_id of the link to record.
 
2544
        :param file_parents: The per-file parent revision ids.
 
2545
        """
 
2546
        self._add_text_to_weave(file_id, [], file_parents.keys())
 
2547
    
 
2548
    def modified_file_text(self, file_id, file_parents,
 
2549
                           get_content_byte_lines, text_sha1=None,
 
2550
                           text_size=None):
 
2551
        """Record the text of file file_id
 
2552
 
 
2553
        :param file_id: The file_id of the file to record the text of.
 
2554
        :param file_parents: The per-file parent revision ids.
 
2555
        :param get_content_byte_lines: A callable which will return the byte
 
2556
            lines for the file.
 
2557
        :param text_sha1: Optional SHA1 of the file contents.
 
2558
        :param text_size: Optional size of the file contents.
 
2559
        """
 
2560
        # mutter('storing text of file {%s} in revision {%s} into %r',
 
2561
        #        file_id, self._new_revision_id, self.repository.weave_store)
 
2562
        # special case to avoid diffing on renames or 
 
2563
        # reparenting
 
2564
        if (len(file_parents) == 1
 
2565
            and text_sha1 == file_parents.values()[0].text_sha1
 
2566
            and text_size == file_parents.values()[0].text_size):
 
2567
            previous_ie = file_parents.values()[0]
 
2568
            versionedfile = self.repository.weave_store.get_weave(file_id, 
 
2569
                self.repository.get_transaction())
 
2570
            versionedfile.clone_text(self._new_revision_id, 
 
2571
                previous_ie.revision, file_parents.keys())
 
2572
            return text_sha1, text_size
 
2573
        else:
 
2574
            new_lines = get_content_byte_lines()
 
2575
            # TODO: Rather than invoking sha_strings here, _add_text_to_weave
 
2576
            # should return the SHA1 and size
 
2577
            self._add_text_to_weave(file_id, new_lines, file_parents.keys())
 
2578
            return osutils.sha_strings(new_lines), \
 
2579
                sum(map(len, new_lines))
 
2580
 
 
2581
    def modified_link(self, file_id, file_parents, link_target):
 
2582
        """Record the presence of a symbolic link.
 
2583
 
 
2584
        :param file_id: The file_id of the link to record.
 
2585
        :param file_parents: The per-file parent revision ids.
 
2586
        :param link_target: Target location of this link.
 
2587
        """
 
2588
        self._add_text_to_weave(file_id, [], file_parents.keys())
 
2589
 
 
2590
    def _add_text_to_weave(self, file_id, new_lines, parents):
 
2591
        versionedfile = self.repository.weave_store.get_weave_or_empty(
 
2592
            file_id, self.repository.get_transaction())
 
2593
        versionedfile.add_lines(self._new_revision_id, parents, new_lines)
 
2594
        versionedfile.clear_cache()
 
2595
 
 
2596
 
 
2597
class _CommitBuilder(CommitBuilder):
 
2598
    """Temporary class so old CommitBuilders are detected properly
 
2599
    
 
2600
    Note: CommitBuilder works whether or not root entry is recorded.
 
2601
    """
 
2602
 
 
2603
    record_root_entry = True
 
2604
 
 
2605
 
 
2606
class RootCommitBuilder(CommitBuilder):
 
2607
    """This commitbuilder actually records the root id"""
 
2608
    
 
2609
    record_root_entry = True
 
2610
 
 
2611
    def record_entry_contents(self, ie, parent_invs, path, tree):
 
2612
        """Record the content of ie from tree into the commit if needed.
 
2613
 
 
2614
        Side effect: sets ie.revision when unchanged
 
2615
 
 
2616
        :param ie: An inventory entry present in the commit.
 
2617
        :param parent_invs: The inventories of the parent revisions of the
 
2618
            commit.
 
2619
        :param path: The path the entry is at in the tree.
 
2620
        :param tree: The tree which contains this entry and should be used to 
 
2621
        obtain content.
 
2622
        """
 
2623
        assert self.new_inventory.root is not None or ie.parent_id is None
 
2624
        self.new_inventory.add(ie)
 
2625
 
 
2626
        # ie.revision is always None if the InventoryEntry is considered
 
2627
        # for committing. ie.snapshot will record the correct revision 
 
2628
        # which may be the sole parent if it is untouched.
 
2629
        if ie.revision is not None:
 
2630
            return
 
2631
 
 
2632
        previous_entries = ie.find_previous_heads(
 
2633
            parent_invs,
 
2634
            self.repository.weave_store,
 
2635
            self.repository.get_transaction())
 
2636
        # we are creating a new revision for ie in the history store
 
2637
        # and inventory.
 
2638
        ie.snapshot(self._new_revision_id, path, previous_entries, tree, self)
 
2639
 
 
2640
 
 
2641
_unescape_map = {
 
2642
    'apos':"'",
 
2643
    'quot':'"',
 
2644
    'amp':'&',
 
2645
    'lt':'<',
 
2646
    'gt':'>'
 
2647
}
 
2648
 
 
2649
 
 
2650
def _unescaper(match, _map=_unescape_map):
 
2651
    return _map[match.group(1)]
 
2652
 
 
2653
 
 
2654
_unescape_re = None
 
2655
 
 
2656
 
 
2657
def _unescape_xml(data):
 
2658
    """Unescape predefined XML entities in a string of data."""
 
2659
    global _unescape_re
 
2660
    if _unescape_re is None:
 
2661
        _unescape_re = re.compile('\&([^;]*);')
 
2662
    return _unescape_re.sub(_unescaper, data)