/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/repository.py

  • Committer: Martin Pool
  • Date: 2007-02-12 06:35:46 UTC
  • mto: This revision was merged to the branch mainline in revision 2283.
  • Revision ID: mbp@sourcefrog.net-20070212063546-h2ku6z7fixzin6ur
doc

Show diffs side-by-side

added added

removed removed

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