/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: John Arbash Meinel
  • Date: 2007-02-17 21:17:22 UTC
  • mto: This revision was merged to the branch mainline in revision 2298.
  • Revision ID: john@arbash-meinel.com-20070217211722-yxx3xjxtxeijc8d7
Add safe_file_id as a helper in osutils.

Show diffs side-by-side

added added

removed removed

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