/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: Aaron Bentley
  • Date: 2007-07-11 22:16:29 UTC
  • mto: This revision was merged to the branch mainline in revision 2606.
  • Revision ID: aaron.bentley@utoronto.ca-20070711221629-tbqh4m4mps264lxe
Fix trailing whitespace

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