/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-06 06:27:24 UTC
  • mto: This revision was merged to the branch mainline in revision 2283.
  • Revision ID: mbp@sourcefrog.net-20070206062724-a5uo1u27jxsal2t0
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.

Change help for --format to just say 'see help formats'

RepositoryFormat.register_metadir gains an optional parameter for the
module name containing the repository format, and lazily loads from there.

Disable test_interrepository_get_returns_correct_optimiser, because it
seems too brittle.

Remove InterWeaveRepo, these should now just be upgraded.

Show diffs side-by-side

added added

removed removed

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