/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/repository.py

  • Committer: Martin Pool
  • Date: 2007-02-20 04:47:54 UTC
  • mto: (2220.2.19 tags)
  • mto: This revision was merged to the branch mainline in revision 2309.
  • Revision ID: mbp@sourcefrog.net-20070220044754-ptovhd212hs4vkkf
add bencode utility

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