~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/repository.py

  • Committer: Wouter van Heyst
  • Date: 2006-06-07 16:05:27 UTC
  • mto: This revision was merged to the branch mainline in revision 1752.
  • Revision ID: larstiq@larstiq.dyndns.org-20060607160527-2b3649154d0e2e84
more code cleanup

Show diffs side-by-side

added added

removed removed

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