1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
 
 
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.
 
 
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.
 
 
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
 
 
17
from cStringIO import StringIO
 
 
19
from bzrlib.lazy_import import lazy_import
 
 
20
lazy_import(globals(), """
 
 
38
    revision as _mod_revision,
 
 
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
 
 
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 (
 
 
57
from bzrlib.trace import mutter, note, warning
 
 
60
# Old formats display a warning, but only once
 
 
61
_deprecation_warning_done = False
 
 
64
######################################################################
 
 
67
class Repository(object):
 
 
68
    """Repository holding history for one or more branches.
 
 
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.
 
 
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 
 
 
79
    _file_ids_altered_regex = lazy_regex.lazy_compile(
 
 
80
        r'file_id="(?P<file_id>[^"]+)"'
 
 
81
        r'.*revision="(?P<revision_id>[^"]+)"'
 
 
85
    def add_inventory(self, revision_id, inv, parents):
 
 
86
        """Add the inventory inv to the repository as revision_id.
 
 
88
        :param parents: The revision ids of the parents that revision_id
 
 
89
                        is known to have and are in the repository already.
 
 
91
        returns the sha1 of the serialized inventory.
 
 
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))
 
 
107
    def _inventory_add_lines(self, inv_vf, revision_id, parents, lines):
 
 
109
        for parent in parents:
 
 
111
                final_parents.append(parent)
 
 
113
        inv_vf.add_lines(revision_id, final_parents, lines)
 
 
116
    def add_revision(self, revision_id, rev, inv=None, config=None):
 
 
117
        """Add rev to the revision store as revision_id.
 
 
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.
 
 
127
        revision_id = osutils.safe_revision_id(revision_id)
 
 
128
        # TODO: jam 20070210 Shouldn't we check rev.revision_id and
 
 
130
        _mod_revision.check_not_reserved_id(revision_id)
 
 
131
        if config is not None and config.signature_needed():
 
 
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():
 
 
139
                raise errors.WeaveRevisionNotPresent(revision_id,
 
 
140
                                                     self.get_inventory_weave())
 
 
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())
 
 
147
    def _all_possible_ids(self):
 
 
148
        """Return all the possible revisions that we could find."""
 
 
149
        return self.get_inventory_weave().versions()
 
 
151
    def all_revision_ids(self):
 
 
152
        """Returns a list of all the revision ids in the repository. 
 
 
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.
 
 
158
        return self._all_revision_ids()
 
 
161
    def _all_revision_ids(self):
 
 
162
        """Returns a list of all the revision ids in the repository. 
 
 
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.
 
 
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)
 
 
176
    def break_lock(self):
 
 
177
        """Break a lock if one is present from another instance.
 
 
179
        Uses the ui factory to ask for confirmation if the lock may be from
 
 
182
        self.control_files.break_lock()
 
 
185
    def _eliminate_revisions_not_present(self, revision_ids):
 
 
186
        """Check every revision id in revision_ids to see if we have it.
 
 
188
        Returns a set of the present revisions.
 
 
191
        for id in revision_ids:
 
 
192
            if self.has_revision(id):
 
 
197
    def create(a_bzrdir):
 
 
198
        """Construct the current default format repository in a_bzrdir."""
 
 
199
        return RepositoryFormat.get_default_format().initialize(a_bzrdir)
 
 
201
    def __init__(self, _format, a_bzrdir, control_files, _revision_store, control_store, text_store):
 
 
202
        """instantiate a Repository.
 
 
204
        :param _format: The format of the repository on disk.
 
 
205
        :param a_bzrdir: The BzrDir of the repository.
 
 
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.
 
 
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 ? 
 
 
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()
 
 
229
        return '%s(%r)' % (self.__class__.__name__, 
 
 
230
                           self.bzrdir.transport.base)
 
 
233
        return self.control_files.is_locked()
 
 
235
    def lock_write(self, token=None):
 
 
236
        """Lock this repository for writing.
 
 
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.
 
 
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
 
 
250
        XXX: this docstring is duplicated in many places, e.g. lockable_files.py
 
 
252
        return self.control_files.lock_write(token=token)
 
 
255
        self.control_files.lock_read()
 
 
257
    def get_physical_lock_status(self):
 
 
258
        return self.control_files.get_physical_lock_status()
 
 
260
    def leave_lock_in_place(self):
 
 
261
        """Tell this repository not to release the physical lock when this
 
 
264
        If lock_write doesn't return a token, then this method is not supported.
 
 
266
        self.control_files.leave_in_place()
 
 
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.
 
 
272
        If lock_write doesn't return a token, then this method is not supported.
 
 
274
        self.control_files.dont_leave_in_place()
 
 
277
    def gather_stats(self, revid=None, committers=None):
 
 
278
        """Gather statistics from a revision id.
 
 
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.
 
 
294
        if revid and committers:
 
 
295
            result['committers'] = 0
 
 
296
        if revid and revid != _mod_revision.NULL_REVISION:
 
 
298
                all_committers = set()
 
 
299
            revisions = self.get_ancestry(revid)
 
 
300
            # pop the leading None
 
 
302
            first_revision = None
 
 
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
 
 
310
                    all_committers.add(revision.committer)
 
 
311
            last_revision = revision
 
 
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)
 
 
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
 
 
327
    def missing_revision_ids(self, other, revision_id=None):
 
 
328
        """Return the revision ids that other has that this does not.
 
 
330
        These are returned in topological order.
 
 
332
        revision_id: only return revision ids included by revision_id.
 
 
334
        revision_id = osutils.safe_revision_id(revision_id)
 
 
335
        return InterRepository.get(other, self).missing_revision_ids(revision_id)
 
 
339
        """Open the repository rooted at base.
 
 
341
        For instance, if the repository is at URL/.bzr/repository,
 
 
342
        Repository.open(URL) -> a Repository instance.
 
 
344
        control = bzrdir.BzrDir.open(base)
 
 
345
        return control.open_repository()
 
 
347
    def copy_content_into(self, destination, revision_id=None):
 
 
348
        """Make a complete copy of the content in self into destination.
 
 
350
        This is a destructive operation! Do not use it on existing 
 
 
353
        revision_id = osutils.safe_revision_id(revision_id)
 
 
354
        return InterRepository.get(self, destination).copy_content(revision_id)
 
 
356
    def fetch(self, source, revision_id=None, pb=None):
 
 
357
        """Fetch the content required to construct revision_id from source.
 
 
359
        If revision_id is None all content is copied.
 
 
361
        revision_id = osutils.safe_revision_id(revision_id)
 
 
362
        inter = InterRepository.get(source, self)
 
 
364
            return inter.fetch(revision_id=revision_id, pb=pb)
 
 
365
        except NotImplementedError:
 
 
366
            raise errors.IncompatibleRepositories(source, self)
 
 
368
    def get_commit_builder(self, branch, parents, config, timestamp=None, 
 
 
369
                           timezone=None, committer=None, revprops=None, 
 
 
371
        """Obtain a CommitBuilder for this repository.
 
 
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.
 
 
382
        revision_id = osutils.safe_revision_id(revision_id)
 
 
383
        return _CommitBuilder(self, parents, config, timestamp, timezone,
 
 
384
                              committer, revprops, revision_id)
 
 
387
        self.control_files.unlock()
 
 
390
    def clone(self, a_bzrdir, revision_id=None):
 
 
391
        """Clone this repository into a_bzrdir using the current format.
 
 
393
        Currently no check is made that the format of this repository and
 
 
394
        the bzrdir format are compatible. FIXME RBC 20060201.
 
 
396
        :return: The newly created destination repository.
 
 
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)
 
 
405
    def sprout(self, to_bzrdir, revision_id=None):
 
 
406
        """Create a descendent repository for new development.
 
 
408
        Unlike clone, this does not copy the settings of the repository.
 
 
410
        dest_repo = self._create_sprouting_repo(to_bzrdir, shared=False)
 
 
411
        dest_repo.fetch(self, revision_id=revision_id)
 
 
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()
 
 
419
            # Most control formats need the repository to be specifically
 
 
420
            # created, but on some old all-in-one formats it's not needed
 
 
422
                dest_repo = self._format.initialize(a_bzrdir, shared=shared)
 
 
423
            except errors.UninitializableFormat:
 
 
424
                dest_repo = a_bzrdir.open_repository()
 
 
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())
 
 
435
    def get_revision_reconcile(self, revision_id):
 
 
436
        """'reconcile' helper routine that allows access to a revision always.
 
 
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.
 
 
443
        if not revision_id or not isinstance(revision_id, basestring):
 
 
444
            raise errors.InvalidRevisionId(revision_id=revision_id,
 
 
446
        return self.get_revisions([revision_id])[0]
 
 
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())
 
 
454
            assert not isinstance(rev.revision_id, unicode)
 
 
455
            for parent_id in rev.parent_ids:
 
 
456
                assert not isinstance(parent_id, unicode)
 
 
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)
 
 
467
        # the current serializer..
 
 
468
        self._revision_store._serializer.write_revision(rev, rev_tmp)
 
 
470
        return rev_tmp.getvalue()
 
 
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
 
 
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)
 
 
490
    def get_deltas_for_revisions(self, revisions):
 
 
491
        """Produce a generator of revision deltas.
 
 
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.
 
 
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()
 
 
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)
 
 
510
                old_tree = trees[revision.parent_ids[0]]
 
 
511
            yield trees[revision.revision_id].changes_from(old_tree)
 
 
514
    def get_revision_delta(self, revision_id):
 
 
515
        """Return the delta for one revision.
 
 
517
        The delta is relative to the left-hand predecessor of the
 
 
520
        r = self.get_revision(revision_id)
 
 
521
        return list(self.get_deltas_for_revisions([r]))[0]
 
 
523
    def _check_revision_parents(self, revision, inventory):
 
 
524
        """Private to Repository and Fetch.
 
 
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.
 
 
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:
 
 
537
                    raise errors.CorruptRepository(self)
 
 
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,
 
 
545
                                                         self.get_transaction())
 
 
547
    def fileids_altered_by_revision_ids(self, revision_ids):
 
 
548
        """Find the file ids and versions affected by revisions.
 
 
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.
 
 
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()
 
 
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
 
 
571
        unescape_revid_cache = {}
 
 
572
        unescape_fileid_cache = {}
 
 
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
 
 
579
        search = self._file_ids_altered_regex.search
 
 
580
        unescape = _unescape_xml
 
 
581
        setdefault = result.setdefault
 
 
582
        pb = ui.ui_factory.nested_progress_bar()
 
 
584
            for line in w.iter_lines_added_or_present_in_versions(
 
 
585
                                        selected_revision_ids, pb=pb):
 
 
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')
 
 
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
 
 
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.
 
 
603
                    revision_id = unescape_revid_cache[revision_id]
 
 
605
                    unescaped = unescape(revision_id)
 
 
606
                    unescape_revid_cache[revision_id] = unescaped
 
 
607
                    revision_id = unescaped
 
 
609
                if revision_id in selected_revision_ids:
 
 
611
                        file_id = unescape_fileid_cache[file_id]
 
 
613
                        unescaped = unescape(file_id)
 
 
614
                        unescape_fileid_cache[file_id] = unescaped
 
 
616
                    setdefault(file_id, set()).add(revision_id)
 
 
622
    def get_inventory_weave(self):
 
 
623
        return self.control_weaves.get_weave('inventory',
 
 
624
            self.get_transaction())
 
 
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))
 
 
635
    def deserialise_inventory(self, revision_id, xml):
 
 
636
        """Transform the xml into an inventory object. 
 
 
638
        :param revision_id: The expected revision id of the inventory.
 
 
639
        :param xml: A serialised inventory.
 
 
641
        revision_id = osutils.safe_revision_id(revision_id)
 
 
642
        result = self._serializer.read_inventory_from_string(xml)
 
 
643
        result.root.revision = revision_id
 
 
646
    def serialise_inventory(self, inv):
 
 
647
        return self._serializer.write_inventory_to_string(inv)
 
 
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)
 
 
654
            assert isinstance(revision_id, str), type(revision_id)
 
 
655
            iw = self.get_inventory_weave()
 
 
656
            return iw.get_text(revision_id)
 
 
658
            raise errors.HistoryMissing(self, 'inventory', revision_id)
 
 
661
    def get_inventory_sha1(self, revision_id):
 
 
662
        """Return the sha1 hash of the inventory entry
 
 
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
 
 
669
    def get_revision_graph(self, revision_id=None):
 
 
670
        """Return a dictionary containing the revision graph.
 
 
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.
 
 
677
        # special case NULL_REVISION
 
 
678
        if revision_id == _mod_revision.NULL_REVISION:
 
 
680
        revision_id = osutils.safe_revision_id(revision_id)
 
 
681
        a_weave = self.get_inventory_weave()
 
 
682
        all_revisions = self._eliminate_revisions_not_present(
 
 
684
        entire_graph = dict([(node, a_weave.get_parents(node)) for 
 
 
685
                             node in all_revisions])
 
 
686
        if revision_id is None:
 
 
688
        elif revision_id not in entire_graph:
 
 
689
            raise errors.NoSuchRevision(self, revision_id)
 
 
691
            # add what can be reached from revision_id
 
 
693
            pending = set([revision_id])
 
 
694
            while len(pending) > 0:
 
 
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)
 
 
703
    def get_revision_graph_with_ghosts(self, revision_ids=None):
 
 
704
        """Return a graph of the revisions with ghosts marked as applicable.
 
 
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.
 
 
709
        result = deprecated_graph.Graph()
 
 
711
            pending = set(self.all_revision_ids())
 
 
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)
 
 
721
            revision_id = pending.pop()
 
 
723
                rev = self.get_revision(revision_id)
 
 
724
            except errors.NoSuchRevision:
 
 
725
                if revision_id in required:
 
 
728
                result.add_ghost(revision_id)
 
 
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):
 
 
735
                    pending.add(parent_id)
 
 
736
            result.add_node(revision_id, rev.parent_ids)
 
 
737
            done.add(revision_id)
 
 
740
    def _get_history_vf(self):
 
 
741
        """Get a versionedfile whose history graph reflects all revisions.
 
 
743
        For weave repositories, this is the inventory weave.
 
 
745
        return self.get_inventory_weave()
 
 
747
    def iter_reverse_revision_history(self, revision_id):
 
 
748
        """Iterate backwards through revision ids in the lefthand history
 
 
750
        :param revision_id: The revision id to start with.  All its lefthand
 
 
751
            ancestors will be traversed.
 
 
753
        revision_id = osutils.safe_revision_id(revision_id)
 
 
754
        if revision_id in (None, _mod_revision.NULL_REVISION):
 
 
756
        next_id = revision_id
 
 
757
        versionedfile = self._get_history_vf()
 
 
760
            parents = versionedfile.get_parents(next_id)
 
 
761
            if len(parents) == 0:
 
 
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())
 
 
780
            return self.get_inventory(revision_id)
 
 
784
        """Return True if this repository is flagged as a shared repository."""
 
 
785
        raise NotImplementedError(self.is_shared)
 
 
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()
 
 
796
    def revision_tree(self, revision_id):
 
 
797
        """Return Tree for a revision on this branch.
 
 
799
        `revision_id` may be None for the empty tree revision.
 
 
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)
 
 
807
            revision_id = osutils.safe_revision_id(revision_id)
 
 
808
            inv = self.get_revision_inventory(revision_id)
 
 
809
            return RevisionTree(self, inv, revision_id)
 
 
812
    def revision_trees(self, revision_ids):
 
 
813
        """Return Tree for a revision on this branch.
 
 
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)
 
 
824
    def get_ancestry(self, revision_id, topo_sorted=True):
 
 
825
        """Return a list of revision-ids integrated by a revision.
 
 
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.
 
 
831
        This is topologically sorted.
 
 
833
        if _mod_revision.is_null(revision_id):
 
 
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)
 
 
843
    def print_file(self, file, revision_id):
 
 
844
        """Print `file` to stdout.
 
 
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.
 
 
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)
 
 
855
            # TODO: jam 20060427 Write a test for this code path
 
 
856
            #       it had a bug in it, and was raising the wrong
 
 
858
            raise errors.BzrError("%r is not present in revision %s" % (file, revision_id))
 
 
859
        tree.print_file(file_id)
 
 
861
    def get_transaction(self):
 
 
862
        return self.control_files.get_transaction()
 
 
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)
 
 
868
    def get_parents(self, revision_ids):
 
 
869
        """See StackedParentsProvider.get_parents"""
 
 
871
        for revision_id in revision_ids:
 
 
872
            if revision_id == _mod_revision.NULL_REVISION:
 
 
876
                    parents = self.get_revision(revision_id).parent_ids
 
 
877
                except errors.NoSuchRevision:
 
 
880
                    if len(parents) == 0:
 
 
881
                        parents = [_mod_revision.NULL_REVISION]
 
 
882
            parents_list.append(parents)
 
 
885
    def _make_parents_provider(self):
 
 
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)
 
 
899
    def set_make_working_trees(self, new_value):
 
 
900
        """Set the policy flag for making working trees when creating branches.
 
 
902
        This only applies to branches that use this repository.
 
 
904
        The default is 'True'.
 
 
905
        :param new_value: True to restore the default, False to disable making
 
 
908
        raise NotImplementedError(self.set_make_working_trees)
 
 
910
    def make_working_trees(self):
 
 
911
        """Returns the policy for making working trees on new branches."""
 
 
912
        raise NotImplementedError(self.make_working_trees)
 
 
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)
 
 
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())
 
 
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())
 
 
935
    def check(self, revision_ids):
 
 
936
        """Check consistency of all history of given revision_ids.
 
 
938
        Different repository implementations should override _check().
 
 
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.
 
 
944
            raise ValueError("revision_ids must be non-empty in %s.check" 
 
 
946
        revision_ids = [osutils.safe_revision_id(r) for r in revision_ids]
 
 
947
        return self._check(revision_ids)
 
 
949
    def _check(self, revision_ids):
 
 
950
        result = check.Check(self)
 
 
954
    def _warn_if_deprecated(self):
 
 
955
        global _deprecation_warning_done
 
 
956
        if _deprecation_warning_done:
 
 
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))
 
 
962
    def supports_rich_root(self):
 
 
963
        return self._format.rich_root_data
 
 
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):
 
 
972
                    revision_id.encode('ascii')
 
 
973
                except UnicodeEncodeError:
 
 
974
                    raise errors.NonAsciiRevisionId(method, self)
 
 
977
                    revision_id.decode('ascii')
 
 
978
                except UnicodeDecodeError:
 
 
979
                    raise errors.NonAsciiRevisionId(method, self)
 
 
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),
 
 
990
        m = __import__(from_module, globals(), locals(), [name])
 
 
992
            return getattr(m, name)
 
 
993
        except AttributeError:
 
 
994
            raise AttributeError('module %s has no name %s'
 
 
996
    globals()[name] = _deprecated_repository_forwarder
 
 
999
        'AllInOneRepository',
 
 
1000
        'WeaveMetaDirRepository',
 
 
1001
        'PreSplitOutRepositoryFormat',
 
 
1002
        'RepositoryFormat4',
 
 
1003
        'RepositoryFormat5',
 
 
1004
        'RepositoryFormat6',
 
 
1005
        'RepositoryFormat7',
 
 
1007
    __make_delegated(_name, 'bzrlib.repofmt.weaverepo')
 
 
1011
        'RepositoryFormatKnit',
 
 
1012
        'RepositoryFormatKnit1',
 
 
1014
    __make_delegated(_name, 'bzrlib.repofmt.knitrepo')
 
 
1017
def install_revision(repository, rev, revision_tree):
 
 
1018
    """Install all revision data into a repository."""
 
 
1019
    present_parents = []
 
 
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)
 
 
1026
            parent_trees[p_id] = repository.revision_tree(None)
 
 
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:
 
 
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
 
 
1045
            for revision, tree in parent_trees.iteritems():
 
 
1046
                if ie.file_id not in tree:
 
 
1048
                parent_id = tree.inventory[ie.file_id].revision
 
 
1049
                if parent_id in text_parents:
 
 
1051
                text_parents.append(parent_id)
 
 
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)
 
 
1058
        # install the inventory
 
 
1059
        repository.add_inventory(rev.revision_id, inv, present_parents)
 
 
1060
    except errors.RevisionAlreadyPresent:
 
 
1062
    repository.add_revision(rev.revision_id, rev, inv)
 
 
1065
class MetaDirRepository(Repository):
 
 
1066
    """Repositories in the new meta-dir layout."""
 
 
1068
    def __init__(self, _format, a_bzrdir, control_files, _revision_store, control_store, text_store):
 
 
1069
        super(MetaDirRepository, self).__init__(_format,
 
 
1075
        dir_mode = self.control_files._dir_mode
 
 
1076
        file_mode = self.control_files._file_mode
 
 
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')
 
 
1084
    def set_make_working_trees(self, new_value):
 
 
1085
        """Set the policy flag for making working trees when creating branches.
 
 
1087
        This only applies to branches that use this repository.
 
 
1089
        The default is 'True'.
 
 
1090
        :param new_value: True to restore the default, False to disable making
 
 
1095
                self.control_files._transport.delete('no-working-trees')
 
 
1096
            except errors.NoSuchFile:
 
 
1099
            self.control_files.put_utf8('no-working-trees', '')
 
 
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')
 
 
1106
class RepositoryFormatRegistry(registry.Registry):
 
 
1107
    """Registry of RepositoryFormats.
 
 
1110
    def get(self, format_string):
 
 
1111
        r = registry.Registry.get(self, format_string)
 
 
1117
format_registry = RepositoryFormatRegistry()
 
 
1118
"""Registry of formats, indexed by their identifying format string.
 
 
1120
This can contain either format instances themselves, or classes/factories that
 
 
1121
can be called to obtain one.
 
 
1125
#####################################################################
 
 
1126
# Repository Formats
 
 
1128
class RepositoryFormat(object):
 
 
1129
    """A repository format.
 
 
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
 
 
1135
     * an open routine which returns a Repository instance.
 
 
1137
    Formats are placed in an dict by their format string for reference 
 
 
1138
    during opening. These should be subclasses of RepositoryFormat
 
 
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.
 
 
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
 
 
1153
        return "<%s>" % self.__class__.__name__
 
 
1155
    def __eq__(self, other):
 
 
1156
        # format objects are generally stateless
 
 
1157
        return isinstance(other, self.__class__)
 
 
1159
    def __ne__(self, other):
 
 
1160
        return not self == other
 
 
1163
    def find_format(klass, a_bzrdir):
 
 
1164
        """Return the format for the repository object in a_bzrdir.
 
 
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 
 
 
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)
 
 
1177
            raise errors.UnknownFormatError(format=format_string)
 
 
1180
    def register_format(klass, format):
 
 
1181
        format_registry.register(format.get_format_string(), format)
 
 
1184
    def unregister_format(klass, format):
 
 
1185
        format_registry.remove(format.get_format_string())
 
 
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
 
 
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)
 
 
1197
    def get_format_string(self):
 
 
1198
        """Return the ASCII format string that identifies this format.
 
 
1200
        Note that in pre format ?? repositories the format string is 
 
 
1201
        not permitted nor written to disk.
 
 
1203
        raise NotImplementedError(self.get_format_string)
 
 
1205
    def get_format_description(self):
 
 
1206
        """Return the short description for this format."""
 
 
1207
        raise NotImplementedError(self.get_format_description)
 
 
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)
 
 
1213
    def _get_text_rev_store(self,
 
 
1220
        """Common logic for getting a revision store for a repository.
 
 
1222
        see self._get_revision_store for the subclass-overridable method to 
 
 
1223
        get the store for a repository.
 
 
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),
 
 
1230
                              compressed=compressed,
 
 
1232
                              file_mode=file_mode)
 
 
1233
        _revision_store = TextRevisionStore(text_store, serializer)
 
 
1234
        return _revision_store
 
 
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,
 
 
1243
                                  versionedfile_class=None,
 
 
1244
                                  versionedfile_kwargs={},
 
 
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,
 
 
1253
                                  file_mode=file_mode,
 
 
1254
                                  versionedfile_class=versionedfile_class,
 
 
1255
                                  versionedfile_kwargs=versionedfile_kwargs,
 
 
1258
    def initialize(self, a_bzrdir, shared=False):
 
 
1259
        """Initialize a repository of this format in a_bzrdir.
 
 
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.
 
 
1265
        This may raise UninitializableFormat if shared repository are not
 
 
1266
        compatible the a_bzrdir.
 
 
1268
        raise NotImplementedError(self.initialize)
 
 
1270
    def is_supported(self):
 
 
1271
        """Is this format supported?
 
 
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.
 
 
1279
    def check_conversion_target(self, target_format):
 
 
1280
        raise NotImplementedError(self.check_conversion_target)
 
 
1282
    def open(self, a_bzrdir, _found=False):
 
 
1283
        """Return an instance of this format for the bzrdir a_bzrdir.
 
 
1285
        _found is a private parameter, do not use it.
 
 
1287
        raise NotImplementedError(self.open)
 
 
1290
class MetaDirRepositoryFormat(RepositoryFormat):
 
 
1291
    """Common base class for the new repositories using the metadir layout."""
 
 
1293
    rich_root_data = False
 
 
1294
    supports_tree_reference = False
 
 
1295
    _matchingbzrdir = bzrdir.BzrDirMetaFormat1()
 
 
1298
        super(MetaDirRepositoryFormat, self).__init__()
 
 
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
 
 
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()
 
 
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)
 
 
1322
                control_files.put_utf8('shared-storage', '')
 
 
1324
            control_files.unlock()
 
 
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.
 
 
1333
format_registry.register_lazy(
 
 
1334
    'Bazaar-NG Repository format 7',
 
 
1335
    'bzrlib.repofmt.weaverepo',
 
 
1338
# KEEP in sync with bzrdir.format_registry default, which controls the overall
 
 
1339
# default control directory format
 
 
1341
format_registry.register_lazy(
 
 
1342
    'Bazaar-NG Knit Repository Format 1',
 
 
1343
    'bzrlib.repofmt.knitrepo',
 
 
1344
    'RepositoryFormatKnit1',
 
 
1346
format_registry.default_key = 'Bazaar-NG Knit Repository Format 1'
 
 
1348
format_registry.register_lazy(
 
 
1349
    'Bazaar Knit Repository Format 3 (bzr 0.15)\n',
 
 
1350
    'bzrlib.repofmt.knitrepo',
 
 
1351
    'RepositoryFormatKnit3',
 
 
1355
class InterRepository(InterObject):
 
 
1356
    """This class represents operations taking place between two repositories.
 
 
1358
    Its instances have methods like copy_content and fetch, and contain
 
 
1359
    references to the source and target repositories these operations can be 
 
 
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).
 
 
1368
    """The available optimised InterRepository types."""
 
 
1370
    def copy_content(self, revision_id=None):
 
 
1371
        raise NotImplementedError(self.copy_content)
 
 
1373
    def fetch(self, revision_id=None, pb=None):
 
 
1374
        """Fetch the content required to construct revision_id.
 
 
1376
        The content is copied from self.source to self.target.
 
 
1378
        :param revision_id: if None all content is copied, if NULL_REVISION no
 
 
1380
        :param pb: optional progress bar to use for progress reports. If not
 
 
1381
                   provided a default one will be created.
 
 
1383
        Returns the copied revision count and the failed revisions in a tuple:
 
 
1386
        raise NotImplementedError(self.fetch)
 
 
1389
    def missing_revision_ids(self, revision_id=None):
 
 
1390
        """Return the revision ids that source has that target does not.
 
 
1392
        These are returned in topological order.
 
 
1394
        :param revision_id: only return revision ids included by this
 
 
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
 
 
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]
 
 
1415
class InterSameDataRepository(InterRepository):
 
 
1416
    """Code for converting between repositories that represent the same data.
 
 
1418
    Data format and model must match for this to work.
 
 
1422
    def _get_repo_format_to_test(self):
 
 
1423
        """Repository format for testing with."""
 
 
1424
        return RepositoryFormat.get_default_format()
 
 
1427
    def is_compatible(source, target):
 
 
1428
        if source.supports_rich_root() != target.supports_rich_root():
 
 
1430
        if source._serializer != target._serializer:
 
 
1435
    def copy_content(self, revision_id=None):
 
 
1436
        """Make a complete copy of the content in self into destination.
 
 
1438
        This copies both the repository's revision data, and configuration information
 
 
1439
        such as the make_working_trees setting.
 
 
1441
        This is a destructive operation! Do not use it on existing 
 
 
1444
        :param revision_id: Only copy the content needed to construct
 
 
1445
                            revision_id and its parents.
 
 
1448
            self.target.set_make_working_trees(self.source.make_working_trees())
 
 
1449
        except NotImplementedError:
 
 
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)):
 
 
1458
        self.target.fetch(self.source, revision_id=revision_id)
 
 
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,
 
 
1473
        return f.count_copied, f.failed_revisions
 
 
1476
class InterWeaveRepo(InterSameDataRepository):
 
 
1477
    """Optimised code paths between Weave based repositories."""
 
 
1480
    def _get_repo_format_to_test(self):
 
 
1481
        from bzrlib.repofmt import weaverepo
 
 
1482
        return weaverepo.RepositoryFormat7()
 
 
1485
    def is_compatible(source, target):
 
 
1486
        """Be compatible with known Weave formats.
 
 
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 
 
 
1492
        from bzrlib.repofmt.weaverepo import (
 
 
1498
            return (isinstance(source._format, (RepositoryFormat5,
 
 
1500
                                                RepositoryFormat7)) and
 
 
1501
                    isinstance(target._format, (RepositoryFormat5,
 
 
1503
                                                RepositoryFormat7)))
 
 
1504
        except AttributeError:
 
 
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)
 
 
1514
            self.target.set_make_working_trees(self.source.make_working_trees())
 
 
1515
        except NotImplementedError:
 
 
1517
        # FIXME do not peek!
 
 
1518
        if self.source.control_files._transport.listable():
 
 
1519
            pb = ui.ui_factory.nested_progress_bar()
 
 
1521
                self.target.weave_store.copy_all_ids(
 
 
1522
                    self.source.weave_store,
 
 
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,
 
 
1537
            self.target.fetch(self.source, revision_id=revision_id)
 
 
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,
 
 
1551
        return f.count_copied, f.failed_revisions
 
 
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.
 
 
1567
        if revision_id is not None:
 
 
1568
            source_ids = self.source.get_ancestry(revision_id)
 
 
1569
            assert source_ids[0] is None
 
 
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
 
 
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)
 
 
1595
class InterKnitRepo(InterSameDataRepository):
 
 
1596
    """Optimised code paths between Knit based repositories."""
 
 
1599
    def _get_repo_format_to_test(self):
 
 
1600
        from bzrlib.repofmt import knitrepo
 
 
1601
        return knitrepo.RepositoryFormatKnit1()
 
 
1604
    def is_compatible(source, target):
 
 
1605
        """Be compatible with known Knit formats.
 
 
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 
 
 
1611
        from bzrlib.repofmt.knitrepo import RepositoryFormatKnit1
 
 
1613
            return (isinstance(source._format, (RepositoryFormatKnit1)) and
 
 
1614
                    isinstance(target._format, (RepositoryFormatKnit1)))
 
 
1615
        except AttributeError:
 
 
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,
 
 
1630
        return f.count_copied, f.failed_revisions
 
 
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
 
 
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
 
 
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)
 
 
1663
class InterModel1and2(InterRepository):
 
 
1666
    def _get_repo_format_to_test(self):
 
 
1670
    def is_compatible(source, target):
 
 
1671
        if not source.supports_rich_root() and target.supports_rich_root():
 
 
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,
 
 
1686
        return f.count_copied, f.failed_revisions
 
 
1689
    def copy_content(self, revision_id=None):
 
 
1690
        """Make a complete copy of the content in self into destination.
 
 
1692
        This is a destructive operation! Do not use it on existing 
 
 
1695
        :param revision_id: Only copy the content needed to construct
 
 
1696
                            revision_id and its parents.
 
 
1699
            self.target.set_make_working_trees(self.source.make_working_trees())
 
 
1700
        except NotImplementedError:
 
 
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)):
 
 
1708
        self.target.fetch(self.source, revision_id=revision_id)
 
 
1711
class InterKnit1and2(InterKnitRepo):
 
 
1714
    def _get_repo_format_to_test(self):
 
 
1718
    def is_compatible(source, target):
 
 
1719
        """Be compatible with Knit1 source and Knit3 target"""
 
 
1720
        from bzrlib.repofmt.knitrepo import RepositoryFormatKnit3
 
 
1722
            from bzrlib.repofmt.knitrepo import RepositoryFormatKnit1, \
 
 
1723
                    RepositoryFormatKnit3
 
 
1724
            return (isinstance(source._format, (RepositoryFormatKnit1)) and
 
 
1725
                    isinstance(target._format, (RepositoryFormatKnit3)))
 
 
1726
        except AttributeError:
 
 
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,
 
 
1742
        return f.count_copied, f.failed_revisions
 
 
1745
class InterRemoteRepository(InterRepository):
 
 
1746
    """Code for converting between RemoteRepository objects.
 
 
1748
    This just gets an non-remote repository from the RemoteRepository, and calls
 
 
1749
    InterRepository.get again.
 
 
1752
    def __init__(self, source, target):
 
 
1753
        if isinstance(source, remote.RemoteRepository):
 
 
1754
            source._ensure_real()
 
 
1755
            real_source = source._real_repository
 
 
1757
            real_source = source
 
 
1758
        if isinstance(target, remote.RemoteRepository):
 
 
1759
            target._ensure_real()
 
 
1760
            real_target = target._real_repository
 
 
1762
            real_target = target
 
 
1763
        self.real_inter = InterRepository.get(real_source, real_target)
 
 
1766
    def is_compatible(source, target):
 
 
1767
        if isinstance(source, remote.RemoteRepository):
 
 
1769
        if isinstance(target, remote.RemoteRepository):
 
 
1773
    def copy_content(self, revision_id=None):
 
 
1774
        self.real_inter.copy_content(revision_id=revision_id)
 
 
1776
    def fetch(self, revision_id=None, pb=None):
 
 
1777
        self.real_inter.fetch(revision_id=revision_id, pb=pb)
 
 
1780
    def _get_repo_format_to_test(self):
 
 
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)
 
 
1792
class CopyConverter(object):
 
 
1793
    """A repository conversion tool which just performs a copy of the content.
 
 
1795
    This is slow but quite reliable.
 
 
1798
    def __init__(self, target_format):
 
 
1799
        """Create a CopyConverter.
 
 
1801
        :param target_format: The format the resulting repository should be.
 
 
1803
        self.target_format = target_format
 
 
1805
    def convert(self, repo, pb):
 
 
1806
        """Perform the conversion of to_convert, giving feedback via pb.
 
 
1808
        :param to_convert: The disk object to convert.
 
 
1809
        :param pb: a progress bar to use for progress information.
 
 
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,
 
 
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()
 
 
1830
            self.step('Copying content into repository.')
 
 
1831
            self.source_repo.copy_content_into(converted)
 
 
1834
        self.step('Deleting old repository content.')
 
 
1835
        self.repo_dir.transport.delete_tree('repository.backup')
 
 
1836
        self.pb.note('repository converted')
 
 
1838
    def step(self, message):
 
 
1839
        """Update the pb by a step."""
 
 
1841
        self.pb.update(message, self.count, self.total)
 
 
1844
class CommitBuilder(object):
 
 
1845
    """Provides an interface to build up a commit.
 
 
1847
    This allows describing a tree to be committed without needing to 
 
 
1848
    know the internals of the format of the repository.
 
 
1851
    record_root_entry = False
 
 
1852
    def __init__(self, repository, parents, config, timestamp=None, 
 
 
1853
                 timezone=None, committer=None, revprops=None, 
 
 
1855
        """Initiate a CommitBuilder.
 
 
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.
 
 
1866
        self._config = config
 
 
1868
        if committer is None:
 
 
1869
            self._committer = self._config.username()
 
 
1871
            assert isinstance(committer, basestring), type(committer)
 
 
1872
            self._committer = committer
 
 
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
 
 
1880
        if revprops is not None:
 
 
1881
            self._revprops.update(revprops)
 
 
1883
        if timestamp is None:
 
 
1884
            timestamp = time.time()
 
 
1885
        # Restrict resolution to 1ms
 
 
1886
        self._timestamp = round(timestamp, 3)
 
 
1888
        if timezone is None:
 
 
1889
            self._timezone = osutils.local_time_offset()
 
 
1891
            self._timezone = int(timezone)
 
 
1893
        self._generate_revision_if_needed()
 
 
1895
    def commit(self, message):
 
 
1896
        """Make the actual commit.
 
 
1898
        :return: The revision id of the recorded revision.
 
 
1900
        rev = _mod_revision.Revision(
 
 
1901
                       timestamp=self._timestamp,
 
 
1902
                       timezone=self._timezone,
 
 
1903
                       committer=self._committer,
 
 
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
 
 
1913
    def revision_tree(self):
 
 
1914
        """Return the tree that was just committed.
 
 
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
 
 
1922
        return RevisionTree(self.repository, self.new_inventory,
 
 
1923
                            self._new_revision_id)
 
 
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,
 
 
1939
    def _gen_revision_id(self):
 
 
1940
        """Return new revision-id."""
 
 
1941
        return generate_ids.gen_revision_id(self._config.username(),
 
 
1944
    def _generate_revision_if_needed(self):
 
 
1945
        """Create a revision id if None was supplied.
 
 
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.
 
 
1951
        :raises: CannotSetRevisionId
 
 
1953
        if self._new_revision_id is None:
 
 
1954
            self._new_revision_id = self._gen_revision_id()
 
 
1956
    def record_entry_contents(self, ie, parent_invs, path, tree):
 
 
1957
        """Record the content of ie from tree into the commit if needed.
 
 
1959
        Side effect: sets ie.revision when unchanged
 
 
1961
        :param ie: An inventory entry present in the commit.
 
 
1962
        :param parent_invs: The inventories of the parent revisions of the
 
 
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 
 
 
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,
 
 
1974
        self.new_inventory.add(ie)
 
 
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:
 
 
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
 
 
1988
        previous_entries = ie.find_previous_heads(
 
 
1990
            self.repository.weave_store,
 
 
1991
            self.repository.get_transaction())
 
 
1992
        # we are creating a new revision for ie in the history store
 
 
1994
        ie.snapshot(self._new_revision_id, path, previous_entries, tree, self)
 
 
1996
    def modified_directory(self, file_id, file_parents):
 
 
1997
        """Record the presence of a symbolic link.
 
 
1999
        :param file_id: The file_id of the link to record.
 
 
2000
        :param file_parents: The per-file parent revision ids.
 
 
2002
        self._add_text_to_weave(file_id, [], file_parents.keys())
 
 
2004
    def modified_reference(self, file_id, file_parents):
 
 
2005
        """Record the modification of a reference.
 
 
2007
        :param file_id: The file_id of the link to record.
 
 
2008
        :param file_parents: The per-file parent revision ids.
 
 
2010
        self._add_text_to_weave(file_id, [], file_parents.keys())
 
 
2012
    def modified_file_text(self, file_id, file_parents,
 
 
2013
                           get_content_byte_lines, text_sha1=None,
 
 
2015
        """Record the text of file file_id
 
 
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
 
 
2021
        :param text_sha1: Optional SHA1 of the file contents.
 
 
2022
        :param text_size: Optional size of the file contents.
 
 
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 
 
 
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
 
 
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))
 
 
2045
    def modified_link(self, file_id, file_parents, link_target):
 
 
2046
        """Record the presence of a symbolic link.
 
 
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.
 
 
2052
        self._add_text_to_weave(file_id, [], file_parents.keys())
 
 
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()
 
 
2061
class _CommitBuilder(CommitBuilder):
 
 
2062
    """Temporary class so old CommitBuilders are detected properly
 
 
2064
    Note: CommitBuilder works whether or not root entry is recorded.
 
 
2067
    record_root_entry = True
 
 
2070
class RootCommitBuilder(CommitBuilder):
 
 
2071
    """This commitbuilder actually records the root id"""
 
 
2073
    record_root_entry = True
 
 
2075
    def record_entry_contents(self, ie, parent_invs, path, tree):
 
 
2076
        """Record the content of ie from tree into the commit if needed.
 
 
2078
        Side effect: sets ie.revision when unchanged
 
 
2080
        :param ie: An inventory entry present in the commit.
 
 
2081
        :param parent_invs: The inventories of the parent revisions of the
 
 
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 
 
 
2087
        assert self.new_inventory.root is not None or ie.parent_id is None
 
 
2088
        self.new_inventory.add(ie)
 
 
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:
 
 
2096
        previous_entries = ie.find_previous_heads(
 
 
2098
            self.repository.weave_store,
 
 
2099
            self.repository.get_transaction())
 
 
2100
        # we are creating a new revision for ie in the history store
 
 
2102
        ie.snapshot(self._new_revision_id, path, previous_entries, tree, self)
 
 
2114
def _unescaper(match, _map=_unescape_map):
 
 
2115
    code = match.group(1)
 
 
2119
        if not code.startswith('#'):
 
 
2121
        return unichr(int(code[1:])).encode('utf8')
 
 
2127
def _unescape_xml(data):
 
 
2128
    """Unescape predefined XML entities in a string of data."""
 
 
2130
    if _unescape_re is None:
 
 
2131
        _unescape_re = re.compile('\&([^;]*);')
 
 
2132
    return _unescape_re.sub(_unescaper, data)