/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Jelmer Vernooij
  • Date: 2009-02-25 02:05:35 UTC
  • mto: This revision was merged to the branch mainline in revision 4053.
  • Revision ID: jelmer@samba.org-20090225020535-qw7udfz9ploqzosn
Add tests for InterBranch.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005, 2006, 2007, 2008 Canonical Ltd
 
2
#
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
 
 
17
 
 
18
import sys
 
19
 
 
20
from bzrlib.lazy_import import lazy_import
 
21
lazy_import(globals(), """
 
22
from itertools import chain
 
23
from bzrlib import (
 
24
        bzrdir,
 
25
        cache_utf8,
 
26
        config as _mod_config,
 
27
        debug,
 
28
        errors,
 
29
        lockdir,
 
30
        lockable_files,
 
31
        repository,
 
32
        revision as _mod_revision,
 
33
        transport,
 
34
        tsort,
 
35
        ui,
 
36
        urlutils,
 
37
        )
 
38
from bzrlib.config import BranchConfig
 
39
from bzrlib.repofmt.pack_repo import RepositoryFormatKnitPack5RichRoot
 
40
from bzrlib.tag import (
 
41
    BasicTags,
 
42
    DisabledTags,
 
43
    )
 
44
""")
 
45
 
 
46
from bzrlib.decorators import needs_read_lock, needs_write_lock
 
47
from bzrlib.hooks import Hooks
 
48
from bzrlib.inter import InterObject
 
49
from bzrlib.symbol_versioning import (
 
50
    deprecated_in,
 
51
    deprecated_method,
 
52
    )
 
53
from bzrlib.trace import mutter, mutter_callsite, note, is_quiet
 
54
 
 
55
 
 
56
BZR_BRANCH_FORMAT_4 = "Bazaar-NG branch, format 0.0.4\n"
 
57
BZR_BRANCH_FORMAT_5 = "Bazaar-NG branch, format 5\n"
 
58
BZR_BRANCH_FORMAT_6 = "Bazaar Branch Format 6 (bzr 0.15)\n"
 
59
 
 
60
 
 
61
# TODO: Maybe include checks for common corruption of newlines, etc?
 
62
 
 
63
# TODO: Some operations like log might retrieve the same revisions
 
64
# repeatedly to calculate deltas.  We could perhaps have a weakref
 
65
# cache in memory to make this faster.  In general anything can be
 
66
# cached in memory between lock and unlock operations. .. nb thats
 
67
# what the transaction identity map provides
 
68
 
 
69
 
 
70
######################################################################
 
71
# branch objects
 
72
 
 
73
class Branch(object):
 
74
    """Branch holding a history of revisions.
 
75
 
 
76
    base
 
77
        Base directory/url of the branch.
 
78
 
 
79
    hooks: An instance of BranchHooks.
 
80
    """
 
81
    # this is really an instance variable - FIXME move it there
 
82
    # - RBC 20060112
 
83
    base = None
 
84
 
 
85
    # override this to set the strategy for storing tags
 
86
    def _make_tags(self):
 
87
        return DisabledTags(self)
 
88
 
 
89
    def __init__(self, *ignored, **ignored_too):
 
90
        self.tags = self._make_tags()
 
91
        self._revision_history_cache = None
 
92
        self._revision_id_to_revno_cache = None
 
93
        self._partial_revision_id_to_revno_cache = {}
 
94
        self._last_revision_info_cache = None
 
95
        self._merge_sorted_revisions_cache = None
 
96
        self._open_hook()
 
97
        hooks = Branch.hooks['open']
 
98
        for hook in hooks:
 
99
            hook(self)
 
100
 
 
101
    def _open_hook(self):
 
102
        """Called by init to allow simpler extension of the base class."""
 
103
 
 
104
    def break_lock(self):
 
105
        """Break a lock if one is present from another instance.
 
106
 
 
107
        Uses the ui factory to ask for confirmation if the lock may be from
 
108
        an active process.
 
109
 
 
110
        This will probe the repository for its lock as well.
 
111
        """
 
112
        self.control_files.break_lock()
 
113
        self.repository.break_lock()
 
114
        master = self.get_master_branch()
 
115
        if master is not None:
 
116
            master.break_lock()
 
117
 
 
118
    @staticmethod
 
119
    def open(base, _unsupported=False, possible_transports=None):
 
120
        """Open the branch rooted at base.
 
121
 
 
122
        For instance, if the branch is at URL/.bzr/branch,
 
123
        Branch.open(URL) -> a Branch instance.
 
124
        """
 
125
        control = bzrdir.BzrDir.open(base, _unsupported,
 
126
                                     possible_transports=possible_transports)
 
127
        return control.open_branch(_unsupported)
 
128
 
 
129
    @staticmethod
 
130
    def open_from_transport(transport, _unsupported=False):
 
131
        """Open the branch rooted at transport"""
 
132
        control = bzrdir.BzrDir.open_from_transport(transport, _unsupported)
 
133
        return control.open_branch(_unsupported)
 
134
 
 
135
    @staticmethod
 
136
    def open_containing(url, possible_transports=None):
 
137
        """Open an existing branch which contains url.
 
138
 
 
139
        This probes for a branch at url, and searches upwards from there.
 
140
 
 
141
        Basically we keep looking up until we find the control directory or
 
142
        run into the root.  If there isn't one, raises NotBranchError.
 
143
        If there is one and it is either an unrecognised format or an unsupported
 
144
        format, UnknownFormatError or UnsupportedFormatError are raised.
 
145
        If there is one, it is returned, along with the unused portion of url.
 
146
        """
 
147
        control, relpath = bzrdir.BzrDir.open_containing(url,
 
148
                                                         possible_transports)
 
149
        return control.open_branch(), relpath
 
150
 
 
151
    def get_config(self):
 
152
        return BranchConfig(self)
 
153
 
 
154
    def _get_nick(self, local=False, possible_transports=None):
 
155
        config = self.get_config()
 
156
        # explicit overrides master, but don't look for master if local is True
 
157
        if not local and not config.has_explicit_nickname():
 
158
            try:
 
159
                master = self.get_master_branch(possible_transports)
 
160
                if master is not None:
 
161
                    # return the master branch value
 
162
                    return master.nick
 
163
            except errors.BzrError, e:
 
164
                # Silently fall back to local implicit nick if the master is
 
165
                # unavailable
 
166
                mutter("Could not connect to bound branch, "
 
167
                    "falling back to local nick.\n " + str(e))
 
168
        return config.get_nickname()
 
169
 
 
170
    def _set_nick(self, nick):
 
171
        self.get_config().set_user_option('nickname', nick, warn_masked=True)
 
172
 
 
173
    nick = property(_get_nick, _set_nick)
 
174
 
 
175
    def is_locked(self):
 
176
        raise NotImplementedError(self.is_locked)
 
177
 
 
178
    def _lefthand_history(self, revision_id, last_rev=None,
 
179
                          other_branch=None):
 
180
        if 'evil' in debug.debug_flags:
 
181
            mutter_callsite(4, "_lefthand_history scales with history.")
 
182
        # stop_revision must be a descendant of last_revision
 
183
        graph = self.repository.get_graph()
 
184
        if last_rev is not None:
 
185
            if not graph.is_ancestor(last_rev, revision_id):
 
186
                # our previous tip is not merged into stop_revision
 
187
                raise errors.DivergedBranches(self, other_branch)
 
188
        # make a new revision history from the graph
 
189
        parents_map = graph.get_parent_map([revision_id])
 
190
        if revision_id not in parents_map:
 
191
            raise errors.NoSuchRevision(self, revision_id)
 
192
        current_rev_id = revision_id
 
193
        new_history = []
 
194
        check_not_reserved_id = _mod_revision.check_not_reserved_id
 
195
        # Do not include ghosts or graph origin in revision_history
 
196
        while (current_rev_id in parents_map and
 
197
               len(parents_map[current_rev_id]) > 0):
 
198
            check_not_reserved_id(current_rev_id)
 
199
            new_history.append(current_rev_id)
 
200
            current_rev_id = parents_map[current_rev_id][0]
 
201
            parents_map = graph.get_parent_map([current_rev_id])
 
202
        new_history.reverse()
 
203
        return new_history
 
204
 
 
205
    def lock_write(self):
 
206
        raise NotImplementedError(self.lock_write)
 
207
 
 
208
    def lock_read(self):
 
209
        raise NotImplementedError(self.lock_read)
 
210
 
 
211
    def unlock(self):
 
212
        raise NotImplementedError(self.unlock)
 
213
 
 
214
    def peek_lock_mode(self):
 
215
        """Return lock mode for the Branch: 'r', 'w' or None"""
 
216
        raise NotImplementedError(self.peek_lock_mode)
 
217
 
 
218
    def get_physical_lock_status(self):
 
219
        raise NotImplementedError(self.get_physical_lock_status)
 
220
 
 
221
    @needs_read_lock
 
222
    def dotted_revno_to_revision_id(self, revno, _cache_reverse=False):
 
223
        """Return the revision_id for a dotted revno.
 
224
 
 
225
        :param revno: a tuple like (1,) or (1,1,2)
 
226
        :param _cache_reverse: a private parameter enabling storage
 
227
           of the reverse mapping in a top level cache. (This should
 
228
           only be done in selective circumstances as we want to
 
229
           avoid having the mapping cached multiple times.)
 
230
        :return: the revision_id
 
231
        :raises errors.NoSuchRevision: if the revno doesn't exist
 
232
        """
 
233
        rev_id = self._do_dotted_revno_to_revision_id(revno)
 
234
        if _cache_reverse:
 
235
            self._partial_revision_id_to_revno_cache[rev_id] = revno
 
236
        return rev_id
 
237
 
 
238
    def _do_dotted_revno_to_revision_id(self, revno):
 
239
        """Worker function for dotted_revno_to_revision_id.
 
240
 
 
241
        Subclasses should override this if they wish to
 
242
        provide a more efficient implementation.
 
243
        """
 
244
        if len(revno) == 1:
 
245
            return self.get_rev_id(revno[0])
 
246
        revision_id_to_revno = self.get_revision_id_to_revno_map()
 
247
        revision_ids = [revision_id for revision_id, this_revno
 
248
                        in revision_id_to_revno.iteritems()
 
249
                        if revno == this_revno]
 
250
        if len(revision_ids) == 1:
 
251
            return revision_ids[0]
 
252
        else:
 
253
            revno_str = '.'.join(map(str, revno))
 
254
            raise errors.NoSuchRevision(self, revno_str)
 
255
 
 
256
    @needs_read_lock
 
257
    def revision_id_to_dotted_revno(self, revision_id):
 
258
        """Given a revision id, return its dotted revno.
 
259
 
 
260
        :return: a tuple like (1,) or (400,1,3).
 
261
        """
 
262
        return self._do_revision_id_to_dotted_revno(revision_id)
 
263
 
 
264
    def _do_revision_id_to_dotted_revno(self, revision_id):
 
265
        """Worker function for revision_id_to_revno."""
 
266
        # Try the caches if they are loaded
 
267
        result = self._partial_revision_id_to_revno_cache.get(revision_id)
 
268
        if result is not None:
 
269
            return result
 
270
        if self._revision_id_to_revno_cache:
 
271
            result = self._revision_id_to_revno_cache.get(revision_id)
 
272
            if result is None:
 
273
                raise errors.NoSuchRevision(self, revision_id)
 
274
        # Try the mainline as it's optimised
 
275
        try:
 
276
            revno = self.revision_id_to_revno(revision_id)
 
277
            return (revno,)
 
278
        except errors.NoSuchRevision:
 
279
            # We need to load and use the full revno map after all
 
280
            result = self.get_revision_id_to_revno_map().get(revision_id)
 
281
            if result is None:
 
282
                raise errors.NoSuchRevision(self, revision_id)
 
283
        return result
 
284
 
 
285
    @needs_read_lock
 
286
    def get_revision_id_to_revno_map(self):
 
287
        """Return the revision_id => dotted revno map.
 
288
 
 
289
        This will be regenerated on demand, but will be cached.
 
290
 
 
291
        :return: A dictionary mapping revision_id => dotted revno.
 
292
            This dictionary should not be modified by the caller.
 
293
        """
 
294
        if self._revision_id_to_revno_cache is not None:
 
295
            mapping = self._revision_id_to_revno_cache
 
296
        else:
 
297
            mapping = self._gen_revno_map()
 
298
            self._cache_revision_id_to_revno(mapping)
 
299
        # TODO: jam 20070417 Since this is being cached, should we be returning
 
300
        #       a copy?
 
301
        # I would rather not, and instead just declare that users should not
 
302
        # modify the return value.
 
303
        return mapping
 
304
 
 
305
    def _gen_revno_map(self):
 
306
        """Create a new mapping from revision ids to dotted revnos.
 
307
 
 
308
        Dotted revnos are generated based on the current tip in the revision
 
309
        history.
 
310
        This is the worker function for get_revision_id_to_revno_map, which
 
311
        just caches the return value.
 
312
 
 
313
        :return: A dictionary mapping revision_id => dotted revno.
 
314
        """
 
315
        revision_id_to_revno = dict((rev_id, revno)
 
316
            for rev_id, depth, revno, end_of_merge
 
317
             in self.iter_merge_sorted_revisions())
 
318
        return revision_id_to_revno
 
319
 
 
320
    @needs_read_lock
 
321
    def iter_merge_sorted_revisions(self, start_revision_id=None,
 
322
            stop_revision_id=None, stop_rule='exclude', direction='reverse'):
 
323
        """Walk the revisions for a branch in merge sorted order.
 
324
 
 
325
        Merge sorted order is the output from a merge-aware,
 
326
        topological sort, i.e. all parents come before their
 
327
        children going forward; the opposite for reverse.
 
328
 
 
329
        :param start_revision_id: the revision_id to begin walking from.
 
330
            If None, the branch tip is used.
 
331
        :param stop_revision_id: the revision_id to terminate the walk
 
332
            after. If None, the rest of history is included.
 
333
        :param stop_rule: if stop_revision_id is not None, the precise rule
 
334
            to use for termination:
 
335
            * 'exclude' - leave the stop revision out of the result (default)
 
336
            * 'include' - the stop revision is the last item in the result
 
337
            * 'with-merges' - include the stop revision and all of its
 
338
              merged revisions in the result
 
339
        :param direction: either 'reverse' or 'forward':
 
340
            * reverse means return the start_revision_id first, i.e.
 
341
              start at the most recent revision and go backwards in history
 
342
            * forward returns tuples in the opposite order to reverse.
 
343
              Note in particular that forward does *not* do any intelligent
 
344
              ordering w.r.t. depth as some clients of this API may like.
 
345
              (If required, that ought to be done at higher layers.)
 
346
 
 
347
        :return: an iterator over (revision_id, depth, revno, end_of_merge)
 
348
            tuples where:
 
349
 
 
350
            * revision_id: the unique id of the revision
 
351
            * depth: How many levels of merging deep this node has been
 
352
              found.
 
353
            * revno_sequence: This field provides a sequence of
 
354
              revision numbers for all revisions. The format is:
 
355
              (REVNO, BRANCHNUM, BRANCHREVNO). BRANCHNUM is the number of the
 
356
              branch that the revno is on. From left to right the REVNO numbers
 
357
              are the sequence numbers within that branch of the revision.
 
358
            * end_of_merge: When True the next node (earlier in history) is
 
359
              part of a different merge.
 
360
        """
 
361
        # Note: depth and revno values are in the context of the branch so
 
362
        # we need the full graph to get stable numbers, regardless of the
 
363
        # start_revision_id.
 
364
        if self._merge_sorted_revisions_cache is None:
 
365
            last_revision = self.last_revision()
 
366
            graph = self.repository.get_graph()
 
367
            parent_map = dict(((key, value) for key, value in
 
368
                     graph.iter_ancestry([last_revision]) if value is not None))
 
369
            revision_graph = repository._strip_NULL_ghosts(parent_map)
 
370
            revs = tsort.merge_sort(revision_graph, last_revision, None,
 
371
                generate_revno=True)
 
372
            # Drop the sequence # before caching
 
373
            self._merge_sorted_revisions_cache = [r[1:] for r in revs]
 
374
 
 
375
        filtered = self._filter_merge_sorted_revisions(
 
376
            self._merge_sorted_revisions_cache, start_revision_id,
 
377
            stop_revision_id, stop_rule)
 
378
        if direction == 'reverse':
 
379
            return filtered
 
380
        if direction == 'forward':
 
381
            return reversed(list(filtered))
 
382
        else:
 
383
            raise ValueError('invalid direction %r' % direction)
 
384
 
 
385
    def _filter_merge_sorted_revisions(self, merge_sorted_revisions,
 
386
        start_revision_id, stop_revision_id, stop_rule):
 
387
        """Iterate over an inclusive range of sorted revisions."""
 
388
        rev_iter = iter(merge_sorted_revisions)
 
389
        if start_revision_id is not None:
 
390
            for rev_id, depth, revno, end_of_merge in rev_iter:
 
391
                if rev_id != start_revision_id:
 
392
                    continue
 
393
                else:
 
394
                    # The decision to include the start or not
 
395
                    # depends on the stop_rule if a stop is provided
 
396
                    rev_iter = chain(
 
397
                        iter([(rev_id, depth, revno, end_of_merge)]),
 
398
                        rev_iter)
 
399
                    break
 
400
        if stop_revision_id is None:
 
401
            for rev_id, depth, revno, end_of_merge in rev_iter:
 
402
                yield rev_id, depth, revno, end_of_merge
 
403
        elif stop_rule == 'exclude':
 
404
            for rev_id, depth, revno, end_of_merge in rev_iter:
 
405
                if rev_id == stop_revision_id:
 
406
                    return
 
407
                yield rev_id, depth, revno, end_of_merge
 
408
        elif stop_rule == 'include':
 
409
            for rev_id, depth, revno, end_of_merge in rev_iter:
 
410
                yield rev_id, depth, revno, end_of_merge
 
411
                if rev_id == stop_revision_id:
 
412
                    return
 
413
        elif stop_rule == 'with-merges':
 
414
            stop_rev = self.repository.get_revision(stop_revision_id)
 
415
            if stop_rev.parent_ids:
 
416
                left_parent = stop_rev.parent_ids[0]
 
417
            else:
 
418
                left_parent = _mod_revision.NULL_REVISION
 
419
            for rev_id, depth, revno, end_of_merge in rev_iter:
 
420
                if rev_id == left_parent:
 
421
                    return
 
422
                yield rev_id, depth, revno, end_of_merge
 
423
        else:
 
424
            raise ValueError('invalid stop_rule %r' % stop_rule)
 
425
 
 
426
    def leave_lock_in_place(self):
 
427
        """Tell this branch object not to release the physical lock when this
 
428
        object is unlocked.
 
429
 
 
430
        If lock_write doesn't return a token, then this method is not supported.
 
431
        """
 
432
        self.control_files.leave_in_place()
 
433
 
 
434
    def dont_leave_lock_in_place(self):
 
435
        """Tell this branch object to release the physical lock when this
 
436
        object is unlocked, even if it didn't originally acquire it.
 
437
 
 
438
        If lock_write doesn't return a token, then this method is not supported.
 
439
        """
 
440
        self.control_files.dont_leave_in_place()
 
441
 
 
442
    def bind(self, other):
 
443
        """Bind the local branch the other branch.
 
444
 
 
445
        :param other: The branch to bind to
 
446
        :type other: Branch
 
447
        """
 
448
        raise errors.UpgradeRequired(self.base)
 
449
 
 
450
    @needs_write_lock
 
451
    def fetch(self, from_branch, last_revision=None, pb=None):
 
452
        """Copy revisions from from_branch into this branch.
 
453
 
 
454
        :param from_branch: Where to copy from.
 
455
        :param last_revision: What revision to stop at (None for at the end
 
456
                              of the branch.
 
457
        :param pb: An optional progress bar to use.
 
458
 
 
459
        Returns the copied revision count and the failed revisions in a tuple:
 
460
        (copied, failures).
 
461
        """
 
462
        if self.base == from_branch.base:
 
463
            return (0, [])
 
464
        if pb is None:
 
465
            nested_pb = ui.ui_factory.nested_progress_bar()
 
466
            pb = nested_pb
 
467
        else:
 
468
            nested_pb = None
 
469
 
 
470
        from_branch.lock_read()
 
471
        try:
 
472
            if last_revision is None:
 
473
                pb.update('get source history')
 
474
                last_revision = from_branch.last_revision()
 
475
                last_revision = _mod_revision.ensure_null(last_revision)
 
476
            return self.repository.fetch(from_branch.repository,
 
477
                                         revision_id=last_revision,
 
478
                                         pb=nested_pb)
 
479
        finally:
 
480
            if nested_pb is not None:
 
481
                nested_pb.finished()
 
482
            from_branch.unlock()
 
483
 
 
484
    def get_bound_location(self):
 
485
        """Return the URL of the branch we are bound to.
 
486
 
 
487
        Older format branches cannot bind, please be sure to use a metadir
 
488
        branch.
 
489
        """
 
490
        return None
 
491
 
 
492
    def get_old_bound_location(self):
 
493
        """Return the URL of the branch we used to be bound to
 
494
        """
 
495
        raise errors.UpgradeRequired(self.base)
 
496
 
 
497
    def get_commit_builder(self, parents, config=None, timestamp=None,
 
498
                           timezone=None, committer=None, revprops=None,
 
499
                           revision_id=None):
 
500
        """Obtain a CommitBuilder for this branch.
 
501
 
 
502
        :param parents: Revision ids of the parents of the new revision.
 
503
        :param config: Optional configuration to use.
 
504
        :param timestamp: Optional timestamp recorded for commit.
 
505
        :param timezone: Optional timezone for timestamp.
 
506
        :param committer: Optional committer to set for commit.
 
507
        :param revprops: Optional dictionary of revision properties.
 
508
        :param revision_id: Optional revision id.
 
509
        """
 
510
 
 
511
        if config is None:
 
512
            config = self.get_config()
 
513
 
 
514
        return self.repository.get_commit_builder(self, parents, config,
 
515
            timestamp, timezone, committer, revprops, revision_id)
 
516
 
 
517
    def get_master_branch(self, possible_transports=None):
 
518
        """Return the branch we are bound to.
 
519
 
 
520
        :return: Either a Branch, or None
 
521
        """
 
522
        return None
 
523
 
 
524
    def get_revision_delta(self, revno):
 
525
        """Return the delta for one revision.
 
526
 
 
527
        The delta is relative to its mainline predecessor, or the
 
528
        empty tree for revision 1.
 
529
        """
 
530
        rh = self.revision_history()
 
531
        if not (1 <= revno <= len(rh)):
 
532
            raise errors.InvalidRevisionNumber(revno)
 
533
        return self.repository.get_revision_delta(rh[revno-1])
 
534
 
 
535
    def get_stacked_on_url(self):
 
536
        """Get the URL this branch is stacked against.
 
537
 
 
538
        :raises NotStacked: If the branch is not stacked.
 
539
        :raises UnstackableBranchFormat: If the branch does not support
 
540
            stacking.
 
541
        """
 
542
        raise NotImplementedError(self.get_stacked_on_url)
 
543
 
 
544
    def print_file(self, file, revision_id):
 
545
        """Print `file` to stdout."""
 
546
        raise NotImplementedError(self.print_file)
 
547
 
 
548
    def set_revision_history(self, rev_history):
 
549
        raise NotImplementedError(self.set_revision_history)
 
550
 
 
551
    def set_stacked_on_url(self, url):
 
552
        """Set the URL this branch is stacked against.
 
553
 
 
554
        :raises UnstackableBranchFormat: If the branch does not support
 
555
            stacking.
 
556
        :raises UnstackableRepositoryFormat: If the repository does not support
 
557
            stacking.
 
558
        """
 
559
        raise NotImplementedError(self.set_stacked_on_url)
 
560
 
 
561
    def _cache_revision_history(self, rev_history):
 
562
        """Set the cached revision history to rev_history.
 
563
 
 
564
        The revision_history method will use this cache to avoid regenerating
 
565
        the revision history.
 
566
 
 
567
        This API is semi-public; it only for use by subclasses, all other code
 
568
        should consider it to be private.
 
569
        """
 
570
        self._revision_history_cache = rev_history
 
571
 
 
572
    def _cache_revision_id_to_revno(self, revision_id_to_revno):
 
573
        """Set the cached revision_id => revno map to revision_id_to_revno.
 
574
 
 
575
        This API is semi-public; it only for use by subclasses, all other code
 
576
        should consider it to be private.
 
577
        """
 
578
        self._revision_id_to_revno_cache = revision_id_to_revno
 
579
 
 
580
    def _clear_cached_state(self):
 
581
        """Clear any cached data on this branch, e.g. cached revision history.
 
582
 
 
583
        This means the next call to revision_history will need to call
 
584
        _gen_revision_history.
 
585
 
 
586
        This API is semi-public; it only for use by subclasses, all other code
 
587
        should consider it to be private.
 
588
        """
 
589
        self._revision_history_cache = None
 
590
        self._revision_id_to_revno_cache = None
 
591
        self._last_revision_info_cache = None
 
592
        self._merge_sorted_revisions_cache = None
 
593
 
 
594
    def _gen_revision_history(self):
 
595
        """Return sequence of revision hashes on to this branch.
 
596
 
 
597
        Unlike revision_history, this method always regenerates or rereads the
 
598
        revision history, i.e. it does not cache the result, so repeated calls
 
599
        may be expensive.
 
600
 
 
601
        Concrete subclasses should override this instead of revision_history so
 
602
        that subclasses do not need to deal with caching logic.
 
603
 
 
604
        This API is semi-public; it only for use by subclasses, all other code
 
605
        should consider it to be private.
 
606
        """
 
607
        raise NotImplementedError(self._gen_revision_history)
 
608
 
 
609
    @needs_read_lock
 
610
    def revision_history(self):
 
611
        """Return sequence of revision ids on this branch.
 
612
 
 
613
        This method will cache the revision history for as long as it is safe to
 
614
        do so.
 
615
        """
 
616
        if 'evil' in debug.debug_flags:
 
617
            mutter_callsite(3, "revision_history scales with history.")
 
618
        if self._revision_history_cache is not None:
 
619
            history = self._revision_history_cache
 
620
        else:
 
621
            history = self._gen_revision_history()
 
622
            self._cache_revision_history(history)
 
623
        return list(history)
 
624
 
 
625
    def revno(self):
 
626
        """Return current revision number for this branch.
 
627
 
 
628
        That is equivalent to the number of revisions committed to
 
629
        this branch.
 
630
        """
 
631
        return self.last_revision_info()[0]
 
632
 
 
633
    def unbind(self):
 
634
        """Older format branches cannot bind or unbind."""
 
635
        raise errors.UpgradeRequired(self.base)
 
636
 
 
637
    def set_append_revisions_only(self, enabled):
 
638
        """Older format branches are never restricted to append-only"""
 
639
        raise errors.UpgradeRequired(self.base)
 
640
 
 
641
    def last_revision(self):
 
642
        """Return last revision id, or NULL_REVISION."""
 
643
        return self.last_revision_info()[1]
 
644
 
 
645
    @needs_read_lock
 
646
    def last_revision_info(self):
 
647
        """Return information about the last revision.
 
648
 
 
649
        :return: A tuple (revno, revision_id).
 
650
        """
 
651
        if self._last_revision_info_cache is None:
 
652
            self._last_revision_info_cache = self._last_revision_info()
 
653
        return self._last_revision_info_cache
 
654
 
 
655
    def _last_revision_info(self):
 
656
        rh = self.revision_history()
 
657
        revno = len(rh)
 
658
        if revno:
 
659
            return (revno, rh[-1])
 
660
        else:
 
661
            return (0, _mod_revision.NULL_REVISION)
 
662
 
 
663
    @deprecated_method(deprecated_in((1, 6, 0)))
 
664
    def missing_revisions(self, other, stop_revision=None):
 
665
        """Return a list of new revisions that would perfectly fit.
 
666
 
 
667
        If self and other have not diverged, return a list of the revisions
 
668
        present in other, but missing from self.
 
669
        """
 
670
        self_history = self.revision_history()
 
671
        self_len = len(self_history)
 
672
        other_history = other.revision_history()
 
673
        other_len = len(other_history)
 
674
        common_index = min(self_len, other_len) -1
 
675
        if common_index >= 0 and \
 
676
            self_history[common_index] != other_history[common_index]:
 
677
            raise errors.DivergedBranches(self, other)
 
678
 
 
679
        if stop_revision is None:
 
680
            stop_revision = other_len
 
681
        else:
 
682
            if stop_revision > other_len:
 
683
                raise errors.NoSuchRevision(self, stop_revision)
 
684
        return other_history[self_len:stop_revision]
 
685
 
 
686
    @needs_write_lock
 
687
    def update_revisions(self, other, stop_revision=None, overwrite=False,
 
688
                         graph=None):
 
689
        """Pull in new perfect-fit revisions.
 
690
 
 
691
        :param other: Another Branch to pull from
 
692
        :param stop_revision: Updated until the given revision
 
693
        :param overwrite: Always set the branch pointer, rather than checking
 
694
            to see if it is a proper descendant.
 
695
        :param graph: A Graph object that can be used to query history
 
696
            information. This can be None.
 
697
        :return: None
 
698
        """
 
699
        return InterBranch.get(other, self).update_revisions(stop_revision,
 
700
            overwrite, graph)
 
701
 
 
702
    def revision_id_to_revno(self, revision_id):
 
703
        """Given a revision id, return its revno"""
 
704
        if _mod_revision.is_null(revision_id):
 
705
            return 0
 
706
        history = self.revision_history()
 
707
        try:
 
708
            return history.index(revision_id) + 1
 
709
        except ValueError:
 
710
            raise errors.NoSuchRevision(self, revision_id)
 
711
 
 
712
    def get_rev_id(self, revno, history=None):
 
713
        """Find the revision id of the specified revno."""
 
714
        if revno == 0:
 
715
            return _mod_revision.NULL_REVISION
 
716
        if history is None:
 
717
            history = self.revision_history()
 
718
        if revno <= 0 or revno > len(history):
 
719
            raise errors.NoSuchRevision(self, revno)
 
720
        return history[revno - 1]
 
721
 
 
722
    def pull(self, source, overwrite=False, stop_revision=None,
 
723
             possible_transports=None, _override_hook_target=None):
 
724
        """Mirror source into this branch.
 
725
 
 
726
        This branch is considered to be 'local', having low latency.
 
727
 
 
728
        :returns: PullResult instance
 
729
        """
 
730
        raise NotImplementedError(self.pull)
 
731
 
 
732
    def push(self, target, overwrite=False, stop_revision=None):
 
733
        """Mirror this branch into target.
 
734
 
 
735
        This branch is considered to be 'local', having low latency.
 
736
        """
 
737
        raise NotImplementedError(self.push)
 
738
 
 
739
    def basis_tree(self):
 
740
        """Return `Tree` object for last revision."""
 
741
        return self.repository.revision_tree(self.last_revision())
 
742
 
 
743
    def get_parent(self):
 
744
        """Return the parent location of the branch.
 
745
 
 
746
        This is the default location for pull/missing.  The usual
 
747
        pattern is that the user can override it by specifying a
 
748
        location.
 
749
        """
 
750
        raise NotImplementedError(self.get_parent)
 
751
 
 
752
    def _set_config_location(self, name, url, config=None,
 
753
                             make_relative=False):
 
754
        if config is None:
 
755
            config = self.get_config()
 
756
        if url is None:
 
757
            url = ''
 
758
        elif make_relative:
 
759
            url = urlutils.relative_url(self.base, url)
 
760
        config.set_user_option(name, url, warn_masked=True)
 
761
 
 
762
    def _get_config_location(self, name, config=None):
 
763
        if config is None:
 
764
            config = self.get_config()
 
765
        location = config.get_user_option(name)
 
766
        if location == '':
 
767
            location = None
 
768
        return location
 
769
 
 
770
    def get_submit_branch(self):
 
771
        """Return the submit location of the branch.
 
772
 
 
773
        This is the default location for bundle.  The usual
 
774
        pattern is that the user can override it by specifying a
 
775
        location.
 
776
        """
 
777
        return self.get_config().get_user_option('submit_branch')
 
778
 
 
779
    def set_submit_branch(self, location):
 
780
        """Return the submit location of the branch.
 
781
 
 
782
        This is the default location for bundle.  The usual
 
783
        pattern is that the user can override it by specifying a
 
784
        location.
 
785
        """
 
786
        self.get_config().set_user_option('submit_branch', location,
 
787
            warn_masked=True)
 
788
 
 
789
    def get_public_branch(self):
 
790
        """Return the public location of the branch.
 
791
 
 
792
        This is is used by merge directives.
 
793
        """
 
794
        return self._get_config_location('public_branch')
 
795
 
 
796
    def set_public_branch(self, location):
 
797
        """Return the submit location of the branch.
 
798
 
 
799
        This is the default location for bundle.  The usual
 
800
        pattern is that the user can override it by specifying a
 
801
        location.
 
802
        """
 
803
        self._set_config_location('public_branch', location)
 
804
 
 
805
    def get_push_location(self):
 
806
        """Return the None or the location to push this branch to."""
 
807
        push_loc = self.get_config().get_user_option('push_location')
 
808
        return push_loc
 
809
 
 
810
    def set_push_location(self, location):
 
811
        """Set a new push location for this branch."""
 
812
        raise NotImplementedError(self.set_push_location)
 
813
 
 
814
    def _run_post_change_branch_tip_hooks(self, old_revno, old_revid):
 
815
        """Run the post_change_branch_tip hooks."""
 
816
        hooks = Branch.hooks['post_change_branch_tip']
 
817
        if not hooks:
 
818
            return
 
819
        new_revno, new_revid = self.last_revision_info()
 
820
        params = ChangeBranchTipParams(
 
821
            self, old_revno, new_revno, old_revid, new_revid)
 
822
        for hook in hooks:
 
823
            hook(params)
 
824
 
 
825
    def _run_pre_change_branch_tip_hooks(self, new_revno, new_revid):
 
826
        """Run the pre_change_branch_tip hooks."""
 
827
        hooks = Branch.hooks['pre_change_branch_tip']
 
828
        if not hooks:
 
829
            return
 
830
        old_revno, old_revid = self.last_revision_info()
 
831
        params = ChangeBranchTipParams(
 
832
            self, old_revno, new_revno, old_revid, new_revid)
 
833
        for hook in hooks:
 
834
            try:
 
835
                hook(params)
 
836
            except errors.TipChangeRejected:
 
837
                raise
 
838
            except Exception:
 
839
                exc_info = sys.exc_info()
 
840
                hook_name = Branch.hooks.get_hook_name(hook)
 
841
                raise errors.HookFailed(
 
842
                    'pre_change_branch_tip', hook_name, exc_info)
 
843
 
 
844
    def set_parent(self, url):
 
845
        raise NotImplementedError(self.set_parent)
 
846
 
 
847
    @needs_write_lock
 
848
    def update(self):
 
849
        """Synchronise this branch with the master branch if any.
 
850
 
 
851
        :return: None or the last_revision pivoted out during the update.
 
852
        """
 
853
        return None
 
854
 
 
855
    def check_revno(self, revno):
 
856
        """\
 
857
        Check whether a revno corresponds to any revision.
 
858
        Zero (the NULL revision) is considered valid.
 
859
        """
 
860
        if revno != 0:
 
861
            self.check_real_revno(revno)
 
862
 
 
863
    def check_real_revno(self, revno):
 
864
        """\
 
865
        Check whether a revno corresponds to a real revision.
 
866
        Zero (the NULL revision) is considered invalid
 
867
        """
 
868
        if revno < 1 or revno > self.revno():
 
869
            raise errors.InvalidRevisionNumber(revno)
 
870
 
 
871
    @needs_read_lock
 
872
    def clone(self, to_bzrdir, revision_id=None):
 
873
        """Clone this branch into to_bzrdir preserving all semantic values.
 
874
 
 
875
        revision_id: if not None, the revision history in the new branch will
 
876
                     be truncated to end with revision_id.
 
877
        """
 
878
        result = to_bzrdir.create_branch()
 
879
        self.copy_content_into(result, revision_id=revision_id)
 
880
        return  result
 
881
 
 
882
    @needs_read_lock
 
883
    def sprout(self, to_bzrdir, revision_id=None):
 
884
        """Create a new line of development from the branch, into to_bzrdir.
 
885
 
 
886
        to_bzrdir controls the branch format.
 
887
 
 
888
        revision_id: if not None, the revision history in the new branch will
 
889
                     be truncated to end with revision_id.
 
890
        """
 
891
        result = to_bzrdir.create_branch()
 
892
        self.copy_content_into(result, revision_id=revision_id)
 
893
        result.set_parent(self.bzrdir.root_transport.base)
 
894
        return result
 
895
 
 
896
    def _synchronize_history(self, destination, revision_id):
 
897
        """Synchronize last revision and revision history between branches.
 
898
 
 
899
        This version is most efficient when the destination is also a
 
900
        BzrBranch6, but works for BzrBranch5, as long as the destination's
 
901
        repository contains all the lefthand ancestors of the intended
 
902
        last_revision.  If not, set_last_revision_info will fail.
 
903
 
 
904
        :param destination: The branch to copy the history into
 
905
        :param revision_id: The revision-id to truncate history at.  May
 
906
          be None to copy complete history.
 
907
        """
 
908
        source_revno, source_revision_id = self.last_revision_info()
 
909
        if revision_id is None:
 
910
            revno, revision_id = source_revno, source_revision_id
 
911
        elif source_revision_id == revision_id:
 
912
            # we know the revno without needing to walk all of history
 
913
            revno = source_revno
 
914
        else:
 
915
            # To figure out the revno for a random revision, we need to build
 
916
            # the revision history, and count its length.
 
917
            # We don't care about the order, just how long it is.
 
918
            # Alternatively, we could start at the current location, and count
 
919
            # backwards. But there is no guarantee that we will find it since
 
920
            # it may be a merged revision.
 
921
            revno = len(list(self.repository.iter_reverse_revision_history(
 
922
                                                                revision_id)))
 
923
        destination.set_last_revision_info(revno, revision_id)
 
924
 
 
925
    @needs_read_lock
 
926
    def copy_content_into(self, destination, revision_id=None):
 
927
        """Copy the content of self into destination.
 
928
 
 
929
        revision_id: if not None, the revision history in the new branch will
 
930
                     be truncated to end with revision_id.
 
931
        """
 
932
        self._synchronize_history(destination, revision_id)
 
933
        try:
 
934
            parent = self.get_parent()
 
935
        except errors.InaccessibleParent, e:
 
936
            mutter('parent was not accessible to copy: %s', e)
 
937
        else:
 
938
            if parent:
 
939
                destination.set_parent(parent)
 
940
        self.tags.merge_to(destination.tags)
 
941
 
 
942
    @needs_read_lock
 
943
    def check(self):
 
944
        """Check consistency of the branch.
 
945
 
 
946
        In particular this checks that revisions given in the revision-history
 
947
        do actually match up in the revision graph, and that they're all
 
948
        present in the repository.
 
949
 
 
950
        Callers will typically also want to check the repository.
 
951
 
 
952
        :return: A BranchCheckResult.
 
953
        """
 
954
        mainline_parent_id = None
 
955
        last_revno, last_revision_id = self.last_revision_info()
 
956
        real_rev_history = list(self.repository.iter_reverse_revision_history(
 
957
                                last_revision_id))
 
958
        real_rev_history.reverse()
 
959
        if len(real_rev_history) != last_revno:
 
960
            raise errors.BzrCheckError('revno does not match len(mainline)'
 
961
                ' %s != %s' % (last_revno, len(real_rev_history)))
 
962
        # TODO: We should probably also check that real_rev_history actually
 
963
        #       matches self.revision_history()
 
964
        for revision_id in real_rev_history:
 
965
            try:
 
966
                revision = self.repository.get_revision(revision_id)
 
967
            except errors.NoSuchRevision, e:
 
968
                raise errors.BzrCheckError("mainline revision {%s} not in repository"
 
969
                            % revision_id)
 
970
            # In general the first entry on the revision history has no parents.
 
971
            # But it's not illegal for it to have parents listed; this can happen
 
972
            # in imports from Arch when the parents weren't reachable.
 
973
            if mainline_parent_id is not None:
 
974
                if mainline_parent_id not in revision.parent_ids:
 
975
                    raise errors.BzrCheckError("previous revision {%s} not listed among "
 
976
                                        "parents of {%s}"
 
977
                                        % (mainline_parent_id, revision_id))
 
978
            mainline_parent_id = revision_id
 
979
        return BranchCheckResult(self)
 
980
 
 
981
    def _get_checkout_format(self):
 
982
        """Return the most suitable metadir for a checkout of this branch.
 
983
        Weaves are used if this branch's repository uses weaves.
 
984
        """
 
985
        if isinstance(self.bzrdir, bzrdir.BzrDirPreSplitOut):
 
986
            from bzrlib.repofmt import weaverepo
 
987
            format = bzrdir.BzrDirMetaFormat1()
 
988
            format.repository_format = weaverepo.RepositoryFormat7()
 
989
        else:
 
990
            format = self.repository.bzrdir.checkout_metadir()
 
991
            format.set_branch_format(self._format)
 
992
        return format
 
993
 
 
994
    def create_checkout(self, to_location, revision_id=None,
 
995
                        lightweight=False, accelerator_tree=None,
 
996
                        hardlink=False):
 
997
        """Create a checkout of a branch.
 
998
 
 
999
        :param to_location: The url to produce the checkout at
 
1000
        :param revision_id: The revision to check out
 
1001
        :param lightweight: If True, produce a lightweight checkout, otherwise,
 
1002
        produce a bound branch (heavyweight checkout)
 
1003
        :param accelerator_tree: A tree which can be used for retrieving file
 
1004
            contents more quickly than the revision tree, i.e. a workingtree.
 
1005
            The revision tree will be used for cases where accelerator_tree's
 
1006
            content is different.
 
1007
        :param hardlink: If true, hard-link files from accelerator_tree,
 
1008
            where possible.
 
1009
        :return: The tree of the created checkout
 
1010
        """
 
1011
        t = transport.get_transport(to_location)
 
1012
        t.ensure_base()
 
1013
        if lightweight:
 
1014
            format = self._get_checkout_format()
 
1015
            checkout = format.initialize_on_transport(t)
 
1016
            from_branch = BranchReferenceFormat().initialize(checkout, self)
 
1017
        else:
 
1018
            format = self._get_checkout_format()
 
1019
            checkout_branch = bzrdir.BzrDir.create_branch_convenience(
 
1020
                to_location, force_new_tree=False, format=format)
 
1021
            checkout = checkout_branch.bzrdir
 
1022
            checkout_branch.bind(self)
 
1023
            # pull up to the specified revision_id to set the initial
 
1024
            # branch tip correctly, and seed it with history.
 
1025
            checkout_branch.pull(self, stop_revision=revision_id)
 
1026
            from_branch=None
 
1027
        tree = checkout.create_workingtree(revision_id,
 
1028
                                           from_branch=from_branch,
 
1029
                                           accelerator_tree=accelerator_tree,
 
1030
                                           hardlink=hardlink)
 
1031
        basis_tree = tree.basis_tree()
 
1032
        basis_tree.lock_read()
 
1033
        try:
 
1034
            for path, file_id in basis_tree.iter_references():
 
1035
                reference_parent = self.reference_parent(file_id, path)
 
1036
                reference_parent.create_checkout(tree.abspath(path),
 
1037
                    basis_tree.get_reference_revision(file_id, path),
 
1038
                    lightweight)
 
1039
        finally:
 
1040
            basis_tree.unlock()
 
1041
        return tree
 
1042
 
 
1043
    @needs_write_lock
 
1044
    def reconcile(self, thorough=True):
 
1045
        """Make sure the data stored in this branch is consistent."""
 
1046
        from bzrlib.reconcile import BranchReconciler
 
1047
        reconciler = BranchReconciler(self, thorough=thorough)
 
1048
        reconciler.reconcile()
 
1049
        return reconciler
 
1050
 
 
1051
    def reference_parent(self, file_id, path):
 
1052
        """Return the parent branch for a tree-reference file_id
 
1053
        :param file_id: The file_id of the tree reference
 
1054
        :param path: The path of the file_id in the tree
 
1055
        :return: A branch associated with the file_id
 
1056
        """
 
1057
        # FIXME should provide multiple branches, based on config
 
1058
        return Branch.open(self.bzrdir.root_transport.clone(path).base)
 
1059
 
 
1060
    def supports_tags(self):
 
1061
        return self._format.supports_tags()
 
1062
 
 
1063
    def _check_if_descendant_or_diverged(self, revision_a, revision_b, graph,
 
1064
                                         other_branch):
 
1065
        """Ensure that revision_b is a descendant of revision_a.
 
1066
 
 
1067
        This is a helper function for update_revisions.
 
1068
 
 
1069
        :raises: DivergedBranches if revision_b has diverged from revision_a.
 
1070
        :returns: True if revision_b is a descendant of revision_a.
 
1071
        """
 
1072
        relation = self._revision_relations(revision_a, revision_b, graph)
 
1073
        if relation == 'b_descends_from_a':
 
1074
            return True
 
1075
        elif relation == 'diverged':
 
1076
            raise errors.DivergedBranches(self, other_branch)
 
1077
        elif relation == 'a_descends_from_b':
 
1078
            return False
 
1079
        else:
 
1080
            raise AssertionError("invalid relation: %r" % (relation,))
 
1081
 
 
1082
    def _revision_relations(self, revision_a, revision_b, graph):
 
1083
        """Determine the relationship between two revisions.
 
1084
 
 
1085
        :returns: One of: 'a_descends_from_b', 'b_descends_from_a', 'diverged'
 
1086
        """
 
1087
        heads = graph.heads([revision_a, revision_b])
 
1088
        if heads == set([revision_b]):
 
1089
            return 'b_descends_from_a'
 
1090
        elif heads == set([revision_a, revision_b]):
 
1091
            # These branches have diverged
 
1092
            return 'diverged'
 
1093
        elif heads == set([revision_a]):
 
1094
            return 'a_descends_from_b'
 
1095
        else:
 
1096
            raise AssertionError("invalid heads: %r" % (heads,))
 
1097
 
 
1098
 
 
1099
class BranchFormat(object):
 
1100
    """An encapsulation of the initialization and open routines for a format.
 
1101
 
 
1102
    Formats provide three things:
 
1103
     * An initialization routine,
 
1104
     * a format string,
 
1105
     * an open routine.
 
1106
 
 
1107
    Formats are placed in an dict by their format string for reference
 
1108
    during branch opening. Its not required that these be instances, they
 
1109
    can be classes themselves with class methods - it simply depends on
 
1110
    whether state is needed for a given format or not.
 
1111
 
 
1112
    Once a format is deprecated, just deprecate the initialize and open
 
1113
    methods on the format class. Do not deprecate the object, as the
 
1114
    object will be created every time regardless.
 
1115
    """
 
1116
 
 
1117
    _default_format = None
 
1118
    """The default format used for new branches."""
 
1119
 
 
1120
    _formats = {}
 
1121
    """The known formats."""
 
1122
 
 
1123
    def __eq__(self, other):
 
1124
        return self.__class__ is other.__class__
 
1125
 
 
1126
    def __ne__(self, other):
 
1127
        return not (self == other)
 
1128
 
 
1129
    @classmethod
 
1130
    def find_format(klass, a_bzrdir):
 
1131
        """Return the format for the branch object in a_bzrdir."""
 
1132
        try:
 
1133
            transport = a_bzrdir.get_branch_transport(None)
 
1134
            format_string = transport.get("format").read()
 
1135
            return klass._formats[format_string]
 
1136
        except errors.NoSuchFile:
 
1137
            raise errors.NotBranchError(path=transport.base)
 
1138
        except KeyError:
 
1139
            raise errors.UnknownFormatError(format=format_string, kind='branch')
 
1140
 
 
1141
    @classmethod
 
1142
    def get_default_format(klass):
 
1143
        """Return the current default format."""
 
1144
        return klass._default_format
 
1145
 
 
1146
    def get_reference(self, a_bzrdir):
 
1147
        """Get the target reference of the branch in a_bzrdir.
 
1148
 
 
1149
        format probing must have been completed before calling
 
1150
        this method - it is assumed that the format of the branch
 
1151
        in a_bzrdir is correct.
 
1152
 
 
1153
        :param a_bzrdir: The bzrdir to get the branch data from.
 
1154
        :return: None if the branch is not a reference branch.
 
1155
        """
 
1156
        return None
 
1157
 
 
1158
    @classmethod
 
1159
    def set_reference(self, a_bzrdir, to_branch):
 
1160
        """Set the target reference of the branch in a_bzrdir.
 
1161
 
 
1162
        format probing must have been completed before calling
 
1163
        this method - it is assumed that the format of the branch
 
1164
        in a_bzrdir is correct.
 
1165
 
 
1166
        :param a_bzrdir: The bzrdir to set the branch reference for.
 
1167
        :param to_branch: branch that the checkout is to reference
 
1168
        """
 
1169
        raise NotImplementedError(self.set_reference)
 
1170
 
 
1171
    def get_format_string(self):
 
1172
        """Return the ASCII format string that identifies this format."""
 
1173
        raise NotImplementedError(self.get_format_string)
 
1174
 
 
1175
    def get_format_description(self):
 
1176
        """Return the short format description for this format."""
 
1177
        raise NotImplementedError(self.get_format_description)
 
1178
 
 
1179
    def _initialize_helper(self, a_bzrdir, utf8_files, lock_type='metadir',
 
1180
                           set_format=True):
 
1181
        """Initialize a branch in a bzrdir, with specified files
 
1182
 
 
1183
        :param a_bzrdir: The bzrdir to initialize the branch in
 
1184
        :param utf8_files: The files to create as a list of
 
1185
            (filename, content) tuples
 
1186
        :param set_format: If True, set the format with
 
1187
            self.get_format_string.  (BzrBranch4 has its format set
 
1188
            elsewhere)
 
1189
        :return: a branch in this format
 
1190
        """
 
1191
        mutter('creating branch %r in %s', self, a_bzrdir.transport.base)
 
1192
        branch_transport = a_bzrdir.get_branch_transport(self)
 
1193
        lock_map = {
 
1194
            'metadir': ('lock', lockdir.LockDir),
 
1195
            'branch4': ('branch-lock', lockable_files.TransportLock),
 
1196
        }
 
1197
        lock_name, lock_class = lock_map[lock_type]
 
1198
        control_files = lockable_files.LockableFiles(branch_transport,
 
1199
            lock_name, lock_class)
 
1200
        control_files.create_lock()
 
1201
        control_files.lock_write()
 
1202
        if set_format:
 
1203
            utf8_files += [('format', self.get_format_string())]
 
1204
        try:
 
1205
            for (filename, content) in utf8_files:
 
1206
                branch_transport.put_bytes(
 
1207
                    filename, content,
 
1208
                    mode=a_bzrdir._get_file_mode())
 
1209
        finally:
 
1210
            control_files.unlock()
 
1211
        return self.open(a_bzrdir, _found=True)
 
1212
 
 
1213
    def initialize(self, a_bzrdir):
 
1214
        """Create a branch of this format in a_bzrdir."""
 
1215
        raise NotImplementedError(self.initialize)
 
1216
 
 
1217
    def is_supported(self):
 
1218
        """Is this format supported?
 
1219
 
 
1220
        Supported formats can be initialized and opened.
 
1221
        Unsupported formats may not support initialization or committing or
 
1222
        some other features depending on the reason for not being supported.
 
1223
        """
 
1224
        return True
 
1225
 
 
1226
    def open(self, a_bzrdir, _found=False):
 
1227
        """Return the branch object for a_bzrdir
 
1228
 
 
1229
        _found is a private parameter, do not use it. It is used to indicate
 
1230
               if format probing has already be done.
 
1231
        """
 
1232
        raise NotImplementedError(self.open)
 
1233
 
 
1234
    @classmethod
 
1235
    def register_format(klass, format):
 
1236
        klass._formats[format.get_format_string()] = format
 
1237
 
 
1238
    @classmethod
 
1239
    def set_default_format(klass, format):
 
1240
        klass._default_format = format
 
1241
 
 
1242
    def supports_stacking(self):
 
1243
        """True if this format records a stacked-on branch."""
 
1244
        return False
 
1245
 
 
1246
    @classmethod
 
1247
    def unregister_format(klass, format):
 
1248
        del klass._formats[format.get_format_string()]
 
1249
 
 
1250
    def __str__(self):
 
1251
        return self.get_format_string().rstrip()
 
1252
 
 
1253
    def supports_tags(self):
 
1254
        """True if this format supports tags stored in the branch"""
 
1255
        return False  # by default
 
1256
 
 
1257
 
 
1258
class BranchHooks(Hooks):
 
1259
    """A dictionary mapping hook name to a list of callables for branch hooks.
 
1260
 
 
1261
    e.g. ['set_rh'] Is the list of items to be called when the
 
1262
    set_revision_history function is invoked.
 
1263
    """
 
1264
 
 
1265
    def __init__(self):
 
1266
        """Create the default hooks.
 
1267
 
 
1268
        These are all empty initially, because by default nothing should get
 
1269
        notified.
 
1270
        """
 
1271
        Hooks.__init__(self)
 
1272
        # Introduced in 0.15:
 
1273
        # invoked whenever the revision history has been set
 
1274
        # with set_revision_history. The api signature is
 
1275
        # (branch, revision_history), and the branch will
 
1276
        # be write-locked.
 
1277
        self['set_rh'] = []
 
1278
        # Invoked after a branch is opened. The api signature is (branch).
 
1279
        self['open'] = []
 
1280
        # invoked after a push operation completes.
 
1281
        # the api signature is
 
1282
        # (push_result)
 
1283
        # containing the members
 
1284
        # (source, local, master, old_revno, old_revid, new_revno, new_revid)
 
1285
        # where local is the local target branch or None, master is the target
 
1286
        # master branch, and the rest should be self explanatory. The source
 
1287
        # is read locked and the target branches write locked. Source will
 
1288
        # be the local low-latency branch.
 
1289
        self['post_push'] = []
 
1290
        # invoked after a pull operation completes.
 
1291
        # the api signature is
 
1292
        # (pull_result)
 
1293
        # containing the members
 
1294
        # (source, local, master, old_revno, old_revid, new_revno, new_revid)
 
1295
        # where local is the local branch or None, master is the target
 
1296
        # master branch, and the rest should be self explanatory. The source
 
1297
        # is read locked and the target branches write locked. The local
 
1298
        # branch is the low-latency branch.
 
1299
        self['post_pull'] = []
 
1300
        # invoked before a commit operation takes place.
 
1301
        # the api signature is
 
1302
        # (local, master, old_revno, old_revid, future_revno, future_revid,
 
1303
        #  tree_delta, future_tree).
 
1304
        # old_revid is NULL_REVISION for the first commit to a branch
 
1305
        # tree_delta is a TreeDelta object describing changes from the basis
 
1306
        # revision, hooks MUST NOT modify this delta
 
1307
        # future_tree is an in-memory tree obtained from
 
1308
        # CommitBuilder.revision_tree() and hooks MUST NOT modify this tree
 
1309
        self['pre_commit'] = []
 
1310
        # invoked after a commit operation completes.
 
1311
        # the api signature is
 
1312
        # (local, master, old_revno, old_revid, new_revno, new_revid)
 
1313
        # old_revid is NULL_REVISION for the first commit to a branch.
 
1314
        self['post_commit'] = []
 
1315
        # invoked after a uncommit operation completes.
 
1316
        # the api signature is
 
1317
        # (local, master, old_revno, old_revid, new_revno, new_revid) where
 
1318
        # local is the local branch or None, master is the target branch,
 
1319
        # and an empty branch recieves new_revno of 0, new_revid of None.
 
1320
        self['post_uncommit'] = []
 
1321
        # Introduced in 1.6
 
1322
        # Invoked before the tip of a branch changes.
 
1323
        # the api signature is
 
1324
        # (params) where params is a ChangeBranchTipParams with the members
 
1325
        # (branch, old_revno, new_revno, old_revid, new_revid)
 
1326
        self['pre_change_branch_tip'] = []
 
1327
        # Introduced in 1.4
 
1328
        # Invoked after the tip of a branch changes.
 
1329
        # the api signature is
 
1330
        # (params) where params is a ChangeBranchTipParams with the members
 
1331
        # (branch, old_revno, new_revno, old_revid, new_revid)
 
1332
        self['post_change_branch_tip'] = []
 
1333
        # Introduced in 1.9
 
1334
        # Invoked when a stacked branch activates its fallback locations and
 
1335
        # allows the transformation of the url of said location.
 
1336
        # the api signature is
 
1337
        # (branch, url) where branch is the branch having its fallback
 
1338
        # location activated and url is the url for the fallback location.
 
1339
        # The hook should return a url.
 
1340
        self['transform_fallback_location'] = []
 
1341
 
 
1342
 
 
1343
# install the default hooks into the Branch class.
 
1344
Branch.hooks = BranchHooks()
 
1345
 
 
1346
 
 
1347
class ChangeBranchTipParams(object):
 
1348
    """Object holding parameters passed to *_change_branch_tip hooks.
 
1349
 
 
1350
    There are 5 fields that hooks may wish to access:
 
1351
 
 
1352
    :ivar branch: the branch being changed
 
1353
    :ivar old_revno: revision number before the change
 
1354
    :ivar new_revno: revision number after the change
 
1355
    :ivar old_revid: revision id before the change
 
1356
    :ivar new_revid: revision id after the change
 
1357
 
 
1358
    The revid fields are strings. The revno fields are integers.
 
1359
    """
 
1360
 
 
1361
    def __init__(self, branch, old_revno, new_revno, old_revid, new_revid):
 
1362
        """Create a group of ChangeBranchTip parameters.
 
1363
 
 
1364
        :param branch: The branch being changed.
 
1365
        :param old_revno: Revision number before the change.
 
1366
        :param new_revno: Revision number after the change.
 
1367
        :param old_revid: Tip revision id before the change.
 
1368
        :param new_revid: Tip revision id after the change.
 
1369
        """
 
1370
        self.branch = branch
 
1371
        self.old_revno = old_revno
 
1372
        self.new_revno = new_revno
 
1373
        self.old_revid = old_revid
 
1374
        self.new_revid = new_revid
 
1375
 
 
1376
    def __eq__(self, other):
 
1377
        return self.__dict__ == other.__dict__
 
1378
 
 
1379
    def __repr__(self):
 
1380
        return "<%s of %s from (%s, %s) to (%s, %s)>" % (
 
1381
            self.__class__.__name__, self.branch,
 
1382
            self.old_revno, self.old_revid, self.new_revno, self.new_revid)
 
1383
 
 
1384
 
 
1385
class BzrBranchFormat4(BranchFormat):
 
1386
    """Bzr branch format 4.
 
1387
 
 
1388
    This format has:
 
1389
     - a revision-history file.
 
1390
     - a branch-lock lock file [ to be shared with the bzrdir ]
 
1391
    """
 
1392
 
 
1393
    def get_format_description(self):
 
1394
        """See BranchFormat.get_format_description()."""
 
1395
        return "Branch format 4"
 
1396
 
 
1397
    def initialize(self, a_bzrdir):
 
1398
        """Create a branch of this format in a_bzrdir."""
 
1399
        utf8_files = [('revision-history', ''),
 
1400
                      ('branch-name', ''),
 
1401
                      ]
 
1402
        return self._initialize_helper(a_bzrdir, utf8_files,
 
1403
                                       lock_type='branch4', set_format=False)
 
1404
 
 
1405
    def __init__(self):
 
1406
        super(BzrBranchFormat4, self).__init__()
 
1407
        self._matchingbzrdir = bzrdir.BzrDirFormat6()
 
1408
 
 
1409
    def open(self, a_bzrdir, _found=False):
 
1410
        """Return the branch object for a_bzrdir
 
1411
 
 
1412
        _found is a private parameter, do not use it. It is used to indicate
 
1413
               if format probing has already be done.
 
1414
        """
 
1415
        if not _found:
 
1416
            # we are being called directly and must probe.
 
1417
            raise NotImplementedError
 
1418
        return BzrBranch(_format=self,
 
1419
                         _control_files=a_bzrdir._control_files,
 
1420
                         a_bzrdir=a_bzrdir,
 
1421
                         _repository=a_bzrdir.open_repository())
 
1422
 
 
1423
    def __str__(self):
 
1424
        return "Bazaar-NG branch format 4"
 
1425
 
 
1426
 
 
1427
class BranchFormatMetadir(BranchFormat):
 
1428
    """Common logic for meta-dir based branch formats."""
 
1429
 
 
1430
    def _branch_class(self):
 
1431
        """What class to instantiate on open calls."""
 
1432
        raise NotImplementedError(self._branch_class)
 
1433
 
 
1434
    def open(self, a_bzrdir, _found=False):
 
1435
        """Return the branch object for a_bzrdir.
 
1436
 
 
1437
        _found is a private parameter, do not use it. It is used to indicate
 
1438
               if format probing has already be done.
 
1439
        """
 
1440
        if not _found:
 
1441
            format = BranchFormat.find_format(a_bzrdir)
 
1442
            if format.__class__ != self.__class__:
 
1443
                raise AssertionError("wrong format %r found for %r" %
 
1444
                    (format, self))
 
1445
        try:
 
1446
            transport = a_bzrdir.get_branch_transport(None)
 
1447
            control_files = lockable_files.LockableFiles(transport, 'lock',
 
1448
                                                         lockdir.LockDir)
 
1449
            return self._branch_class()(_format=self,
 
1450
                              _control_files=control_files,
 
1451
                              a_bzrdir=a_bzrdir,
 
1452
                              _repository=a_bzrdir.find_repository())
 
1453
        except errors.NoSuchFile:
 
1454
            raise errors.NotBranchError(path=transport.base)
 
1455
 
 
1456
    def __init__(self):
 
1457
        super(BranchFormatMetadir, self).__init__()
 
1458
        self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
 
1459
        self._matchingbzrdir.set_branch_format(self)
 
1460
 
 
1461
    def supports_tags(self):
 
1462
        return True
 
1463
 
 
1464
 
 
1465
class BzrBranchFormat5(BranchFormatMetadir):
 
1466
    """Bzr branch format 5.
 
1467
 
 
1468
    This format has:
 
1469
     - a revision-history file.
 
1470
     - a format string
 
1471
     - a lock dir guarding the branch itself
 
1472
     - all of this stored in a branch/ subdirectory
 
1473
     - works with shared repositories.
 
1474
 
 
1475
    This format is new in bzr 0.8.
 
1476
    """
 
1477
 
 
1478
    def _branch_class(self):
 
1479
        return BzrBranch5
 
1480
 
 
1481
    def get_format_string(self):
 
1482
        """See BranchFormat.get_format_string()."""
 
1483
        return "Bazaar-NG branch format 5\n"
 
1484
 
 
1485
    def get_format_description(self):
 
1486
        """See BranchFormat.get_format_description()."""
 
1487
        return "Branch format 5"
 
1488
 
 
1489
    def initialize(self, a_bzrdir):
 
1490
        """Create a branch of this format in a_bzrdir."""
 
1491
        utf8_files = [('revision-history', ''),
 
1492
                      ('branch-name', ''),
 
1493
                      ]
 
1494
        return self._initialize_helper(a_bzrdir, utf8_files)
 
1495
 
 
1496
    def supports_tags(self):
 
1497
        return False
 
1498
 
 
1499
 
 
1500
class BzrBranchFormat6(BranchFormatMetadir):
 
1501
    """Branch format with last-revision and tags.
 
1502
 
 
1503
    Unlike previous formats, this has no explicit revision history. Instead,
 
1504
    this just stores the last-revision, and the left-hand history leading
 
1505
    up to there is the history.
 
1506
 
 
1507
    This format was introduced in bzr 0.15
 
1508
    and became the default in 0.91.
 
1509
    """
 
1510
 
 
1511
    def _branch_class(self):
 
1512
        return BzrBranch6
 
1513
 
 
1514
    def get_format_string(self):
 
1515
        """See BranchFormat.get_format_string()."""
 
1516
        return "Bazaar Branch Format 6 (bzr 0.15)\n"
 
1517
 
 
1518
    def get_format_description(self):
 
1519
        """See BranchFormat.get_format_description()."""
 
1520
        return "Branch format 6"
 
1521
 
 
1522
    def initialize(self, a_bzrdir):
 
1523
        """Create a branch of this format in a_bzrdir."""
 
1524
        utf8_files = [('last-revision', '0 null:\n'),
 
1525
                      ('branch.conf', ''),
 
1526
                      ('tags', ''),
 
1527
                      ]
 
1528
        return self._initialize_helper(a_bzrdir, utf8_files)
 
1529
 
 
1530
 
 
1531
class BzrBranchFormat7(BranchFormatMetadir):
 
1532
    """Branch format with last-revision, tags, and a stacked location pointer.
 
1533
 
 
1534
    The stacked location pointer is passed down to the repository and requires
 
1535
    a repository format with supports_external_lookups = True.
 
1536
 
 
1537
    This format was introduced in bzr 1.6.
 
1538
    """
 
1539
 
 
1540
    def _branch_class(self):
 
1541
        return BzrBranch7
 
1542
 
 
1543
    def get_format_string(self):
 
1544
        """See BranchFormat.get_format_string()."""
 
1545
        return "Bazaar Branch Format 7 (needs bzr 1.6)\n"
 
1546
 
 
1547
    def get_format_description(self):
 
1548
        """See BranchFormat.get_format_description()."""
 
1549
        return "Branch format 7"
 
1550
 
 
1551
    def initialize(self, a_bzrdir):
 
1552
        """Create a branch of this format in a_bzrdir."""
 
1553
        utf8_files = [('last-revision', '0 null:\n'),
 
1554
                      ('branch.conf', ''),
 
1555
                      ('tags', ''),
 
1556
                      ]
 
1557
        return self._initialize_helper(a_bzrdir, utf8_files)
 
1558
 
 
1559
    def __init__(self):
 
1560
        super(BzrBranchFormat7, self).__init__()
 
1561
        self._matchingbzrdir.repository_format = \
 
1562
            RepositoryFormatKnitPack5RichRoot()
 
1563
 
 
1564
    def supports_stacking(self):
 
1565
        return True
 
1566
 
 
1567
 
 
1568
class BranchReferenceFormat(BranchFormat):
 
1569
    """Bzr branch reference format.
 
1570
 
 
1571
    Branch references are used in implementing checkouts, they
 
1572
    act as an alias to the real branch which is at some other url.
 
1573
 
 
1574
    This format has:
 
1575
     - A location file
 
1576
     - a format string
 
1577
    """
 
1578
 
 
1579
    def get_format_string(self):
 
1580
        """See BranchFormat.get_format_string()."""
 
1581
        return "Bazaar-NG Branch Reference Format 1\n"
 
1582
 
 
1583
    def get_format_description(self):
 
1584
        """See BranchFormat.get_format_description()."""
 
1585
        return "Checkout reference format 1"
 
1586
 
 
1587
    def get_reference(self, a_bzrdir):
 
1588
        """See BranchFormat.get_reference()."""
 
1589
        transport = a_bzrdir.get_branch_transport(None)
 
1590
        return transport.get('location').read()
 
1591
 
 
1592
    def set_reference(self, a_bzrdir, to_branch):
 
1593
        """See BranchFormat.set_reference()."""
 
1594
        transport = a_bzrdir.get_branch_transport(None)
 
1595
        location = transport.put_bytes('location', to_branch.base)
 
1596
 
 
1597
    def initialize(self, a_bzrdir, target_branch=None):
 
1598
        """Create a branch of this format in a_bzrdir."""
 
1599
        if target_branch is None:
 
1600
            # this format does not implement branch itself, thus the implicit
 
1601
            # creation contract must see it as uninitializable
 
1602
            raise errors.UninitializableFormat(self)
 
1603
        mutter('creating branch reference in %s', a_bzrdir.transport.base)
 
1604
        branch_transport = a_bzrdir.get_branch_transport(self)
 
1605
        branch_transport.put_bytes('location',
 
1606
            target_branch.bzrdir.root_transport.base)
 
1607
        branch_transport.put_bytes('format', self.get_format_string())
 
1608
        return self.open(
 
1609
            a_bzrdir, _found=True,
 
1610
            possible_transports=[target_branch.bzrdir.root_transport])
 
1611
 
 
1612
    def __init__(self):
 
1613
        super(BranchReferenceFormat, self).__init__()
 
1614
        self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
 
1615
        self._matchingbzrdir.set_branch_format(self)
 
1616
 
 
1617
    def _make_reference_clone_function(format, a_branch):
 
1618
        """Create a clone() routine for a branch dynamically."""
 
1619
        def clone(to_bzrdir, revision_id=None):
 
1620
            """See Branch.clone()."""
 
1621
            return format.initialize(to_bzrdir, a_branch)
 
1622
            # cannot obey revision_id limits when cloning a reference ...
 
1623
            # FIXME RBC 20060210 either nuke revision_id for clone, or
 
1624
            # emit some sort of warning/error to the caller ?!
 
1625
        return clone
 
1626
 
 
1627
    def open(self, a_bzrdir, _found=False, location=None,
 
1628
             possible_transports=None):
 
1629
        """Return the branch that the branch reference in a_bzrdir points at.
 
1630
 
 
1631
        _found is a private parameter, do not use it. It is used to indicate
 
1632
               if format probing has already be done.
 
1633
        """
 
1634
        if not _found:
 
1635
            format = BranchFormat.find_format(a_bzrdir)
 
1636
            if format.__class__ != self.__class__:
 
1637
                raise AssertionError("wrong format %r found for %r" %
 
1638
                    (format, self))
 
1639
        if location is None:
 
1640
            location = self.get_reference(a_bzrdir)
 
1641
        real_bzrdir = bzrdir.BzrDir.open(
 
1642
            location, possible_transports=possible_transports)
 
1643
        result = real_bzrdir.open_branch()
 
1644
        # this changes the behaviour of result.clone to create a new reference
 
1645
        # rather than a copy of the content of the branch.
 
1646
        # I did not use a proxy object because that needs much more extensive
 
1647
        # testing, and we are only changing one behaviour at the moment.
 
1648
        # If we decide to alter more behaviours - i.e. the implicit nickname
 
1649
        # then this should be refactored to introduce a tested proxy branch
 
1650
        # and a subclass of that for use in overriding clone() and ....
 
1651
        # - RBC 20060210
 
1652
        result.clone = self._make_reference_clone_function(result)
 
1653
        return result
 
1654
 
 
1655
 
 
1656
# formats which have no format string are not discoverable
 
1657
# and not independently creatable, so are not registered.
 
1658
__format5 = BzrBranchFormat5()
 
1659
__format6 = BzrBranchFormat6()
 
1660
__format7 = BzrBranchFormat7()
 
1661
BranchFormat.register_format(__format5)
 
1662
BranchFormat.register_format(BranchReferenceFormat())
 
1663
BranchFormat.register_format(__format6)
 
1664
BranchFormat.register_format(__format7)
 
1665
BranchFormat.set_default_format(__format6)
 
1666
_legacy_formats = [BzrBranchFormat4(),
 
1667
                   ]
 
1668
 
 
1669
class BzrBranch(Branch):
 
1670
    """A branch stored in the actual filesystem.
 
1671
 
 
1672
    Note that it's "local" in the context of the filesystem; it doesn't
 
1673
    really matter if it's on an nfs/smb/afs/coda/... share, as long as
 
1674
    it's writable, and can be accessed via the normal filesystem API.
 
1675
 
 
1676
    :ivar _transport: Transport for file operations on this branch's
 
1677
        control files, typically pointing to the .bzr/branch directory.
 
1678
    :ivar repository: Repository for this branch.
 
1679
    :ivar base: The url of the base directory for this branch; the one
 
1680
        containing the .bzr directory.
 
1681
    """
 
1682
 
 
1683
    def __init__(self, _format=None,
 
1684
                 _control_files=None, a_bzrdir=None, _repository=None):
 
1685
        """Create new branch object at a particular location."""
 
1686
        if a_bzrdir is None:
 
1687
            raise ValueError('a_bzrdir must be supplied')
 
1688
        else:
 
1689
            self.bzrdir = a_bzrdir
 
1690
        self._base = self.bzrdir.transport.clone('..').base
 
1691
        # XXX: We should be able to just do
 
1692
        #   self.base = self.bzrdir.root_transport.base
 
1693
        # but this does not quite work yet -- mbp 20080522
 
1694
        self._format = _format
 
1695
        if _control_files is None:
 
1696
            raise ValueError('BzrBranch _control_files is None')
 
1697
        self.control_files = _control_files
 
1698
        self._transport = _control_files._transport
 
1699
        self.repository = _repository
 
1700
        Branch.__init__(self)
 
1701
 
 
1702
    def __str__(self):
 
1703
        return '%s(%r)' % (self.__class__.__name__, self.base)
 
1704
 
 
1705
    __repr__ = __str__
 
1706
 
 
1707
    def _get_base(self):
 
1708
        """Returns the directory containing the control directory."""
 
1709
        return self._base
 
1710
 
 
1711
    base = property(_get_base, doc="The URL for the root of this branch.")
 
1712
 
 
1713
    def is_locked(self):
 
1714
        return self.control_files.is_locked()
 
1715
 
 
1716
    def lock_write(self, token=None):
 
1717
        repo_token = self.repository.lock_write()
 
1718
        try:
 
1719
            token = self.control_files.lock_write(token=token)
 
1720
        except:
 
1721
            self.repository.unlock()
 
1722
            raise
 
1723
        return token
 
1724
 
 
1725
    def lock_read(self):
 
1726
        self.repository.lock_read()
 
1727
        try:
 
1728
            self.control_files.lock_read()
 
1729
        except:
 
1730
            self.repository.unlock()
 
1731
            raise
 
1732
 
 
1733
    def unlock(self):
 
1734
        # TODO: test for failed two phase locks. This is known broken.
 
1735
        try:
 
1736
            self.control_files.unlock()
 
1737
        finally:
 
1738
            self.repository.unlock()
 
1739
        if not self.control_files.is_locked():
 
1740
            # we just released the lock
 
1741
            self._clear_cached_state()
 
1742
 
 
1743
    def peek_lock_mode(self):
 
1744
        if self.control_files._lock_count == 0:
 
1745
            return None
 
1746
        else:
 
1747
            return self.control_files._lock_mode
 
1748
 
 
1749
    def get_physical_lock_status(self):
 
1750
        return self.control_files.get_physical_lock_status()
 
1751
 
 
1752
    @needs_read_lock
 
1753
    def print_file(self, file, revision_id):
 
1754
        """See Branch.print_file."""
 
1755
        return self.repository.print_file(file, revision_id)
 
1756
 
 
1757
    def _write_revision_history(self, history):
 
1758
        """Factored out of set_revision_history.
 
1759
 
 
1760
        This performs the actual writing to disk.
 
1761
        It is intended to be called by BzrBranch5.set_revision_history."""
 
1762
        self._transport.put_bytes(
 
1763
            'revision-history', '\n'.join(history),
 
1764
            mode=self.bzrdir._get_file_mode())
 
1765
 
 
1766
    @needs_write_lock
 
1767
    def set_revision_history(self, rev_history):
 
1768
        """See Branch.set_revision_history."""
 
1769
        if 'evil' in debug.debug_flags:
 
1770
            mutter_callsite(3, "set_revision_history scales with history.")
 
1771
        check_not_reserved_id = _mod_revision.check_not_reserved_id
 
1772
        for rev_id in rev_history:
 
1773
            check_not_reserved_id(rev_id)
 
1774
        if Branch.hooks['post_change_branch_tip']:
 
1775
            # Don't calculate the last_revision_info() if there are no hooks
 
1776
            # that will use it.
 
1777
            old_revno, old_revid = self.last_revision_info()
 
1778
        if len(rev_history) == 0:
 
1779
            revid = _mod_revision.NULL_REVISION
 
1780
        else:
 
1781
            revid = rev_history[-1]
 
1782
        self._run_pre_change_branch_tip_hooks(len(rev_history), revid)
 
1783
        self._write_revision_history(rev_history)
 
1784
        self._clear_cached_state()
 
1785
        self._cache_revision_history(rev_history)
 
1786
        for hook in Branch.hooks['set_rh']:
 
1787
            hook(self, rev_history)
 
1788
        if Branch.hooks['post_change_branch_tip']:
 
1789
            self._run_post_change_branch_tip_hooks(old_revno, old_revid)
 
1790
 
 
1791
    def _synchronize_history(self, destination, revision_id):
 
1792
        """Synchronize last revision and revision history between branches.
 
1793
 
 
1794
        This version is most efficient when the destination is also a
 
1795
        BzrBranch5, but works for BzrBranch6 as long as the revision
 
1796
        history is the true lefthand parent history, and all of the revisions
 
1797
        are in the destination's repository.  If not, set_revision_history
 
1798
        will fail.
 
1799
 
 
1800
        :param destination: The branch to copy the history into
 
1801
        :param revision_id: The revision-id to truncate history at.  May
 
1802
          be None to copy complete history.
 
1803
        """
 
1804
        if not isinstance(destination._format, BzrBranchFormat5):
 
1805
            super(BzrBranch, self)._synchronize_history(
 
1806
                destination, revision_id)
 
1807
            return
 
1808
        if revision_id == _mod_revision.NULL_REVISION:
 
1809
            new_history = []
 
1810
        else:
 
1811
            new_history = self.revision_history()
 
1812
        if revision_id is not None and new_history != []:
 
1813
            try:
 
1814
                new_history = new_history[:new_history.index(revision_id) + 1]
 
1815
            except ValueError:
 
1816
                rev = self.repository.get_revision(revision_id)
 
1817
                new_history = rev.get_history(self.repository)[1:]
 
1818
        destination.set_revision_history(new_history)
 
1819
 
 
1820
    @needs_write_lock
 
1821
    def set_last_revision_info(self, revno, revision_id):
 
1822
        """Set the last revision of this branch.
 
1823
 
 
1824
        The caller is responsible for checking that the revno is correct
 
1825
        for this revision id.
 
1826
 
 
1827
        It may be possible to set the branch last revision to an id not
 
1828
        present in the repository.  However, branches can also be
 
1829
        configured to check constraints on history, in which case this may not
 
1830
        be permitted.
 
1831
        """
 
1832
        revision_id = _mod_revision.ensure_null(revision_id)
 
1833
        # this old format stores the full history, but this api doesn't
 
1834
        # provide it, so we must generate, and might as well check it's
 
1835
        # correct
 
1836
        history = self._lefthand_history(revision_id)
 
1837
        if len(history) != revno:
 
1838
            raise AssertionError('%d != %d' % (len(history), revno))
 
1839
        self.set_revision_history(history)
 
1840
 
 
1841
    def _gen_revision_history(self):
 
1842
        history = self._transport.get_bytes('revision-history').split('\n')
 
1843
        if history[-1:] == ['']:
 
1844
            # There shouldn't be a trailing newline, but just in case.
 
1845
            history.pop()
 
1846
        return history
 
1847
 
 
1848
    @needs_write_lock
 
1849
    def generate_revision_history(self, revision_id, last_rev=None,
 
1850
        other_branch=None):
 
1851
        """Create a new revision history that will finish with revision_id.
 
1852
 
 
1853
        :param revision_id: the new tip to use.
 
1854
        :param last_rev: The previous last_revision. If not None, then this
 
1855
            must be a ancestory of revision_id, or DivergedBranches is raised.
 
1856
        :param other_branch: The other branch that DivergedBranches should
 
1857
            raise with respect to.
 
1858
        """
 
1859
        self.set_revision_history(self._lefthand_history(revision_id,
 
1860
            last_rev, other_branch))
 
1861
 
 
1862
    def basis_tree(self):
 
1863
        """See Branch.basis_tree."""
 
1864
        return self.repository.revision_tree(self.last_revision())
 
1865
 
 
1866
    @needs_write_lock
 
1867
    def pull(self, source, overwrite=False, stop_revision=None,
 
1868
             _hook_master=None, run_hooks=True, possible_transports=None,
 
1869
             _override_hook_target=None):
 
1870
        """See Branch.pull.
 
1871
 
 
1872
        :param _hook_master: Private parameter - set the branch to
 
1873
            be supplied as the master to pull hooks.
 
1874
        :param run_hooks: Private parameter - if false, this branch
 
1875
            is being called because it's the master of the primary branch,
 
1876
            so it should not run its hooks.
 
1877
        :param _override_hook_target: Private parameter - set the branch to be
 
1878
            supplied as the target_branch to pull hooks.
 
1879
        """
 
1880
        result = PullResult()
 
1881
        result.source_branch = source
 
1882
        if _override_hook_target is None:
 
1883
            result.target_branch = self
 
1884
        else:
 
1885
            result.target_branch = _override_hook_target
 
1886
        source.lock_read()
 
1887
        try:
 
1888
            # We assume that during 'pull' the local repository is closer than
 
1889
            # the remote one.
 
1890
            graph = self.repository.get_graph(source.repository)
 
1891
            result.old_revno, result.old_revid = self.last_revision_info()
 
1892
            self.update_revisions(source, stop_revision, overwrite=overwrite,
 
1893
                                  graph=graph)
 
1894
            result.tag_conflicts = source.tags.merge_to(self.tags, overwrite)
 
1895
            result.new_revno, result.new_revid = self.last_revision_info()
 
1896
            if _hook_master:
 
1897
                result.master_branch = _hook_master
 
1898
                result.local_branch = result.target_branch
 
1899
            else:
 
1900
                result.master_branch = result.target_branch
 
1901
                result.local_branch = None
 
1902
            if run_hooks:
 
1903
                for hook in Branch.hooks['post_pull']:
 
1904
                    hook(result)
 
1905
        finally:
 
1906
            source.unlock()
 
1907
        return result
 
1908
 
 
1909
    def _get_parent_location(self):
 
1910
        _locs = ['parent', 'pull', 'x-pull']
 
1911
        for l in _locs:
 
1912
            try:
 
1913
                return self._transport.get_bytes(l).strip('\n')
 
1914
            except errors.NoSuchFile:
 
1915
                pass
 
1916
        return None
 
1917
 
 
1918
    @needs_read_lock
 
1919
    def push(self, target, overwrite=False, stop_revision=None,
 
1920
             _override_hook_source_branch=None):
 
1921
        """See Branch.push.
 
1922
 
 
1923
        This is the basic concrete implementation of push()
 
1924
 
 
1925
        :param _override_hook_source_branch: If specified, run
 
1926
        the hooks passing this Branch as the source, rather than self.
 
1927
        This is for use of RemoteBranch, where push is delegated to the
 
1928
        underlying vfs-based Branch.
 
1929
        """
 
1930
        # TODO: Public option to disable running hooks - should be trivial but
 
1931
        # needs tests.
 
1932
        return _run_with_write_locked_target(
 
1933
            target, self._push_with_bound_branches, target, overwrite,
 
1934
            stop_revision,
 
1935
            _override_hook_source_branch=_override_hook_source_branch)
 
1936
 
 
1937
    def _push_with_bound_branches(self, target, overwrite,
 
1938
            stop_revision,
 
1939
            _override_hook_source_branch=None):
 
1940
        """Push from self into target, and into target's master if any.
 
1941
 
 
1942
        This is on the base BzrBranch class even though it doesn't support
 
1943
        bound branches because the *target* might be bound.
 
1944
        """
 
1945
        def _run_hooks():
 
1946
            if _override_hook_source_branch:
 
1947
                result.source_branch = _override_hook_source_branch
 
1948
            for hook in Branch.hooks['post_push']:
 
1949
                hook(result)
 
1950
 
 
1951
        bound_location = target.get_bound_location()
 
1952
        if bound_location and target.base != bound_location:
 
1953
            # there is a master branch.
 
1954
            #
 
1955
            # XXX: Why the second check?  Is it even supported for a branch to
 
1956
            # be bound to itself? -- mbp 20070507
 
1957
            master_branch = target.get_master_branch()
 
1958
            master_branch.lock_write()
 
1959
            try:
 
1960
                # push into the master from this branch.
 
1961
                self._basic_push(master_branch, overwrite, stop_revision)
 
1962
                # and push into the target branch from this. Note that we push from
 
1963
                # this branch again, because its considered the highest bandwidth
 
1964
                # repository.
 
1965
                result = self._basic_push(target, overwrite, stop_revision)
 
1966
                result.master_branch = master_branch
 
1967
                result.local_branch = target
 
1968
                _run_hooks()
 
1969
                return result
 
1970
            finally:
 
1971
                master_branch.unlock()
 
1972
        else:
 
1973
            # no master branch
 
1974
            result = self._basic_push(target, overwrite, stop_revision)
 
1975
            # TODO: Why set master_branch and local_branch if there's no
 
1976
            # binding?  Maybe cleaner to just leave them unset? -- mbp
 
1977
            # 20070504
 
1978
            result.master_branch = target
 
1979
            result.local_branch = None
 
1980
            _run_hooks()
 
1981
            return result
 
1982
 
 
1983
    def _basic_push(self, target, overwrite, stop_revision):
 
1984
        """Basic implementation of push without bound branches or hooks.
 
1985
 
 
1986
        Must be called with self read locked and target write locked.
 
1987
        """
 
1988
        result = PushResult()
 
1989
        result.source_branch = self
 
1990
        result.target_branch = target
 
1991
        result.old_revno, result.old_revid = target.last_revision_info()
 
1992
        if result.old_revid != self.last_revision():
 
1993
            # We assume that during 'push' this repository is closer than
 
1994
            # the target.
 
1995
            graph = self.repository.get_graph(target.repository)
 
1996
            target.update_revisions(self, stop_revision, overwrite=overwrite,
 
1997
                                    graph=graph)
 
1998
        if self._push_should_merge_tags():
 
1999
            result.tag_conflicts = self.tags.merge_to(target.tags, overwrite)
 
2000
        result.new_revno, result.new_revid = target.last_revision_info()
 
2001
        return result
 
2002
 
 
2003
    def _push_should_merge_tags(self):
 
2004
        """Should _basic_push merge this branch's tags into the target?
 
2005
 
 
2006
        The default implementation returns False if this branch has no tags,
 
2007
        and True the rest of the time.  Subclasses may override this.
 
2008
        """
 
2009
        return self.tags.supports_tags() and self.tags.get_tag_dict()
 
2010
 
 
2011
    def get_parent(self):
 
2012
        """See Branch.get_parent."""
 
2013
        parent = self._get_parent_location()
 
2014
        if parent is None:
 
2015
            return parent
 
2016
        # This is an old-format absolute path to a local branch
 
2017
        # turn it into a url
 
2018
        if parent.startswith('/'):
 
2019
            parent = urlutils.local_path_to_url(parent.decode('utf8'))
 
2020
        try:
 
2021
            return urlutils.join(self.base[:-1], parent)
 
2022
        except errors.InvalidURLJoin, e:
 
2023
            raise errors.InaccessibleParent(parent, self.base)
 
2024
 
 
2025
    def get_stacked_on_url(self):
 
2026
        raise errors.UnstackableBranchFormat(self._format, self.base)
 
2027
 
 
2028
    def set_push_location(self, location):
 
2029
        """See Branch.set_push_location."""
 
2030
        self.get_config().set_user_option(
 
2031
            'push_location', location,
 
2032
            store=_mod_config.STORE_LOCATION_NORECURSE)
 
2033
 
 
2034
    @needs_write_lock
 
2035
    def set_parent(self, url):
 
2036
        """See Branch.set_parent."""
 
2037
        # TODO: Maybe delete old location files?
 
2038
        # URLs should never be unicode, even on the local fs,
 
2039
        # FIXUP this and get_parent in a future branch format bump:
 
2040
        # read and rewrite the file. RBC 20060125
 
2041
        if url is not None:
 
2042
            if isinstance(url, unicode):
 
2043
                try:
 
2044
                    url = url.encode('ascii')
 
2045
                except UnicodeEncodeError:
 
2046
                    raise errors.InvalidURL(url,
 
2047
                        "Urls must be 7-bit ascii, "
 
2048
                        "use bzrlib.urlutils.escape")
 
2049
            url = urlutils.relative_url(self.base, url)
 
2050
        self._set_parent_location(url)
 
2051
 
 
2052
    def _set_parent_location(self, url):
 
2053
        if url is None:
 
2054
            self._transport.delete('parent')
 
2055
        else:
 
2056
            self._transport.put_bytes('parent', url + '\n',
 
2057
                mode=self.bzrdir._get_file_mode())
 
2058
 
 
2059
    def set_stacked_on_url(self, url):
 
2060
        raise errors.UnstackableBranchFormat(self._format, self.base)
 
2061
 
 
2062
 
 
2063
class BzrBranch5(BzrBranch):
 
2064
    """A format 5 branch. This supports new features over plain branches.
 
2065
 
 
2066
    It has support for a master_branch which is the data for bound branches.
 
2067
    """
 
2068
 
 
2069
    @needs_write_lock
 
2070
    def pull(self, source, overwrite=False, stop_revision=None,
 
2071
             run_hooks=True, possible_transports=None,
 
2072
             _override_hook_target=None):
 
2073
        """Pull from source into self, updating my master if any.
 
2074
 
 
2075
        :param run_hooks: Private parameter - if false, this branch
 
2076
            is being called because it's the master of the primary branch,
 
2077
            so it should not run its hooks.
 
2078
        """
 
2079
        bound_location = self.get_bound_location()
 
2080
        master_branch = None
 
2081
        if bound_location and source.base != bound_location:
 
2082
            # not pulling from master, so we need to update master.
 
2083
            master_branch = self.get_master_branch(possible_transports)
 
2084
            master_branch.lock_write()
 
2085
        try:
 
2086
            if master_branch:
 
2087
                # pull from source into master.
 
2088
                master_branch.pull(source, overwrite, stop_revision,
 
2089
                    run_hooks=False)
 
2090
            return super(BzrBranch5, self).pull(source, overwrite,
 
2091
                stop_revision, _hook_master=master_branch,
 
2092
                run_hooks=run_hooks,
 
2093
                _override_hook_target=_override_hook_target)
 
2094
        finally:
 
2095
            if master_branch:
 
2096
                master_branch.unlock()
 
2097
 
 
2098
    def get_bound_location(self):
 
2099
        try:
 
2100
            return self._transport.get_bytes('bound')[:-1]
 
2101
        except errors.NoSuchFile:
 
2102
            return None
 
2103
 
 
2104
    @needs_read_lock
 
2105
    def get_master_branch(self, possible_transports=None):
 
2106
        """Return the branch we are bound to.
 
2107
 
 
2108
        :return: Either a Branch, or None
 
2109
 
 
2110
        This could memoise the branch, but if thats done
 
2111
        it must be revalidated on each new lock.
 
2112
        So for now we just don't memoise it.
 
2113
        # RBC 20060304 review this decision.
 
2114
        """
 
2115
        bound_loc = self.get_bound_location()
 
2116
        if not bound_loc:
 
2117
            return None
 
2118
        try:
 
2119
            return Branch.open(bound_loc,
 
2120
                               possible_transports=possible_transports)
 
2121
        except (errors.NotBranchError, errors.ConnectionError), e:
 
2122
            raise errors.BoundBranchConnectionFailure(
 
2123
                    self, bound_loc, e)
 
2124
 
 
2125
    @needs_write_lock
 
2126
    def set_bound_location(self, location):
 
2127
        """Set the target where this branch is bound to.
 
2128
 
 
2129
        :param location: URL to the target branch
 
2130
        """
 
2131
        if location:
 
2132
            self._transport.put_bytes('bound', location+'\n',
 
2133
                mode=self.bzrdir._get_file_mode())
 
2134
        else:
 
2135
            try:
 
2136
                self._transport.delete('bound')
 
2137
            except errors.NoSuchFile:
 
2138
                return False
 
2139
            return True
 
2140
 
 
2141
    @needs_write_lock
 
2142
    def bind(self, other):
 
2143
        """Bind this branch to the branch other.
 
2144
 
 
2145
        This does not push or pull data between the branches, though it does
 
2146
        check for divergence to raise an error when the branches are not
 
2147
        either the same, or one a prefix of the other. That behaviour may not
 
2148
        be useful, so that check may be removed in future.
 
2149
 
 
2150
        :param other: The branch to bind to
 
2151
        :type other: Branch
 
2152
        """
 
2153
        # TODO: jam 20051230 Consider checking if the target is bound
 
2154
        #       It is debatable whether you should be able to bind to
 
2155
        #       a branch which is itself bound.
 
2156
        #       Committing is obviously forbidden,
 
2157
        #       but binding itself may not be.
 
2158
        #       Since we *have* to check at commit time, we don't
 
2159
        #       *need* to check here
 
2160
 
 
2161
        # we want to raise diverged if:
 
2162
        # last_rev is not in the other_last_rev history, AND
 
2163
        # other_last_rev is not in our history, and do it without pulling
 
2164
        # history around
 
2165
        self.set_bound_location(other.base)
 
2166
 
 
2167
    @needs_write_lock
 
2168
    def unbind(self):
 
2169
        """If bound, unbind"""
 
2170
        return self.set_bound_location(None)
 
2171
 
 
2172
    @needs_write_lock
 
2173
    def update(self, possible_transports=None):
 
2174
        """Synchronise this branch with the master branch if any.
 
2175
 
 
2176
        :return: None or the last_revision that was pivoted out during the
 
2177
                 update.
 
2178
        """
 
2179
        master = self.get_master_branch(possible_transports)
 
2180
        if master is not None:
 
2181
            old_tip = _mod_revision.ensure_null(self.last_revision())
 
2182
            self.pull(master, overwrite=True)
 
2183
            if self.repository.get_graph().is_ancestor(old_tip,
 
2184
                _mod_revision.ensure_null(self.last_revision())):
 
2185
                return None
 
2186
            return old_tip
 
2187
        return None
 
2188
 
 
2189
 
 
2190
class BzrBranch7(BzrBranch5):
 
2191
    """A branch with support for a fallback repository."""
 
2192
 
 
2193
    def _get_fallback_repository(self, url):
 
2194
        """Get the repository we fallback to at url."""
 
2195
        url = urlutils.join(self.base, url)
 
2196
        a_bzrdir = bzrdir.BzrDir.open(url,
 
2197
                                      possible_transports=[self._transport])
 
2198
        return a_bzrdir.open_branch().repository
 
2199
 
 
2200
    def _activate_fallback_location(self, url):
 
2201
        """Activate the branch/repository from url as a fallback repository."""
 
2202
        self.repository.add_fallback_repository(
 
2203
            self._get_fallback_repository(url))
 
2204
 
 
2205
    def _open_hook(self):
 
2206
        try:
 
2207
            url = self.get_stacked_on_url()
 
2208
        except (errors.UnstackableRepositoryFormat, errors.NotStacked,
 
2209
            errors.UnstackableBranchFormat):
 
2210
            pass
 
2211
        else:
 
2212
            for hook in Branch.hooks['transform_fallback_location']:
 
2213
                url = hook(self, url)
 
2214
                if url is None:
 
2215
                    hook_name = Branch.hooks.get_hook_name(hook)
 
2216
                    raise AssertionError(
 
2217
                        "'transform_fallback_location' hook %s returned "
 
2218
                        "None, not a URL." % hook_name)
 
2219
            self._activate_fallback_location(url)
 
2220
 
 
2221
    def _check_stackable_repo(self):
 
2222
        if not self.repository._format.supports_external_lookups:
 
2223
            raise errors.UnstackableRepositoryFormat(self.repository._format,
 
2224
                self.repository.base)
 
2225
 
 
2226
    def __init__(self, *args, **kwargs):
 
2227
        super(BzrBranch7, self).__init__(*args, **kwargs)
 
2228
        self._last_revision_info_cache = None
 
2229
        self._partial_revision_history_cache = []
 
2230
 
 
2231
    def _clear_cached_state(self):
 
2232
        super(BzrBranch7, self)._clear_cached_state()
 
2233
        self._last_revision_info_cache = None
 
2234
        self._partial_revision_history_cache = []
 
2235
 
 
2236
    def _last_revision_info(self):
 
2237
        revision_string = self._transport.get_bytes('last-revision')
 
2238
        revno, revision_id = revision_string.rstrip('\n').split(' ', 1)
 
2239
        revision_id = cache_utf8.get_cached_utf8(revision_id)
 
2240
        revno = int(revno)
 
2241
        return revno, revision_id
 
2242
 
 
2243
    def _write_last_revision_info(self, revno, revision_id):
 
2244
        """Simply write out the revision id, with no checks.
 
2245
 
 
2246
        Use set_last_revision_info to perform this safely.
 
2247
 
 
2248
        Does not update the revision_history cache.
 
2249
        Intended to be called by set_last_revision_info and
 
2250
        _write_revision_history.
 
2251
        """
 
2252
        revision_id = _mod_revision.ensure_null(revision_id)
 
2253
        out_string = '%d %s\n' % (revno, revision_id)
 
2254
        self._transport.put_bytes('last-revision', out_string,
 
2255
            mode=self.bzrdir._get_file_mode())
 
2256
 
 
2257
    @needs_write_lock
 
2258
    def set_last_revision_info(self, revno, revision_id):
 
2259
        revision_id = _mod_revision.ensure_null(revision_id)
 
2260
        old_revno, old_revid = self.last_revision_info()
 
2261
        if self._get_append_revisions_only():
 
2262
            self._check_history_violation(revision_id)
 
2263
        self._run_pre_change_branch_tip_hooks(revno, revision_id)
 
2264
        self._write_last_revision_info(revno, revision_id)
 
2265
        self._clear_cached_state()
 
2266
        self._last_revision_info_cache = revno, revision_id
 
2267
        self._run_post_change_branch_tip_hooks(old_revno, old_revid)
 
2268
 
 
2269
    def _synchronize_history(self, destination, revision_id):
 
2270
        """Synchronize last revision and revision history between branches.
 
2271
 
 
2272
        :see: Branch._synchronize_history
 
2273
        """
 
2274
        # XXX: The base Branch has a fast implementation of this method based
 
2275
        # on set_last_revision_info, but BzrBranch/BzrBranch5 have a slower one
 
2276
        # that uses set_revision_history.  This class inherits from BzrBranch5,
 
2277
        # but wants the fast implementation, so it calls
 
2278
        # Branch._synchronize_history directly.
 
2279
        Branch._synchronize_history(self, destination, revision_id)
 
2280
 
 
2281
    def _check_history_violation(self, revision_id):
 
2282
        last_revision = _mod_revision.ensure_null(self.last_revision())
 
2283
        if _mod_revision.is_null(last_revision):
 
2284
            return
 
2285
        if last_revision not in self._lefthand_history(revision_id):
 
2286
            raise errors.AppendRevisionsOnlyViolation(self.base)
 
2287
 
 
2288
    def _gen_revision_history(self):
 
2289
        """Generate the revision history from last revision
 
2290
        """
 
2291
        last_revno, last_revision = self.last_revision_info()
 
2292
        self._extend_partial_history(stop_index=last_revno-1)
 
2293
        return list(reversed(self._partial_revision_history_cache))
 
2294
 
 
2295
    def _extend_partial_history(self, stop_index=None, stop_revision=None):
 
2296
        """Extend the partial history to include a given index
 
2297
 
 
2298
        If a stop_index is supplied, stop when that index has been reached.
 
2299
        If a stop_revision is supplied, stop when that revision is
 
2300
        encountered.  Otherwise, stop when the beginning of history is
 
2301
        reached.
 
2302
 
 
2303
        :param stop_index: The index which should be present.  When it is
 
2304
            present, history extension will stop.
 
2305
        :param revision_id: The revision id which should be present.  When
 
2306
            it is encountered, history extension will stop.
 
2307
        """
 
2308
        repo = self.repository
 
2309
        if len(self._partial_revision_history_cache) == 0:
 
2310
            iterator = repo.iter_reverse_revision_history(self.last_revision())
 
2311
        else:
 
2312
            start_revision = self._partial_revision_history_cache[-1]
 
2313
            iterator = repo.iter_reverse_revision_history(start_revision)
 
2314
            #skip the last revision in the list
 
2315
            next_revision = iterator.next()
 
2316
        for revision_id in iterator:
 
2317
            self._partial_revision_history_cache.append(revision_id)
 
2318
            if (stop_index is not None and
 
2319
                len(self._partial_revision_history_cache) > stop_index):
 
2320
                break
 
2321
            if revision_id == stop_revision:
 
2322
                break
 
2323
 
 
2324
    def _write_revision_history(self, history):
 
2325
        """Factored out of set_revision_history.
 
2326
 
 
2327
        This performs the actual writing to disk, with format-specific checks.
 
2328
        It is intended to be called by BzrBranch5.set_revision_history.
 
2329
        """
 
2330
        if len(history) == 0:
 
2331
            last_revision = 'null:'
 
2332
        else:
 
2333
            if history != self._lefthand_history(history[-1]):
 
2334
                raise errors.NotLefthandHistory(history)
 
2335
            last_revision = history[-1]
 
2336
        if self._get_append_revisions_only():
 
2337
            self._check_history_violation(last_revision)
 
2338
        self._write_last_revision_info(len(history), last_revision)
 
2339
 
 
2340
    @needs_write_lock
 
2341
    def _set_parent_location(self, url):
 
2342
        """Set the parent branch"""
 
2343
        self._set_config_location('parent_location', url, make_relative=True)
 
2344
 
 
2345
    @needs_read_lock
 
2346
    def _get_parent_location(self):
 
2347
        """Set the parent branch"""
 
2348
        return self._get_config_location('parent_location')
 
2349
 
 
2350
    def set_push_location(self, location):
 
2351
        """See Branch.set_push_location."""
 
2352
        self._set_config_location('push_location', location)
 
2353
 
 
2354
    def set_bound_location(self, location):
 
2355
        """See Branch.set_push_location."""
 
2356
        result = None
 
2357
        config = self.get_config()
 
2358
        if location is None:
 
2359
            if config.get_user_option('bound') != 'True':
 
2360
                return False
 
2361
            else:
 
2362
                config.set_user_option('bound', 'False', warn_masked=True)
 
2363
                return True
 
2364
        else:
 
2365
            self._set_config_location('bound_location', location,
 
2366
                                      config=config)
 
2367
            config.set_user_option('bound', 'True', warn_masked=True)
 
2368
        return True
 
2369
 
 
2370
    def _get_bound_location(self, bound):
 
2371
        """Return the bound location in the config file.
 
2372
 
 
2373
        Return None if the bound parameter does not match"""
 
2374
        config = self.get_config()
 
2375
        config_bound = (config.get_user_option('bound') == 'True')
 
2376
        if config_bound != bound:
 
2377
            return None
 
2378
        return self._get_config_location('bound_location', config=config)
 
2379
 
 
2380
    def get_bound_location(self):
 
2381
        """See Branch.set_push_location."""
 
2382
        return self._get_bound_location(True)
 
2383
 
 
2384
    def get_old_bound_location(self):
 
2385
        """See Branch.get_old_bound_location"""
 
2386
        return self._get_bound_location(False)
 
2387
 
 
2388
    def get_stacked_on_url(self):
 
2389
        # you can always ask for the URL; but you might not be able to use it
 
2390
        # if the repo can't support stacking.
 
2391
        ## self._check_stackable_repo()
 
2392
        stacked_url = self._get_config_location('stacked_on_location')
 
2393
        if stacked_url is None:
 
2394
            raise errors.NotStacked(self)
 
2395
        return stacked_url
 
2396
 
 
2397
    def set_append_revisions_only(self, enabled):
 
2398
        if enabled:
 
2399
            value = 'True'
 
2400
        else:
 
2401
            value = 'False'
 
2402
        self.get_config().set_user_option('append_revisions_only', value,
 
2403
            warn_masked=True)
 
2404
 
 
2405
    def set_stacked_on_url(self, url):
 
2406
        self._check_stackable_repo()
 
2407
        if not url:
 
2408
            try:
 
2409
                old_url = self.get_stacked_on_url()
 
2410
            except (errors.NotStacked, errors.UnstackableBranchFormat,
 
2411
                errors.UnstackableRepositoryFormat):
 
2412
                return
 
2413
            url = ''
 
2414
            # repositories don't offer an interface to remove fallback
 
2415
            # repositories today; take the conceptually simpler option and just
 
2416
            # reopen it.
 
2417
            self.repository = self.bzrdir.find_repository()
 
2418
            # for every revision reference the branch has, ensure it is pulled
 
2419
            # in.
 
2420
            source_repository = self._get_fallback_repository(old_url)
 
2421
            for revision_id in chain([self.last_revision()],
 
2422
                self.tags.get_reverse_tag_dict()):
 
2423
                self.repository.fetch(source_repository, revision_id,
 
2424
                    find_ghosts=True)
 
2425
        else:
 
2426
            self._activate_fallback_location(url)
 
2427
        # write this out after the repository is stacked to avoid setting a
 
2428
        # stacked config that doesn't work.
 
2429
        self._set_config_location('stacked_on_location', url)
 
2430
 
 
2431
    def _get_append_revisions_only(self):
 
2432
        value = self.get_config().get_user_option('append_revisions_only')
 
2433
        return value == 'True'
 
2434
 
 
2435
    def _make_tags(self):
 
2436
        return BasicTags(self)
 
2437
 
 
2438
    @needs_write_lock
 
2439
    def generate_revision_history(self, revision_id, last_rev=None,
 
2440
                                  other_branch=None):
 
2441
        """See BzrBranch5.generate_revision_history"""
 
2442
        history = self._lefthand_history(revision_id, last_rev, other_branch)
 
2443
        revno = len(history)
 
2444
        self.set_last_revision_info(revno, revision_id)
 
2445
 
 
2446
    @needs_read_lock
 
2447
    def get_rev_id(self, revno, history=None):
 
2448
        """Find the revision id of the specified revno."""
 
2449
        if revno == 0:
 
2450
            return _mod_revision.NULL_REVISION
 
2451
 
 
2452
        last_revno, last_revision_id = self.last_revision_info()
 
2453
        if revno <= 0 or revno > last_revno:
 
2454
            raise errors.NoSuchRevision(self, revno)
 
2455
 
 
2456
        if history is not None:
 
2457
            return history[revno - 1]
 
2458
 
 
2459
        index = last_revno - revno
 
2460
        if len(self._partial_revision_history_cache) <= index:
 
2461
            self._extend_partial_history(stop_index=index)
 
2462
        if len(self._partial_revision_history_cache) > index:
 
2463
            return self._partial_revision_history_cache[index]
 
2464
        else:
 
2465
            raise errors.NoSuchRevision(self, revno)
 
2466
 
 
2467
    @needs_read_lock
 
2468
    def revision_id_to_revno(self, revision_id):
 
2469
        """Given a revision id, return its revno"""
 
2470
        if _mod_revision.is_null(revision_id):
 
2471
            return 0
 
2472
        try:
 
2473
            index = self._partial_revision_history_cache.index(revision_id)
 
2474
        except ValueError:
 
2475
            self._extend_partial_history(stop_revision=revision_id)
 
2476
            index = len(self._partial_revision_history_cache) - 1
 
2477
            if self._partial_revision_history_cache[index] != revision_id:
 
2478
                raise errors.NoSuchRevision(self, revision_id)
 
2479
        return self.revno() - index
 
2480
 
 
2481
 
 
2482
class BzrBranch6(BzrBranch7):
 
2483
    """See BzrBranchFormat6 for the capabilities of this branch.
 
2484
 
 
2485
    This subclass of BzrBranch7 disables the new features BzrBranch7 added,
 
2486
    i.e. stacking.
 
2487
    """
 
2488
 
 
2489
    def get_stacked_on_url(self):
 
2490
        raise errors.UnstackableBranchFormat(self._format, self.base)
 
2491
 
 
2492
    def set_stacked_on_url(self, url):
 
2493
        raise errors.UnstackableBranchFormat(self._format, self.base)
 
2494
 
 
2495
 
 
2496
######################################################################
 
2497
# results of operations
 
2498
 
 
2499
 
 
2500
class _Result(object):
 
2501
 
 
2502
    def _show_tag_conficts(self, to_file):
 
2503
        if not getattr(self, 'tag_conflicts', None):
 
2504
            return
 
2505
        to_file.write('Conflicting tags:\n')
 
2506
        for name, value1, value2 in self.tag_conflicts:
 
2507
            to_file.write('    %s\n' % (name, ))
 
2508
 
 
2509
 
 
2510
class PullResult(_Result):
 
2511
    """Result of a Branch.pull operation.
 
2512
 
 
2513
    :ivar old_revno: Revision number before pull.
 
2514
    :ivar new_revno: Revision number after pull.
 
2515
    :ivar old_revid: Tip revision id before pull.
 
2516
    :ivar new_revid: Tip revision id after pull.
 
2517
    :ivar source_branch: Source (local) branch object.
 
2518
    :ivar master_branch: Master branch of the target, or the target if no
 
2519
        Master
 
2520
    :ivar local_branch: target branch if there is a Master, else None
 
2521
    :ivar target_branch: Target/destination branch object.
 
2522
    :ivar tag_conflicts: A list of tag conflicts, see BasicTags.merge_to
 
2523
    """
 
2524
 
 
2525
    def __int__(self):
 
2526
        # DEPRECATED: pull used to return the change in revno
 
2527
        return self.new_revno - self.old_revno
 
2528
 
 
2529
    def report(self, to_file):
 
2530
        if not is_quiet():
 
2531
            if self.old_revid == self.new_revid:
 
2532
                to_file.write('No revisions to pull.\n')
 
2533
            else:
 
2534
                to_file.write('Now on revision %d.\n' % self.new_revno)
 
2535
        self._show_tag_conficts(to_file)
 
2536
 
 
2537
 
 
2538
class PushResult(_Result):
 
2539
    """Result of a Branch.push operation.
 
2540
 
 
2541
    :ivar old_revno: Revision number before push.
 
2542
    :ivar new_revno: Revision number after push.
 
2543
    :ivar old_revid: Tip revision id before push.
 
2544
    :ivar new_revid: Tip revision id after push.
 
2545
    :ivar source_branch: Source branch object.
 
2546
    :ivar master_branch: Master branch of the target, or None.
 
2547
    :ivar target_branch: Target/destination branch object.
 
2548
    """
 
2549
 
 
2550
    def __int__(self):
 
2551
        # DEPRECATED: push used to return the change in revno
 
2552
        return self.new_revno - self.old_revno
 
2553
 
 
2554
    def report(self, to_file):
 
2555
        """Write a human-readable description of the result."""
 
2556
        if self.old_revid == self.new_revid:
 
2557
            to_file.write('No new revisions to push.\n')
 
2558
        else:
 
2559
            to_file.write('Pushed up to revision %d.\n' % self.new_revno)
 
2560
        self._show_tag_conficts(to_file)
 
2561
 
 
2562
 
 
2563
class BranchCheckResult(object):
 
2564
    """Results of checking branch consistency.
 
2565
 
 
2566
    :see: Branch.check
 
2567
    """
 
2568
 
 
2569
    def __init__(self, branch):
 
2570
        self.branch = branch
 
2571
 
 
2572
    def report_results(self, verbose):
 
2573
        """Report the check results via trace.note.
 
2574
 
 
2575
        :param verbose: Requests more detailed display of what was checked,
 
2576
            if any.
 
2577
        """
 
2578
        note('checked branch %s format %s',
 
2579
             self.branch.base,
 
2580
             self.branch._format)
 
2581
 
 
2582
 
 
2583
class Converter5to6(object):
 
2584
    """Perform an in-place upgrade of format 5 to format 6"""
 
2585
 
 
2586
    def convert(self, branch):
 
2587
        # Data for 5 and 6 can peacefully coexist.
 
2588
        format = BzrBranchFormat6()
 
2589
        new_branch = format.open(branch.bzrdir, _found=True)
 
2590
 
 
2591
        # Copy source data into target
 
2592
        new_branch._write_last_revision_info(*branch.last_revision_info())
 
2593
        new_branch.set_parent(branch.get_parent())
 
2594
        new_branch.set_bound_location(branch.get_bound_location())
 
2595
        new_branch.set_push_location(branch.get_push_location())
 
2596
 
 
2597
        # New branch has no tags by default
 
2598
        new_branch.tags._set_tag_dict({})
 
2599
 
 
2600
        # Copying done; now update target format
 
2601
        new_branch._transport.put_bytes('format',
 
2602
            format.get_format_string(),
 
2603
            mode=new_branch.bzrdir._get_file_mode())
 
2604
 
 
2605
        # Clean up old files
 
2606
        new_branch._transport.delete('revision-history')
 
2607
        try:
 
2608
            branch.set_parent(None)
 
2609
        except errors.NoSuchFile:
 
2610
            pass
 
2611
        branch.set_bound_location(None)
 
2612
 
 
2613
 
 
2614
class Converter6to7(object):
 
2615
    """Perform an in-place upgrade of format 6 to format 7"""
 
2616
 
 
2617
    def convert(self, branch):
 
2618
        format = BzrBranchFormat7()
 
2619
        branch._set_config_location('stacked_on_location', '')
 
2620
        # update target format
 
2621
        branch._transport.put_bytes('format', format.get_format_string())
 
2622
 
 
2623
 
 
2624
 
 
2625
def _run_with_write_locked_target(target, callable, *args, **kwargs):
 
2626
    """Run ``callable(*args, **kwargs)``, write-locking target for the
 
2627
    duration.
 
2628
 
 
2629
    _run_with_write_locked_target will attempt to release the lock it acquires.
 
2630
 
 
2631
    If an exception is raised by callable, then that exception *will* be
 
2632
    propagated, even if the unlock attempt raises its own error.  Thus
 
2633
    _run_with_write_locked_target should be preferred to simply doing::
 
2634
 
 
2635
        target.lock_write()
 
2636
        try:
 
2637
            return callable(*args, **kwargs)
 
2638
        finally:
 
2639
            target.unlock()
 
2640
 
 
2641
    """
 
2642
    # This is very similar to bzrlib.decorators.needs_write_lock.  Perhaps they
 
2643
    # should share code?
 
2644
    target.lock_write()
 
2645
    try:
 
2646
        result = callable(*args, **kwargs)
 
2647
    except:
 
2648
        exc_info = sys.exc_info()
 
2649
        try:
 
2650
            target.unlock()
 
2651
        finally:
 
2652
            raise exc_info[0], exc_info[1], exc_info[2]
 
2653
    else:
 
2654
        target.unlock()
 
2655
        return result
 
2656
 
 
2657
 
 
2658
class InterBranch(InterObject):
 
2659
    """This class represents operations taking place between two branches.
 
2660
 
 
2661
    Its instances have methods like pull() and push() and contain
 
2662
    references to the source and target repositories these operations
 
2663
    can be carried out on.
 
2664
    """
 
2665
 
 
2666
    _optimisers = []
 
2667
    """The available optimised InterBranch types."""
 
2668
 
 
2669
    @staticmethod
 
2670
    def _get_branch_format_to_test():
 
2671
        """Return the Branch format to use when testing this InterBranch."""
 
2672
        raise NotImplementedError(self._get_branch_format_to_test)
 
2673
 
 
2674
    def update_revisions(self, stop_revision=None, overwrite=False,
 
2675
                         graph=None):
 
2676
        """Pull in new perfect-fit revisions.
 
2677
 
 
2678
        :param stop_revision: Updated until the given revision
 
2679
        :param overwrite: Always set the branch pointer, rather than checking
 
2680
            to see if it is a proper descendant.
 
2681
        :param graph: A Graph object that can be used to query history
 
2682
            information. This can be None.
 
2683
        :return: None
 
2684
        """
 
2685
        raise NotImplementedError(self.update_revisions)
 
2686
 
 
2687
 
 
2688
class GenericInterBranch(InterBranch):
 
2689
    """InterBranch implementation that uses public Branch functions.
 
2690
    """
 
2691
 
 
2692
    @staticmethod
 
2693
    def _get_branch_format_to_test():
 
2694
        return BranchFormat._default_format
 
2695
 
 
2696
    def update_revisions(self, stop_revision=None, overwrite=False,
 
2697
        graph=None):
 
2698
        """See InterBranch.update_revisions()."""
 
2699
        self.source.lock_read()
 
2700
        try:
 
2701
            other_revno, other_last_revision = self.source.last_revision_info()
 
2702
            stop_revno = None # unknown
 
2703
            if stop_revision is None:
 
2704
                stop_revision = other_last_revision
 
2705
                if _mod_revision.is_null(stop_revision):
 
2706
                    # if there are no commits, we're done.
 
2707
                    return
 
2708
                stop_revno = other_revno
 
2709
 
 
2710
            # what's the current last revision, before we fetch [and change it
 
2711
            # possibly]
 
2712
            last_rev = _mod_revision.ensure_null(self.target.last_revision())
 
2713
            # we fetch here so that we don't process data twice in the common
 
2714
            # case of having something to pull, and so that the check for
 
2715
            # already merged can operate on the just fetched graph, which will
 
2716
            # be cached in memory.
 
2717
            self.target.fetch(self.source, stop_revision)
 
2718
            # Check to see if one is an ancestor of the other
 
2719
            if not overwrite:
 
2720
                if graph is None:
 
2721
                    graph = self.target.repository.get_graph()
 
2722
                if self.target._check_if_descendant_or_diverged(
 
2723
                        stop_revision, last_rev, graph, self.source):
 
2724
                    # stop_revision is a descendant of last_rev, but we aren't
 
2725
                    # overwriting, so we're done.
 
2726
                    return
 
2727
            if stop_revno is None:
 
2728
                if graph is None:
 
2729
                    graph = self.target.repository.get_graph()
 
2730
                this_revno, this_last_revision = \
 
2731
                        self.target.last_revision_info()
 
2732
                stop_revno = graph.find_distance_to_null(stop_revision,
 
2733
                                [(other_last_revision, other_revno),
 
2734
                                 (this_last_revision, this_revno)])
 
2735
            self.target.set_last_revision_info(stop_revno, stop_revision)
 
2736
        finally:
 
2737
            self.source.unlock()
 
2738
 
 
2739
    @classmethod
 
2740
    def is_compatible(self, source, target):
 
2741
        # GenericBranch uses the public API, so always compatible
 
2742
        return True
 
2743
 
 
2744
 
 
2745
InterBranch.register_optimiser(GenericInterBranch)