/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to breezy/repository.py

  • Committer: Jelmer Vernooij
  • Date: 2019-08-12 20:24:50 UTC
  • mto: (7290.1.35 work)
  • mto: This revision was merged to the branch mainline in revision 7405.
  • Revision ID: jelmer@jelmer.uk-20190812202450-vdpamxay6sebo93w
Fix path to brz.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005-2011 Canonical Ltd
 
2
#
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
 
17
from __future__ import absolute_import
 
18
 
 
19
from .lazy_import import lazy_import
 
20
lazy_import(globals(), """
 
21
import time
 
22
 
 
23
from breezy import (
 
24
    config,
 
25
    controldir,
 
26
    debug,
 
27
    graph,
 
28
    osutils,
 
29
    revision as _mod_revision,
 
30
    gpg,
 
31
    )
 
32
from breezy.bundle import serializer
 
33
from breezy.i18n import gettext
 
34
""")
 
35
 
 
36
from . import (
 
37
    errors,
 
38
    registry,
 
39
    ui,
 
40
    )
 
41
from .decorators import only_raises
 
42
from .inter import InterObject
 
43
from .lock import _RelockDebugMixin, LogicalLockResult
 
44
from .sixish import (
 
45
    text_type,
 
46
    viewitems,
 
47
    )
 
48
from .trace import (
 
49
    log_exception_quietly, note, mutter, mutter_callsite, warning)
 
50
 
 
51
 
 
52
# Old formats display a warning, but only once
 
53
_deprecation_warning_done = False
 
54
 
 
55
 
 
56
class IsInWriteGroupError(errors.InternalBzrError):
 
57
 
 
58
    _fmt = "May not refresh_data of repo %(repo)s while in a write group."
 
59
 
 
60
    def __init__(self, repo):
 
61
        errors.InternalBzrError.__init__(self, repo=repo)
 
62
 
 
63
 
 
64
class CannotSetRevisionId(errors.BzrError):
 
65
 
 
66
    _fmt = "Repository format does not support setting revision ids."
 
67
 
 
68
 
 
69
class CommitBuilder(object):
 
70
    """Provides an interface to build up a commit.
 
71
 
 
72
    This allows describing a tree to be committed without needing to
 
73
    know the internals of the format of the repository.
 
74
    """
 
75
 
 
76
    # all clients should supply tree roots.
 
77
    record_root_entry = True
 
78
    # whether this commit builder will automatically update the branch that is
 
79
    # being committed to
 
80
    updates_branch = False
 
81
 
 
82
    def __init__(self, repository, parents, config_stack, timestamp=None,
 
83
                 timezone=None, committer=None, revprops=None,
 
84
                 revision_id=None, lossy=False):
 
85
        """Initiate a CommitBuilder.
 
86
 
 
87
        :param repository: Repository to commit to.
 
88
        :param parents: Revision ids of the parents of the new revision.
 
89
        :param timestamp: Optional timestamp recorded for commit.
 
90
        :param timezone: Optional timezone for timestamp.
 
91
        :param committer: Optional committer to set for commit.
 
92
        :param revprops: Optional dictionary of revision properties.
 
93
        :param revision_id: Optional revision id.
 
94
        :param lossy: Whether to discard data that can not be natively
 
95
            represented, when pushing to a foreign VCS
 
96
        """
 
97
        self._config_stack = config_stack
 
98
        self._lossy = lossy
 
99
 
 
100
        if committer is None:
 
101
            self._committer = self._config_stack.get('email')
 
102
        elif not isinstance(committer, text_type):
 
103
            self._committer = committer.decode()  # throw if non-ascii
 
104
        else:
 
105
            self._committer = committer
 
106
 
 
107
        self.parents = parents
 
108
        self.repository = repository
 
109
 
 
110
        self._revprops = {}
 
111
        if revprops is not None:
 
112
            self._validate_revprops(revprops)
 
113
            self._revprops.update(revprops)
 
114
 
 
115
        if timestamp is None:
 
116
            timestamp = time.time()
 
117
        # Restrict resolution to 1ms
 
118
        self._timestamp = round(timestamp, 3)
 
119
 
 
120
        if timezone is None:
 
121
            self._timezone = osutils.local_time_offset()
 
122
        else:
 
123
            self._timezone = int(timezone)
 
124
 
 
125
        self._generate_revision_if_needed(revision_id)
 
126
 
 
127
    def any_changes(self):
 
128
        """Return True if any entries were changed.
 
129
 
 
130
        This includes merge-only changes. It is the core for the --unchanged
 
131
        detection in commit.
 
132
 
 
133
        :return: True if any changes have occured.
 
134
        """
 
135
        raise NotImplementedError(self.any_changes)
 
136
 
 
137
    def _validate_unicode_text(self, text, context):
 
138
        """Verify things like commit messages don't have bogus characters."""
 
139
        # TODO(jelmer): Make this repository-format specific
 
140
        if u'\r' in text:
 
141
            raise ValueError('Invalid value for %s: %r' % (context, text))
 
142
 
 
143
    def _validate_revprops(self, revprops):
 
144
        for key, value in viewitems(revprops):
 
145
            # We know that the XML serializers do not round trip '\r'
 
146
            # correctly, so refuse to accept them
 
147
            if not isinstance(value, (text_type, str)):
 
148
                raise ValueError('revision property (%s) is not a valid'
 
149
                                 ' (unicode) string: %r' % (key, value))
 
150
            # TODO(jelmer): Make this repository-format specific
 
151
            self._validate_unicode_text(value,
 
152
                                        'revision property (%s)' % (key,))
 
153
 
 
154
    def commit(self, message):
 
155
        """Make the actual commit.
 
156
 
 
157
        :return: The revision id of the recorded revision.
 
158
        """
 
159
        raise NotImplementedError(self.commit)
 
160
 
 
161
    def abort(self):
 
162
        """Abort the commit that is being built.
 
163
        """
 
164
        raise NotImplementedError(self.abort)
 
165
 
 
166
    def revision_tree(self):
 
167
        """Return the tree that was just committed.
 
168
 
 
169
        After calling commit() this can be called to get a
 
170
        RevisionTree representing the newly committed tree. This is
 
171
        preferred to calling Repository.revision_tree() because that may
 
172
        require deserializing the inventory, while we already have a copy in
 
173
        memory.
 
174
        """
 
175
        raise NotImplementedError(self.revision_tree)
 
176
 
 
177
    def finish_inventory(self):
 
178
        """Tell the builder that the inventory is finished.
 
179
 
 
180
        :return: The inventory id in the repository, which can be used with
 
181
            repository.get_inventory.
 
182
        """
 
183
        raise NotImplementedError(self.finish_inventory)
 
184
 
 
185
    def _generate_revision_if_needed(self, revision_id):
 
186
        """Create a revision id if None was supplied.
 
187
 
 
188
        If the repository can not support user-specified revision ids
 
189
        they should override this function and raise CannotSetRevisionId
 
190
        if _new_revision_id is not None.
 
191
 
 
192
        :raises: CannotSetRevisionId
 
193
        """
 
194
        if not self.repository._format.supports_setting_revision_ids:
 
195
            if revision_id is not None:
 
196
                raise CannotSetRevisionId()
 
197
            return
 
198
        if revision_id is None:
 
199
            self._new_revision_id = self._gen_revision_id()
 
200
            self.random_revid = True
 
201
        else:
 
202
            self._new_revision_id = revision_id
 
203
            self.random_revid = False
 
204
 
 
205
    def record_iter_changes(self, tree, basis_revision_id, iter_changes):
 
206
        """Record a new tree via iter_changes.
 
207
 
 
208
        :param tree: The tree to obtain text contents from for changed objects.
 
209
        :param basis_revision_id: The revision id of the tree the iter_changes
 
210
            has been generated against. Currently assumed to be the same
 
211
            as self.parents[0] - if it is not, errors may occur.
 
212
        :param iter_changes: An iter_changes iterator with the changes to apply
 
213
            to basis_revision_id. The iterator must not include any items with
 
214
            a current kind of None - missing items must be either filtered out
 
215
            or errored-on beefore record_iter_changes sees the item.
 
216
        :return: A generator of (relpath, fs_hash) tuples for use with
 
217
            tree._observed_sha1.
 
218
        """
 
219
        raise NotImplementedError(self.record_iter_changes)
 
220
 
 
221
 
 
222
class RepositoryWriteLockResult(LogicalLockResult):
 
223
    """The result of write locking a repository.
 
224
 
 
225
    :ivar repository_token: The token obtained from the underlying lock, or
 
226
        None.
 
227
    :ivar unlock: A callable which will unlock the lock.
 
228
    """
 
229
 
 
230
    def __init__(self, unlock, repository_token):
 
231
        LogicalLockResult.__init__(self, unlock)
 
232
        self.repository_token = repository_token
 
233
 
 
234
    def __repr__(self):
 
235
        return "RepositoryWriteLockResult(%s, %s)" % (self.repository_token,
 
236
                                                      self.unlock)
 
237
 
 
238
 
 
239
######################################################################
 
240
# Repositories
 
241
 
 
242
 
 
243
class Repository(controldir.ControlComponent, _RelockDebugMixin):
 
244
    """Repository holding history for one or more branches.
 
245
 
 
246
    The repository holds and retrieves historical information including
 
247
    revisions and file history.  It's normally accessed only by the Branch,
 
248
    which views a particular line of development through that history.
 
249
 
 
250
    See VersionedFileRepository in breezy.vf_repository for the
 
251
    base class for most Bazaar repositories.
 
252
    """
 
253
 
 
254
    # Does this repository implementation support random access to
 
255
    # items in the tree, or just bulk fetching/pushing of data?
 
256
    supports_random_access = True
 
257
 
 
258
    def abort_write_group(self, suppress_errors=False):
 
259
        """Commit the contents accrued within the current write group.
 
260
 
 
261
        :param suppress_errors: if true, abort_write_group will catch and log
 
262
            unexpected errors that happen during the abort, rather than
 
263
            allowing them to propagate.  Defaults to False.
 
264
 
 
265
        :seealso: start_write_group.
 
266
        """
 
267
        if self._write_group is not self.get_transaction():
 
268
            # has an unlock or relock occured ?
 
269
            if suppress_errors:
 
270
                mutter(
 
271
                    '(suppressed) mismatched lock context and write group. %r, %r',
 
272
                    self._write_group, self.get_transaction())
 
273
                return
 
274
            raise errors.BzrError(
 
275
                'mismatched lock context and write group. %r, %r' %
 
276
                (self._write_group, self.get_transaction()))
 
277
        try:
 
278
            self._abort_write_group()
 
279
        except Exception as exc:
 
280
            self._write_group = None
 
281
            if not suppress_errors:
 
282
                raise
 
283
            mutter('abort_write_group failed')
 
284
            log_exception_quietly()
 
285
            note(gettext('brz: ERROR (ignored): %s'), exc)
 
286
        self._write_group = None
 
287
 
 
288
    def _abort_write_group(self):
 
289
        """Template method for per-repository write group cleanup.
 
290
 
 
291
        This is called during abort before the write group is considered to be
 
292
        finished and should cleanup any internal state accrued during the write
 
293
        group. There is no requirement that data handed to the repository be
 
294
        *not* made available - this is not a rollback - but neither should any
 
295
        attempt be made to ensure that data added is fully commited. Abort is
 
296
        invoked when an error has occured so futher disk or network operations
 
297
        may not be possible or may error and if possible should not be
 
298
        attempted.
 
299
        """
 
300
 
 
301
    def add_fallback_repository(self, repository):
 
302
        """Add a repository to use for looking up data not held locally.
 
303
 
 
304
        :param repository: A repository.
 
305
        """
 
306
        raise NotImplementedError(self.add_fallback_repository)
 
307
 
 
308
    def _check_fallback_repository(self, repository):
 
309
        """Check that this repository can fallback to repository safely.
 
310
 
 
311
        Raise an error if not.
 
312
 
 
313
        :param repository: A repository to fallback to.
 
314
        """
 
315
        return InterRepository._assert_same_model(self, repository)
 
316
 
 
317
    def all_revision_ids(self):
 
318
        """Returns a list of all the revision ids in the repository.
 
319
 
 
320
        This is conceptually deprecated because code should generally work on
 
321
        the graph reachable from a particular revision, and ignore any other
 
322
        revisions that might be present.  There is no direct replacement
 
323
        method.
 
324
        """
 
325
        if 'evil' in debug.debug_flags:
 
326
            mutter_callsite(2, "all_revision_ids is linear with history.")
 
327
        return self._all_revision_ids()
 
328
 
 
329
    def _all_revision_ids(self):
 
330
        """Returns a list of all the revision ids in the repository.
 
331
 
 
332
        These are in as much topological order as the underlying store can
 
333
        present.
 
334
        """
 
335
        raise NotImplementedError(self._all_revision_ids)
 
336
 
 
337
    def break_lock(self):
 
338
        """Break a lock if one is present from another instance.
 
339
 
 
340
        Uses the ui factory to ask for confirmation if the lock may be from
 
341
        an active process.
 
342
        """
 
343
        self.control_files.break_lock()
 
344
 
 
345
    @staticmethod
 
346
    def create(controldir):
 
347
        """Construct the current default format repository in controldir."""
 
348
        return RepositoryFormat.get_default_format().initialize(controldir)
 
349
 
 
350
    def __init__(self, _format, controldir, control_files):
 
351
        """instantiate a Repository.
 
352
 
 
353
        :param _format: The format of the repository on disk.
 
354
        :param controldir: The ControlDir of the repository.
 
355
        :param control_files: Control files to use for locking, etc.
 
356
        """
 
357
        # In the future we will have a single api for all stores for
 
358
        # getting file texts, inventories and revisions, then
 
359
        # this construct will accept instances of those things.
 
360
        super(Repository, self).__init__()
 
361
        self._format = _format
 
362
        # the following are part of the public API for Repository:
 
363
        self.controldir = controldir
 
364
        self.control_files = control_files
 
365
        # for tests
 
366
        self._write_group = None
 
367
        # Additional places to query for data.
 
368
        self._fallback_repositories = []
 
369
 
 
370
    @property
 
371
    def user_transport(self):
 
372
        return self.controldir.user_transport
 
373
 
 
374
    @property
 
375
    def control_transport(self):
 
376
        return self._transport
 
377
 
 
378
    def __repr__(self):
 
379
        if self._fallback_repositories:
 
380
            return '%s(%r, fallback_repositories=%r)' % (
 
381
                self.__class__.__name__,
 
382
                self.base,
 
383
                self._fallback_repositories)
 
384
        else:
 
385
            return '%s(%r)' % (self.__class__.__name__,
 
386
                               self.base)
 
387
 
 
388
    def _has_same_fallbacks(self, other_repo):
 
389
        """Returns true if the repositories have the same fallbacks."""
 
390
        my_fb = self._fallback_repositories
 
391
        other_fb = other_repo._fallback_repositories
 
392
        if len(my_fb) != len(other_fb):
 
393
            return False
 
394
        for f, g in zip(my_fb, other_fb):
 
395
            if not f.has_same_location(g):
 
396
                return False
 
397
        return True
 
398
 
 
399
    def has_same_location(self, other):
 
400
        """Returns a boolean indicating if this repository is at the same
 
401
        location as another repository.
 
402
 
 
403
        This might return False even when two repository objects are accessing
 
404
        the same physical repository via different URLs.
 
405
        """
 
406
        if self.__class__ is not other.__class__:
 
407
            return False
 
408
        return (self.control_url == other.control_url)
 
409
 
 
410
    def is_in_write_group(self):
 
411
        """Return True if there is an open write group.
 
412
 
 
413
        :seealso: start_write_group.
 
414
        """
 
415
        return self._write_group is not None
 
416
 
 
417
    def is_locked(self):
 
418
        return self.control_files.is_locked()
 
419
 
 
420
    def is_write_locked(self):
 
421
        """Return True if this object is write locked."""
 
422
        return self.is_locked() and self.control_files._lock_mode == 'w'
 
423
 
 
424
    def lock_write(self, token=None):
 
425
        """Lock this repository for writing.
 
426
 
 
427
        This causes caching within the repository obejct to start accumlating
 
428
        data during reads, and allows a 'write_group' to be obtained. Write
 
429
        groups must be used for actual data insertion.
 
430
 
 
431
        A token should be passed in if you know that you have locked the object
 
432
        some other way, and need to synchronise this object's state with that
 
433
        fact.
 
434
 
 
435
        XXX: this docstring is duplicated in many places, e.g. lockable_files.py
 
436
 
 
437
        :param token: if this is already locked, then lock_write will fail
 
438
            unless the token matches the existing lock.
 
439
        :returns: a token if this instance supports tokens, otherwise None.
 
440
        :raises TokenLockingNotSupported: when a token is given but this
 
441
            instance doesn't support using token locks.
 
442
        :raises MismatchedToken: if the specified token doesn't match the token
 
443
            of the existing lock.
 
444
        :seealso: start_write_group.
 
445
        :return: A RepositoryWriteLockResult.
 
446
        """
 
447
        locked = self.is_locked()
 
448
        token = self.control_files.lock_write(token=token)
 
449
        if not locked:
 
450
            self._warn_if_deprecated()
 
451
            self._note_lock('w')
 
452
            for repo in self._fallback_repositories:
 
453
                # Writes don't affect fallback repos
 
454
                repo.lock_read()
 
455
            self._refresh_data()
 
456
        return RepositoryWriteLockResult(self.unlock, token)
 
457
 
 
458
    def lock_read(self):
 
459
        """Lock the repository for read operations.
 
460
 
 
461
        :return: An object with an unlock method which will release the lock
 
462
            obtained.
 
463
        """
 
464
        locked = self.is_locked()
 
465
        self.control_files.lock_read()
 
466
        if not locked:
 
467
            self._warn_if_deprecated()
 
468
            self._note_lock('r')
 
469
            for repo in self._fallback_repositories:
 
470
                repo.lock_read()
 
471
            self._refresh_data()
 
472
        return LogicalLockResult(self.unlock)
 
473
 
 
474
    def get_physical_lock_status(self):
 
475
        return self.control_files.get_physical_lock_status()
 
476
 
 
477
    def leave_lock_in_place(self):
 
478
        """Tell this repository not to release the physical lock when this
 
479
        object is unlocked.
 
480
 
 
481
        If lock_write doesn't return a token, then this method is not supported.
 
482
        """
 
483
        self.control_files.leave_in_place()
 
484
 
 
485
    def dont_leave_lock_in_place(self):
 
486
        """Tell this repository to release the physical lock when this
 
487
        object is unlocked, even if it didn't originally acquire it.
 
488
 
 
489
        If lock_write doesn't return a token, then this method is not supported.
 
490
        """
 
491
        self.control_files.dont_leave_in_place()
 
492
 
 
493
    def gather_stats(self, revid=None, committers=None):
 
494
        """Gather statistics from a revision id.
 
495
 
 
496
        :param revid: The revision id to gather statistics from, if None, then
 
497
            no revision specific statistics are gathered.
 
498
        :param committers: Optional parameter controlling whether to grab
 
499
            a count of committers from the revision specific statistics.
 
500
        :return: A dictionary of statistics. Currently this contains:
 
501
            committers: The number of committers if requested.
 
502
            firstrev: A tuple with timestamp, timezone for the penultimate left
 
503
                most ancestor of revid, if revid is not the NULL_REVISION.
 
504
            latestrev: A tuple with timestamp, timezone for revid, if revid is
 
505
                not the NULL_REVISION.
 
506
            revisions: The total revision count in the repository.
 
507
            size: An estimate disk size of the repository in bytes.
 
508
        """
 
509
        with self.lock_read():
 
510
            result = {}
 
511
            if revid and committers:
 
512
                result['committers'] = 0
 
513
            if revid and revid != _mod_revision.NULL_REVISION:
 
514
                graph = self.get_graph()
 
515
                if committers:
 
516
                    all_committers = set()
 
517
                revisions = [r for (r, p) in graph.iter_ancestry([revid])
 
518
                             if r != _mod_revision.NULL_REVISION]
 
519
                last_revision = None
 
520
                if not committers:
 
521
                    # ignore the revisions in the middle - just grab first and last
 
522
                    revisions = revisions[0], revisions[-1]
 
523
                for revision in self.get_revisions(revisions):
 
524
                    if not last_revision:
 
525
                        last_revision = revision
 
526
                    if committers:
 
527
                        all_committers.add(revision.committer)
 
528
                first_revision = revision
 
529
                if committers:
 
530
                    result['committers'] = len(all_committers)
 
531
                result['firstrev'] = (first_revision.timestamp,
 
532
                                      first_revision.timezone)
 
533
                result['latestrev'] = (last_revision.timestamp,
 
534
                                       last_revision.timezone)
 
535
            return result
 
536
 
 
537
    def find_branches(self, using=False):
 
538
        """Find branches underneath this repository.
 
539
 
 
540
        This will include branches inside other branches.
 
541
 
 
542
        :param using: If True, list only branches using this repository.
 
543
        """
 
544
        if using and not self.is_shared():
 
545
            return self.controldir.list_branches()
 
546
 
 
547
        class Evaluator(object):
 
548
 
 
549
            def __init__(self):
 
550
                self.first_call = True
 
551
 
 
552
            def __call__(self, controldir):
 
553
                # On the first call, the parameter is always the controldir
 
554
                # containing the current repo.
 
555
                if not self.first_call:
 
556
                    try:
 
557
                        repository = controldir.open_repository()
 
558
                    except errors.NoRepositoryPresent:
 
559
                        pass
 
560
                    else:
 
561
                        return False, ([], repository)
 
562
                self.first_call = False
 
563
                value = (controldir.list_branches(), None)
 
564
                return True, value
 
565
 
 
566
        ret = []
 
567
        for branches, repository in controldir.ControlDir.find_controldirs(
 
568
                self.user_transport, evaluate=Evaluator()):
 
569
            if branches is not None:
 
570
                ret.extend(branches)
 
571
            if not using and repository is not None:
 
572
                ret.extend(repository.find_branches())
 
573
        return ret
 
574
 
 
575
    def search_missing_revision_ids(self, other,
 
576
                                    find_ghosts=True, revision_ids=None, if_present_ids=None,
 
577
                                    limit=None):
 
578
        """Return the revision ids that other has that this does not.
 
579
 
 
580
        These are returned in topological order.
 
581
 
 
582
        revision_ids: only return revision ids included by revision_id.
 
583
        """
 
584
        with self.lock_read():
 
585
            return InterRepository.get(other, self).search_missing_revision_ids(
 
586
                find_ghosts=find_ghosts, revision_ids=revision_ids,
 
587
                if_present_ids=if_present_ids, limit=limit)
 
588
 
 
589
    @staticmethod
 
590
    def open(base):
 
591
        """Open the repository rooted at base.
 
592
 
 
593
        For instance, if the repository is at URL/.bzr/repository,
 
594
        Repository.open(URL) -> a Repository instance.
 
595
        """
 
596
        control = controldir.ControlDir.open(base)
 
597
        return control.open_repository()
 
598
 
 
599
    def copy_content_into(self, destination, revision_id=None):
 
600
        """Make a complete copy of the content in self into destination.
 
601
 
 
602
        This is a destructive operation! Do not use it on existing
 
603
        repositories.
 
604
        """
 
605
        return InterRepository.get(self, destination).copy_content(revision_id)
 
606
 
 
607
    def commit_write_group(self):
 
608
        """Commit the contents accrued within the current write group.
 
609
 
 
610
        :seealso: start_write_group.
 
611
 
 
612
        :return: it may return an opaque hint that can be passed to 'pack'.
 
613
        """
 
614
        if self._write_group is not self.get_transaction():
 
615
            # has an unlock or relock occured ?
 
616
            raise errors.BzrError('mismatched lock context %r and '
 
617
                                  'write group %r.' %
 
618
                                  (self.get_transaction(), self._write_group))
 
619
        result = self._commit_write_group()
 
620
        self._write_group = None
 
621
        return result
 
622
 
 
623
    def _commit_write_group(self):
 
624
        """Template method for per-repository write group cleanup.
 
625
 
 
626
        This is called before the write group is considered to be
 
627
        finished and should ensure that all data handed to the repository
 
628
        for writing during the write group is safely committed (to the
 
629
        extent possible considering file system caching etc).
 
630
        """
 
631
 
 
632
    def suspend_write_group(self):
 
633
        """Suspend a write group.
 
634
 
 
635
        :raise UnsuspendableWriteGroup: If the write group can not be
 
636
            suspended.
 
637
        :return: List of tokens
 
638
        """
 
639
        raise errors.UnsuspendableWriteGroup(self)
 
640
 
 
641
    def refresh_data(self):
 
642
        """Re-read any data needed to synchronise with disk.
 
643
 
 
644
        This method is intended to be called after another repository instance
 
645
        (such as one used by a smart server) has inserted data into the
 
646
        repository. On all repositories this will work outside of write groups.
 
647
        Some repository formats (pack and newer for breezy native formats)
 
648
        support refresh_data inside write groups. If called inside a write
 
649
        group on a repository that does not support refreshing in a write group
 
650
        IsInWriteGroupError will be raised.
 
651
        """
 
652
        self._refresh_data()
 
653
 
 
654
    def resume_write_group(self, tokens):
 
655
        if not self.is_write_locked():
 
656
            raise errors.NotWriteLocked(self)
 
657
        if self._write_group:
 
658
            raise errors.BzrError('already in a write group')
 
659
        self._resume_write_group(tokens)
 
660
        # so we can detect unlock/relock - the write group is now entered.
 
661
        self._write_group = self.get_transaction()
 
662
 
 
663
    def _resume_write_group(self, tokens):
 
664
        raise errors.UnsuspendableWriteGroup(self)
 
665
 
 
666
    def fetch(self, source, revision_id=None, find_ghosts=False):
 
667
        """Fetch the content required to construct revision_id from source.
 
668
 
 
669
        If revision_id is None, then all content is copied.
 
670
 
 
671
        fetch() may not be used when the repository is in a write group -
 
672
        either finish the current write group before using fetch, or use
 
673
        fetch before starting the write group.
 
674
 
 
675
        :param find_ghosts: Find and copy revisions in the source that are
 
676
            ghosts in the target (and not reachable directly by walking out to
 
677
            the first-present revision in target from revision_id).
 
678
        :param revision_id: If specified, all the content needed for this
 
679
            revision ID will be copied to the target.  Fetch will determine for
 
680
            itself which content needs to be copied.
 
681
        """
 
682
        if self.is_in_write_group():
 
683
            raise errors.InternalBzrError(
 
684
                "May not fetch while in a write group.")
 
685
        # fast path same-url fetch operations
 
686
        # TODO: lift out to somewhere common with RemoteRepository
 
687
        # <https://bugs.launchpad.net/bzr/+bug/401646>
 
688
        if (self.has_same_location(source)
 
689
                and self._has_same_fallbacks(source)):
 
690
            # check that last_revision is in 'from' and then return a
 
691
            # no-operation.
 
692
            if (revision_id is not None and
 
693
                    not _mod_revision.is_null(revision_id)):
 
694
                self.get_revision(revision_id)
 
695
            return 0, []
 
696
        inter = InterRepository.get(source, self)
 
697
        return inter.fetch(revision_id=revision_id, find_ghosts=find_ghosts)
 
698
 
 
699
    def create_bundle(self, target, base, fileobj, format=None):
 
700
        return serializer.write_bundle(self, target, base, fileobj, format)
 
701
 
 
702
    def get_commit_builder(self, branch, parents, config_stack, timestamp=None,
 
703
                           timezone=None, committer=None, revprops=None,
 
704
                           revision_id=None, lossy=False):
 
705
        """Obtain a CommitBuilder for this repository.
 
706
 
 
707
        :param branch: Branch to commit to.
 
708
        :param parents: Revision ids of the parents of the new revision.
 
709
        :param config_stack: Configuration stack to use.
 
710
        :param timestamp: Optional timestamp recorded for commit.
 
711
        :param timezone: Optional timezone for timestamp.
 
712
        :param committer: Optional committer to set for commit.
 
713
        :param revprops: Optional dictionary of revision properties.
 
714
        :param revision_id: Optional revision id.
 
715
        :param lossy: Whether to discard data that can not be natively
 
716
            represented, when pushing to a foreign VCS
 
717
        """
 
718
        raise NotImplementedError(self.get_commit_builder)
 
719
 
 
720
    @only_raises(errors.LockNotHeld, errors.LockBroken)
 
721
    def unlock(self):
 
722
        if (self.control_files._lock_count == 1 and
 
723
                self.control_files._lock_mode == 'w'):
 
724
            if self._write_group is not None:
 
725
                self.abort_write_group()
 
726
                self.control_files.unlock()
 
727
                raise errors.BzrError(
 
728
                    'Must end write groups before releasing write locks.')
 
729
        self.control_files.unlock()
 
730
        if self.control_files._lock_count == 0:
 
731
            for repo in self._fallback_repositories:
 
732
                repo.unlock()
 
733
 
 
734
    def clone(self, controldir, revision_id=None):
 
735
        """Clone this repository into controldir using the current format.
 
736
 
 
737
        Currently no check is made that the format of this repository and
 
738
        the bzrdir format are compatible. FIXME RBC 20060201.
 
739
 
 
740
        :return: The newly created destination repository.
 
741
        """
 
742
        with self.lock_read():
 
743
            # TODO: deprecate after 0.16; cloning this with all its settings is
 
744
            # probably not very useful -- mbp 20070423
 
745
            dest_repo = self._create_sprouting_repo(
 
746
                controldir, shared=self.is_shared())
 
747
            self.copy_content_into(dest_repo, revision_id)
 
748
            return dest_repo
 
749
 
 
750
    def start_write_group(self):
 
751
        """Start a write group in the repository.
 
752
 
 
753
        Write groups are used by repositories which do not have a 1:1 mapping
 
754
        between file ids and backend store to manage the insertion of data from
 
755
        both fetch and commit operations.
 
756
 
 
757
        A write lock is required around the
 
758
        start_write_group/commit_write_group for the support of lock-requiring
 
759
        repository formats.
 
760
 
 
761
        One can only insert data into a repository inside a write group.
 
762
 
 
763
        :return: None.
 
764
        """
 
765
        if not self.is_write_locked():
 
766
            raise errors.NotWriteLocked(self)
 
767
        if self._write_group:
 
768
            raise errors.BzrError('already in a write group')
 
769
        self._start_write_group()
 
770
        # so we can detect unlock/relock - the write group is now entered.
 
771
        self._write_group = self.get_transaction()
 
772
 
 
773
    def _start_write_group(self):
 
774
        """Template method for per-repository write group startup.
 
775
 
 
776
        This is called before the write group is considered to be
 
777
        entered.
 
778
        """
 
779
 
 
780
    def sprout(self, to_bzrdir, revision_id=None):
 
781
        """Create a descendent repository for new development.
 
782
 
 
783
        Unlike clone, this does not copy the settings of the repository.
 
784
        """
 
785
        with self.lock_read():
 
786
            dest_repo = self._create_sprouting_repo(to_bzrdir, shared=False)
 
787
            dest_repo.fetch(self, revision_id=revision_id)
 
788
            return dest_repo
 
789
 
 
790
    def _create_sprouting_repo(self, a_controldir, shared):
 
791
        if not isinstance(
 
792
                a_controldir._format, self.controldir._format.__class__):
 
793
            # use target default format.
 
794
            dest_repo = a_controldir.create_repository()
 
795
        else:
 
796
            # Most control formats need the repository to be specifically
 
797
            # created, but on some old all-in-one formats it's not needed
 
798
            try:
 
799
                dest_repo = self._format.initialize(
 
800
                    a_controldir, shared=shared)
 
801
            except errors.UninitializableFormat:
 
802
                dest_repo = a_controldir.open_repository()
 
803
        return dest_repo
 
804
 
 
805
    def has_revision(self, revision_id):
 
806
        """True if this repository has a copy of the revision."""
 
807
        with self.lock_read():
 
808
            return revision_id in self.has_revisions((revision_id,))
 
809
 
 
810
    def has_revisions(self, revision_ids):
 
811
        """Probe to find out the presence of multiple revisions.
 
812
 
 
813
        :param revision_ids: An iterable of revision_ids.
 
814
        :return: A set of the revision_ids that were present.
 
815
        """
 
816
        raise NotImplementedError(self.has_revisions)
 
817
 
 
818
    def get_revision(self, revision_id):
 
819
        """Return the Revision object for a named revision."""
 
820
        with self.lock_read():
 
821
            return self.get_revisions([revision_id])[0]
 
822
 
 
823
    def get_revision_reconcile(self, revision_id):
 
824
        """'reconcile' helper routine that allows access to a revision always.
 
825
 
 
826
        This variant of get_revision does not cross check the weave graph
 
827
        against the revision one as get_revision does: but it should only
 
828
        be used by reconcile, or reconcile-alike commands that are correcting
 
829
        or testing the revision graph.
 
830
        """
 
831
        raise NotImplementedError(self.get_revision_reconcile)
 
832
 
 
833
    def get_revisions(self, revision_ids):
 
834
        """Get many revisions at once.
 
835
 
 
836
        Repositories that need to check data on every revision read should
 
837
        subclass this method.
 
838
        """
 
839
        revs = {}
 
840
        for revid, rev in self.iter_revisions(revision_ids):
 
841
            if rev is None:
 
842
                raise errors.NoSuchRevision(self, revid)
 
843
            revs[revid] = rev
 
844
        return [revs[revid] for revid in revision_ids]
 
845
 
 
846
    def iter_revisions(self, revision_ids):
 
847
        """Iterate over revision objects.
 
848
 
 
849
        :param revision_ids: An iterable of revisions to examine. None may be
 
850
            passed to request all revisions known to the repository. Note that
 
851
            not all repositories can find unreferenced revisions; for those
 
852
            repositories only referenced ones will be returned.
 
853
        :return: An iterator of (revid, revision) tuples. Absent revisions (
 
854
            those asked for but not available) are returned as (revid, None).
 
855
            N.B.: Revisions are not necessarily yielded in order.
 
856
        """
 
857
        raise NotImplementedError(self.iter_revisions)
 
858
 
 
859
    def get_deltas_for_revisions(self, revisions, specific_fileids=None):
 
860
        """Produce a generator of revision deltas.
 
861
 
 
862
        Note that the input is a sequence of REVISIONS, not revision_ids.
 
863
        Trees will be held in memory until the generator exits.
 
864
        Each delta is relative to the revision's lefthand predecessor.
 
865
 
 
866
        :param specific_fileids: if not None, the result is filtered
 
867
          so that only those file-ids, their parents and their
 
868
          children are included.
 
869
        """
 
870
        raise NotImplementedError(self.get_deltas_for_revisions)
 
871
 
 
872
    def get_revision_delta(self, revision_id, specific_fileids=None):
 
873
        """Return the delta for one revision.
 
874
 
 
875
        The delta is relative to the left-hand predecessor of the
 
876
        revision.
 
877
 
 
878
        :param specific_fileids: if not None, the result is filtered
 
879
          so that only those file-ids, their parents and their
 
880
          children are included.
 
881
        """
 
882
        with self.lock_read():
 
883
            r = self.get_revision(revision_id)
 
884
            return list(self.get_deltas_for_revisions(
 
885
                [r], specific_fileids=specific_fileids))[0]
 
886
 
 
887
    def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
 
888
        raise NotImplementedError(self.store_revision_signature)
 
889
 
 
890
    def add_signature_text(self, revision_id, signature):
 
891
        """Store a signature text for a revision.
 
892
 
 
893
        :param revision_id: Revision id of the revision
 
894
        :param signature: Signature text.
 
895
        """
 
896
        raise NotImplementedError(self.add_signature_text)
 
897
 
 
898
    def iter_files_bytes(self, desired_files):
 
899
        """Iterate through file versions.
 
900
 
 
901
        Files will not necessarily be returned in the order they occur in
 
902
        desired_files.  No specific order is guaranteed.
 
903
 
 
904
        Yields pairs of identifier, bytes_iterator.  identifier is an opaque
 
905
        value supplied by the caller as part of desired_files.  It should
 
906
        uniquely identify the file version in the caller's context.  (Examples:
 
907
        an index number or a TreeTransform trans_id.)
 
908
 
 
909
        :param desired_files: a list of (file_id, revision_id, identifier)
 
910
            triples
 
911
        """
 
912
        raise NotImplementedError(self.iter_files_bytes)
 
913
 
 
914
    def get_rev_id_for_revno(self, revno, known_pair):
 
915
        """Return the revision id of a revno, given a later (revno, revid)
 
916
        pair in the same history.
 
917
 
 
918
        :return: if found (True, revid).  If the available history ran out
 
919
            before reaching the revno, then this returns
 
920
            (False, (closest_revno, closest_revid)).
 
921
        """
 
922
        known_revno, known_revid = known_pair
 
923
        partial_history = [known_revid]
 
924
        distance_from_known = known_revno - revno
 
925
        if distance_from_known < 0:
 
926
            raise errors.RevnoOutOfBounds(revno, (0, known_revno))
 
927
        try:
 
928
            _iter_for_revno(
 
929
                self, partial_history, stop_index=distance_from_known)
 
930
        except errors.RevisionNotPresent as err:
 
931
            if err.revision_id == known_revid:
 
932
                # The start revision (known_revid) wasn't found.
 
933
                raise errors.NoSuchRevision(self, known_revid)
 
934
            # This is a stacked repository with no fallbacks, or a there's a
 
935
            # left-hand ghost.  Either way, even though the revision named in
 
936
            # the error isn't in this repo, we know it's the next step in this
 
937
            # left-hand history.
 
938
            partial_history.append(err.revision_id)
 
939
        if len(partial_history) <= distance_from_known:
 
940
            # Didn't find enough history to get a revid for the revno.
 
941
            earliest_revno = known_revno - len(partial_history) + 1
 
942
            return (False, (earliest_revno, partial_history[-1]))
 
943
        if len(partial_history) - 1 > distance_from_known:
 
944
            raise AssertionError('_iter_for_revno returned too much history')
 
945
        return (True, partial_history[-1])
 
946
 
 
947
    def is_shared(self):
 
948
        """Return True if this repository is flagged as a shared repository."""
 
949
        raise NotImplementedError(self.is_shared)
 
950
 
 
951
    def reconcile(self, other=None, thorough=False):
 
952
        """Reconcile this repository."""
 
953
        raise NotImplementedError(self.reconcile)
 
954
 
 
955
    def _refresh_data(self):
 
956
        """Helper called from lock_* to ensure coherency with disk.
 
957
 
 
958
        The default implementation does nothing; it is however possible
 
959
        for repositories to maintain loaded indices across multiple locks
 
960
        by checking inside their implementation of this method to see
 
961
        whether their indices are still valid. This depends of course on
 
962
        the disk format being validatable in this manner. This method is
 
963
        also called by the refresh_data() public interface to cause a refresh
 
964
        to occur while in a write lock so that data inserted by a smart server
 
965
        push operation is visible on the client's instance of the physical
 
966
        repository.
 
967
        """
 
968
 
 
969
    def revision_tree(self, revision_id):
 
970
        """Return Tree for a revision on this branch.
 
971
 
 
972
        `revision_id` may be NULL_REVISION for the empty tree revision.
 
973
        """
 
974
        raise NotImplementedError(self.revision_tree)
 
975
 
 
976
    def revision_trees(self, revision_ids):
 
977
        """Return Trees for revisions in this repository.
 
978
 
 
979
        :param revision_ids: a sequence of revision-ids;
 
980
          a revision-id may not be None or b'null:'
 
981
        """
 
982
        raise NotImplementedError(self.revision_trees)
 
983
 
 
984
    def pack(self, hint=None, clean_obsolete_packs=False):
 
985
        """Compress the data within the repository.
 
986
 
 
987
        This operation only makes sense for some repository types. For other
 
988
        types it should be a no-op that just returns.
 
989
 
 
990
        This stub method does not require a lock, but subclasses should use
 
991
        self.write_lock as this is a long running call it's reasonable to
 
992
        implicitly lock for the user.
 
993
 
 
994
        :param hint: If not supplied, the whole repository is packed.
 
995
            If supplied, the repository may use the hint parameter as a
 
996
            hint for the parts of the repository to pack. A hint can be
 
997
            obtained from the result of commit_write_group(). Out of
 
998
            date hints are simply ignored, because concurrent operations
 
999
            can obsolete them rapidly.
 
1000
 
 
1001
        :param clean_obsolete_packs: Clean obsolete packs immediately after
 
1002
            the pack operation.
 
1003
        """
 
1004
 
 
1005
    def get_transaction(self):
 
1006
        return self.control_files.get_transaction()
 
1007
 
 
1008
    def get_parent_map(self, revision_ids):
 
1009
        """See graph.StackedParentsProvider.get_parent_map"""
 
1010
        raise NotImplementedError(self.get_parent_map)
 
1011
 
 
1012
    def _get_parent_map_no_fallbacks(self, revision_ids):
 
1013
        """Same as Repository.get_parent_map except doesn't query fallbacks."""
 
1014
        # revisions index works in keys; this just works in revisions
 
1015
        # therefore wrap and unwrap
 
1016
        query_keys = []
 
1017
        result = {}
 
1018
        for revision_id in revision_ids:
 
1019
            if revision_id == _mod_revision.NULL_REVISION:
 
1020
                result[revision_id] = ()
 
1021
            elif revision_id is None:
 
1022
                raise ValueError('get_parent_map(None) is not valid')
 
1023
            else:
 
1024
                query_keys.append((revision_id,))
 
1025
        vf = self.revisions.without_fallbacks()
 
1026
        for (revision_id,), parent_keys in viewitems(
 
1027
                vf.get_parent_map(query_keys)):
 
1028
            if parent_keys:
 
1029
                result[revision_id] = tuple([parent_revid
 
1030
                                             for (parent_revid,) in parent_keys])
 
1031
            else:
 
1032
                result[revision_id] = (_mod_revision.NULL_REVISION,)
 
1033
        return result
 
1034
 
 
1035
    def _make_parents_provider(self):
 
1036
        if not self._format.supports_external_lookups:
 
1037
            return self
 
1038
        return graph.StackedParentsProvider(_LazyListJoin(
 
1039
            [self._make_parents_provider_unstacked()],
 
1040
            self._fallback_repositories))
 
1041
 
 
1042
    def _make_parents_provider_unstacked(self):
 
1043
        return graph.CallableToParentsProviderAdapter(
 
1044
            self._get_parent_map_no_fallbacks)
 
1045
 
 
1046
    def get_known_graph_ancestry(self, revision_ids):
 
1047
        """Return the known graph for a set of revision ids and their ancestors.
 
1048
        """
 
1049
        raise NotImplementedError(self.get_known_graph_ancestry)
 
1050
 
 
1051
    def get_file_graph(self):
 
1052
        """Return the graph walker for files."""
 
1053
        raise NotImplementedError(self.get_file_graph)
 
1054
 
 
1055
    def get_graph(self, other_repository=None):
 
1056
        """Return the graph walker for this repository format"""
 
1057
        parents_provider = self._make_parents_provider()
 
1058
        if (other_repository is not None and
 
1059
                not self.has_same_location(other_repository)):
 
1060
            parents_provider = graph.StackedParentsProvider(
 
1061
                [parents_provider, other_repository._make_parents_provider()])
 
1062
        return graph.Graph(parents_provider)
 
1063
 
 
1064
    def set_make_working_trees(self, new_value):
 
1065
        """Set the policy flag for making working trees when creating branches.
 
1066
 
 
1067
        This only applies to branches that use this repository.
 
1068
 
 
1069
        The default is 'True'.
 
1070
        :param new_value: True to restore the default, False to disable making
 
1071
                          working trees.
 
1072
        """
 
1073
        raise NotImplementedError(self.set_make_working_trees)
 
1074
 
 
1075
    def make_working_trees(self):
 
1076
        """Returns the policy for making working trees on new branches."""
 
1077
        raise NotImplementedError(self.make_working_trees)
 
1078
 
 
1079
    def sign_revision(self, revision_id, gpg_strategy):
 
1080
        raise NotImplementedError(self.sign_revision)
 
1081
 
 
1082
    def verify_revision_signature(self, revision_id, gpg_strategy):
 
1083
        """Verify the signature on a revision.
 
1084
 
 
1085
        :param revision_id: the revision to verify
 
1086
        :gpg_strategy: the GPGStrategy object to used
 
1087
 
 
1088
        :return: gpg.SIGNATURE_VALID or a failed SIGNATURE_ value
 
1089
        """
 
1090
        raise NotImplementedError(self.verify_revision_signature)
 
1091
 
 
1092
    def verify_revision_signatures(self, revision_ids, gpg_strategy):
 
1093
        """Verify revision signatures for a number of revisions.
 
1094
 
 
1095
        :param revision_id: the revision to verify
 
1096
        :gpg_strategy: the GPGStrategy object to used
 
1097
        :return: Iterator over tuples with revision id, result and keys
 
1098
        """
 
1099
        with self.lock_read():
 
1100
            for revid in revision_ids:
 
1101
                (result, key) = self.verify_revision_signature(revid, gpg_strategy)
 
1102
                yield revid, result, key
 
1103
 
 
1104
    def has_signature_for_revision_id(self, revision_id):
 
1105
        """Query for a revision signature for revision_id in the repository."""
 
1106
        raise NotImplementedError(self.has_signature_for_revision_id)
 
1107
 
 
1108
    def get_signature_text(self, revision_id):
 
1109
        """Return the text for a signature."""
 
1110
        raise NotImplementedError(self.get_signature_text)
 
1111
 
 
1112
    def check(self, revision_ids=None, callback_refs=None, check_repo=True):
 
1113
        """Check consistency of all history of given revision_ids.
 
1114
 
 
1115
        Different repository implementations should override _check().
 
1116
 
 
1117
        :param revision_ids: A non-empty list of revision_ids whose ancestry
 
1118
             will be checked.  Typically the last revision_id of a branch.
 
1119
        :param callback_refs: A dict of check-refs to resolve and callback
 
1120
            the check/_check method on the items listed as wanting the ref.
 
1121
            see breezy.check.
 
1122
        :param check_repo: If False do not check the repository contents, just
 
1123
            calculate the data callback_refs requires and call them back.
 
1124
        """
 
1125
        return self._check(revision_ids=revision_ids, callback_refs=callback_refs,
 
1126
                           check_repo=check_repo)
 
1127
 
 
1128
    def _check(self, revision_ids=None, callback_refs=None, check_repo=True):
 
1129
        raise NotImplementedError(self.check)
 
1130
 
 
1131
    def _warn_if_deprecated(self, branch=None):
 
1132
        if not self._format.is_deprecated():
 
1133
            return
 
1134
        global _deprecation_warning_done
 
1135
        if _deprecation_warning_done:
 
1136
            return
 
1137
        try:
 
1138
            if branch is None:
 
1139
                conf = config.GlobalStack()
 
1140
            else:
 
1141
                conf = branch.get_config_stack()
 
1142
            if 'format_deprecation' in conf.get('suppress_warnings'):
 
1143
                return
 
1144
            warning("Format %s for %s is deprecated -"
 
1145
                    " please use 'brz upgrade' to get better performance"
 
1146
                    % (self._format, self.controldir.transport.base))
 
1147
        finally:
 
1148
            _deprecation_warning_done = True
 
1149
 
 
1150
    def supports_rich_root(self):
 
1151
        return self._format.rich_root_data
 
1152
 
 
1153
    def _check_ascii_revisionid(self, revision_id, method):
 
1154
        """Private helper for ascii-only repositories."""
 
1155
        # weave repositories refuse to store revisionids that are non-ascii.
 
1156
        if revision_id is not None:
 
1157
            # weaves require ascii revision ids.
 
1158
            if isinstance(revision_id, text_type):
 
1159
                try:
 
1160
                    revision_id.encode('ascii')
 
1161
                except UnicodeEncodeError:
 
1162
                    raise errors.NonAsciiRevisionId(method, self)
 
1163
            else:
 
1164
                try:
 
1165
                    revision_id.decode('ascii')
 
1166
                except UnicodeDecodeError:
 
1167
                    raise errors.NonAsciiRevisionId(method, self)
 
1168
 
 
1169
 
 
1170
class RepositoryFormatRegistry(controldir.ControlComponentFormatRegistry):
 
1171
    """Repository format registry."""
 
1172
 
 
1173
    def get_default(self):
 
1174
        """Return the current default format."""
 
1175
        return controldir.format_registry.make_controldir('default').repository_format
 
1176
 
 
1177
 
 
1178
network_format_registry = registry.FormatRegistry()
 
1179
"""Registry of formats indexed by their network name.
 
1180
 
 
1181
The network name for a repository format is an identifier that can be used when
 
1182
referring to formats with smart server operations. See
 
1183
RepositoryFormat.network_name() for more detail.
 
1184
"""
 
1185
 
 
1186
 
 
1187
format_registry = RepositoryFormatRegistry(network_format_registry)
 
1188
"""Registry of formats, indexed by their BzrDirMetaFormat format string.
 
1189
 
 
1190
This can contain either format instances themselves, or classes/factories that
 
1191
can be called to obtain one.
 
1192
"""
 
1193
 
 
1194
 
 
1195
#####################################################################
 
1196
# Repository Formats
 
1197
 
 
1198
class RepositoryFormat(controldir.ControlComponentFormat):
 
1199
    """A repository format.
 
1200
 
 
1201
    Formats provide four things:
 
1202
     * An initialization routine to construct repository data on disk.
 
1203
     * a optional format string which is used when the BzrDir supports
 
1204
       versioned children.
 
1205
     * an open routine which returns a Repository instance.
 
1206
     * A network name for referring to the format in smart server RPC
 
1207
       methods.
 
1208
 
 
1209
    There is one and only one Format subclass for each on-disk format. But
 
1210
    there can be one Repository subclass that is used for several different
 
1211
    formats. The _format attribute on a Repository instance can be used to
 
1212
    determine the disk format.
 
1213
 
 
1214
    Formats are placed in a registry by their format string for reference
 
1215
    during opening. These should be subclasses of RepositoryFormat for
 
1216
    consistency.
 
1217
 
 
1218
    Once a format is deprecated, just deprecate the initialize and open
 
1219
    methods on the format class. Do not deprecate the object, as the
 
1220
    object may be created even when a repository instance hasn't been
 
1221
    created.
 
1222
 
 
1223
    Common instance attributes:
 
1224
    _matchingcontroldir - the controldir format that the repository format was
 
1225
    originally written to work with. This can be used if manually
 
1226
    constructing a bzrdir and repository, or more commonly for test suite
 
1227
    parameterization.
 
1228
    """
 
1229
 
 
1230
    # Set to True or False in derived classes. True indicates that the format
 
1231
    # supports ghosts gracefully.
 
1232
    supports_ghosts = None
 
1233
    # Can this repository be given external locations to lookup additional
 
1234
    # data. Set to True or False in derived classes.
 
1235
    supports_external_lookups = None
 
1236
    # Does this format support CHK bytestring lookups. Set to True or False in
 
1237
    # derived classes.
 
1238
    supports_chks = None
 
1239
    # Should fetch trigger a reconcile after the fetch? Only needed for
 
1240
    # some repository formats that can suffer internal inconsistencies.
 
1241
    _fetch_reconcile = False
 
1242
    # Does this format have < O(tree_size) delta generation. Used to hint what
 
1243
    # code path for commit, amongst other things.
 
1244
    fast_deltas = None
 
1245
    # Does doing a pack operation compress data? Useful for the pack UI command
 
1246
    # (so if there is one pack, the operation can still proceed because it may
 
1247
    # help), and for fetching when data won't have come from the same
 
1248
    # compressor.
 
1249
    pack_compresses = False
 
1250
    # Does the repository storage understand references to trees?
 
1251
    supports_tree_reference = None
 
1252
    # Is the format experimental ?
 
1253
    experimental = False
 
1254
    # Does this repository format escape funky characters, or does it create
 
1255
    # files with similar names as the versioned files in its contents on disk
 
1256
    # ?
 
1257
    supports_funky_characters = None
 
1258
    # Does this repository format support leaving locks?
 
1259
    supports_leaving_lock = None
 
1260
    # Does this format support the full VersionedFiles interface?
 
1261
    supports_full_versioned_files = None
 
1262
    # Does this format support signing revision signatures?
 
1263
    supports_revision_signatures = True
 
1264
    # Can the revision graph have incorrect parents?
 
1265
    revision_graph_can_have_wrong_parents = None
 
1266
    # Does this format support setting revision ids?
 
1267
    supports_setting_revision_ids = True
 
1268
    # Does this format support rich root data?
 
1269
    rich_root_data = None
 
1270
    # Does this format support explicitly versioned directories?
 
1271
    supports_versioned_directories = None
 
1272
    # Can other repositories be nested into one of this format?
 
1273
    supports_nesting_repositories = None
 
1274
    # Is it possible for revisions to be present without being referenced
 
1275
    # somewhere ?
 
1276
    supports_unreferenced_revisions = None
 
1277
    # Does this format store the current Branch.nick in a revision when
 
1278
    # creating commits?
 
1279
    supports_storing_branch_nick = True
 
1280
    # Does the format support overriding the transport to use
 
1281
    supports_overriding_transport = True
 
1282
    # Does the format support setting custom revision properties?
 
1283
    supports_custom_revision_properties = True
 
1284
    # Does the format record per-file revision metadata?
 
1285
    records_per_file_revision = True
 
1286
 
 
1287
    def __repr__(self):
 
1288
        return "%s()" % self.__class__.__name__
 
1289
 
 
1290
    def __eq__(self, other):
 
1291
        # format objects are generally stateless
 
1292
        return isinstance(other, self.__class__)
 
1293
 
 
1294
    def __ne__(self, other):
 
1295
        return not self == other
 
1296
 
 
1297
    def get_format_description(self):
 
1298
        """Return the short description for this format."""
 
1299
        raise NotImplementedError(self.get_format_description)
 
1300
 
 
1301
    def initialize(self, controldir, shared=False):
 
1302
        """Initialize a repository of this format in controldir.
 
1303
 
 
1304
        :param controldir: The controldir to put the new repository in it.
 
1305
        :param shared: The repository should be initialized as a sharable one.
 
1306
        :returns: The new repository object.
 
1307
 
 
1308
        This may raise UninitializableFormat if shared repository are not
 
1309
        compatible the controldir.
 
1310
        """
 
1311
        raise NotImplementedError(self.initialize)
 
1312
 
 
1313
    def is_supported(self):
 
1314
        """Is this format supported?
 
1315
 
 
1316
        Supported formats must be initializable and openable.
 
1317
        Unsupported formats may not support initialization or committing or
 
1318
        some other features depending on the reason for not being supported.
 
1319
        """
 
1320
        return True
 
1321
 
 
1322
    def is_deprecated(self):
 
1323
        """Is this format deprecated?
 
1324
 
 
1325
        Deprecated formats may trigger a user-visible warning recommending
 
1326
        the user to upgrade. They are still fully supported.
 
1327
        """
 
1328
        return False
 
1329
 
 
1330
    def network_name(self):
 
1331
        """A simple byte string uniquely identifying this format for RPC calls.
 
1332
 
 
1333
        MetaDir repository formats use their disk format string to identify the
 
1334
        repository over the wire. All in one formats such as bzr < 0.8, and
 
1335
        foreign formats like svn/git and hg should use some marker which is
 
1336
        unique and immutable.
 
1337
        """
 
1338
        raise NotImplementedError(self.network_name)
 
1339
 
 
1340
    def check_conversion_target(self, target_format):
 
1341
        if self.rich_root_data and not target_format.rich_root_data:
 
1342
            raise errors.BadConversionTarget(
 
1343
                'Does not support rich root data.', target_format,
 
1344
                from_format=self)
 
1345
        if (self.supports_tree_reference
 
1346
                and not getattr(target_format, 'supports_tree_reference', False)):
 
1347
            raise errors.BadConversionTarget(
 
1348
                'Does not support nested trees', target_format,
 
1349
                from_format=self)
 
1350
 
 
1351
    def open(self, controldir, _found=False):
 
1352
        """Return an instance of this format for a controldir.
 
1353
 
 
1354
        _found is a private parameter, do not use it.
 
1355
        """
 
1356
        raise NotImplementedError(self.open)
 
1357
 
 
1358
    def _run_post_repo_init_hooks(self, repository, controldir, shared):
 
1359
        from .controldir import ControlDir, RepoInitHookParams
 
1360
        hooks = ControlDir.hooks['post_repo_init']
 
1361
        if not hooks:
 
1362
            return
 
1363
        params = RepoInitHookParams(repository, self, controldir, shared)
 
1364
        for hook in hooks:
 
1365
            hook(params)
 
1366
 
 
1367
 
 
1368
# formats which have no format string are not discoverable or independently
 
1369
# creatable on disk, so are not registered in format_registry.  They're
 
1370
# all in breezy.bzr.knitreponow.  When an instance of one of these is
 
1371
# needed, it's constructed directly by the ControlDir.  Non-native formats where
 
1372
# the repository is not separately opened are similar.
 
1373
 
 
1374
format_registry.register_lazy(
 
1375
    b'Bazaar-NG Knit Repository Format 1',
 
1376
    'breezy.bzr.knitrepo',
 
1377
    'RepositoryFormatKnit1',
 
1378
    )
 
1379
 
 
1380
format_registry.register_lazy(
 
1381
    b'Bazaar Knit Repository Format 3 (bzr 0.15)\n',
 
1382
    'breezy.bzr.knitrepo',
 
1383
    'RepositoryFormatKnit3',
 
1384
    )
 
1385
 
 
1386
format_registry.register_lazy(
 
1387
    b'Bazaar Knit Repository Format 4 (bzr 1.0)\n',
 
1388
    'breezy.bzr.knitrepo',
 
1389
    'RepositoryFormatKnit4',
 
1390
    )
 
1391
 
 
1392
# Pack-based formats. There is one format for pre-subtrees, and one for
 
1393
# post-subtrees to allow ease of testing.
 
1394
# NOTE: These are experimental in 0.92. Stable in 1.0 and above
 
1395
format_registry.register_lazy(
 
1396
    b'Bazaar pack repository format 1 (needs bzr 0.92)\n',
 
1397
    'breezy.bzr.knitpack_repo',
 
1398
    'RepositoryFormatKnitPack1',
 
1399
    )
 
1400
format_registry.register_lazy(
 
1401
    b'Bazaar pack repository format 1 with subtree support (needs bzr 0.92)\n',
 
1402
    'breezy.bzr.knitpack_repo',
 
1403
    'RepositoryFormatKnitPack3',
 
1404
    )
 
1405
format_registry.register_lazy(
 
1406
    b'Bazaar pack repository format 1 with rich root (needs bzr 1.0)\n',
 
1407
    'breezy.bzr.knitpack_repo',
 
1408
    'RepositoryFormatKnitPack4',
 
1409
    )
 
1410
format_registry.register_lazy(
 
1411
    b'Bazaar RepositoryFormatKnitPack5 (bzr 1.6)\n',
 
1412
    'breezy.bzr.knitpack_repo',
 
1413
    'RepositoryFormatKnitPack5',
 
1414
    )
 
1415
format_registry.register_lazy(
 
1416
    b'Bazaar RepositoryFormatKnitPack5RichRoot (bzr 1.6.1)\n',
 
1417
    'breezy.bzr.knitpack_repo',
 
1418
    'RepositoryFormatKnitPack5RichRoot',
 
1419
    )
 
1420
format_registry.register_lazy(
 
1421
    b'Bazaar RepositoryFormatKnitPack5RichRoot (bzr 1.6)\n',
 
1422
    'breezy.bzr.knitpack_repo',
 
1423
    'RepositoryFormatKnitPack5RichRootBroken',
 
1424
    )
 
1425
format_registry.register_lazy(
 
1426
    b'Bazaar RepositoryFormatKnitPack6 (bzr 1.9)\n',
 
1427
    'breezy.bzr.knitpack_repo',
 
1428
    'RepositoryFormatKnitPack6',
 
1429
    )
 
1430
format_registry.register_lazy(
 
1431
    b'Bazaar RepositoryFormatKnitPack6RichRoot (bzr 1.9)\n',
 
1432
    'breezy.bzr.knitpack_repo',
 
1433
    'RepositoryFormatKnitPack6RichRoot',
 
1434
    )
 
1435
format_registry.register_lazy(
 
1436
    b'Bazaar repository format 2a (needs bzr 1.16 or later)\n',
 
1437
    'breezy.bzr.groupcompress_repo',
 
1438
    'RepositoryFormat2a',
 
1439
    )
 
1440
 
 
1441
# Development formats.
 
1442
# Check their docstrings to see if/when they are obsolete.
 
1443
format_registry.register_lazy(
 
1444
    (b"Bazaar development format 2 with subtree support "
 
1445
        b"(needs bzr.dev from before 1.8)\n"),
 
1446
    'breezy.bzr.knitpack_repo',
 
1447
    'RepositoryFormatPackDevelopment2Subtree',
 
1448
    )
 
1449
format_registry.register_lazy(
 
1450
    b'Bazaar development format 8\n',
 
1451
    'breezy.bzr.groupcompress_repo',
 
1452
    'RepositoryFormat2aSubtree',
 
1453
    )
 
1454
 
 
1455
 
 
1456
class InterRepository(InterObject):
 
1457
    """This class represents operations taking place between two repositories.
 
1458
 
 
1459
    Its instances have methods like copy_content and fetch, and contain
 
1460
    references to the source and target repositories these operations can be
 
1461
    carried out on.
 
1462
 
 
1463
    Often we will provide convenience methods on 'repository' which carry out
 
1464
    operations with another repository - they will always forward to
 
1465
    InterRepository.get(other).method_name(parameters).
 
1466
    """
 
1467
 
 
1468
    _optimisers = []
 
1469
    """The available optimised InterRepository types."""
 
1470
 
 
1471
    def copy_content(self, revision_id=None):
 
1472
        """Make a complete copy of the content in self into destination.
 
1473
 
 
1474
        This is a destructive operation! Do not use it on existing
 
1475
        repositories.
 
1476
 
 
1477
        :param revision_id: Only copy the content needed to construct
 
1478
                            revision_id and its parents.
 
1479
        """
 
1480
        with self.lock_write():
 
1481
            try:
 
1482
                self.target.set_make_working_trees(
 
1483
                    self.source.make_working_trees())
 
1484
            except NotImplementedError:
 
1485
                pass
 
1486
            self.target.fetch(self.source, revision_id=revision_id)
 
1487
 
 
1488
    def fetch(self, revision_id=None, find_ghosts=False):
 
1489
        """Fetch the content required to construct revision_id.
 
1490
 
 
1491
        The content is copied from self.source to self.target.
 
1492
 
 
1493
        :param revision_id: if None all content is copied, if NULL_REVISION no
 
1494
                            content is copied.
 
1495
        :return: None.
 
1496
        """
 
1497
        raise NotImplementedError(self.fetch)
 
1498
 
 
1499
    def search_missing_revision_ids(
 
1500
            self, find_ghosts=True, revision_ids=None, if_present_ids=None,
 
1501
            limit=None):
 
1502
        """Return the revision ids that source has that target does not.
 
1503
 
 
1504
        :param revision_ids: return revision ids included by these
 
1505
            revision_ids.  NoSuchRevision will be raised if any of these
 
1506
            revisions are not present.
 
1507
        :param if_present_ids: like revision_ids, but will not cause
 
1508
            NoSuchRevision if any of these are absent, instead they will simply
 
1509
            not be in the result.  This is useful for e.g. finding revisions
 
1510
            to fetch for tags, which may reference absent revisions.
 
1511
        :param find_ghosts: If True find missing revisions in deep history
 
1512
            rather than just finding the surface difference.
 
1513
        :param limit: Maximum number of revisions to return, topologically
 
1514
            ordered
 
1515
        :return: A breezy.graph.SearchResult.
 
1516
        """
 
1517
        raise NotImplementedError(self.search_missing_revision_ids)
 
1518
 
 
1519
    @staticmethod
 
1520
    def _same_model(source, target):
 
1521
        """True if source and target have the same data representation.
 
1522
 
 
1523
        Note: this is always called on the base class; overriding it in a
 
1524
        subclass will have no effect.
 
1525
        """
 
1526
        try:
 
1527
            InterRepository._assert_same_model(source, target)
 
1528
            return True
 
1529
        except errors.IncompatibleRepositories as e:
 
1530
            return False
 
1531
 
 
1532
    @staticmethod
 
1533
    def _assert_same_model(source, target):
 
1534
        """Raise an exception if two repositories do not use the same model.
 
1535
        """
 
1536
        if source.supports_rich_root() != target.supports_rich_root():
 
1537
            raise errors.IncompatibleRepositories(source, target,
 
1538
                                                  "different rich-root support")
 
1539
        if source._serializer != target._serializer:
 
1540
            raise errors.IncompatibleRepositories(source, target,
 
1541
                                                  "different serializers")
 
1542
 
 
1543
 
 
1544
class CopyConverter(object):
 
1545
    """A repository conversion tool which just performs a copy of the content.
 
1546
 
 
1547
    This is slow but quite reliable.
 
1548
    """
 
1549
 
 
1550
    def __init__(self, target_format):
 
1551
        """Create a CopyConverter.
 
1552
 
 
1553
        :param target_format: The format the resulting repository should be.
 
1554
        """
 
1555
        self.target_format = target_format
 
1556
 
 
1557
    def convert(self, repo, pb):
 
1558
        """Perform the conversion of to_convert, giving feedback via pb.
 
1559
 
 
1560
        :param to_convert: The disk object to convert.
 
1561
        :param pb: a progress bar to use for progress information.
 
1562
        """
 
1563
        with ui.ui_factory.nested_progress_bar() as pb:
 
1564
            self.count = 0
 
1565
            self.total = 4
 
1566
            # this is only useful with metadir layouts - separated repo content.
 
1567
            # trigger an assertion if not such
 
1568
            repo._format.get_format_string()
 
1569
            self.repo_dir = repo.controldir
 
1570
            pb.update(gettext('Moving repository to repository.backup'))
 
1571
            self.repo_dir.transport.move('repository', 'repository.backup')
 
1572
            backup_transport = self.repo_dir.transport.clone(
 
1573
                'repository.backup')
 
1574
            repo._format.check_conversion_target(self.target_format)
 
1575
            self.source_repo = repo._format.open(self.repo_dir,
 
1576
                                                 _found=True,
 
1577
                                                 _override_transport=backup_transport)
 
1578
            pb.update(gettext('Creating new repository'))
 
1579
            converted = self.target_format.initialize(self.repo_dir,
 
1580
                                                      self.source_repo.is_shared())
 
1581
            converted.lock_write()
 
1582
            try:
 
1583
                pb.update(gettext('Copying content'))
 
1584
                self.source_repo.copy_content_into(converted)
 
1585
            finally:
 
1586
                converted.unlock()
 
1587
            pb.update(gettext('Deleting old repository content'))
 
1588
            self.repo_dir.transport.delete_tree('repository.backup')
 
1589
            ui.ui_factory.note(gettext('repository converted'))
 
1590
 
 
1591
 
 
1592
def _strip_NULL_ghosts(revision_graph):
 
1593
    """Also don't use this. more compatibility code for unmigrated clients."""
 
1594
    # Filter ghosts, and null:
 
1595
    if _mod_revision.NULL_REVISION in revision_graph:
 
1596
        del revision_graph[_mod_revision.NULL_REVISION]
 
1597
    for key, parents in viewitems(revision_graph):
 
1598
        revision_graph[key] = tuple(parent for parent in parents if parent
 
1599
                                    in revision_graph)
 
1600
    return revision_graph
 
1601
 
 
1602
 
 
1603
def _iter_for_revno(repo, partial_history_cache, stop_index=None,
 
1604
                    stop_revision=None):
 
1605
    """Extend the partial history to include a given index
 
1606
 
 
1607
    If a stop_index is supplied, stop when that index has been reached.
 
1608
    If a stop_revision is supplied, stop when that revision is
 
1609
    encountered.  Otherwise, stop when the beginning of history is
 
1610
    reached.
 
1611
 
 
1612
    :param stop_index: The index which should be present.  When it is
 
1613
        present, history extension will stop.
 
1614
    :param stop_revision: The revision id which should be present.  When
 
1615
        it is encountered, history extension will stop.
 
1616
    """
 
1617
    start_revision = partial_history_cache[-1]
 
1618
    graph = repo.get_graph()
 
1619
    iterator = graph.iter_lefthand_ancestry(start_revision,
 
1620
                                            (_mod_revision.NULL_REVISION,))
 
1621
    try:
 
1622
        # skip the last revision in the list
 
1623
        next(iterator)
 
1624
        while True:
 
1625
            if (stop_index is not None and
 
1626
                    len(partial_history_cache) > stop_index):
 
1627
                break
 
1628
            if partial_history_cache[-1] == stop_revision:
 
1629
                break
 
1630
            revision_id = next(iterator)
 
1631
            partial_history_cache.append(revision_id)
 
1632
    except StopIteration:
 
1633
        # No more history
 
1634
        return
 
1635
 
 
1636
 
 
1637
class _LazyListJoin(object):
 
1638
    """An iterable yielding the contents of many lists as one list.
 
1639
 
 
1640
    Each iterator made from this will reflect the current contents of the lists
 
1641
    at the time the iterator is made.
 
1642
 
 
1643
    This is used by Repository's _make_parents_provider implementation so that
 
1644
    it is safe to do::
 
1645
 
 
1646
      pp = repo._make_parents_provider()      # uses a list of fallback repos
 
1647
      pp.add_fallback_repository(other_repo)  # appends to that list
 
1648
      result = pp.get_parent_map(...)
 
1649
      # The result will include revs from other_repo
 
1650
    """
 
1651
 
 
1652
    def __init__(self, *list_parts):
 
1653
        self.list_parts = list_parts
 
1654
 
 
1655
    def __iter__(self):
 
1656
        full_list = []
 
1657
        for list_part in self.list_parts:
 
1658
            full_list.extend(list_part)
 
1659
        return iter(full_list)
 
1660
 
 
1661
    def __repr__(self):
 
1662
        return "%s.%s(%s)" % (self.__module__, self.__class__.__name__,
 
1663
                              self.list_parts)