/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: INADA Naoki
  • Date: 2011-05-18 06:27:34 UTC
  • mfrom: (5887 +trunk)
  • mto: This revision was merged to the branch mainline in revision 5894.
  • Revision ID: songofacandy@gmail.com-20110518062734-1ilhll0rrqyyp8um
merge from lp:bzr and resolve conflicts.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005-2011 Canonical Ltd
 
2
#
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
 
17
 
 
18
from cStringIO import StringIO
 
19
import sys
 
20
 
 
21
from bzrlib.lazy_import import lazy_import
 
22
lazy_import(globals(), """
 
23
from itertools import chain
 
24
from bzrlib import (
 
25
        bzrdir,
 
26
        cache_utf8,
 
27
        config as _mod_config,
 
28
        debug,
 
29
        errors,
 
30
        fetch,
 
31
        graph as _mod_graph,
 
32
        lockdir,
 
33
        lockable_files,
 
34
        remote,
 
35
        repository,
 
36
        revision as _mod_revision,
 
37
        rio,
 
38
        transport,
 
39
        ui,
 
40
        urlutils,
 
41
        )
 
42
from bzrlib.config import BranchConfig, TransportConfig
 
43
from bzrlib.tag import (
 
44
    BasicTags,
 
45
    DisabledTags,
 
46
    )
 
47
""")
 
48
 
 
49
from bzrlib import (
 
50
    controldir,
 
51
    )
 
52
from bzrlib.decorators import (
 
53
    needs_read_lock,
 
54
    needs_write_lock,
 
55
    only_raises,
 
56
    )
 
57
from bzrlib.hooks import Hooks
 
58
from bzrlib.inter import InterObject
 
59
from bzrlib.lock import _RelockDebugMixin, LogicalLockResult
 
60
from bzrlib import registry
 
61
from bzrlib.symbol_versioning import (
 
62
    deprecated_in,
 
63
    deprecated_method,
 
64
    )
 
65
from bzrlib.trace import mutter, mutter_callsite, note, is_quiet
 
66
 
 
67
 
 
68
BZR_BRANCH_FORMAT_4 = "Bazaar-NG branch, format 0.0.4\n"
 
69
BZR_BRANCH_FORMAT_5 = "Bazaar-NG branch, format 5\n"
 
70
BZR_BRANCH_FORMAT_6 = "Bazaar Branch Format 6 (bzr 0.15)\n"
 
71
 
 
72
 
 
73
class Branch(controldir.ControlComponent):
 
74
    """Branch holding a history of revisions.
 
75
 
 
76
    :ivar base:
 
77
        Base directory/url of the branch; using control_url and
 
78
        control_transport is more standardized.
 
79
    :ivar hooks: An instance of BranchHooks.
 
80
    :ivar _master_branch_cache: cached result of get_master_branch, see
 
81
        _clear_cached_state.
 
82
    """
 
83
    # this is really an instance variable - FIXME move it there
 
84
    # - RBC 20060112
 
85
    base = None
 
86
 
 
87
    @property
 
88
    def control_transport(self):
 
89
        return self._transport
 
90
 
 
91
    @property
 
92
    def user_transport(self):
 
93
        return self.bzrdir.user_transport
 
94
 
 
95
    def __init__(self, *ignored, **ignored_too):
 
96
        self.tags = self._format.make_tags(self)
 
97
        self._revision_history_cache = None
 
98
        self._revision_id_to_revno_cache = None
 
99
        self._partial_revision_id_to_revno_cache = {}
 
100
        self._partial_revision_history_cache = []
 
101
        self._tags_bytes = None
 
102
        self._last_revision_info_cache = None
 
103
        self._master_branch_cache = None
 
104
        self._merge_sorted_revisions_cache = None
 
105
        self._open_hook()
 
106
        hooks = Branch.hooks['open']
 
107
        for hook in hooks:
 
108
            hook(self)
 
109
 
 
110
    def _open_hook(self):
 
111
        """Called by init to allow simpler extension of the base class."""
 
112
 
 
113
    def _activate_fallback_location(self, url):
 
114
        """Activate the branch/repository from url as a fallback repository."""
 
115
        for existing_fallback_repo in self.repository._fallback_repositories:
 
116
            if existing_fallback_repo.user_url == url:
 
117
                # This fallback is already configured.  This probably only
 
118
                # happens because BzrDir.sprout is a horrible mess.  To avoid
 
119
                # confusing _unstack we don't add this a second time.
 
120
                mutter('duplicate activation of fallback %r on %r', url, self)
 
121
                return
 
122
        repo = self._get_fallback_repository(url)
 
123
        if repo.has_same_location(self.repository):
 
124
            raise errors.UnstackableLocationError(self.user_url, url)
 
125
        self.repository.add_fallback_repository(repo)
 
126
 
 
127
    def break_lock(self):
 
128
        """Break a lock if one is present from another instance.
 
129
 
 
130
        Uses the ui factory to ask for confirmation if the lock may be from
 
131
        an active process.
 
132
 
 
133
        This will probe the repository for its lock as well.
 
134
        """
 
135
        self.control_files.break_lock()
 
136
        self.repository.break_lock()
 
137
        master = self.get_master_branch()
 
138
        if master is not None:
 
139
            master.break_lock()
 
140
 
 
141
    def _check_stackable_repo(self):
 
142
        if not self.repository._format.supports_external_lookups:
 
143
            raise errors.UnstackableRepositoryFormat(self.repository._format,
 
144
                self.repository.base)
 
145
 
 
146
    def _extend_partial_history(self, stop_index=None, stop_revision=None):
 
147
        """Extend the partial history to include a given index
 
148
 
 
149
        If a stop_index is supplied, stop when that index has been reached.
 
150
        If a stop_revision is supplied, stop when that revision is
 
151
        encountered.  Otherwise, stop when the beginning of history is
 
152
        reached.
 
153
 
 
154
        :param stop_index: The index which should be present.  When it is
 
155
            present, history extension will stop.
 
156
        :param stop_revision: The revision id which should be present.  When
 
157
            it is encountered, history extension will stop.
 
158
        """
 
159
        if len(self._partial_revision_history_cache) == 0:
 
160
            self._partial_revision_history_cache = [self.last_revision()]
 
161
        repository._iter_for_revno(
 
162
            self.repository, self._partial_revision_history_cache,
 
163
            stop_index=stop_index, stop_revision=stop_revision)
 
164
        if self._partial_revision_history_cache[-1] == _mod_revision.NULL_REVISION:
 
165
            self._partial_revision_history_cache.pop()
 
166
 
 
167
    def _get_check_refs(self):
 
168
        """Get the references needed for check().
 
169
 
 
170
        See bzrlib.check.
 
171
        """
 
172
        revid = self.last_revision()
 
173
        return [('revision-existence', revid), ('lefthand-distance', revid)]
 
174
 
 
175
    @staticmethod
 
176
    def open(base, _unsupported=False, possible_transports=None):
 
177
        """Open the branch rooted at base.
 
178
 
 
179
        For instance, if the branch is at URL/.bzr/branch,
 
180
        Branch.open(URL) -> a Branch instance.
 
181
        """
 
182
        control = bzrdir.BzrDir.open(base, _unsupported,
 
183
                                     possible_transports=possible_transports)
 
184
        return control.open_branch(unsupported=_unsupported)
 
185
 
 
186
    @staticmethod
 
187
    def open_from_transport(transport, name=None, _unsupported=False):
 
188
        """Open the branch rooted at transport"""
 
189
        control = bzrdir.BzrDir.open_from_transport(transport, _unsupported)
 
190
        return control.open_branch(name=name, unsupported=_unsupported)
 
191
 
 
192
    @staticmethod
 
193
    def open_containing(url, possible_transports=None):
 
194
        """Open an existing branch which contains url.
 
195
 
 
196
        This probes for a branch at url, and searches upwards from there.
 
197
 
 
198
        Basically we keep looking up until we find the control directory or
 
199
        run into the root.  If there isn't one, raises NotBranchError.
 
200
        If there is one and it is either an unrecognised format or an unsupported
 
201
        format, UnknownFormatError or UnsupportedFormatError are raised.
 
202
        If there is one, it is returned, along with the unused portion of url.
 
203
        """
 
204
        control, relpath = bzrdir.BzrDir.open_containing(url,
 
205
                                                         possible_transports)
 
206
        return control.open_branch(), relpath
 
207
 
 
208
    def _push_should_merge_tags(self):
 
209
        """Should _basic_push merge this branch's tags into the target?
 
210
 
 
211
        The default implementation returns False if this branch has no tags,
 
212
        and True the rest of the time.  Subclasses may override this.
 
213
        """
 
214
        return self.supports_tags() and self.tags.get_tag_dict()
 
215
 
 
216
    def get_config(self):
 
217
        """Get a bzrlib.config.BranchConfig for this Branch.
 
218
 
 
219
        This can then be used to get and set configuration options for the
 
220
        branch.
 
221
 
 
222
        :return: A bzrlib.config.BranchConfig.
 
223
        """
 
224
        return BranchConfig(self)
 
225
 
 
226
    def _get_config(self):
 
227
        """Get the concrete config for just the config in this branch.
 
228
 
 
229
        This is not intended for client use; see Branch.get_config for the
 
230
        public API.
 
231
 
 
232
        Added in 1.14.
 
233
 
 
234
        :return: An object supporting get_option and set_option.
 
235
        """
 
236
        raise NotImplementedError(self._get_config)
 
237
 
 
238
    def _get_fallback_repository(self, url):
 
239
        """Get the repository we fallback to at url."""
 
240
        url = urlutils.join(self.base, url)
 
241
        a_branch = Branch.open(url,
 
242
            possible_transports=[self.bzrdir.root_transport])
 
243
        return a_branch.repository
 
244
 
 
245
    @needs_read_lock
 
246
    def _get_tags_bytes(self):
 
247
        """Get the bytes of a serialised tags dict.
 
248
 
 
249
        Note that not all branches support tags, nor do all use the same tags
 
250
        logic: this method is specific to BasicTags. Other tag implementations
 
251
        may use the same method name and behave differently, safely, because
 
252
        of the double-dispatch via
 
253
        format.make_tags->tags_instance->get_tags_dict.
 
254
 
 
255
        :return: The bytes of the tags file.
 
256
        :seealso: Branch._set_tags_bytes.
 
257
        """
 
258
        if self._tags_bytes is None:
 
259
            self._tags_bytes = self._transport.get_bytes('tags')
 
260
        return self._tags_bytes
 
261
 
 
262
    def _get_nick(self, local=False, possible_transports=None):
 
263
        config = self.get_config()
 
264
        # explicit overrides master, but don't look for master if local is True
 
265
        if not local and not config.has_explicit_nickname():
 
266
            try:
 
267
                master = self.get_master_branch(possible_transports)
 
268
                if master and self.user_url == master.user_url:
 
269
                    raise errors.RecursiveBind(self.user_url)
 
270
                if master is not None:
 
271
                    # return the master branch value
 
272
                    return master.nick
 
273
            except errors.RecursiveBind, e:
 
274
                raise e
 
275
            except errors.BzrError, e:
 
276
                # Silently fall back to local implicit nick if the master is
 
277
                # unavailable
 
278
                mutter("Could not connect to bound branch, "
 
279
                    "falling back to local nick.\n " + str(e))
 
280
        return config.get_nickname()
 
281
 
 
282
    def _set_nick(self, nick):
 
283
        self.get_config().set_user_option('nickname', nick, warn_masked=True)
 
284
 
 
285
    nick = property(_get_nick, _set_nick)
 
286
 
 
287
    def is_locked(self):
 
288
        raise NotImplementedError(self.is_locked)
 
289
 
 
290
    def _lefthand_history(self, revision_id, last_rev=None,
 
291
                          other_branch=None):
 
292
        if 'evil' in debug.debug_flags:
 
293
            mutter_callsite(4, "_lefthand_history scales with history.")
 
294
        # stop_revision must be a descendant of last_revision
 
295
        graph = self.repository.get_graph()
 
296
        if last_rev is not None:
 
297
            if not graph.is_ancestor(last_rev, revision_id):
 
298
                # our previous tip is not merged into stop_revision
 
299
                raise errors.DivergedBranches(self, other_branch)
 
300
        # make a new revision history from the graph
 
301
        parents_map = graph.get_parent_map([revision_id])
 
302
        if revision_id not in parents_map:
 
303
            raise errors.NoSuchRevision(self, revision_id)
 
304
        current_rev_id = revision_id
 
305
        new_history = []
 
306
        check_not_reserved_id = _mod_revision.check_not_reserved_id
 
307
        # Do not include ghosts or graph origin in revision_history
 
308
        while (current_rev_id in parents_map and
 
309
               len(parents_map[current_rev_id]) > 0):
 
310
            check_not_reserved_id(current_rev_id)
 
311
            new_history.append(current_rev_id)
 
312
            current_rev_id = parents_map[current_rev_id][0]
 
313
            parents_map = graph.get_parent_map([current_rev_id])
 
314
        new_history.reverse()
 
315
        return new_history
 
316
 
 
317
    def lock_write(self, token=None):
 
318
        """Lock the branch for write operations.
 
319
 
 
320
        :param token: A token to permit reacquiring a previously held and
 
321
            preserved lock.
 
322
        :return: A BranchWriteLockResult.
 
323
        """
 
324
        raise NotImplementedError(self.lock_write)
 
325
 
 
326
    def lock_read(self):
 
327
        """Lock the branch for read operations.
 
328
 
 
329
        :return: A bzrlib.lock.LogicalLockResult.
 
330
        """
 
331
        raise NotImplementedError(self.lock_read)
 
332
 
 
333
    def unlock(self):
 
334
        raise NotImplementedError(self.unlock)
 
335
 
 
336
    def peek_lock_mode(self):
 
337
        """Return lock mode for the Branch: 'r', 'w' or None"""
 
338
        raise NotImplementedError(self.peek_lock_mode)
 
339
 
 
340
    def get_physical_lock_status(self):
 
341
        raise NotImplementedError(self.get_physical_lock_status)
 
342
 
 
343
    @needs_read_lock
 
344
    def dotted_revno_to_revision_id(self, revno, _cache_reverse=False):
 
345
        """Return the revision_id for a dotted revno.
 
346
 
 
347
        :param revno: a tuple like (1,) or (1,1,2)
 
348
        :param _cache_reverse: a private parameter enabling storage
 
349
           of the reverse mapping in a top level cache. (This should
 
350
           only be done in selective circumstances as we want to
 
351
           avoid having the mapping cached multiple times.)
 
352
        :return: the revision_id
 
353
        :raises errors.NoSuchRevision: if the revno doesn't exist
 
354
        """
 
355
        rev_id = self._do_dotted_revno_to_revision_id(revno)
 
356
        if _cache_reverse:
 
357
            self._partial_revision_id_to_revno_cache[rev_id] = revno
 
358
        return rev_id
 
359
 
 
360
    def _do_dotted_revno_to_revision_id(self, revno):
 
361
        """Worker function for dotted_revno_to_revision_id.
 
362
 
 
363
        Subclasses should override this if they wish to
 
364
        provide a more efficient implementation.
 
365
        """
 
366
        if len(revno) == 1:
 
367
            return self.get_rev_id(revno[0])
 
368
        revision_id_to_revno = self.get_revision_id_to_revno_map()
 
369
        revision_ids = [revision_id for revision_id, this_revno
 
370
                        in revision_id_to_revno.iteritems()
 
371
                        if revno == this_revno]
 
372
        if len(revision_ids) == 1:
 
373
            return revision_ids[0]
 
374
        else:
 
375
            revno_str = '.'.join(map(str, revno))
 
376
            raise errors.NoSuchRevision(self, revno_str)
 
377
 
 
378
    @needs_read_lock
 
379
    def revision_id_to_dotted_revno(self, revision_id):
 
380
        """Given a revision id, return its dotted revno.
 
381
 
 
382
        :return: a tuple like (1,) or (400,1,3).
 
383
        """
 
384
        return self._do_revision_id_to_dotted_revno(revision_id)
 
385
 
 
386
    def _do_revision_id_to_dotted_revno(self, revision_id):
 
387
        """Worker function for revision_id_to_revno."""
 
388
        # Try the caches if they are loaded
 
389
        result = self._partial_revision_id_to_revno_cache.get(revision_id)
 
390
        if result is not None:
 
391
            return result
 
392
        if self._revision_id_to_revno_cache:
 
393
            result = self._revision_id_to_revno_cache.get(revision_id)
 
394
            if result is None:
 
395
                raise errors.NoSuchRevision(self, revision_id)
 
396
        # Try the mainline as it's optimised
 
397
        try:
 
398
            revno = self.revision_id_to_revno(revision_id)
 
399
            return (revno,)
 
400
        except errors.NoSuchRevision:
 
401
            # We need to load and use the full revno map after all
 
402
            result = self.get_revision_id_to_revno_map().get(revision_id)
 
403
            if result is None:
 
404
                raise errors.NoSuchRevision(self, revision_id)
 
405
        return result
 
406
 
 
407
    @needs_read_lock
 
408
    def get_revision_id_to_revno_map(self):
 
409
        """Return the revision_id => dotted revno map.
 
410
 
 
411
        This will be regenerated on demand, but will be cached.
 
412
 
 
413
        :return: A dictionary mapping revision_id => dotted revno.
 
414
            This dictionary should not be modified by the caller.
 
415
        """
 
416
        if self._revision_id_to_revno_cache is not None:
 
417
            mapping = self._revision_id_to_revno_cache
 
418
        else:
 
419
            mapping = self._gen_revno_map()
 
420
            self._cache_revision_id_to_revno(mapping)
 
421
        # TODO: jam 20070417 Since this is being cached, should we be returning
 
422
        #       a copy?
 
423
        # I would rather not, and instead just declare that users should not
 
424
        # modify the return value.
 
425
        return mapping
 
426
 
 
427
    def _gen_revno_map(self):
 
428
        """Create a new mapping from revision ids to dotted revnos.
 
429
 
 
430
        Dotted revnos are generated based on the current tip in the revision
 
431
        history.
 
432
        This is the worker function for get_revision_id_to_revno_map, which
 
433
        just caches the return value.
 
434
 
 
435
        :return: A dictionary mapping revision_id => dotted revno.
 
436
        """
 
437
        revision_id_to_revno = dict((rev_id, revno)
 
438
            for rev_id, depth, revno, end_of_merge
 
439
             in self.iter_merge_sorted_revisions())
 
440
        return revision_id_to_revno
 
441
 
 
442
    @needs_read_lock
 
443
    def iter_merge_sorted_revisions(self, start_revision_id=None,
 
444
            stop_revision_id=None, stop_rule='exclude', direction='reverse'):
 
445
        """Walk the revisions for a branch in merge sorted order.
 
446
 
 
447
        Merge sorted order is the output from a merge-aware,
 
448
        topological sort, i.e. all parents come before their
 
449
        children going forward; the opposite for reverse.
 
450
 
 
451
        :param start_revision_id: the revision_id to begin walking from.
 
452
            If None, the branch tip is used.
 
453
        :param stop_revision_id: the revision_id to terminate the walk
 
454
            after. If None, the rest of history is included.
 
455
        :param stop_rule: if stop_revision_id is not None, the precise rule
 
456
            to use for termination:
 
457
            * 'exclude' - leave the stop revision out of the result (default)
 
458
            * 'include' - the stop revision is the last item in the result
 
459
            * 'with-merges' - include the stop revision and all of its
 
460
              merged revisions in the result
 
461
            * 'with-merges-without-common-ancestry' - filter out revisions 
 
462
              that are in both ancestries
 
463
        :param direction: either 'reverse' or 'forward':
 
464
            * reverse means return the start_revision_id first, i.e.
 
465
              start at the most recent revision and go backwards in history
 
466
            * forward returns tuples in the opposite order to reverse.
 
467
              Note in particular that forward does *not* do any intelligent
 
468
              ordering w.r.t. depth as some clients of this API may like.
 
469
              (If required, that ought to be done at higher layers.)
 
470
 
 
471
        :return: an iterator over (revision_id, depth, revno, end_of_merge)
 
472
            tuples where:
 
473
 
 
474
            * revision_id: the unique id of the revision
 
475
            * depth: How many levels of merging deep this node has been
 
476
              found.
 
477
            * revno_sequence: This field provides a sequence of
 
478
              revision numbers for all revisions. The format is:
 
479
              (REVNO, BRANCHNUM, BRANCHREVNO). BRANCHNUM is the number of the
 
480
              branch that the revno is on. From left to right the REVNO numbers
 
481
              are the sequence numbers within that branch of the revision.
 
482
            * end_of_merge: When True the next node (earlier in history) is
 
483
              part of a different merge.
 
484
        """
 
485
        # Note: depth and revno values are in the context of the branch so
 
486
        # we need the full graph to get stable numbers, regardless of the
 
487
        # start_revision_id.
 
488
        if self._merge_sorted_revisions_cache is None:
 
489
            last_revision = self.last_revision()
 
490
            known_graph = self.repository.get_known_graph_ancestry(
 
491
                [last_revision])
 
492
            self._merge_sorted_revisions_cache = known_graph.merge_sort(
 
493
                last_revision)
 
494
        filtered = self._filter_merge_sorted_revisions(
 
495
            self._merge_sorted_revisions_cache, start_revision_id,
 
496
            stop_revision_id, stop_rule)
 
497
        # Make sure we don't return revisions that are not part of the
 
498
        # start_revision_id ancestry.
 
499
        filtered = self._filter_start_non_ancestors(filtered)
 
500
        if direction == 'reverse':
 
501
            return filtered
 
502
        if direction == 'forward':
 
503
            return reversed(list(filtered))
 
504
        else:
 
505
            raise ValueError('invalid direction %r' % direction)
 
506
 
 
507
    def _filter_merge_sorted_revisions(self, merge_sorted_revisions,
 
508
        start_revision_id, stop_revision_id, stop_rule):
 
509
        """Iterate over an inclusive range of sorted revisions."""
 
510
        rev_iter = iter(merge_sorted_revisions)
 
511
        if start_revision_id is not None:
 
512
            for node in rev_iter:
 
513
                rev_id = node.key[-1]
 
514
                if rev_id != start_revision_id:
 
515
                    continue
 
516
                else:
 
517
                    # The decision to include the start or not
 
518
                    # depends on the stop_rule if a stop is provided
 
519
                    # so pop this node back into the iterator
 
520
                    rev_iter = chain(iter([node]), rev_iter)
 
521
                    break
 
522
        if stop_revision_id is None:
 
523
            # Yield everything
 
524
            for node in rev_iter:
 
525
                rev_id = node.key[-1]
 
526
                yield (rev_id, node.merge_depth, node.revno,
 
527
                       node.end_of_merge)
 
528
        elif stop_rule == 'exclude':
 
529
            for node in rev_iter:
 
530
                rev_id = node.key[-1]
 
531
                if rev_id == stop_revision_id:
 
532
                    return
 
533
                yield (rev_id, node.merge_depth, node.revno,
 
534
                       node.end_of_merge)
 
535
        elif stop_rule == 'include':
 
536
            for node in rev_iter:
 
537
                rev_id = node.key[-1]
 
538
                yield (rev_id, node.merge_depth, node.revno,
 
539
                       node.end_of_merge)
 
540
                if rev_id == stop_revision_id:
 
541
                    return
 
542
        elif stop_rule == 'with-merges-without-common-ancestry':
 
543
            # We want to exclude all revisions that are already part of the
 
544
            # stop_revision_id ancestry.
 
545
            graph = self.repository.get_graph()
 
546
            ancestors = graph.find_unique_ancestors(start_revision_id,
 
547
                                                    [stop_revision_id])
 
548
            for node in rev_iter:
 
549
                rev_id = node.key[-1]
 
550
                if rev_id not in ancestors:
 
551
                    continue
 
552
                yield (rev_id, node.merge_depth, node.revno,
 
553
                       node.end_of_merge)
 
554
        elif stop_rule == 'with-merges':
 
555
            stop_rev = self.repository.get_revision(stop_revision_id)
 
556
            if stop_rev.parent_ids:
 
557
                left_parent = stop_rev.parent_ids[0]
 
558
            else:
 
559
                left_parent = _mod_revision.NULL_REVISION
 
560
            # left_parent is the actual revision we want to stop logging at,
 
561
            # since we want to show the merged revisions after the stop_rev too
 
562
            reached_stop_revision_id = False
 
563
            revision_id_whitelist = []
 
564
            for node in rev_iter:
 
565
                rev_id = node.key[-1]
 
566
                if rev_id == left_parent:
 
567
                    # reached the left parent after the stop_revision
 
568
                    return
 
569
                if (not reached_stop_revision_id or
 
570
                        rev_id in revision_id_whitelist):
 
571
                    yield (rev_id, node.merge_depth, node.revno,
 
572
                       node.end_of_merge)
 
573
                    if reached_stop_revision_id or rev_id == stop_revision_id:
 
574
                        # only do the merged revs of rev_id from now on
 
575
                        rev = self.repository.get_revision(rev_id)
 
576
                        if rev.parent_ids:
 
577
                            reached_stop_revision_id = True
 
578
                            revision_id_whitelist.extend(rev.parent_ids)
 
579
        else:
 
580
            raise ValueError('invalid stop_rule %r' % stop_rule)
 
581
 
 
582
    def _filter_start_non_ancestors(self, rev_iter):
 
583
        # If we started from a dotted revno, we want to consider it as a tip
 
584
        # and don't want to yield revisions that are not part of its
 
585
        # ancestry. Given the order guaranteed by the merge sort, we will see
 
586
        # uninteresting descendants of the first parent of our tip before the
 
587
        # tip itself.
 
588
        first = rev_iter.next()
 
589
        (rev_id, merge_depth, revno, end_of_merge) = first
 
590
        yield first
 
591
        if not merge_depth:
 
592
            # We start at a mainline revision so by definition, all others
 
593
            # revisions in rev_iter are ancestors
 
594
            for node in rev_iter:
 
595
                yield node
 
596
 
 
597
        clean = False
 
598
        whitelist = set()
 
599
        pmap = self.repository.get_parent_map([rev_id])
 
600
        parents = pmap.get(rev_id, [])
 
601
        if parents:
 
602
            whitelist.update(parents)
 
603
        else:
 
604
            # If there is no parents, there is nothing of interest left
 
605
 
 
606
            # FIXME: It's hard to test this scenario here as this code is never
 
607
            # called in that case. -- vila 20100322
 
608
            return
 
609
 
 
610
        for (rev_id, merge_depth, revno, end_of_merge) in rev_iter:
 
611
            if not clean:
 
612
                if rev_id in whitelist:
 
613
                    pmap = self.repository.get_parent_map([rev_id])
 
614
                    parents = pmap.get(rev_id, [])
 
615
                    whitelist.remove(rev_id)
 
616
                    whitelist.update(parents)
 
617
                    if merge_depth == 0:
 
618
                        # We've reached the mainline, there is nothing left to
 
619
                        # filter
 
620
                        clean = True
 
621
                else:
 
622
                    # A revision that is not part of the ancestry of our
 
623
                    # starting revision.
 
624
                    continue
 
625
            yield (rev_id, merge_depth, revno, end_of_merge)
 
626
 
 
627
    def leave_lock_in_place(self):
 
628
        """Tell this branch object not to release the physical lock when this
 
629
        object is unlocked.
 
630
 
 
631
        If lock_write doesn't return a token, then this method is not supported.
 
632
        """
 
633
        self.control_files.leave_in_place()
 
634
 
 
635
    def dont_leave_lock_in_place(self):
 
636
        """Tell this branch object to release the physical lock when this
 
637
        object is unlocked, even if it didn't originally acquire it.
 
638
 
 
639
        If lock_write doesn't return a token, then this method is not supported.
 
640
        """
 
641
        self.control_files.dont_leave_in_place()
 
642
 
 
643
    def bind(self, other):
 
644
        """Bind the local branch the other branch.
 
645
 
 
646
        :param other: The branch to bind to
 
647
        :type other: Branch
 
648
        """
 
649
        raise errors.UpgradeRequired(self.user_url)
 
650
 
 
651
    def set_append_revisions_only(self, enabled):
 
652
        if not self._format.supports_set_append_revisions_only():
 
653
            raise errors.UpgradeRequired(self.user_url)
 
654
        if enabled:
 
655
            value = 'True'
 
656
        else:
 
657
            value = 'False'
 
658
        self.get_config().set_user_option('append_revisions_only', value,
 
659
            warn_masked=True)
 
660
 
 
661
    def set_reference_info(self, file_id, tree_path, branch_location):
 
662
        """Set the branch location to use for a tree reference."""
 
663
        raise errors.UnsupportedOperation(self.set_reference_info, self)
 
664
 
 
665
    def get_reference_info(self, file_id):
 
666
        """Get the tree_path and branch_location for a tree reference."""
 
667
        raise errors.UnsupportedOperation(self.get_reference_info, self)
 
668
 
 
669
    @needs_write_lock
 
670
    def fetch(self, from_branch, last_revision=None):
 
671
        """Copy revisions from from_branch into this branch.
 
672
 
 
673
        :param from_branch: Where to copy from.
 
674
        :param last_revision: What revision to stop at (None for at the end
 
675
                              of the branch.
 
676
        :return: None
 
677
        """
 
678
        return InterBranch.get(from_branch, self).fetch(last_revision)
 
679
 
 
680
    def get_bound_location(self):
 
681
        """Return the URL of the branch we are bound to.
 
682
 
 
683
        Older format branches cannot bind, please be sure to use a metadir
 
684
        branch.
 
685
        """
 
686
        return None
 
687
 
 
688
    def get_old_bound_location(self):
 
689
        """Return the URL of the branch we used to be bound to
 
690
        """
 
691
        raise errors.UpgradeRequired(self.user_url)
 
692
 
 
693
    def get_commit_builder(self, parents, config=None, timestamp=None,
 
694
                           timezone=None, committer=None, revprops=None,
 
695
                           revision_id=None, lossy=False):
 
696
        """Obtain a CommitBuilder for this branch.
 
697
 
 
698
        :param parents: Revision ids of the parents of the new revision.
 
699
        :param config: Optional configuration to use.
 
700
        :param timestamp: Optional timestamp recorded for commit.
 
701
        :param timezone: Optional timezone for timestamp.
 
702
        :param committer: Optional committer to set for commit.
 
703
        :param revprops: Optional dictionary of revision properties.
 
704
        :param revision_id: Optional revision id.
 
705
        :param lossy: Whether to discard data that can not be natively
 
706
            represented, when pushing to a foreign VCS 
 
707
        """
 
708
 
 
709
        if config is None:
 
710
            config = self.get_config()
 
711
 
 
712
        return self.repository.get_commit_builder(self, parents, config,
 
713
            timestamp, timezone, committer, revprops, revision_id,
 
714
            lossy)
 
715
 
 
716
    def get_master_branch(self, possible_transports=None):
 
717
        """Return the branch we are bound to.
 
718
 
 
719
        :return: Either a Branch, or None
 
720
        """
 
721
        return None
 
722
 
 
723
    def get_revision_delta(self, revno):
 
724
        """Return the delta for one revision.
 
725
 
 
726
        The delta is relative to its mainline predecessor, or the
 
727
        empty tree for revision 1.
 
728
        """
 
729
        rh = self.revision_history()
 
730
        if not (1 <= revno <= len(rh)):
 
731
            raise errors.InvalidRevisionNumber(revno)
 
732
        return self.repository.get_revision_delta(rh[revno-1])
 
733
 
 
734
    def get_stacked_on_url(self):
 
735
        """Get the URL this branch is stacked against.
 
736
 
 
737
        :raises NotStacked: If the branch is not stacked.
 
738
        :raises UnstackableBranchFormat: If the branch does not support
 
739
            stacking.
 
740
        """
 
741
        raise NotImplementedError(self.get_stacked_on_url)
 
742
 
 
743
    def print_file(self, file, revision_id):
 
744
        """Print `file` to stdout."""
 
745
        raise NotImplementedError(self.print_file)
 
746
 
 
747
    @deprecated_method(deprecated_in((2, 4, 0)))
 
748
    def set_revision_history(self, rev_history):
 
749
        """See Branch.set_revision_history."""
 
750
        self._set_revision_history(rev_history)
 
751
 
 
752
    @needs_write_lock
 
753
    def _set_revision_history(self, rev_history):
 
754
        if len(rev_history) == 0:
 
755
            revid = _mod_revision.NULL_REVISION
 
756
        else:
 
757
            revid = rev_history[-1]
 
758
        if rev_history != self._lefthand_history(revid):
 
759
            raise errors.NotLefthandHistory(rev_history)
 
760
        self.set_last_revision_info(len(rev_history), revid)
 
761
        self._cache_revision_history(rev_history)
 
762
        for hook in Branch.hooks['set_rh']:
 
763
            hook(self, rev_history)
 
764
 
 
765
    @needs_write_lock
 
766
    def set_last_revision_info(self, revno, revision_id):
 
767
        """Set the last revision of this branch.
 
768
 
 
769
        The caller is responsible for checking that the revno is correct
 
770
        for this revision id.
 
771
 
 
772
        It may be possible to set the branch last revision to an id not
 
773
        present in the repository.  However, branches can also be
 
774
        configured to check constraints on history, in which case this may not
 
775
        be permitted.
 
776
        """
 
777
        raise NotImplementedError(self.last_revision_info)
 
778
 
 
779
    @needs_write_lock
 
780
    def generate_revision_history(self, revision_id, last_rev=None,
 
781
                                  other_branch=None):
 
782
        """See Branch.generate_revision_history"""
 
783
        graph = self.repository.get_graph()
 
784
        known_revision_ids = [
 
785
            self.last_revision_info(),
 
786
            (_mod_revision.NULL_REVISION, 0),
 
787
            ]
 
788
        if last_rev is not None:
 
789
            if not graph.is_ancestor(last_rev, revision_id):
 
790
                # our previous tip is not merged into stop_revision
 
791
                raise errors.DivergedBranches(self, other_branch)
 
792
        revno = graph.find_distance_to_null(revision_id, known_revision_ids)
 
793
        self.set_last_revision_info(revno, revision_id)
 
794
 
 
795
    @needs_write_lock
 
796
    def set_parent(self, url):
 
797
        """See Branch.set_parent."""
 
798
        # TODO: Maybe delete old location files?
 
799
        # URLs should never be unicode, even on the local fs,
 
800
        # FIXUP this and get_parent in a future branch format bump:
 
801
        # read and rewrite the file. RBC 20060125
 
802
        if url is not None:
 
803
            if isinstance(url, unicode):
 
804
                try:
 
805
                    url = url.encode('ascii')
 
806
                except UnicodeEncodeError:
 
807
                    raise errors.InvalidURL(url,
 
808
                        "Urls must be 7-bit ascii, "
 
809
                        "use bzrlib.urlutils.escape")
 
810
            url = urlutils.relative_url(self.base, url)
 
811
        self._set_parent_location(url)
 
812
 
 
813
    @needs_write_lock
 
814
    def set_stacked_on_url(self, url):
 
815
        """Set the URL this branch is stacked against.
 
816
 
 
817
        :raises UnstackableBranchFormat: If the branch does not support
 
818
            stacking.
 
819
        :raises UnstackableRepositoryFormat: If the repository does not support
 
820
            stacking.
 
821
        """
 
822
        if not self._format.supports_stacking():
 
823
            raise errors.UnstackableBranchFormat(self._format, self.user_url)
 
824
        # XXX: Changing from one fallback repository to another does not check
 
825
        # that all the data you need is present in the new fallback.
 
826
        # Possibly it should.
 
827
        self._check_stackable_repo()
 
828
        if not url:
 
829
            try:
 
830
                old_url = self.get_stacked_on_url()
 
831
            except (errors.NotStacked, errors.UnstackableBranchFormat,
 
832
                errors.UnstackableRepositoryFormat):
 
833
                return
 
834
            self._unstack()
 
835
        else:
 
836
            self._activate_fallback_location(url)
 
837
        # write this out after the repository is stacked to avoid setting a
 
838
        # stacked config that doesn't work.
 
839
        self._set_config_location('stacked_on_location', url)
 
840
 
 
841
    def _unstack(self):
 
842
        """Change a branch to be unstacked, copying data as needed.
 
843
 
 
844
        Don't call this directly, use set_stacked_on_url(None).
 
845
        """
 
846
        pb = ui.ui_factory.nested_progress_bar()
 
847
        try:
 
848
            pb.update("Unstacking")
 
849
            # The basic approach here is to fetch the tip of the branch,
 
850
            # including all available ghosts, from the existing stacked
 
851
            # repository into a new repository object without the fallbacks. 
 
852
            #
 
853
            # XXX: See <https://launchpad.net/bugs/397286> - this may not be
 
854
            # correct for CHKMap repostiories
 
855
            old_repository = self.repository
 
856
            if len(old_repository._fallback_repositories) != 1:
 
857
                raise AssertionError("can't cope with fallback repositories "
 
858
                    "of %r (fallbacks: %r)" % (old_repository,
 
859
                        old_repository._fallback_repositories))
 
860
            # Open the new repository object.
 
861
            # Repositories don't offer an interface to remove fallback
 
862
            # repositories today; take the conceptually simpler option and just
 
863
            # reopen it.  We reopen it starting from the URL so that we
 
864
            # get a separate connection for RemoteRepositories and can
 
865
            # stream from one of them to the other.  This does mean doing
 
866
            # separate SSH connection setup, but unstacking is not a
 
867
            # common operation so it's tolerable.
 
868
            new_bzrdir = bzrdir.BzrDir.open(self.bzrdir.root_transport.base)
 
869
            new_repository = new_bzrdir.find_repository()
 
870
            if new_repository._fallback_repositories:
 
871
                raise AssertionError("didn't expect %r to have "
 
872
                    "fallback_repositories"
 
873
                    % (self.repository,))
 
874
            # Replace self.repository with the new repository.
 
875
            # Do our best to transfer the lock state (i.e. lock-tokens and
 
876
            # lock count) of self.repository to the new repository.
 
877
            lock_token = old_repository.lock_write().repository_token
 
878
            self.repository = new_repository
 
879
            if isinstance(self, remote.RemoteBranch):
 
880
                # Remote branches can have a second reference to the old
 
881
                # repository that need to be replaced.
 
882
                if self._real_branch is not None:
 
883
                    self._real_branch.repository = new_repository
 
884
            self.repository.lock_write(token=lock_token)
 
885
            if lock_token is not None:
 
886
                old_repository.leave_lock_in_place()
 
887
            old_repository.unlock()
 
888
            if lock_token is not None:
 
889
                # XXX: self.repository.leave_lock_in_place() before this
 
890
                # function will not be preserved.  Fortunately that doesn't
 
891
                # affect the current default format (2a), and would be a
 
892
                # corner-case anyway.
 
893
                #  - Andrew Bennetts, 2010/06/30
 
894
                self.repository.dont_leave_lock_in_place()
 
895
            old_lock_count = 0
 
896
            while True:
 
897
                try:
 
898
                    old_repository.unlock()
 
899
                except errors.LockNotHeld:
 
900
                    break
 
901
                old_lock_count += 1
 
902
            if old_lock_count == 0:
 
903
                raise AssertionError(
 
904
                    'old_repository should have been locked at least once.')
 
905
            for i in range(old_lock_count-1):
 
906
                self.repository.lock_write()
 
907
            # Fetch from the old repository into the new.
 
908
            old_repository.lock_read()
 
909
            try:
 
910
                # XXX: If you unstack a branch while it has a working tree
 
911
                # with a pending merge, the pending-merged revisions will no
 
912
                # longer be present.  You can (probably) revert and remerge.
 
913
                try:
 
914
                    tags_to_fetch = set(self.tags.get_reverse_tag_dict())
 
915
                except errors.TagsNotSupported:
 
916
                    tags_to_fetch = set()
 
917
                fetch_spec = _mod_graph.NotInOtherForRevs(self.repository,
 
918
                    old_repository, required_ids=[self.last_revision()],
 
919
                    if_present_ids=tags_to_fetch, find_ghosts=True).execute()
 
920
                self.repository.fetch(old_repository, fetch_spec=fetch_spec)
 
921
            finally:
 
922
                old_repository.unlock()
 
923
        finally:
 
924
            pb.finished()
 
925
 
 
926
    def _set_tags_bytes(self, bytes):
 
927
        """Mirror method for _get_tags_bytes.
 
928
 
 
929
        :seealso: Branch._get_tags_bytes.
 
930
        """
 
931
        return _run_with_write_locked_target(self, self._set_tags_bytes_locked,
 
932
                bytes)
 
933
 
 
934
    def _set_tags_bytes_locked(self, bytes):
 
935
        self._tags_bytes = bytes
 
936
        return self._transport.put_bytes('tags', bytes)
 
937
 
 
938
    def _cache_revision_history(self, rev_history):
 
939
        """Set the cached revision history to rev_history.
 
940
 
 
941
        The revision_history method will use this cache to avoid regenerating
 
942
        the revision history.
 
943
 
 
944
        This API is semi-public; it only for use by subclasses, all other code
 
945
        should consider it to be private.
 
946
        """
 
947
        self._revision_history_cache = rev_history
 
948
 
 
949
    def _cache_revision_id_to_revno(self, revision_id_to_revno):
 
950
        """Set the cached revision_id => revno map to revision_id_to_revno.
 
951
 
 
952
        This API is semi-public; it only for use by subclasses, all other code
 
953
        should consider it to be private.
 
954
        """
 
955
        self._revision_id_to_revno_cache = revision_id_to_revno
 
956
 
 
957
    def _clear_cached_state(self):
 
958
        """Clear any cached data on this branch, e.g. cached revision history.
 
959
 
 
960
        This means the next call to revision_history will need to call
 
961
        _gen_revision_history.
 
962
 
 
963
        This API is semi-public; it only for use by subclasses, all other code
 
964
        should consider it to be private.
 
965
        """
 
966
        self._revision_history_cache = None
 
967
        self._revision_id_to_revno_cache = None
 
968
        self._last_revision_info_cache = None
 
969
        self._master_branch_cache = None
 
970
        self._merge_sorted_revisions_cache = None
 
971
        self._partial_revision_history_cache = []
 
972
        self._partial_revision_id_to_revno_cache = {}
 
973
        self._tags_bytes = None
 
974
 
 
975
    def _gen_revision_history(self):
 
976
        """Return sequence of revision hashes on to this branch.
 
977
 
 
978
        Unlike revision_history, this method always regenerates or rereads the
 
979
        revision history, i.e. it does not cache the result, so repeated calls
 
980
        may be expensive.
 
981
 
 
982
        Concrete subclasses should override this instead of revision_history so
 
983
        that subclasses do not need to deal with caching logic.
 
984
 
 
985
        This API is semi-public; it only for use by subclasses, all other code
 
986
        should consider it to be private.
 
987
        """
 
988
        raise NotImplementedError(self._gen_revision_history)
 
989
 
 
990
    @needs_read_lock
 
991
    def revision_history(self):
 
992
        """Return sequence of revision ids on this branch.
 
993
 
 
994
        This method will cache the revision history for as long as it is safe to
 
995
        do so.
 
996
        """
 
997
        if 'evil' in debug.debug_flags:
 
998
            mutter_callsite(3, "revision_history scales with history.")
 
999
        if self._revision_history_cache is not None:
 
1000
            history = self._revision_history_cache
 
1001
        else:
 
1002
            history = self._gen_revision_history()
 
1003
            self._cache_revision_history(history)
 
1004
        return list(history)
 
1005
 
 
1006
    def revno(self):
 
1007
        """Return current revision number for this branch.
 
1008
 
 
1009
        That is equivalent to the number of revisions committed to
 
1010
        this branch.
 
1011
        """
 
1012
        return self.last_revision_info()[0]
 
1013
 
 
1014
    def unbind(self):
 
1015
        """Older format branches cannot bind or unbind."""
 
1016
        raise errors.UpgradeRequired(self.user_url)
 
1017
 
 
1018
    def last_revision(self):
 
1019
        """Return last revision id, or NULL_REVISION."""
 
1020
        return self.last_revision_info()[1]
 
1021
 
 
1022
    @needs_read_lock
 
1023
    def last_revision_info(self):
 
1024
        """Return information about the last revision.
 
1025
 
 
1026
        :return: A tuple (revno, revision_id).
 
1027
        """
 
1028
        if self._last_revision_info_cache is None:
 
1029
            self._last_revision_info_cache = self._read_last_revision_info()
 
1030
        return self._last_revision_info_cache
 
1031
 
 
1032
    def _read_last_revision_info(self):
 
1033
        raise NotImplementedError(self._read_last_revision_info)
 
1034
 
 
1035
    @deprecated_method(deprecated_in((2, 4, 0)))
 
1036
    def import_last_revision_info(self, source_repo, revno, revid):
 
1037
        """Set the last revision info, importing from another repo if necessary.
 
1038
 
 
1039
        :param source_repo: Source repository to optionally fetch from
 
1040
        :param revno: Revision number of the new tip
 
1041
        :param revid: Revision id of the new tip
 
1042
        """
 
1043
        if not self.repository.has_same_location(source_repo):
 
1044
            self.repository.fetch(source_repo, revision_id=revid)
 
1045
        self.set_last_revision_info(revno, revid)
 
1046
 
 
1047
    def import_last_revision_info_and_tags(self, source, revno, revid,
 
1048
                                           lossy=False):
 
1049
        """Set the last revision info, importing from another repo if necessary.
 
1050
 
 
1051
        This is used by the bound branch code to upload a revision to
 
1052
        the master branch first before updating the tip of the local branch.
 
1053
        Revisions referenced by source's tags are also transferred.
 
1054
 
 
1055
        :param source: Source branch to optionally fetch from
 
1056
        :param revno: Revision number of the new tip
 
1057
        :param revid: Revision id of the new tip
 
1058
        :param lossy: Whether to discard metadata that can not be
 
1059
            natively represented
 
1060
        :return: Tuple with the new revision number and revision id
 
1061
            (should only be different from the arguments when lossy=True)
 
1062
        """
 
1063
        if not self.repository.has_same_location(source.repository):
 
1064
            self.fetch(source, revid)
 
1065
        self.set_last_revision_info(revno, revid)
 
1066
        return (revno, revid)
 
1067
 
 
1068
    def revision_id_to_revno(self, revision_id):
 
1069
        """Given a revision id, return its revno"""
 
1070
        if _mod_revision.is_null(revision_id):
 
1071
            return 0
 
1072
        history = self.revision_history()
 
1073
        try:
 
1074
            return history.index(revision_id) + 1
 
1075
        except ValueError:
 
1076
            raise errors.NoSuchRevision(self, revision_id)
 
1077
 
 
1078
    @needs_read_lock
 
1079
    def get_rev_id(self, revno, history=None):
 
1080
        """Find the revision id of the specified revno."""
 
1081
        if revno == 0:
 
1082
            return _mod_revision.NULL_REVISION
 
1083
        last_revno, last_revid = self.last_revision_info()
 
1084
        if revno == last_revno:
 
1085
            return last_revid
 
1086
        if revno <= 0 or revno > last_revno:
 
1087
            raise errors.NoSuchRevision(self, revno)
 
1088
        distance_from_last = last_revno - revno
 
1089
        if len(self._partial_revision_history_cache) <= distance_from_last:
 
1090
            self._extend_partial_history(distance_from_last)
 
1091
        return self._partial_revision_history_cache[distance_from_last]
 
1092
 
 
1093
    def pull(self, source, overwrite=False, stop_revision=None,
 
1094
             possible_transports=None, *args, **kwargs):
 
1095
        """Mirror source into this branch.
 
1096
 
 
1097
        This branch is considered to be 'local', having low latency.
 
1098
 
 
1099
        :returns: PullResult instance
 
1100
        """
 
1101
        return InterBranch.get(source, self).pull(overwrite=overwrite,
 
1102
            stop_revision=stop_revision,
 
1103
            possible_transports=possible_transports, *args, **kwargs)
 
1104
 
 
1105
    def push(self, target, overwrite=False, stop_revision=None, lossy=False,
 
1106
            *args, **kwargs):
 
1107
        """Mirror this branch into target.
 
1108
 
 
1109
        This branch is considered to be 'local', having low latency.
 
1110
        """
 
1111
        return InterBranch.get(self, target).push(overwrite, stop_revision,
 
1112
            lossy, *args, **kwargs)
 
1113
 
 
1114
    def basis_tree(self):
 
1115
        """Return `Tree` object for last revision."""
 
1116
        return self.repository.revision_tree(self.last_revision())
 
1117
 
 
1118
    def get_parent(self):
 
1119
        """Return the parent location of the branch.
 
1120
 
 
1121
        This is the default location for pull/missing.  The usual
 
1122
        pattern is that the user can override it by specifying a
 
1123
        location.
 
1124
        """
 
1125
        parent = self._get_parent_location()
 
1126
        if parent is None:
 
1127
            return parent
 
1128
        # This is an old-format absolute path to a local branch
 
1129
        # turn it into a url
 
1130
        if parent.startswith('/'):
 
1131
            parent = urlutils.local_path_to_url(parent.decode('utf8'))
 
1132
        try:
 
1133
            return urlutils.join(self.base[:-1], parent)
 
1134
        except errors.InvalidURLJoin, e:
 
1135
            raise errors.InaccessibleParent(parent, self.user_url)
 
1136
 
 
1137
    def _get_parent_location(self):
 
1138
        raise NotImplementedError(self._get_parent_location)
 
1139
 
 
1140
    def _set_config_location(self, name, url, config=None,
 
1141
                             make_relative=False):
 
1142
        if config is None:
 
1143
            config = self.get_config()
 
1144
        if url is None:
 
1145
            url = ''
 
1146
        elif make_relative:
 
1147
            url = urlutils.relative_url(self.base, url)
 
1148
        config.set_user_option(name, url, warn_masked=True)
 
1149
 
 
1150
    def _get_config_location(self, name, config=None):
 
1151
        if config is None:
 
1152
            config = self.get_config()
 
1153
        location = config.get_user_option(name)
 
1154
        if location == '':
 
1155
            location = None
 
1156
        return location
 
1157
 
 
1158
    def get_child_submit_format(self):
 
1159
        """Return the preferred format of submissions to this branch."""
 
1160
        return self.get_config().get_user_option("child_submit_format")
 
1161
 
 
1162
    def get_submit_branch(self):
 
1163
        """Return the submit location of the branch.
 
1164
 
 
1165
        This is the default location for bundle.  The usual
 
1166
        pattern is that the user can override it by specifying a
 
1167
        location.
 
1168
        """
 
1169
        return self.get_config().get_user_option('submit_branch')
 
1170
 
 
1171
    def set_submit_branch(self, location):
 
1172
        """Return the submit location of the branch.
 
1173
 
 
1174
        This is the default location for bundle.  The usual
 
1175
        pattern is that the user can override it by specifying a
 
1176
        location.
 
1177
        """
 
1178
        self.get_config().set_user_option('submit_branch', location,
 
1179
            warn_masked=True)
 
1180
 
 
1181
    def get_public_branch(self):
 
1182
        """Return the public location of the branch.
 
1183
 
 
1184
        This is used by merge directives.
 
1185
        """
 
1186
        return self._get_config_location('public_branch')
 
1187
 
 
1188
    def set_public_branch(self, location):
 
1189
        """Return the submit location of the branch.
 
1190
 
 
1191
        This is the default location for bundle.  The usual
 
1192
        pattern is that the user can override it by specifying a
 
1193
        location.
 
1194
        """
 
1195
        self._set_config_location('public_branch', location)
 
1196
 
 
1197
    def get_push_location(self):
 
1198
        """Return the None or the location to push this branch to."""
 
1199
        push_loc = self.get_config().get_user_option('push_location')
 
1200
        return push_loc
 
1201
 
 
1202
    def set_push_location(self, location):
 
1203
        """Set a new push location for this branch."""
 
1204
        raise NotImplementedError(self.set_push_location)
 
1205
 
 
1206
    def _run_post_change_branch_tip_hooks(self, old_revno, old_revid):
 
1207
        """Run the post_change_branch_tip hooks."""
 
1208
        hooks = Branch.hooks['post_change_branch_tip']
 
1209
        if not hooks:
 
1210
            return
 
1211
        new_revno, new_revid = self.last_revision_info()
 
1212
        params = ChangeBranchTipParams(
 
1213
            self, old_revno, new_revno, old_revid, new_revid)
 
1214
        for hook in hooks:
 
1215
            hook(params)
 
1216
 
 
1217
    def _run_pre_change_branch_tip_hooks(self, new_revno, new_revid):
 
1218
        """Run the pre_change_branch_tip hooks."""
 
1219
        hooks = Branch.hooks['pre_change_branch_tip']
 
1220
        if not hooks:
 
1221
            return
 
1222
        old_revno, old_revid = self.last_revision_info()
 
1223
        params = ChangeBranchTipParams(
 
1224
            self, old_revno, new_revno, old_revid, new_revid)
 
1225
        for hook in hooks:
 
1226
            hook(params)
 
1227
 
 
1228
    @needs_write_lock
 
1229
    def update(self):
 
1230
        """Synchronise this branch with the master branch if any.
 
1231
 
 
1232
        :return: None or the last_revision pivoted out during the update.
 
1233
        """
 
1234
        return None
 
1235
 
 
1236
    def check_revno(self, revno):
 
1237
        """\
 
1238
        Check whether a revno corresponds to any revision.
 
1239
        Zero (the NULL revision) is considered valid.
 
1240
        """
 
1241
        if revno != 0:
 
1242
            self.check_real_revno(revno)
 
1243
 
 
1244
    def check_real_revno(self, revno):
 
1245
        """\
 
1246
        Check whether a revno corresponds to a real revision.
 
1247
        Zero (the NULL revision) is considered invalid
 
1248
        """
 
1249
        if revno < 1 or revno > self.revno():
 
1250
            raise errors.InvalidRevisionNumber(revno)
 
1251
 
 
1252
    @needs_read_lock
 
1253
    def clone(self, to_bzrdir, revision_id=None, repository_policy=None):
 
1254
        """Clone this branch into to_bzrdir preserving all semantic values.
 
1255
 
 
1256
        Most API users will want 'create_clone_on_transport', which creates a
 
1257
        new bzrdir and branch on the fly.
 
1258
 
 
1259
        revision_id: if not None, the revision history in the new branch will
 
1260
                     be truncated to end with revision_id.
 
1261
        """
 
1262
        result = to_bzrdir.create_branch()
 
1263
        result.lock_write()
 
1264
        try:
 
1265
            if repository_policy is not None:
 
1266
                repository_policy.configure_branch(result)
 
1267
            self.copy_content_into(result, revision_id=revision_id)
 
1268
        finally:
 
1269
            result.unlock()
 
1270
        return result
 
1271
 
 
1272
    @needs_read_lock
 
1273
    def sprout(self, to_bzrdir, revision_id=None, repository_policy=None,
 
1274
            repository=None):
 
1275
        """Create a new line of development from the branch, into to_bzrdir.
 
1276
 
 
1277
        to_bzrdir controls the branch format.
 
1278
 
 
1279
        revision_id: if not None, the revision history in the new branch will
 
1280
                     be truncated to end with revision_id.
 
1281
        """
 
1282
        if (repository_policy is not None and
 
1283
            repository_policy.requires_stacking()):
 
1284
            to_bzrdir._format.require_stacking(_skip_repo=True)
 
1285
        result = to_bzrdir.create_branch(repository=repository)
 
1286
        result.lock_write()
 
1287
        try:
 
1288
            if repository_policy is not None:
 
1289
                repository_policy.configure_branch(result)
 
1290
            self.copy_content_into(result, revision_id=revision_id)
 
1291
            master_branch = self.get_master_branch()
 
1292
            if master_branch is None:
 
1293
                result.set_parent(self.bzrdir.root_transport.base)
 
1294
            else:
 
1295
                result.set_parent(master_branch.bzrdir.root_transport.base)
 
1296
        finally:
 
1297
            result.unlock()
 
1298
        return result
 
1299
 
 
1300
    def _synchronize_history(self, destination, revision_id):
 
1301
        """Synchronize last revision and revision history between branches.
 
1302
 
 
1303
        This version is most efficient when the destination is also a
 
1304
        BzrBranch6, but works for BzrBranch5, as long as the destination's
 
1305
        repository contains all the lefthand ancestors of the intended
 
1306
        last_revision.  If not, set_last_revision_info will fail.
 
1307
 
 
1308
        :param destination: The branch to copy the history into
 
1309
        :param revision_id: The revision-id to truncate history at.  May
 
1310
          be None to copy complete history.
 
1311
        """
 
1312
        source_revno, source_revision_id = self.last_revision_info()
 
1313
        if revision_id is None:
 
1314
            revno, revision_id = source_revno, source_revision_id
 
1315
        else:
 
1316
            graph = self.repository.get_graph()
 
1317
            try:
 
1318
                revno = graph.find_distance_to_null(revision_id, 
 
1319
                    [(source_revision_id, source_revno)])
 
1320
            except errors.GhostRevisionsHaveNoRevno:
 
1321
                # Default to 1, if we can't find anything else
 
1322
                revno = 1
 
1323
        destination.set_last_revision_info(revno, revision_id)
 
1324
 
 
1325
    def copy_content_into(self, destination, revision_id=None):
 
1326
        """Copy the content of self into destination.
 
1327
 
 
1328
        revision_id: if not None, the revision history in the new branch will
 
1329
                     be truncated to end with revision_id.
 
1330
        """
 
1331
        return InterBranch.get(self, destination).copy_content_into(
 
1332
            revision_id=revision_id)
 
1333
 
 
1334
    def update_references(self, target):
 
1335
        if not getattr(self._format, 'supports_reference_locations', False):
 
1336
            return
 
1337
        reference_dict = self._get_all_reference_info()
 
1338
        if len(reference_dict) == 0:
 
1339
            return
 
1340
        old_base = self.base
 
1341
        new_base = target.base
 
1342
        target_reference_dict = target._get_all_reference_info()
 
1343
        for file_id, (tree_path, branch_location) in (
 
1344
            reference_dict.items()):
 
1345
            branch_location = urlutils.rebase_url(branch_location,
 
1346
                                                  old_base, new_base)
 
1347
            target_reference_dict.setdefault(
 
1348
                file_id, (tree_path, branch_location))
 
1349
        target._set_all_reference_info(target_reference_dict)
 
1350
 
 
1351
    @needs_read_lock
 
1352
    def check(self, refs):
 
1353
        """Check consistency of the branch.
 
1354
 
 
1355
        In particular this checks that revisions given in the revision-history
 
1356
        do actually match up in the revision graph, and that they're all
 
1357
        present in the repository.
 
1358
 
 
1359
        Callers will typically also want to check the repository.
 
1360
 
 
1361
        :param refs: Calculated refs for this branch as specified by
 
1362
            branch._get_check_refs()
 
1363
        :return: A BranchCheckResult.
 
1364
        """
 
1365
        result = BranchCheckResult(self)
 
1366
        last_revno, last_revision_id = self.last_revision_info()
 
1367
        actual_revno = refs[('lefthand-distance', last_revision_id)]
 
1368
        if actual_revno != last_revno:
 
1369
            result.errors.append(errors.BzrCheckError(
 
1370
                'revno does not match len(mainline) %s != %s' % (
 
1371
                last_revno, actual_revno)))
 
1372
        # TODO: We should probably also check that self.revision_history
 
1373
        # matches the repository for older branch formats.
 
1374
        # If looking for the code that cross-checks repository parents against
 
1375
        # the iter_reverse_revision_history output, that is now a repository
 
1376
        # specific check.
 
1377
        return result
 
1378
 
 
1379
    def _get_checkout_format(self):
 
1380
        """Return the most suitable metadir for a checkout of this branch.
 
1381
        Weaves are used if this branch's repository uses weaves.
 
1382
        """
 
1383
        format = self.repository.bzrdir.checkout_metadir()
 
1384
        format.set_branch_format(self._format)
 
1385
        return format
 
1386
 
 
1387
    def create_clone_on_transport(self, to_transport, revision_id=None,
 
1388
        stacked_on=None, create_prefix=False, use_existing_dir=False,
 
1389
        no_tree=None):
 
1390
        """Create a clone of this branch and its bzrdir.
 
1391
 
 
1392
        :param to_transport: The transport to clone onto.
 
1393
        :param revision_id: The revision id to use as tip in the new branch.
 
1394
            If None the tip is obtained from this branch.
 
1395
        :param stacked_on: An optional URL to stack the clone on.
 
1396
        :param create_prefix: Create any missing directories leading up to
 
1397
            to_transport.
 
1398
        :param use_existing_dir: Use an existing directory if one exists.
 
1399
        """
 
1400
        # XXX: Fix the bzrdir API to allow getting the branch back from the
 
1401
        # clone call. Or something. 20090224 RBC/spiv.
 
1402
        # XXX: Should this perhaps clone colocated branches as well, 
 
1403
        # rather than just the default branch? 20100319 JRV
 
1404
        if revision_id is None:
 
1405
            revision_id = self.last_revision()
 
1406
        dir_to = self.bzrdir.clone_on_transport(to_transport,
 
1407
            revision_id=revision_id, stacked_on=stacked_on,
 
1408
            create_prefix=create_prefix, use_existing_dir=use_existing_dir,
 
1409
            no_tree=no_tree)
 
1410
        return dir_to.open_branch()
 
1411
 
 
1412
    def create_checkout(self, to_location, revision_id=None,
 
1413
                        lightweight=False, accelerator_tree=None,
 
1414
                        hardlink=False):
 
1415
        """Create a checkout of a branch.
 
1416
 
 
1417
        :param to_location: The url to produce the checkout at
 
1418
        :param revision_id: The revision to check out
 
1419
        :param lightweight: If True, produce a lightweight checkout, otherwise,
 
1420
        produce a bound branch (heavyweight checkout)
 
1421
        :param accelerator_tree: A tree which can be used for retrieving file
 
1422
            contents more quickly than the revision tree, i.e. a workingtree.
 
1423
            The revision tree will be used for cases where accelerator_tree's
 
1424
            content is different.
 
1425
        :param hardlink: If true, hard-link files from accelerator_tree,
 
1426
            where possible.
 
1427
        :return: The tree of the created checkout
 
1428
        """
 
1429
        t = transport.get_transport(to_location)
 
1430
        t.ensure_base()
 
1431
        if lightweight:
 
1432
            format = self._get_checkout_format()
 
1433
            checkout = format.initialize_on_transport(t)
 
1434
            from_branch = BranchReferenceFormat().initialize(checkout, 
 
1435
                target_branch=self)
 
1436
        else:
 
1437
            format = self._get_checkout_format()
 
1438
            checkout_branch = bzrdir.BzrDir.create_branch_convenience(
 
1439
                to_location, force_new_tree=False, format=format)
 
1440
            checkout = checkout_branch.bzrdir
 
1441
            checkout_branch.bind(self)
 
1442
            # pull up to the specified revision_id to set the initial
 
1443
            # branch tip correctly, and seed it with history.
 
1444
            checkout_branch.pull(self, stop_revision=revision_id)
 
1445
            from_branch=None
 
1446
        tree = checkout.create_workingtree(revision_id,
 
1447
                                           from_branch=from_branch,
 
1448
                                           accelerator_tree=accelerator_tree,
 
1449
                                           hardlink=hardlink)
 
1450
        basis_tree = tree.basis_tree()
 
1451
        basis_tree.lock_read()
 
1452
        try:
 
1453
            for path, file_id in basis_tree.iter_references():
 
1454
                reference_parent = self.reference_parent(file_id, path)
 
1455
                reference_parent.create_checkout(tree.abspath(path),
 
1456
                    basis_tree.get_reference_revision(file_id, path),
 
1457
                    lightweight)
 
1458
        finally:
 
1459
            basis_tree.unlock()
 
1460
        return tree
 
1461
 
 
1462
    @needs_write_lock
 
1463
    def reconcile(self, thorough=True):
 
1464
        """Make sure the data stored in this branch is consistent."""
 
1465
        from bzrlib.reconcile import BranchReconciler
 
1466
        reconciler = BranchReconciler(self, thorough=thorough)
 
1467
        reconciler.reconcile()
 
1468
        return reconciler
 
1469
 
 
1470
    def reference_parent(self, file_id, path, possible_transports=None):
 
1471
        """Return the parent branch for a tree-reference file_id
 
1472
        :param file_id: The file_id of the tree reference
 
1473
        :param path: The path of the file_id in the tree
 
1474
        :return: A branch associated with the file_id
 
1475
        """
 
1476
        # FIXME should provide multiple branches, based on config
 
1477
        return Branch.open(self.bzrdir.root_transport.clone(path).base,
 
1478
                           possible_transports=possible_transports)
 
1479
 
 
1480
    def supports_tags(self):
 
1481
        return self._format.supports_tags()
 
1482
 
 
1483
    def automatic_tag_name(self, revision_id):
 
1484
        """Try to automatically find the tag name for a revision.
 
1485
 
 
1486
        :param revision_id: Revision id of the revision.
 
1487
        :return: A tag name or None if no tag name could be determined.
 
1488
        """
 
1489
        for hook in Branch.hooks['automatic_tag_name']:
 
1490
            ret = hook(self, revision_id)
 
1491
            if ret is not None:
 
1492
                return ret
 
1493
        return None
 
1494
 
 
1495
    def _check_if_descendant_or_diverged(self, revision_a, revision_b, graph,
 
1496
                                         other_branch):
 
1497
        """Ensure that revision_b is a descendant of revision_a.
 
1498
 
 
1499
        This is a helper function for update_revisions.
 
1500
 
 
1501
        :raises: DivergedBranches if revision_b has diverged from revision_a.
 
1502
        :returns: True if revision_b is a descendant of revision_a.
 
1503
        """
 
1504
        relation = self._revision_relations(revision_a, revision_b, graph)
 
1505
        if relation == 'b_descends_from_a':
 
1506
            return True
 
1507
        elif relation == 'diverged':
 
1508
            raise errors.DivergedBranches(self, other_branch)
 
1509
        elif relation == 'a_descends_from_b':
 
1510
            return False
 
1511
        else:
 
1512
            raise AssertionError("invalid relation: %r" % (relation,))
 
1513
 
 
1514
    def _revision_relations(self, revision_a, revision_b, graph):
 
1515
        """Determine the relationship between two revisions.
 
1516
 
 
1517
        :returns: One of: 'a_descends_from_b', 'b_descends_from_a', 'diverged'
 
1518
        """
 
1519
        heads = graph.heads([revision_a, revision_b])
 
1520
        if heads == set([revision_b]):
 
1521
            return 'b_descends_from_a'
 
1522
        elif heads == set([revision_a, revision_b]):
 
1523
            # These branches have diverged
 
1524
            return 'diverged'
 
1525
        elif heads == set([revision_a]):
 
1526
            return 'a_descends_from_b'
 
1527
        else:
 
1528
            raise AssertionError("invalid heads: %r" % (heads,))
 
1529
 
 
1530
    def heads_to_fetch(self):
 
1531
        """Return the heads that must and that should be fetched to copy this
 
1532
        branch into another repo.
 
1533
 
 
1534
        :returns: a 2-tuple of (must_fetch, if_present_fetch).  must_fetch is a
 
1535
            set of heads that must be fetched.  if_present_fetch is a set of
 
1536
            heads that must be fetched if present, but no error is necessary if
 
1537
            they are not present.
 
1538
        """
 
1539
        # For bzr native formats must_fetch is just the tip, and if_present_fetch
 
1540
        # are the tags.
 
1541
        must_fetch = set([self.last_revision()])
 
1542
        try:
 
1543
            if_present_fetch = set(self.tags.get_reverse_tag_dict())
 
1544
        except errors.TagsNotSupported:
 
1545
            if_present_fetch = set()
 
1546
        must_fetch.discard(_mod_revision.NULL_REVISION)
 
1547
        if_present_fetch.discard(_mod_revision.NULL_REVISION)
 
1548
        return must_fetch, if_present_fetch
 
1549
 
 
1550
 
 
1551
class BranchFormat(controldir.ControlComponentFormat):
 
1552
    """An encapsulation of the initialization and open routines for a format.
 
1553
 
 
1554
    Formats provide three things:
 
1555
     * An initialization routine,
 
1556
     * a format string,
 
1557
     * an open routine.
 
1558
 
 
1559
    Formats are placed in an dict by their format string for reference
 
1560
    during branch opening. It's not required that these be instances, they
 
1561
    can be classes themselves with class methods - it simply depends on
 
1562
    whether state is needed for a given format or not.
 
1563
 
 
1564
    Once a format is deprecated, just deprecate the initialize and open
 
1565
    methods on the format class. Do not deprecate the object, as the
 
1566
    object will be created every time regardless.
 
1567
    """
 
1568
 
 
1569
    can_set_append_revisions_only = True
 
1570
 
 
1571
    def __eq__(self, other):
 
1572
        return self.__class__ is other.__class__
 
1573
 
 
1574
    def __ne__(self, other):
 
1575
        return not (self == other)
 
1576
 
 
1577
    @classmethod
 
1578
    def find_format(klass, a_bzrdir, name=None):
 
1579
        """Return the format for the branch object in a_bzrdir."""
 
1580
        try:
 
1581
            transport = a_bzrdir.get_branch_transport(None, name=name)
 
1582
            format_string = transport.get_bytes("format")
 
1583
            return format_registry.get(format_string)
 
1584
        except errors.NoSuchFile:
 
1585
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
 
1586
        except KeyError:
 
1587
            raise errors.UnknownFormatError(format=format_string, kind='branch')
 
1588
 
 
1589
    @classmethod
 
1590
    @deprecated_method(deprecated_in((2, 4, 0)))
 
1591
    def get_default_format(klass):
 
1592
        """Return the current default format."""
 
1593
        return format_registry.get_default()
 
1594
 
 
1595
    @classmethod
 
1596
    @deprecated_method(deprecated_in((2, 4, 0)))
 
1597
    def get_formats(klass):
 
1598
        """Get all the known formats.
 
1599
 
 
1600
        Warning: This triggers a load of all lazy registered formats: do not
 
1601
        use except when that is desireed.
 
1602
        """
 
1603
        return format_registry._get_all()
 
1604
 
 
1605
    def get_reference(self, a_bzrdir, name=None):
 
1606
        """Get the target reference of the branch in a_bzrdir.
 
1607
 
 
1608
        format probing must have been completed before calling
 
1609
        this method - it is assumed that the format of the branch
 
1610
        in a_bzrdir is correct.
 
1611
 
 
1612
        :param a_bzrdir: The bzrdir to get the branch data from.
 
1613
        :param name: Name of the colocated branch to fetch
 
1614
        :return: None if the branch is not a reference branch.
 
1615
        """
 
1616
        return None
 
1617
 
 
1618
    @classmethod
 
1619
    def set_reference(self, a_bzrdir, name, to_branch):
 
1620
        """Set the target reference of the branch in a_bzrdir.
 
1621
 
 
1622
        format probing must have been completed before calling
 
1623
        this method - it is assumed that the format of the branch
 
1624
        in a_bzrdir is correct.
 
1625
 
 
1626
        :param a_bzrdir: The bzrdir to set the branch reference for.
 
1627
        :param name: Name of colocated branch to set, None for default
 
1628
        :param to_branch: branch that the checkout is to reference
 
1629
        """
 
1630
        raise NotImplementedError(self.set_reference)
 
1631
 
 
1632
    def get_format_string(self):
 
1633
        """Return the ASCII format string that identifies this format."""
 
1634
        raise NotImplementedError(self.get_format_string)
 
1635
 
 
1636
    def get_format_description(self):
 
1637
        """Return the short format description for this format."""
 
1638
        raise NotImplementedError(self.get_format_description)
 
1639
 
 
1640
    def _run_post_branch_init_hooks(self, a_bzrdir, name, branch):
 
1641
        hooks = Branch.hooks['post_branch_init']
 
1642
        if not hooks:
 
1643
            return
 
1644
        params = BranchInitHookParams(self, a_bzrdir, name, branch)
 
1645
        for hook in hooks:
 
1646
            hook(params)
 
1647
 
 
1648
    def initialize(self, a_bzrdir, name=None, repository=None):
 
1649
        """Create a branch of this format in a_bzrdir.
 
1650
        
 
1651
        :param name: Name of the colocated branch to create.
 
1652
        """
 
1653
        raise NotImplementedError(self.initialize)
 
1654
 
 
1655
    def is_supported(self):
 
1656
        """Is this format supported?
 
1657
 
 
1658
        Supported formats can be initialized and opened.
 
1659
        Unsupported formats may not support initialization or committing or
 
1660
        some other features depending on the reason for not being supported.
 
1661
        """
 
1662
        return True
 
1663
 
 
1664
    def make_tags(self, branch):
 
1665
        """Create a tags object for branch.
 
1666
 
 
1667
        This method is on BranchFormat, because BranchFormats are reflected
 
1668
        over the wire via network_name(), whereas full Branch instances require
 
1669
        multiple VFS method calls to operate at all.
 
1670
 
 
1671
        The default implementation returns a disabled-tags instance.
 
1672
 
 
1673
        Note that it is normal for branch to be a RemoteBranch when using tags
 
1674
        on a RemoteBranch.
 
1675
        """
 
1676
        return DisabledTags(branch)
 
1677
 
 
1678
    def network_name(self):
 
1679
        """A simple byte string uniquely identifying this format for RPC calls.
 
1680
 
 
1681
        MetaDir branch formats use their disk format string to identify the
 
1682
        repository over the wire. All in one formats such as bzr < 0.8, and
 
1683
        foreign formats like svn/git and hg should use some marker which is
 
1684
        unique and immutable.
 
1685
        """
 
1686
        raise NotImplementedError(self.network_name)
 
1687
 
 
1688
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False,
 
1689
            found_repository=None):
 
1690
        """Return the branch object for a_bzrdir
 
1691
 
 
1692
        :param a_bzrdir: A BzrDir that contains a branch.
 
1693
        :param name: Name of colocated branch to open
 
1694
        :param _found: a private parameter, do not use it. It is used to
 
1695
            indicate if format probing has already be done.
 
1696
        :param ignore_fallbacks: when set, no fallback branches will be opened
 
1697
            (if there are any).  Default is to open fallbacks.
 
1698
        """
 
1699
        raise NotImplementedError(self.open)
 
1700
 
 
1701
    @classmethod
 
1702
    @deprecated_method(deprecated_in((2, 4, 0)))
 
1703
    def register_format(klass, format):
 
1704
        """Register a metadir format.
 
1705
 
 
1706
        See MetaDirBranchFormatFactory for the ability to register a format
 
1707
        without loading the code the format needs until it is actually used.
 
1708
        """
 
1709
        format_registry.register(format)
 
1710
 
 
1711
    @classmethod
 
1712
    @deprecated_method(deprecated_in((2, 4, 0)))
 
1713
    def set_default_format(klass, format):
 
1714
        format_registry.set_default(format)
 
1715
 
 
1716
    def supports_set_append_revisions_only(self):
 
1717
        """True if this format supports set_append_revisions_only."""
 
1718
        return False
 
1719
 
 
1720
    def supports_stacking(self):
 
1721
        """True if this format records a stacked-on branch."""
 
1722
        return False
 
1723
 
 
1724
    def supports_leaving_lock(self):
 
1725
        """True if this format supports leaving locks in place."""
 
1726
        return False # by default
 
1727
 
 
1728
    @classmethod
 
1729
    @deprecated_method(deprecated_in((2, 4, 0)))
 
1730
    def unregister_format(klass, format):
 
1731
        format_registry.remove(format)
 
1732
 
 
1733
    def __str__(self):
 
1734
        return self.get_format_description().rstrip()
 
1735
 
 
1736
    def supports_tags(self):
 
1737
        """True if this format supports tags stored in the branch"""
 
1738
        return False  # by default
 
1739
 
 
1740
 
 
1741
class MetaDirBranchFormatFactory(registry._LazyObjectGetter):
 
1742
    """A factory for a BranchFormat object, permitting simple lazy registration.
 
1743
    
 
1744
    While none of the built in BranchFormats are lazy registered yet,
 
1745
    bzrlib.tests.test_branch.TestMetaDirBranchFormatFactory demonstrates how to
 
1746
    use it, and the bzr-loom plugin uses it as well (see
 
1747
    bzrlib.plugins.loom.formats).
 
1748
    """
 
1749
 
 
1750
    def __init__(self, format_string, module_name, member_name):
 
1751
        """Create a MetaDirBranchFormatFactory.
 
1752
 
 
1753
        :param format_string: The format string the format has.
 
1754
        :param module_name: Module to load the format class from.
 
1755
        :param member_name: Attribute name within the module for the format class.
 
1756
        """
 
1757
        registry._LazyObjectGetter.__init__(self, module_name, member_name)
 
1758
        self._format_string = format_string
 
1759
        
 
1760
    def get_format_string(self):
 
1761
        """See BranchFormat.get_format_string."""
 
1762
        return self._format_string
 
1763
 
 
1764
    def __call__(self):
 
1765
        """Used for network_format_registry support."""
 
1766
        return self.get_obj()()
 
1767
 
 
1768
 
 
1769
class BranchHooks(Hooks):
 
1770
    """A dictionary mapping hook name to a list of callables for branch hooks.
 
1771
 
 
1772
    e.g. ['set_rh'] Is the list of items to be called when the
 
1773
    set_revision_history function is invoked.
 
1774
    """
 
1775
 
 
1776
    def __init__(self):
 
1777
        """Create the default hooks.
 
1778
 
 
1779
        These are all empty initially, because by default nothing should get
 
1780
        notified.
 
1781
        """
 
1782
        Hooks.__init__(self, "bzrlib.branch", "Branch.hooks")
 
1783
        self.add_hook('set_rh',
 
1784
            "Invoked whenever the revision history has been set via "
 
1785
            "set_revision_history. The api signature is (branch, "
 
1786
            "revision_history), and the branch will be write-locked. "
 
1787
            "The set_rh hook can be expensive for bzr to trigger, a better "
 
1788
            "hook to use is Branch.post_change_branch_tip.", (0, 15))
 
1789
        self.add_hook('open',
 
1790
            "Called with the Branch object that has been opened after a "
 
1791
            "branch is opened.", (1, 8))
 
1792
        self.add_hook('post_push',
 
1793
            "Called after a push operation completes. post_push is called "
 
1794
            "with a bzrlib.branch.BranchPushResult object and only runs in the "
 
1795
            "bzr client.", (0, 15))
 
1796
        self.add_hook('post_pull',
 
1797
            "Called after a pull operation completes. post_pull is called "
 
1798
            "with a bzrlib.branch.PullResult object and only runs in the "
 
1799
            "bzr client.", (0, 15))
 
1800
        self.add_hook('pre_commit',
 
1801
            "Called after a commit is calculated but before it is "
 
1802
            "completed. pre_commit is called with (local, master, old_revno, "
 
1803
            "old_revid, future_revno, future_revid, tree_delta, future_tree"
 
1804
            "). old_revid is NULL_REVISION for the first commit to a branch, "
 
1805
            "tree_delta is a TreeDelta object describing changes from the "
 
1806
            "basis revision. hooks MUST NOT modify this delta. "
 
1807
            " future_tree is an in-memory tree obtained from "
 
1808
            "CommitBuilder.revision_tree() and hooks MUST NOT modify this "
 
1809
            "tree.", (0,91))
 
1810
        self.add_hook('post_commit',
 
1811
            "Called in the bzr client after a commit has completed. "
 
1812
            "post_commit is called with (local, master, old_revno, old_revid, "
 
1813
            "new_revno, new_revid). old_revid is NULL_REVISION for the first "
 
1814
            "commit to a branch.", (0, 15))
 
1815
        self.add_hook('post_uncommit',
 
1816
            "Called in the bzr client after an uncommit completes. "
 
1817
            "post_uncommit is called with (local, master, old_revno, "
 
1818
            "old_revid, new_revno, new_revid) where local is the local branch "
 
1819
            "or None, master is the target branch, and an empty branch "
 
1820
            "receives new_revno of 0, new_revid of None.", (0, 15))
 
1821
        self.add_hook('pre_change_branch_tip',
 
1822
            "Called in bzr client and server before a change to the tip of a "
 
1823
            "branch is made. pre_change_branch_tip is called with a "
 
1824
            "bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
 
1825
            "commit, uncommit will all trigger this hook.", (1, 6))
 
1826
        self.add_hook('post_change_branch_tip',
 
1827
            "Called in bzr client and server after a change to the tip of a "
 
1828
            "branch is made. post_change_branch_tip is called with a "
 
1829
            "bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
 
1830
            "commit, uncommit will all trigger this hook.", (1, 4))
 
1831
        self.add_hook('transform_fallback_location',
 
1832
            "Called when a stacked branch is activating its fallback "
 
1833
            "locations. transform_fallback_location is called with (branch, "
 
1834
            "url), and should return a new url. Returning the same url "
 
1835
            "allows it to be used as-is, returning a different one can be "
 
1836
            "used to cause the branch to stack on a closer copy of that "
 
1837
            "fallback_location. Note that the branch cannot have history "
 
1838
            "accessing methods called on it during this hook because the "
 
1839
            "fallback locations have not been activated. When there are "
 
1840
            "multiple hooks installed for transform_fallback_location, "
 
1841
            "all are called with the url returned from the previous hook."
 
1842
            "The order is however undefined.", (1, 9))
 
1843
        self.add_hook('automatic_tag_name',
 
1844
            "Called to determine an automatic tag name for a revision. "
 
1845
            "automatic_tag_name is called with (branch, revision_id) and "
 
1846
            "should return a tag name or None if no tag name could be "
 
1847
            "determined. The first non-None tag name returned will be used.",
 
1848
            (2, 2))
 
1849
        self.add_hook('post_branch_init',
 
1850
            "Called after new branch initialization completes. "
 
1851
            "post_branch_init is called with a "
 
1852
            "bzrlib.branch.BranchInitHookParams. "
 
1853
            "Note that init, branch and checkout (both heavyweight and "
 
1854
            "lightweight) will all trigger this hook.", (2, 2))
 
1855
        self.add_hook('post_switch',
 
1856
            "Called after a checkout switches branch. "
 
1857
            "post_switch is called with a "
 
1858
            "bzrlib.branch.SwitchHookParams.", (2, 2))
 
1859
 
 
1860
 
 
1861
 
 
1862
# install the default hooks into the Branch class.
 
1863
Branch.hooks = BranchHooks()
 
1864
 
 
1865
 
 
1866
class ChangeBranchTipParams(object):
 
1867
    """Object holding parameters passed to *_change_branch_tip hooks.
 
1868
 
 
1869
    There are 5 fields that hooks may wish to access:
 
1870
 
 
1871
    :ivar branch: the branch being changed
 
1872
    :ivar old_revno: revision number before the change
 
1873
    :ivar new_revno: revision number after the change
 
1874
    :ivar old_revid: revision id before the change
 
1875
    :ivar new_revid: revision id after the change
 
1876
 
 
1877
    The revid fields are strings. The revno fields are integers.
 
1878
    """
 
1879
 
 
1880
    def __init__(self, branch, old_revno, new_revno, old_revid, new_revid):
 
1881
        """Create a group of ChangeBranchTip parameters.
 
1882
 
 
1883
        :param branch: The branch being changed.
 
1884
        :param old_revno: Revision number before the change.
 
1885
        :param new_revno: Revision number after the change.
 
1886
        :param old_revid: Tip revision id before the change.
 
1887
        :param new_revid: Tip revision id after the change.
 
1888
        """
 
1889
        self.branch = branch
 
1890
        self.old_revno = old_revno
 
1891
        self.new_revno = new_revno
 
1892
        self.old_revid = old_revid
 
1893
        self.new_revid = new_revid
 
1894
 
 
1895
    def __eq__(self, other):
 
1896
        return self.__dict__ == other.__dict__
 
1897
 
 
1898
    def __repr__(self):
 
1899
        return "<%s of %s from (%s, %s) to (%s, %s)>" % (
 
1900
            self.__class__.__name__, self.branch,
 
1901
            self.old_revno, self.old_revid, self.new_revno, self.new_revid)
 
1902
 
 
1903
 
 
1904
class BranchInitHookParams(object):
 
1905
    """Object holding parameters passed to *_branch_init hooks.
 
1906
 
 
1907
    There are 4 fields that hooks may wish to access:
 
1908
 
 
1909
    :ivar format: the branch format
 
1910
    :ivar bzrdir: the BzrDir where the branch will be/has been initialized
 
1911
    :ivar name: name of colocated branch, if any (or None)
 
1912
    :ivar branch: the branch created
 
1913
 
 
1914
    Note that for lightweight checkouts, the bzrdir and format fields refer to
 
1915
    the checkout, hence they are different from the corresponding fields in
 
1916
    branch, which refer to the original branch.
 
1917
    """
 
1918
 
 
1919
    def __init__(self, format, a_bzrdir, name, branch):
 
1920
        """Create a group of BranchInitHook parameters.
 
1921
 
 
1922
        :param format: the branch format
 
1923
        :param a_bzrdir: the BzrDir where the branch will be/has been
 
1924
            initialized
 
1925
        :param name: name of colocated branch, if any (or None)
 
1926
        :param branch: the branch created
 
1927
 
 
1928
        Note that for lightweight checkouts, the bzrdir and format fields refer
 
1929
        to the checkout, hence they are different from the corresponding fields
 
1930
        in branch, which refer to the original branch.
 
1931
        """
 
1932
        self.format = format
 
1933
        self.bzrdir = a_bzrdir
 
1934
        self.name = name
 
1935
        self.branch = branch
 
1936
 
 
1937
    def __eq__(self, other):
 
1938
        return self.__dict__ == other.__dict__
 
1939
 
 
1940
    def __repr__(self):
 
1941
        return "<%s of %s>" % (self.__class__.__name__, self.branch)
 
1942
 
 
1943
 
 
1944
class SwitchHookParams(object):
 
1945
    """Object holding parameters passed to *_switch hooks.
 
1946
 
 
1947
    There are 4 fields that hooks may wish to access:
 
1948
 
 
1949
    :ivar control_dir: BzrDir of the checkout to change
 
1950
    :ivar to_branch: branch that the checkout is to reference
 
1951
    :ivar force: skip the check for local commits in a heavy checkout
 
1952
    :ivar revision_id: revision ID to switch to (or None)
 
1953
    """
 
1954
 
 
1955
    def __init__(self, control_dir, to_branch, force, revision_id):
 
1956
        """Create a group of SwitchHook parameters.
 
1957
 
 
1958
        :param control_dir: BzrDir of the checkout to change
 
1959
        :param to_branch: branch that the checkout is to reference
 
1960
        :param force: skip the check for local commits in a heavy checkout
 
1961
        :param revision_id: revision ID to switch to (or None)
 
1962
        """
 
1963
        self.control_dir = control_dir
 
1964
        self.to_branch = to_branch
 
1965
        self.force = force
 
1966
        self.revision_id = revision_id
 
1967
 
 
1968
    def __eq__(self, other):
 
1969
        return self.__dict__ == other.__dict__
 
1970
 
 
1971
    def __repr__(self):
 
1972
        return "<%s for %s to (%s, %s)>" % (self.__class__.__name__,
 
1973
            self.control_dir, self.to_branch,
 
1974
            self.revision_id)
 
1975
 
 
1976
 
 
1977
class BranchFormatMetadir(BranchFormat):
 
1978
    """Common logic for meta-dir based branch formats."""
 
1979
 
 
1980
    def _branch_class(self):
 
1981
        """What class to instantiate on open calls."""
 
1982
        raise NotImplementedError(self._branch_class)
 
1983
 
 
1984
    def _initialize_helper(self, a_bzrdir, utf8_files, name=None,
 
1985
                           repository=None):
 
1986
        """Initialize a branch in a bzrdir, with specified files
 
1987
 
 
1988
        :param a_bzrdir: The bzrdir to initialize the branch in
 
1989
        :param utf8_files: The files to create as a list of
 
1990
            (filename, content) tuples
 
1991
        :param name: Name of colocated branch to create, if any
 
1992
        :return: a branch in this format
 
1993
        """
 
1994
        mutter('creating branch %r in %s', self, a_bzrdir.user_url)
 
1995
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
 
1996
        control_files = lockable_files.LockableFiles(branch_transport,
 
1997
            'lock', lockdir.LockDir)
 
1998
        control_files.create_lock()
 
1999
        control_files.lock_write()
 
2000
        try:
 
2001
            utf8_files += [('format', self.get_format_string())]
 
2002
            for (filename, content) in utf8_files:
 
2003
                branch_transport.put_bytes(
 
2004
                    filename, content,
 
2005
                    mode=a_bzrdir._get_file_mode())
 
2006
        finally:
 
2007
            control_files.unlock()
 
2008
        branch = self.open(a_bzrdir, name, _found=True,
 
2009
                found_repository=repository)
 
2010
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
 
2011
        return branch
 
2012
 
 
2013
    def network_name(self):
 
2014
        """A simple byte string uniquely identifying this format for RPC calls.
 
2015
 
 
2016
        Metadir branch formats use their format string.
 
2017
        """
 
2018
        return self.get_format_string()
 
2019
 
 
2020
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False,
 
2021
            found_repository=None):
 
2022
        """See BranchFormat.open()."""
 
2023
        if not _found:
 
2024
            format = BranchFormat.find_format(a_bzrdir, name=name)
 
2025
            if format.__class__ != self.__class__:
 
2026
                raise AssertionError("wrong format %r found for %r" %
 
2027
                    (format, self))
 
2028
        transport = a_bzrdir.get_branch_transport(None, name=name)
 
2029
        try:
 
2030
            control_files = lockable_files.LockableFiles(transport, 'lock',
 
2031
                                                         lockdir.LockDir)
 
2032
            if found_repository is None:
 
2033
                found_repository = a_bzrdir.find_repository()
 
2034
            return self._branch_class()(_format=self,
 
2035
                              _control_files=control_files,
 
2036
                              name=name,
 
2037
                              a_bzrdir=a_bzrdir,
 
2038
                              _repository=found_repository,
 
2039
                              ignore_fallbacks=ignore_fallbacks)
 
2040
        except errors.NoSuchFile:
 
2041
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
 
2042
 
 
2043
    def __init__(self):
 
2044
        super(BranchFormatMetadir, self).__init__()
 
2045
        self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
 
2046
        self._matchingbzrdir.set_branch_format(self)
 
2047
 
 
2048
    def supports_tags(self):
 
2049
        return True
 
2050
 
 
2051
    def supports_leaving_lock(self):
 
2052
        return True
 
2053
 
 
2054
 
 
2055
class BzrBranchFormat5(BranchFormatMetadir):
 
2056
    """Bzr branch format 5.
 
2057
 
 
2058
    This format has:
 
2059
     - a revision-history file.
 
2060
     - a format string
 
2061
     - a lock dir guarding the branch itself
 
2062
     - all of this stored in a branch/ subdirectory
 
2063
     - works with shared repositories.
 
2064
 
 
2065
    This format is new in bzr 0.8.
 
2066
    """
 
2067
 
 
2068
    def _branch_class(self):
 
2069
        return BzrBranch5
 
2070
 
 
2071
    def get_format_string(self):
 
2072
        """See BranchFormat.get_format_string()."""
 
2073
        return "Bazaar-NG branch format 5\n"
 
2074
 
 
2075
    def get_format_description(self):
 
2076
        """See BranchFormat.get_format_description()."""
 
2077
        return "Branch format 5"
 
2078
 
 
2079
    def initialize(self, a_bzrdir, name=None, repository=None):
 
2080
        """Create a branch of this format in a_bzrdir."""
 
2081
        utf8_files = [('revision-history', ''),
 
2082
                      ('branch-name', ''),
 
2083
                      ]
 
2084
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
 
2085
 
 
2086
    def supports_tags(self):
 
2087
        return False
 
2088
 
 
2089
 
 
2090
class BzrBranchFormat6(BranchFormatMetadir):
 
2091
    """Branch format with last-revision and tags.
 
2092
 
 
2093
    Unlike previous formats, this has no explicit revision history. Instead,
 
2094
    this just stores the last-revision, and the left-hand history leading
 
2095
    up to there is the history.
 
2096
 
 
2097
    This format was introduced in bzr 0.15
 
2098
    and became the default in 0.91.
 
2099
    """
 
2100
 
 
2101
    def _branch_class(self):
 
2102
        return BzrBranch6
 
2103
 
 
2104
    def get_format_string(self):
 
2105
        """See BranchFormat.get_format_string()."""
 
2106
        return "Bazaar Branch Format 6 (bzr 0.15)\n"
 
2107
 
 
2108
    def get_format_description(self):
 
2109
        """See BranchFormat.get_format_description()."""
 
2110
        return "Branch format 6"
 
2111
 
 
2112
    def initialize(self, a_bzrdir, name=None, repository=None):
 
2113
        """Create a branch of this format in a_bzrdir."""
 
2114
        utf8_files = [('last-revision', '0 null:\n'),
 
2115
                      ('branch.conf', ''),
 
2116
                      ('tags', ''),
 
2117
                      ]
 
2118
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
 
2119
 
 
2120
    def make_tags(self, branch):
 
2121
        """See bzrlib.branch.BranchFormat.make_tags()."""
 
2122
        return BasicTags(branch)
 
2123
 
 
2124
    def supports_set_append_revisions_only(self):
 
2125
        return True
 
2126
 
 
2127
 
 
2128
class BzrBranchFormat8(BranchFormatMetadir):
 
2129
    """Metadir format supporting storing locations of subtree branches."""
 
2130
 
 
2131
    def _branch_class(self):
 
2132
        return BzrBranch8
 
2133
 
 
2134
    def get_format_string(self):
 
2135
        """See BranchFormat.get_format_string()."""
 
2136
        return "Bazaar Branch Format 8 (needs bzr 1.15)\n"
 
2137
 
 
2138
    def get_format_description(self):
 
2139
        """See BranchFormat.get_format_description()."""
 
2140
        return "Branch format 8"
 
2141
 
 
2142
    def initialize(self, a_bzrdir, name=None, repository=None):
 
2143
        """Create a branch of this format in a_bzrdir."""
 
2144
        utf8_files = [('last-revision', '0 null:\n'),
 
2145
                      ('branch.conf', ''),
 
2146
                      ('tags', ''),
 
2147
                      ('references', '')
 
2148
                      ]
 
2149
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
 
2150
 
 
2151
    def make_tags(self, branch):
 
2152
        """See bzrlib.branch.BranchFormat.make_tags()."""
 
2153
        return BasicTags(branch)
 
2154
 
 
2155
    def supports_set_append_revisions_only(self):
 
2156
        return True
 
2157
 
 
2158
    def supports_stacking(self):
 
2159
        return True
 
2160
 
 
2161
    supports_reference_locations = True
 
2162
 
 
2163
 
 
2164
class BzrBranchFormat7(BranchFormatMetadir):
 
2165
    """Branch format with last-revision, tags, and a stacked location pointer.
 
2166
 
 
2167
    The stacked location pointer is passed down to the repository and requires
 
2168
    a repository format with supports_external_lookups = True.
 
2169
 
 
2170
    This format was introduced in bzr 1.6.
 
2171
    """
 
2172
 
 
2173
    def initialize(self, a_bzrdir, name=None, repository=None):
 
2174
        """Create a branch of this format in a_bzrdir."""
 
2175
        utf8_files = [('last-revision', '0 null:\n'),
 
2176
                      ('branch.conf', ''),
 
2177
                      ('tags', ''),
 
2178
                      ]
 
2179
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
 
2180
 
 
2181
    def _branch_class(self):
 
2182
        return BzrBranch7
 
2183
 
 
2184
    def get_format_string(self):
 
2185
        """See BranchFormat.get_format_string()."""
 
2186
        return "Bazaar Branch Format 7 (needs bzr 1.6)\n"
 
2187
 
 
2188
    def get_format_description(self):
 
2189
        """See BranchFormat.get_format_description()."""
 
2190
        return "Branch format 7"
 
2191
 
 
2192
    def supports_set_append_revisions_only(self):
 
2193
        return True
 
2194
 
 
2195
    def supports_stacking(self):
 
2196
        return True
 
2197
 
 
2198
    def make_tags(self, branch):
 
2199
        """See bzrlib.branch.BranchFormat.make_tags()."""
 
2200
        return BasicTags(branch)
 
2201
 
 
2202
    supports_reference_locations = False
 
2203
 
 
2204
 
 
2205
class BranchReferenceFormat(BranchFormat):
 
2206
    """Bzr branch reference format.
 
2207
 
 
2208
    Branch references are used in implementing checkouts, they
 
2209
    act as an alias to the real branch which is at some other url.
 
2210
 
 
2211
    This format has:
 
2212
     - A location file
 
2213
     - a format string
 
2214
    """
 
2215
 
 
2216
    def get_format_string(self):
 
2217
        """See BranchFormat.get_format_string()."""
 
2218
        return "Bazaar-NG Branch Reference Format 1\n"
 
2219
 
 
2220
    def get_format_description(self):
 
2221
        """See BranchFormat.get_format_description()."""
 
2222
        return "Checkout reference format 1"
 
2223
 
 
2224
    def get_reference(self, a_bzrdir, name=None):
 
2225
        """See BranchFormat.get_reference()."""
 
2226
        transport = a_bzrdir.get_branch_transport(None, name=name)
 
2227
        return transport.get_bytes('location')
 
2228
 
 
2229
    def set_reference(self, a_bzrdir, name, to_branch):
 
2230
        """See BranchFormat.set_reference()."""
 
2231
        transport = a_bzrdir.get_branch_transport(None, name=name)
 
2232
        location = transport.put_bytes('location', to_branch.base)
 
2233
 
 
2234
    def initialize(self, a_bzrdir, name=None, target_branch=None,
 
2235
            repository=None):
 
2236
        """Create a branch of this format in a_bzrdir."""
 
2237
        if target_branch is None:
 
2238
            # this format does not implement branch itself, thus the implicit
 
2239
            # creation contract must see it as uninitializable
 
2240
            raise errors.UninitializableFormat(self)
 
2241
        mutter('creating branch reference in %s', a_bzrdir.user_url)
 
2242
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
 
2243
        branch_transport.put_bytes('location',
 
2244
            target_branch.bzrdir.user_url)
 
2245
        branch_transport.put_bytes('format', self.get_format_string())
 
2246
        branch = self.open(
 
2247
            a_bzrdir, name, _found=True,
 
2248
            possible_transports=[target_branch.bzrdir.root_transport])
 
2249
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
 
2250
        return branch
 
2251
 
 
2252
    def __init__(self):
 
2253
        super(BranchReferenceFormat, self).__init__()
 
2254
        self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
 
2255
        self._matchingbzrdir.set_branch_format(self)
 
2256
 
 
2257
    def _make_reference_clone_function(format, a_branch):
 
2258
        """Create a clone() routine for a branch dynamically."""
 
2259
        def clone(to_bzrdir, revision_id=None,
 
2260
            repository_policy=None):
 
2261
            """See Branch.clone()."""
 
2262
            return format.initialize(to_bzrdir, target_branch=a_branch)
 
2263
            # cannot obey revision_id limits when cloning a reference ...
 
2264
            # FIXME RBC 20060210 either nuke revision_id for clone, or
 
2265
            # emit some sort of warning/error to the caller ?!
 
2266
        return clone
 
2267
 
 
2268
    def open(self, a_bzrdir, name=None, _found=False, location=None,
 
2269
             possible_transports=None, ignore_fallbacks=False,
 
2270
             found_repository=None):
 
2271
        """Return the branch that the branch reference in a_bzrdir points at.
 
2272
 
 
2273
        :param a_bzrdir: A BzrDir that contains a branch.
 
2274
        :param name: Name of colocated branch to open, if any
 
2275
        :param _found: a private parameter, do not use it. It is used to
 
2276
            indicate if format probing has already be done.
 
2277
        :param ignore_fallbacks: when set, no fallback branches will be opened
 
2278
            (if there are any).  Default is to open fallbacks.
 
2279
        :param location: The location of the referenced branch.  If
 
2280
            unspecified, this will be determined from the branch reference in
 
2281
            a_bzrdir.
 
2282
        :param possible_transports: An optional reusable transports list.
 
2283
        """
 
2284
        if not _found:
 
2285
            format = BranchFormat.find_format(a_bzrdir, name=name)
 
2286
            if format.__class__ != self.__class__:
 
2287
                raise AssertionError("wrong format %r found for %r" %
 
2288
                    (format, self))
 
2289
        if location is None:
 
2290
            location = self.get_reference(a_bzrdir, name)
 
2291
        real_bzrdir = bzrdir.BzrDir.open(
 
2292
            location, possible_transports=possible_transports)
 
2293
        result = real_bzrdir.open_branch(name=name, 
 
2294
            ignore_fallbacks=ignore_fallbacks)
 
2295
        # this changes the behaviour of result.clone to create a new reference
 
2296
        # rather than a copy of the content of the branch.
 
2297
        # I did not use a proxy object because that needs much more extensive
 
2298
        # testing, and we are only changing one behaviour at the moment.
 
2299
        # If we decide to alter more behaviours - i.e. the implicit nickname
 
2300
        # then this should be refactored to introduce a tested proxy branch
 
2301
        # and a subclass of that for use in overriding clone() and ....
 
2302
        # - RBC 20060210
 
2303
        result.clone = self._make_reference_clone_function(result)
 
2304
        return result
 
2305
 
 
2306
 
 
2307
class BranchFormatRegistry(controldir.ControlComponentFormatRegistry):
 
2308
    """Branch format registry."""
 
2309
 
 
2310
    def __init__(self, other_registry=None):
 
2311
        super(BranchFormatRegistry, self).__init__(other_registry)
 
2312
        self._default_format = None
 
2313
 
 
2314
    def set_default(self, format):
 
2315
        self._default_format = format
 
2316
 
 
2317
    def get_default(self):
 
2318
        return self._default_format
 
2319
 
 
2320
 
 
2321
network_format_registry = registry.FormatRegistry()
 
2322
"""Registry of formats indexed by their network name.
 
2323
 
 
2324
The network name for a branch format is an identifier that can be used when
 
2325
referring to formats with smart server operations. See
 
2326
BranchFormat.network_name() for more detail.
 
2327
"""
 
2328
 
 
2329
format_registry = BranchFormatRegistry(network_format_registry)
 
2330
 
 
2331
 
 
2332
# formats which have no format string are not discoverable
 
2333
# and not independently creatable, so are not registered.
 
2334
__format5 = BzrBranchFormat5()
 
2335
__format6 = BzrBranchFormat6()
 
2336
__format7 = BzrBranchFormat7()
 
2337
__format8 = BzrBranchFormat8()
 
2338
format_registry.register(__format5)
 
2339
format_registry.register(BranchReferenceFormat())
 
2340
format_registry.register(__format6)
 
2341
format_registry.register(__format7)
 
2342
format_registry.register(__format8)
 
2343
format_registry.set_default(__format7)
 
2344
 
 
2345
 
 
2346
class BranchWriteLockResult(LogicalLockResult):
 
2347
    """The result of write locking a branch.
 
2348
 
 
2349
    :ivar branch_token: The token obtained from the underlying branch lock, or
 
2350
        None.
 
2351
    :ivar unlock: A callable which will unlock the lock.
 
2352
    """
 
2353
 
 
2354
    def __init__(self, unlock, branch_token):
 
2355
        LogicalLockResult.__init__(self, unlock)
 
2356
        self.branch_token = branch_token
 
2357
 
 
2358
    def __repr__(self):
 
2359
        return "BranchWriteLockResult(%s, %s)" % (self.branch_token,
 
2360
            self.unlock)
 
2361
 
 
2362
 
 
2363
class BzrBranch(Branch, _RelockDebugMixin):
 
2364
    """A branch stored in the actual filesystem.
 
2365
 
 
2366
    Note that it's "local" in the context of the filesystem; it doesn't
 
2367
    really matter if it's on an nfs/smb/afs/coda/... share, as long as
 
2368
    it's writable, and can be accessed via the normal filesystem API.
 
2369
 
 
2370
    :ivar _transport: Transport for file operations on this branch's
 
2371
        control files, typically pointing to the .bzr/branch directory.
 
2372
    :ivar repository: Repository for this branch.
 
2373
    :ivar base: The url of the base directory for this branch; the one
 
2374
        containing the .bzr directory.
 
2375
    :ivar name: Optional colocated branch name as it exists in the control
 
2376
        directory.
 
2377
    """
 
2378
 
 
2379
    def __init__(self, _format=None,
 
2380
                 _control_files=None, a_bzrdir=None, name=None,
 
2381
                 _repository=None, ignore_fallbacks=False):
 
2382
        """Create new branch object at a particular location."""
 
2383
        if a_bzrdir is None:
 
2384
            raise ValueError('a_bzrdir must be supplied')
 
2385
        else:
 
2386
            self.bzrdir = a_bzrdir
 
2387
        self._base = self.bzrdir.transport.clone('..').base
 
2388
        self.name = name
 
2389
        # XXX: We should be able to just do
 
2390
        #   self.base = self.bzrdir.root_transport.base
 
2391
        # but this does not quite work yet -- mbp 20080522
 
2392
        self._format = _format
 
2393
        if _control_files is None:
 
2394
            raise ValueError('BzrBranch _control_files is None')
 
2395
        self.control_files = _control_files
 
2396
        self._transport = _control_files._transport
 
2397
        self.repository = _repository
 
2398
        Branch.__init__(self)
 
2399
 
 
2400
    def __str__(self):
 
2401
        if self.name is None:
 
2402
            return '%s(%s)' % (self.__class__.__name__, self.user_url)
 
2403
        else:
 
2404
            return '%s(%s,%s)' % (self.__class__.__name__, self.user_url,
 
2405
                self.name)
 
2406
 
 
2407
    __repr__ = __str__
 
2408
 
 
2409
    def _get_base(self):
 
2410
        """Returns the directory containing the control directory."""
 
2411
        return self._base
 
2412
 
 
2413
    base = property(_get_base, doc="The URL for the root of this branch.")
 
2414
 
 
2415
    def _get_config(self):
 
2416
        return TransportConfig(self._transport, 'branch.conf')
 
2417
 
 
2418
    def is_locked(self):
 
2419
        return self.control_files.is_locked()
 
2420
 
 
2421
    def lock_write(self, token=None):
 
2422
        """Lock the branch for write operations.
 
2423
 
 
2424
        :param token: A token to permit reacquiring a previously held and
 
2425
            preserved lock.
 
2426
        :return: A BranchWriteLockResult.
 
2427
        """
 
2428
        if not self.is_locked():
 
2429
            self._note_lock('w')
 
2430
        # All-in-one needs to always unlock/lock.
 
2431
        repo_control = getattr(self.repository, 'control_files', None)
 
2432
        if self.control_files == repo_control or not self.is_locked():
 
2433
            self.repository._warn_if_deprecated(self)
 
2434
            self.repository.lock_write()
 
2435
            took_lock = True
 
2436
        else:
 
2437
            took_lock = False
 
2438
        try:
 
2439
            return BranchWriteLockResult(self.unlock,
 
2440
                self.control_files.lock_write(token=token))
 
2441
        except:
 
2442
            if took_lock:
 
2443
                self.repository.unlock()
 
2444
            raise
 
2445
 
 
2446
    def lock_read(self):
 
2447
        """Lock the branch for read operations.
 
2448
 
 
2449
        :return: A bzrlib.lock.LogicalLockResult.
 
2450
        """
 
2451
        if not self.is_locked():
 
2452
            self._note_lock('r')
 
2453
        # All-in-one needs to always unlock/lock.
 
2454
        repo_control = getattr(self.repository, 'control_files', None)
 
2455
        if self.control_files == repo_control or not self.is_locked():
 
2456
            self.repository._warn_if_deprecated(self)
 
2457
            self.repository.lock_read()
 
2458
            took_lock = True
 
2459
        else:
 
2460
            took_lock = False
 
2461
        try:
 
2462
            self.control_files.lock_read()
 
2463
            return LogicalLockResult(self.unlock)
 
2464
        except:
 
2465
            if took_lock:
 
2466
                self.repository.unlock()
 
2467
            raise
 
2468
 
 
2469
    @only_raises(errors.LockNotHeld, errors.LockBroken)
 
2470
    def unlock(self):
 
2471
        try:
 
2472
            self.control_files.unlock()
 
2473
        finally:
 
2474
            # All-in-one needs to always unlock/lock.
 
2475
            repo_control = getattr(self.repository, 'control_files', None)
 
2476
            if (self.control_files == repo_control or
 
2477
                not self.control_files.is_locked()):
 
2478
                self.repository.unlock()
 
2479
            if not self.control_files.is_locked():
 
2480
                # we just released the lock
 
2481
                self._clear_cached_state()
 
2482
 
 
2483
    def peek_lock_mode(self):
 
2484
        if self.control_files._lock_count == 0:
 
2485
            return None
 
2486
        else:
 
2487
            return self.control_files._lock_mode
 
2488
 
 
2489
    def get_physical_lock_status(self):
 
2490
        return self.control_files.get_physical_lock_status()
 
2491
 
 
2492
    @needs_read_lock
 
2493
    def print_file(self, file, revision_id):
 
2494
        """See Branch.print_file."""
 
2495
        return self.repository.print_file(file, revision_id)
 
2496
 
 
2497
    @needs_write_lock
 
2498
    def set_last_revision_info(self, revno, revision_id):
 
2499
        if not revision_id or not isinstance(revision_id, basestring):
 
2500
            raise errors.InvalidRevisionId(revision_id=revision_id, branch=self)
 
2501
        revision_id = _mod_revision.ensure_null(revision_id)
 
2502
        old_revno, old_revid = self.last_revision_info()
 
2503
        if self._get_append_revisions_only():
 
2504
            self._check_history_violation(revision_id)
 
2505
        self._run_pre_change_branch_tip_hooks(revno, revision_id)
 
2506
        self._write_last_revision_info(revno, revision_id)
 
2507
        self._clear_cached_state()
 
2508
        self._last_revision_info_cache = revno, revision_id
 
2509
        self._run_post_change_branch_tip_hooks(old_revno, old_revid)
 
2510
 
 
2511
    def basis_tree(self):
 
2512
        """See Branch.basis_tree."""
 
2513
        return self.repository.revision_tree(self.last_revision())
 
2514
 
 
2515
    def _get_parent_location(self):
 
2516
        _locs = ['parent', 'pull', 'x-pull']
 
2517
        for l in _locs:
 
2518
            try:
 
2519
                return self._transport.get_bytes(l).strip('\n')
 
2520
            except errors.NoSuchFile:
 
2521
                pass
 
2522
        return None
 
2523
 
 
2524
    def get_stacked_on_url(self):
 
2525
        raise errors.UnstackableBranchFormat(self._format, self.user_url)
 
2526
 
 
2527
    def set_push_location(self, location):
 
2528
        """See Branch.set_push_location."""
 
2529
        self.get_config().set_user_option(
 
2530
            'push_location', location,
 
2531
            store=_mod_config.STORE_LOCATION_NORECURSE)
 
2532
 
 
2533
    def _set_parent_location(self, url):
 
2534
        if url is None:
 
2535
            self._transport.delete('parent')
 
2536
        else:
 
2537
            self._transport.put_bytes('parent', url + '\n',
 
2538
                mode=self.bzrdir._get_file_mode())
 
2539
 
 
2540
    @needs_write_lock
 
2541
    def unbind(self):
 
2542
        """If bound, unbind"""
 
2543
        return self.set_bound_location(None)
 
2544
 
 
2545
    @needs_write_lock
 
2546
    def bind(self, other):
 
2547
        """Bind this branch to the branch other.
 
2548
 
 
2549
        This does not push or pull data between the branches, though it does
 
2550
        check for divergence to raise an error when the branches are not
 
2551
        either the same, or one a prefix of the other. That behaviour may not
 
2552
        be useful, so that check may be removed in future.
 
2553
 
 
2554
        :param other: The branch to bind to
 
2555
        :type other: Branch
 
2556
        """
 
2557
        # TODO: jam 20051230 Consider checking if the target is bound
 
2558
        #       It is debatable whether you should be able to bind to
 
2559
        #       a branch which is itself bound.
 
2560
        #       Committing is obviously forbidden,
 
2561
        #       but binding itself may not be.
 
2562
        #       Since we *have* to check at commit time, we don't
 
2563
        #       *need* to check here
 
2564
 
 
2565
        # we want to raise diverged if:
 
2566
        # last_rev is not in the other_last_rev history, AND
 
2567
        # other_last_rev is not in our history, and do it without pulling
 
2568
        # history around
 
2569
        self.set_bound_location(other.base)
 
2570
 
 
2571
    def get_bound_location(self):
 
2572
        try:
 
2573
            return self._transport.get_bytes('bound')[:-1]
 
2574
        except errors.NoSuchFile:
 
2575
            return None
 
2576
 
 
2577
    @needs_read_lock
 
2578
    def get_master_branch(self, possible_transports=None):
 
2579
        """Return the branch we are bound to.
 
2580
 
 
2581
        :return: Either a Branch, or None
 
2582
        """
 
2583
        if self._master_branch_cache is None:
 
2584
            self._master_branch_cache = self._get_master_branch(
 
2585
                possible_transports)
 
2586
        return self._master_branch_cache
 
2587
 
 
2588
    def _get_master_branch(self, possible_transports):
 
2589
        bound_loc = self.get_bound_location()
 
2590
        if not bound_loc:
 
2591
            return None
 
2592
        try:
 
2593
            return Branch.open(bound_loc,
 
2594
                               possible_transports=possible_transports)
 
2595
        except (errors.NotBranchError, errors.ConnectionError), e:
 
2596
            raise errors.BoundBranchConnectionFailure(
 
2597
                    self, bound_loc, e)
 
2598
 
 
2599
    @needs_write_lock
 
2600
    def set_bound_location(self, location):
 
2601
        """Set the target where this branch is bound to.
 
2602
 
 
2603
        :param location: URL to the target branch
 
2604
        """
 
2605
        self._master_branch_cache = None
 
2606
        if location:
 
2607
            self._transport.put_bytes('bound', location+'\n',
 
2608
                mode=self.bzrdir._get_file_mode())
 
2609
        else:
 
2610
            try:
 
2611
                self._transport.delete('bound')
 
2612
            except errors.NoSuchFile:
 
2613
                return False
 
2614
            return True
 
2615
 
 
2616
    @needs_write_lock
 
2617
    def update(self, possible_transports=None):
 
2618
        """Synchronise this branch with the master branch if any.
 
2619
 
 
2620
        :return: None or the last_revision that was pivoted out during the
 
2621
                 update.
 
2622
        """
 
2623
        master = self.get_master_branch(possible_transports)
 
2624
        if master is not None:
 
2625
            old_tip = _mod_revision.ensure_null(self.last_revision())
 
2626
            self.pull(master, overwrite=True)
 
2627
            if self.repository.get_graph().is_ancestor(old_tip,
 
2628
                _mod_revision.ensure_null(self.last_revision())):
 
2629
                return None
 
2630
            return old_tip
 
2631
        return None
 
2632
 
 
2633
    def _read_last_revision_info(self):
 
2634
        revision_string = self._transport.get_bytes('last-revision')
 
2635
        revno, revision_id = revision_string.rstrip('\n').split(' ', 1)
 
2636
        revision_id = cache_utf8.get_cached_utf8(revision_id)
 
2637
        revno = int(revno)
 
2638
        return revno, revision_id
 
2639
 
 
2640
    def _write_last_revision_info(self, revno, revision_id):
 
2641
        """Simply write out the revision id, with no checks.
 
2642
 
 
2643
        Use set_last_revision_info to perform this safely.
 
2644
 
 
2645
        Does not update the revision_history cache.
 
2646
        """
 
2647
        revision_id = _mod_revision.ensure_null(revision_id)
 
2648
        out_string = '%d %s\n' % (revno, revision_id)
 
2649
        self._transport.put_bytes('last-revision', out_string,
 
2650
            mode=self.bzrdir._get_file_mode())
 
2651
 
 
2652
 
 
2653
class FullHistoryBzrBranch(BzrBranch):
 
2654
    """Bzr branch which contains the full revision history."""
 
2655
 
 
2656
    @needs_write_lock
 
2657
    def set_last_revision_info(self, revno, revision_id):
 
2658
        if not revision_id or not isinstance(revision_id, basestring):
 
2659
            raise errors.InvalidRevisionId(revision_id=revision_id, branch=self)
 
2660
        revision_id = _mod_revision.ensure_null(revision_id)
 
2661
        # this old format stores the full history, but this api doesn't
 
2662
        # provide it, so we must generate, and might as well check it's
 
2663
        # correct
 
2664
        history = self._lefthand_history(revision_id)
 
2665
        if len(history) != revno:
 
2666
            raise AssertionError('%d != %d' % (len(history), revno))
 
2667
        self._set_revision_history(history)
 
2668
 
 
2669
    def _read_last_revision_info(self):
 
2670
        rh = self.revision_history()
 
2671
        revno = len(rh)
 
2672
        if revno:
 
2673
            return (revno, rh[-1])
 
2674
        else:
 
2675
            return (0, _mod_revision.NULL_REVISION)
 
2676
 
 
2677
    @deprecated_method(deprecated_in((2, 4, 0)))
 
2678
    @needs_write_lock
 
2679
    def set_revision_history(self, rev_history):
 
2680
        """See Branch.set_revision_history."""
 
2681
        self._set_revision_history(rev_history)
 
2682
 
 
2683
    def _set_revision_history(self, rev_history):
 
2684
        if 'evil' in debug.debug_flags:
 
2685
            mutter_callsite(3, "set_revision_history scales with history.")
 
2686
        check_not_reserved_id = _mod_revision.check_not_reserved_id
 
2687
        for rev_id in rev_history:
 
2688
            check_not_reserved_id(rev_id)
 
2689
        if Branch.hooks['post_change_branch_tip']:
 
2690
            # Don't calculate the last_revision_info() if there are no hooks
 
2691
            # that will use it.
 
2692
            old_revno, old_revid = self.last_revision_info()
 
2693
        if len(rev_history) == 0:
 
2694
            revid = _mod_revision.NULL_REVISION
 
2695
        else:
 
2696
            revid = rev_history[-1]
 
2697
        self._run_pre_change_branch_tip_hooks(len(rev_history), revid)
 
2698
        self._write_revision_history(rev_history)
 
2699
        self._clear_cached_state()
 
2700
        self._cache_revision_history(rev_history)
 
2701
        for hook in Branch.hooks['set_rh']:
 
2702
            hook(self, rev_history)
 
2703
        if Branch.hooks['post_change_branch_tip']:
 
2704
            self._run_post_change_branch_tip_hooks(old_revno, old_revid)
 
2705
 
 
2706
    def _write_revision_history(self, history):
 
2707
        """Factored out of set_revision_history.
 
2708
 
 
2709
        This performs the actual writing to disk.
 
2710
        It is intended to be called by set_revision_history."""
 
2711
        self._transport.put_bytes(
 
2712
            'revision-history', '\n'.join(history),
 
2713
            mode=self.bzrdir._get_file_mode())
 
2714
 
 
2715
    def _gen_revision_history(self):
 
2716
        history = self._transport.get_bytes('revision-history').split('\n')
 
2717
        if history[-1:] == ['']:
 
2718
            # There shouldn't be a trailing newline, but just in case.
 
2719
            history.pop()
 
2720
        return history
 
2721
 
 
2722
    def _synchronize_history(self, destination, revision_id):
 
2723
        if not isinstance(destination, FullHistoryBzrBranch):
 
2724
            super(BzrBranch, self)._synchronize_history(
 
2725
                destination, revision_id)
 
2726
            return
 
2727
        if revision_id == _mod_revision.NULL_REVISION:
 
2728
            new_history = []
 
2729
        else:
 
2730
            new_history = self.revision_history()
 
2731
        if revision_id is not None and new_history != []:
 
2732
            try:
 
2733
                new_history = new_history[:new_history.index(revision_id) + 1]
 
2734
            except ValueError:
 
2735
                rev = self.repository.get_revision(revision_id)
 
2736
                new_history = rev.get_history(self.repository)[1:]
 
2737
        destination._set_revision_history(new_history)
 
2738
 
 
2739
    @needs_write_lock
 
2740
    def generate_revision_history(self, revision_id, last_rev=None,
 
2741
        other_branch=None):
 
2742
        """Create a new revision history that will finish with revision_id.
 
2743
 
 
2744
        :param revision_id: the new tip to use.
 
2745
        :param last_rev: The previous last_revision. If not None, then this
 
2746
            must be a ancestory of revision_id, or DivergedBranches is raised.
 
2747
        :param other_branch: The other branch that DivergedBranches should
 
2748
            raise with respect to.
 
2749
        """
 
2750
        self._set_revision_history(self._lefthand_history(revision_id,
 
2751
            last_rev, other_branch))
 
2752
 
 
2753
 
 
2754
class BzrBranch5(FullHistoryBzrBranch):
 
2755
    """A format 5 branch. This supports new features over plain branches.
 
2756
 
 
2757
    It has support for a master_branch which is the data for bound branches.
 
2758
    """
 
2759
 
 
2760
 
 
2761
class BzrBranch8(BzrBranch):
 
2762
    """A branch that stores tree-reference locations."""
 
2763
 
 
2764
    def _open_hook(self):
 
2765
        if self._ignore_fallbacks:
 
2766
            return
 
2767
        try:
 
2768
            url = self.get_stacked_on_url()
 
2769
        except (errors.UnstackableRepositoryFormat, errors.NotStacked,
 
2770
            errors.UnstackableBranchFormat):
 
2771
            pass
 
2772
        else:
 
2773
            for hook in Branch.hooks['transform_fallback_location']:
 
2774
                url = hook(self, url)
 
2775
                if url is None:
 
2776
                    hook_name = Branch.hooks.get_hook_name(hook)
 
2777
                    raise AssertionError(
 
2778
                        "'transform_fallback_location' hook %s returned "
 
2779
                        "None, not a URL." % hook_name)
 
2780
            self._activate_fallback_location(url)
 
2781
 
 
2782
    def __init__(self, *args, **kwargs):
 
2783
        self._ignore_fallbacks = kwargs.get('ignore_fallbacks', False)
 
2784
        super(BzrBranch8, self).__init__(*args, **kwargs)
 
2785
        self._last_revision_info_cache = None
 
2786
        self._reference_info = None
 
2787
 
 
2788
    def _clear_cached_state(self):
 
2789
        super(BzrBranch8, self)._clear_cached_state()
 
2790
        self._last_revision_info_cache = None
 
2791
        self._reference_info = None
 
2792
 
 
2793
    def _check_history_violation(self, revision_id):
 
2794
        current_revid = self.last_revision()
 
2795
        last_revision = _mod_revision.ensure_null(current_revid)
 
2796
        if _mod_revision.is_null(last_revision):
 
2797
            return
 
2798
        graph = self.repository.get_graph()
 
2799
        for lh_ancestor in graph.iter_lefthand_ancestry(revision_id):
 
2800
            if lh_ancestor == current_revid:
 
2801
                return
 
2802
        raise errors.AppendRevisionsOnlyViolation(self.user_url)
 
2803
 
 
2804
    def _gen_revision_history(self):
 
2805
        """Generate the revision history from last revision
 
2806
        """
 
2807
        last_revno, last_revision = self.last_revision_info()
 
2808
        self._extend_partial_history(stop_index=last_revno-1)
 
2809
        return list(reversed(self._partial_revision_history_cache))
 
2810
 
 
2811
    @needs_write_lock
 
2812
    def _set_parent_location(self, url):
 
2813
        """Set the parent branch"""
 
2814
        self._set_config_location('parent_location', url, make_relative=True)
 
2815
 
 
2816
    @needs_read_lock
 
2817
    def _get_parent_location(self):
 
2818
        """Set the parent branch"""
 
2819
        return self._get_config_location('parent_location')
 
2820
 
 
2821
    @needs_write_lock
 
2822
    def _set_all_reference_info(self, info_dict):
 
2823
        """Replace all reference info stored in a branch.
 
2824
 
 
2825
        :param info_dict: A dict of {file_id: (tree_path, branch_location)}
 
2826
        """
 
2827
        s = StringIO()
 
2828
        writer = rio.RioWriter(s)
 
2829
        for key, (tree_path, branch_location) in info_dict.iteritems():
 
2830
            stanza = rio.Stanza(file_id=key, tree_path=tree_path,
 
2831
                                branch_location=branch_location)
 
2832
            writer.write_stanza(stanza)
 
2833
        self._transport.put_bytes('references', s.getvalue())
 
2834
        self._reference_info = info_dict
 
2835
 
 
2836
    @needs_read_lock
 
2837
    def _get_all_reference_info(self):
 
2838
        """Return all the reference info stored in a branch.
 
2839
 
 
2840
        :return: A dict of {file_id: (tree_path, branch_location)}
 
2841
        """
 
2842
        if self._reference_info is not None:
 
2843
            return self._reference_info
 
2844
        rio_file = self._transport.get('references')
 
2845
        try:
 
2846
            stanzas = rio.read_stanzas(rio_file)
 
2847
            info_dict = dict((s['file_id'], (s['tree_path'],
 
2848
                             s['branch_location'])) for s in stanzas)
 
2849
        finally:
 
2850
            rio_file.close()
 
2851
        self._reference_info = info_dict
 
2852
        return info_dict
 
2853
 
 
2854
    def set_reference_info(self, file_id, tree_path, branch_location):
 
2855
        """Set the branch location to use for a tree reference.
 
2856
 
 
2857
        :param file_id: The file-id of the tree reference.
 
2858
        :param tree_path: The path of the tree reference in the tree.
 
2859
        :param branch_location: The location of the branch to retrieve tree
 
2860
            references from.
 
2861
        """
 
2862
        info_dict = self._get_all_reference_info()
 
2863
        info_dict[file_id] = (tree_path, branch_location)
 
2864
        if None in (tree_path, branch_location):
 
2865
            if tree_path is not None:
 
2866
                raise ValueError('tree_path must be None when branch_location'
 
2867
                                 ' is None.')
 
2868
            if branch_location is not None:
 
2869
                raise ValueError('branch_location must be None when tree_path'
 
2870
                                 ' is None.')
 
2871
            del info_dict[file_id]
 
2872
        self._set_all_reference_info(info_dict)
 
2873
 
 
2874
    def get_reference_info(self, file_id):
 
2875
        """Get the tree_path and branch_location for a tree reference.
 
2876
 
 
2877
        :return: a tuple of (tree_path, branch_location)
 
2878
        """
 
2879
        return self._get_all_reference_info().get(file_id, (None, None))
 
2880
 
 
2881
    def reference_parent(self, file_id, path, possible_transports=None):
 
2882
        """Return the parent branch for a tree-reference file_id.
 
2883
 
 
2884
        :param file_id: The file_id of the tree reference
 
2885
        :param path: The path of the file_id in the tree
 
2886
        :return: A branch associated with the file_id
 
2887
        """
 
2888
        branch_location = self.get_reference_info(file_id)[1]
 
2889
        if branch_location is None:
 
2890
            return Branch.reference_parent(self, file_id, path,
 
2891
                                           possible_transports)
 
2892
        branch_location = urlutils.join(self.user_url, branch_location)
 
2893
        return Branch.open(branch_location,
 
2894
                           possible_transports=possible_transports)
 
2895
 
 
2896
    def set_push_location(self, location):
 
2897
        """See Branch.set_push_location."""
 
2898
        self._set_config_location('push_location', location)
 
2899
 
 
2900
    def set_bound_location(self, location):
 
2901
        """See Branch.set_push_location."""
 
2902
        self._master_branch_cache = None
 
2903
        result = None
 
2904
        config = self.get_config()
 
2905
        if location is None:
 
2906
            if config.get_user_option('bound') != 'True':
 
2907
                return False
 
2908
            else:
 
2909
                config.set_user_option('bound', 'False', warn_masked=True)
 
2910
                return True
 
2911
        else:
 
2912
            self._set_config_location('bound_location', location,
 
2913
                                      config=config)
 
2914
            config.set_user_option('bound', 'True', warn_masked=True)
 
2915
        return True
 
2916
 
 
2917
    def _get_bound_location(self, bound):
 
2918
        """Return the bound location in the config file.
 
2919
 
 
2920
        Return None if the bound parameter does not match"""
 
2921
        config = self.get_config()
 
2922
        config_bound = (config.get_user_option('bound') == 'True')
 
2923
        if config_bound != bound:
 
2924
            return None
 
2925
        return self._get_config_location('bound_location', config=config)
 
2926
 
 
2927
    def get_bound_location(self):
 
2928
        """See Branch.set_push_location."""
 
2929
        return self._get_bound_location(True)
 
2930
 
 
2931
    def get_old_bound_location(self):
 
2932
        """See Branch.get_old_bound_location"""
 
2933
        return self._get_bound_location(False)
 
2934
 
 
2935
    def get_stacked_on_url(self):
 
2936
        # you can always ask for the URL; but you might not be able to use it
 
2937
        # if the repo can't support stacking.
 
2938
        ## self._check_stackable_repo()
 
2939
        stacked_url = self._get_config_location('stacked_on_location')
 
2940
        if stacked_url is None:
 
2941
            raise errors.NotStacked(self)
 
2942
        return stacked_url
 
2943
 
 
2944
    def _get_append_revisions_only(self):
 
2945
        return self.get_config(
 
2946
            ).get_user_option_as_bool('append_revisions_only')
 
2947
 
 
2948
    @needs_read_lock
 
2949
    def get_rev_id(self, revno, history=None):
 
2950
        """Find the revision id of the specified revno."""
 
2951
        if revno == 0:
 
2952
            return _mod_revision.NULL_REVISION
 
2953
 
 
2954
        last_revno, last_revision_id = self.last_revision_info()
 
2955
        if revno <= 0 or revno > last_revno:
 
2956
            raise errors.NoSuchRevision(self, revno)
 
2957
 
 
2958
        if history is not None:
 
2959
            return history[revno - 1]
 
2960
 
 
2961
        index = last_revno - revno
 
2962
        if len(self._partial_revision_history_cache) <= index:
 
2963
            self._extend_partial_history(stop_index=index)
 
2964
        if len(self._partial_revision_history_cache) > index:
 
2965
            return self._partial_revision_history_cache[index]
 
2966
        else:
 
2967
            raise errors.NoSuchRevision(self, revno)
 
2968
 
 
2969
    @needs_read_lock
 
2970
    def revision_id_to_revno(self, revision_id):
 
2971
        """Given a revision id, return its revno"""
 
2972
        if _mod_revision.is_null(revision_id):
 
2973
            return 0
 
2974
        try:
 
2975
            index = self._partial_revision_history_cache.index(revision_id)
 
2976
        except ValueError:
 
2977
            try:
 
2978
                self._extend_partial_history(stop_revision=revision_id)
 
2979
            except errors.RevisionNotPresent, e:
 
2980
                raise errors.GhostRevisionsHaveNoRevno(revision_id, e.revision_id)
 
2981
            index = len(self._partial_revision_history_cache) - 1
 
2982
            if self._partial_revision_history_cache[index] != revision_id:
 
2983
                raise errors.NoSuchRevision(self, revision_id)
 
2984
        return self.revno() - index
 
2985
 
 
2986
 
 
2987
class BzrBranch7(BzrBranch8):
 
2988
    """A branch with support for a fallback repository."""
 
2989
 
 
2990
    def set_reference_info(self, file_id, tree_path, branch_location):
 
2991
        Branch.set_reference_info(self, file_id, tree_path, branch_location)
 
2992
 
 
2993
    def get_reference_info(self, file_id):
 
2994
        Branch.get_reference_info(self, file_id)
 
2995
 
 
2996
    def reference_parent(self, file_id, path, possible_transports=None):
 
2997
        return Branch.reference_parent(self, file_id, path,
 
2998
                                       possible_transports)
 
2999
 
 
3000
 
 
3001
class BzrBranch6(BzrBranch7):
 
3002
    """See BzrBranchFormat6 for the capabilities of this branch.
 
3003
 
 
3004
    This subclass of BzrBranch7 disables the new features BzrBranch7 added,
 
3005
    i.e. stacking.
 
3006
    """
 
3007
 
 
3008
    def get_stacked_on_url(self):
 
3009
        raise errors.UnstackableBranchFormat(self._format, self.user_url)
 
3010
 
 
3011
 
 
3012
######################################################################
 
3013
# results of operations
 
3014
 
 
3015
 
 
3016
class _Result(object):
 
3017
 
 
3018
    def _show_tag_conficts(self, to_file):
 
3019
        if not getattr(self, 'tag_conflicts', None):
 
3020
            return
 
3021
        to_file.write('Conflicting tags:\n')
 
3022
        for name, value1, value2 in self.tag_conflicts:
 
3023
            to_file.write('    %s\n' % (name, ))
 
3024
 
 
3025
 
 
3026
class PullResult(_Result):
 
3027
    """Result of a Branch.pull operation.
 
3028
 
 
3029
    :ivar old_revno: Revision number before pull.
 
3030
    :ivar new_revno: Revision number after pull.
 
3031
    :ivar old_revid: Tip revision id before pull.
 
3032
    :ivar new_revid: Tip revision id after pull.
 
3033
    :ivar source_branch: Source (local) branch object. (read locked)
 
3034
    :ivar master_branch: Master branch of the target, or the target if no
 
3035
        Master
 
3036
    :ivar local_branch: target branch if there is a Master, else None
 
3037
    :ivar target_branch: Target/destination branch object. (write locked)
 
3038
    :ivar tag_conflicts: A list of tag conflicts, see BasicTags.merge_to
 
3039
    """
 
3040
 
 
3041
    @deprecated_method(deprecated_in((2, 3, 0)))
 
3042
    def __int__(self):
 
3043
        """Return the relative change in revno.
 
3044
 
 
3045
        :deprecated: Use `new_revno` and `old_revno` instead.
 
3046
        """
 
3047
        return self.new_revno - self.old_revno
 
3048
 
 
3049
    def report(self, to_file):
 
3050
        if not is_quiet():
 
3051
            if self.old_revid == self.new_revid:
 
3052
                to_file.write('No revisions to pull.\n')
 
3053
            else:
 
3054
                to_file.write('Now on revision %d.\n' % self.new_revno)
 
3055
        self._show_tag_conficts(to_file)
 
3056
 
 
3057
 
 
3058
class BranchPushResult(_Result):
 
3059
    """Result of a Branch.push operation.
 
3060
 
 
3061
    :ivar old_revno: Revision number (eg 10) of the target before push.
 
3062
    :ivar new_revno: Revision number (eg 12) of the target after push.
 
3063
    :ivar old_revid: Tip revision id (eg joe@foo.com-1234234-aoeua34) of target
 
3064
        before the push.
 
3065
    :ivar new_revid: Tip revision id (eg joe@foo.com-5676566-boa234a) of target
 
3066
        after the push.
 
3067
    :ivar source_branch: Source branch object that the push was from. This is
 
3068
        read locked, and generally is a local (and thus low latency) branch.
 
3069
    :ivar master_branch: If target is a bound branch, the master branch of
 
3070
        target, or target itself. Always write locked.
 
3071
    :ivar target_branch: The direct Branch where data is being sent (write
 
3072
        locked).
 
3073
    :ivar local_branch: If the target is a bound branch this will be the
 
3074
        target, otherwise it will be None.
 
3075
    """
 
3076
 
 
3077
    @deprecated_method(deprecated_in((2, 3, 0)))
 
3078
    def __int__(self):
 
3079
        """Return the relative change in revno.
 
3080
 
 
3081
        :deprecated: Use `new_revno` and `old_revno` instead.
 
3082
        """
 
3083
        return self.new_revno - self.old_revno
 
3084
 
 
3085
    def report(self, to_file):
 
3086
        """Write a human-readable description of the result."""
 
3087
        if self.old_revid == self.new_revid:
 
3088
            note('No new revisions to push.')
 
3089
        else:
 
3090
            note('Pushed up to revision %d.' % self.new_revno)
 
3091
        self._show_tag_conficts(to_file)
 
3092
 
 
3093
 
 
3094
class BranchCheckResult(object):
 
3095
    """Results of checking branch consistency.
 
3096
 
 
3097
    :see: Branch.check
 
3098
    """
 
3099
 
 
3100
    def __init__(self, branch):
 
3101
        self.branch = branch
 
3102
        self.errors = []
 
3103
 
 
3104
    def report_results(self, verbose):
 
3105
        """Report the check results via trace.note.
 
3106
 
 
3107
        :param verbose: Requests more detailed display of what was checked,
 
3108
            if any.
 
3109
        """
 
3110
        note('checked branch %s format %s', self.branch.user_url,
 
3111
            self.branch._format)
 
3112
        for error in self.errors:
 
3113
            note('found error:%s', error)
 
3114
 
 
3115
 
 
3116
class Converter5to6(object):
 
3117
    """Perform an in-place upgrade of format 5 to format 6"""
 
3118
 
 
3119
    def convert(self, branch):
 
3120
        # Data for 5 and 6 can peacefully coexist.
 
3121
        format = BzrBranchFormat6()
 
3122
        new_branch = format.open(branch.bzrdir, _found=True)
 
3123
 
 
3124
        # Copy source data into target
 
3125
        new_branch._write_last_revision_info(*branch.last_revision_info())
 
3126
        new_branch.set_parent(branch.get_parent())
 
3127
        new_branch.set_bound_location(branch.get_bound_location())
 
3128
        new_branch.set_push_location(branch.get_push_location())
 
3129
 
 
3130
        # New branch has no tags by default
 
3131
        new_branch.tags._set_tag_dict({})
 
3132
 
 
3133
        # Copying done; now update target format
 
3134
        new_branch._transport.put_bytes('format',
 
3135
            format.get_format_string(),
 
3136
            mode=new_branch.bzrdir._get_file_mode())
 
3137
 
 
3138
        # Clean up old files
 
3139
        new_branch._transport.delete('revision-history')
 
3140
        try:
 
3141
            branch.set_parent(None)
 
3142
        except errors.NoSuchFile:
 
3143
            pass
 
3144
        branch.set_bound_location(None)
 
3145
 
 
3146
 
 
3147
class Converter6to7(object):
 
3148
    """Perform an in-place upgrade of format 6 to format 7"""
 
3149
 
 
3150
    def convert(self, branch):
 
3151
        format = BzrBranchFormat7()
 
3152
        branch._set_config_location('stacked_on_location', '')
 
3153
        # update target format
 
3154
        branch._transport.put_bytes('format', format.get_format_string())
 
3155
 
 
3156
 
 
3157
class Converter7to8(object):
 
3158
    """Perform an in-place upgrade of format 6 to format 7"""
 
3159
 
 
3160
    def convert(self, branch):
 
3161
        format = BzrBranchFormat8()
 
3162
        branch._transport.put_bytes('references', '')
 
3163
        # update target format
 
3164
        branch._transport.put_bytes('format', format.get_format_string())
 
3165
 
 
3166
 
 
3167
def _run_with_write_locked_target(target, callable, *args, **kwargs):
 
3168
    """Run ``callable(*args, **kwargs)``, write-locking target for the
 
3169
    duration.
 
3170
 
 
3171
    _run_with_write_locked_target will attempt to release the lock it acquires.
 
3172
 
 
3173
    If an exception is raised by callable, then that exception *will* be
 
3174
    propagated, even if the unlock attempt raises its own error.  Thus
 
3175
    _run_with_write_locked_target should be preferred to simply doing::
 
3176
 
 
3177
        target.lock_write()
 
3178
        try:
 
3179
            return callable(*args, **kwargs)
 
3180
        finally:
 
3181
            target.unlock()
 
3182
 
 
3183
    """
 
3184
    # This is very similar to bzrlib.decorators.needs_write_lock.  Perhaps they
 
3185
    # should share code?
 
3186
    target.lock_write()
 
3187
    try:
 
3188
        result = callable(*args, **kwargs)
 
3189
    except:
 
3190
        exc_info = sys.exc_info()
 
3191
        try:
 
3192
            target.unlock()
 
3193
        finally:
 
3194
            raise exc_info[0], exc_info[1], exc_info[2]
 
3195
    else:
 
3196
        target.unlock()
 
3197
        return result
 
3198
 
 
3199
 
 
3200
class InterBranch(InterObject):
 
3201
    """This class represents operations taking place between two branches.
 
3202
 
 
3203
    Its instances have methods like pull() and push() and contain
 
3204
    references to the source and target repositories these operations
 
3205
    can be carried out on.
 
3206
    """
 
3207
 
 
3208
    _optimisers = []
 
3209
    """The available optimised InterBranch types."""
 
3210
 
 
3211
    @classmethod
 
3212
    def _get_branch_formats_to_test(klass):
 
3213
        """Return an iterable of format tuples for testing.
 
3214
        
 
3215
        :return: An iterable of (from_format, to_format) to use when testing
 
3216
            this InterBranch class. Each InterBranch class should define this
 
3217
            method itself.
 
3218
        """
 
3219
        raise NotImplementedError(klass._get_branch_formats_to_test)
 
3220
 
 
3221
    @needs_write_lock
 
3222
    def pull(self, overwrite=False, stop_revision=None,
 
3223
             possible_transports=None, local=False):
 
3224
        """Mirror source into target branch.
 
3225
 
 
3226
        The target branch is considered to be 'local', having low latency.
 
3227
 
 
3228
        :returns: PullResult instance
 
3229
        """
 
3230
        raise NotImplementedError(self.pull)
 
3231
 
 
3232
    @needs_write_lock
 
3233
    def push(self, overwrite=False, stop_revision=None, lossy=False,
 
3234
             _override_hook_source_branch=None):
 
3235
        """Mirror the source branch into the target branch.
 
3236
 
 
3237
        The source branch is considered to be 'local', having low latency.
 
3238
        """
 
3239
        raise NotImplementedError(self.push)
 
3240
 
 
3241
    @needs_write_lock
 
3242
    def copy_content_into(self, revision_id=None):
 
3243
        """Copy the content of source into target
 
3244
 
 
3245
        revision_id: if not None, the revision history in the new branch will
 
3246
                     be truncated to end with revision_id.
 
3247
        """
 
3248
        raise NotImplementedError(self.copy_content_into)
 
3249
 
 
3250
    @needs_write_lock
 
3251
    def fetch(self, stop_revision=None):
 
3252
        """Fetch revisions.
 
3253
 
 
3254
        :param stop_revision: Last revision to fetch
 
3255
        """
 
3256
        raise NotImplementedError(self.fetch)
 
3257
 
 
3258
 
 
3259
class GenericInterBranch(InterBranch):
 
3260
    """InterBranch implementation that uses public Branch functions."""
 
3261
 
 
3262
    @classmethod
 
3263
    def is_compatible(klass, source, target):
 
3264
        # GenericBranch uses the public API, so always compatible
 
3265
        return True
 
3266
 
 
3267
    @classmethod
 
3268
    def _get_branch_formats_to_test(klass):
 
3269
        return [(format_registry.get_default(), format_registry.get_default())]
 
3270
 
 
3271
    @classmethod
 
3272
    def unwrap_format(klass, format):
 
3273
        if isinstance(format, remote.RemoteBranchFormat):
 
3274
            format._ensure_real()
 
3275
            return format._custom_format
 
3276
        return format
 
3277
 
 
3278
    @needs_write_lock
 
3279
    def copy_content_into(self, revision_id=None):
 
3280
        """Copy the content of source into target
 
3281
 
 
3282
        revision_id: if not None, the revision history in the new branch will
 
3283
                     be truncated to end with revision_id.
 
3284
        """
 
3285
        self.source.update_references(self.target)
 
3286
        self.source._synchronize_history(self.target, revision_id)
 
3287
        try:
 
3288
            parent = self.source.get_parent()
 
3289
        except errors.InaccessibleParent, e:
 
3290
            mutter('parent was not accessible to copy: %s', e)
 
3291
        else:
 
3292
            if parent:
 
3293
                self.target.set_parent(parent)
 
3294
        if self.source._push_should_merge_tags():
 
3295
            self.source.tags.merge_to(self.target.tags)
 
3296
 
 
3297
    @needs_write_lock
 
3298
    def fetch(self, stop_revision=None):
 
3299
        if self.target.base == self.source.base:
 
3300
            return (0, [])
 
3301
        self.source.lock_read()
 
3302
        try:
 
3303
            fetch_spec_factory = fetch.FetchSpecFactory()
 
3304
            fetch_spec_factory.source_branch = self.source
 
3305
            fetch_spec_factory.source_branch_stop_revision_id = stop_revision
 
3306
            fetch_spec_factory.source_repo = self.source.repository
 
3307
            fetch_spec_factory.target_repo = self.target.repository
 
3308
            fetch_spec_factory.target_repo_kind = fetch.TargetRepoKinds.PREEXISTING
 
3309
            fetch_spec = fetch_spec_factory.make_fetch_spec()
 
3310
            return self.target.repository.fetch(self.source.repository,
 
3311
                fetch_spec=fetch_spec)
 
3312
        finally:
 
3313
            self.source.unlock()
 
3314
 
 
3315
    @needs_write_lock
 
3316
    def _update_revisions(self, stop_revision=None, overwrite=False,
 
3317
            graph=None):
 
3318
        other_revno, other_last_revision = self.source.last_revision_info()
 
3319
        stop_revno = None # unknown
 
3320
        if stop_revision is None:
 
3321
            stop_revision = other_last_revision
 
3322
            if _mod_revision.is_null(stop_revision):
 
3323
                # if there are no commits, we're done.
 
3324
                return
 
3325
            stop_revno = other_revno
 
3326
 
 
3327
        # what's the current last revision, before we fetch [and change it
 
3328
        # possibly]
 
3329
        last_rev = _mod_revision.ensure_null(self.target.last_revision())
 
3330
        # we fetch here so that we don't process data twice in the common
 
3331
        # case of having something to pull, and so that the check for
 
3332
        # already merged can operate on the just fetched graph, which will
 
3333
        # be cached in memory.
 
3334
        self.fetch(stop_revision=stop_revision)
 
3335
        # Check to see if one is an ancestor of the other
 
3336
        if not overwrite:
 
3337
            if graph is None:
 
3338
                graph = self.target.repository.get_graph()
 
3339
            if self.target._check_if_descendant_or_diverged(
 
3340
                    stop_revision, last_rev, graph, self.source):
 
3341
                # stop_revision is a descendant of last_rev, but we aren't
 
3342
                # overwriting, so we're done.
 
3343
                return
 
3344
        if stop_revno is None:
 
3345
            if graph is None:
 
3346
                graph = self.target.repository.get_graph()
 
3347
            this_revno, this_last_revision = \
 
3348
                    self.target.last_revision_info()
 
3349
            stop_revno = graph.find_distance_to_null(stop_revision,
 
3350
                            [(other_last_revision, other_revno),
 
3351
                             (this_last_revision, this_revno)])
 
3352
        self.target.set_last_revision_info(stop_revno, stop_revision)
 
3353
 
 
3354
    @needs_write_lock
 
3355
    def pull(self, overwrite=False, stop_revision=None,
 
3356
             possible_transports=None, run_hooks=True,
 
3357
             _override_hook_target=None, local=False):
 
3358
        """Pull from source into self, updating my master if any.
 
3359
 
 
3360
        :param run_hooks: Private parameter - if false, this branch
 
3361
            is being called because it's the master of the primary branch,
 
3362
            so it should not run its hooks.
 
3363
        """
 
3364
        bound_location = self.target.get_bound_location()
 
3365
        if local and not bound_location:
 
3366
            raise errors.LocalRequiresBoundBranch()
 
3367
        master_branch = None
 
3368
        source_is_master = (self.source.user_url == bound_location)
 
3369
        if not local and bound_location and not source_is_master:
 
3370
            # not pulling from master, so we need to update master.
 
3371
            master_branch = self.target.get_master_branch(possible_transports)
 
3372
            master_branch.lock_write()
 
3373
        try:
 
3374
            if master_branch:
 
3375
                # pull from source into master.
 
3376
                master_branch.pull(self.source, overwrite, stop_revision,
 
3377
                    run_hooks=False)
 
3378
            return self._pull(overwrite,
 
3379
                stop_revision, _hook_master=master_branch,
 
3380
                run_hooks=run_hooks,
 
3381
                _override_hook_target=_override_hook_target,
 
3382
                merge_tags_to_master=not source_is_master)
 
3383
        finally:
 
3384
            if master_branch:
 
3385
                master_branch.unlock()
 
3386
 
 
3387
    def push(self, overwrite=False, stop_revision=None, lossy=False,
 
3388
             _override_hook_source_branch=None):
 
3389
        """See InterBranch.push.
 
3390
 
 
3391
        This is the basic concrete implementation of push()
 
3392
 
 
3393
        :param _override_hook_source_branch: If specified, run
 
3394
        the hooks passing this Branch as the source, rather than self.
 
3395
        This is for use of RemoteBranch, where push is delegated to the
 
3396
        underlying vfs-based Branch.
 
3397
        """
 
3398
        if lossy:
 
3399
            raise errors.LossyPushToSameVCS(self.source, self.target)
 
3400
        # TODO: Public option to disable running hooks - should be trivial but
 
3401
        # needs tests.
 
3402
        self.source.lock_read()
 
3403
        try:
 
3404
            return _run_with_write_locked_target(
 
3405
                self.target, self._push_with_bound_branches, overwrite,
 
3406
                stop_revision, 
 
3407
                _override_hook_source_branch=_override_hook_source_branch)
 
3408
        finally:
 
3409
            self.source.unlock()
 
3410
 
 
3411
    def _basic_push(self, overwrite, stop_revision):
 
3412
        """Basic implementation of push without bound branches or hooks.
 
3413
 
 
3414
        Must be called with source read locked and target write locked.
 
3415
        """
 
3416
        result = BranchPushResult()
 
3417
        result.source_branch = self.source
 
3418
        result.target_branch = self.target
 
3419
        result.old_revno, result.old_revid = self.target.last_revision_info()
 
3420
        self.source.update_references(self.target)
 
3421
        if result.old_revid != stop_revision:
 
3422
            # We assume that during 'push' this repository is closer than
 
3423
            # the target.
 
3424
            graph = self.source.repository.get_graph(self.target.repository)
 
3425
            self._update_revisions(stop_revision, overwrite=overwrite,
 
3426
                    graph=graph)
 
3427
        if self.source._push_should_merge_tags():
 
3428
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
 
3429
                overwrite)
 
3430
        result.new_revno, result.new_revid = self.target.last_revision_info()
 
3431
        return result
 
3432
 
 
3433
    def _push_with_bound_branches(self, overwrite, stop_revision,
 
3434
            _override_hook_source_branch=None):
 
3435
        """Push from source into target, and into target's master if any.
 
3436
        """
 
3437
        def _run_hooks():
 
3438
            if _override_hook_source_branch:
 
3439
                result.source_branch = _override_hook_source_branch
 
3440
            for hook in Branch.hooks['post_push']:
 
3441
                hook(result)
 
3442
 
 
3443
        bound_location = self.target.get_bound_location()
 
3444
        if bound_location and self.target.base != bound_location:
 
3445
            # there is a master branch.
 
3446
            #
 
3447
            # XXX: Why the second check?  Is it even supported for a branch to
 
3448
            # be bound to itself? -- mbp 20070507
 
3449
            master_branch = self.target.get_master_branch()
 
3450
            master_branch.lock_write()
 
3451
            try:
 
3452
                # push into the master from the source branch.
 
3453
                master_inter = InterBranch.get(self.source, master_branch)
 
3454
                master_inter._basic_push(overwrite, stop_revision)
 
3455
                # and push into the target branch from the source. Note that
 
3456
                # we push from the source branch again, because it's considered
 
3457
                # the highest bandwidth repository.
 
3458
                result = self._basic_push(overwrite, stop_revision)
 
3459
                result.master_branch = master_branch
 
3460
                result.local_branch = self.target
 
3461
                _run_hooks()
 
3462
                return result
 
3463
            finally:
 
3464
                master_branch.unlock()
 
3465
        else:
 
3466
            # no master branch
 
3467
            result = self._basic_push(overwrite, stop_revision)
 
3468
            # TODO: Why set master_branch and local_branch if there's no
 
3469
            # binding?  Maybe cleaner to just leave them unset? -- mbp
 
3470
            # 20070504
 
3471
            result.master_branch = self.target
 
3472
            result.local_branch = None
 
3473
            _run_hooks()
 
3474
            return result
 
3475
 
 
3476
    def _pull(self, overwrite=False, stop_revision=None,
 
3477
             possible_transports=None, _hook_master=None, run_hooks=True,
 
3478
             _override_hook_target=None, local=False,
 
3479
             merge_tags_to_master=True):
 
3480
        """See Branch.pull.
 
3481
 
 
3482
        This function is the core worker, used by GenericInterBranch.pull to
 
3483
        avoid duplication when pulling source->master and source->local.
 
3484
 
 
3485
        :param _hook_master: Private parameter - set the branch to
 
3486
            be supplied as the master to pull hooks.
 
3487
        :param run_hooks: Private parameter - if false, this branch
 
3488
            is being called because it's the master of the primary branch,
 
3489
            so it should not run its hooks.
 
3490
            is being called because it's the master of the primary branch,
 
3491
            so it should not run its hooks.
 
3492
        :param _override_hook_target: Private parameter - set the branch to be
 
3493
            supplied as the target_branch to pull hooks.
 
3494
        :param local: Only update the local branch, and not the bound branch.
 
3495
        """
 
3496
        # This type of branch can't be bound.
 
3497
        if local:
 
3498
            raise errors.LocalRequiresBoundBranch()
 
3499
        result = PullResult()
 
3500
        result.source_branch = self.source
 
3501
        if _override_hook_target is None:
 
3502
            result.target_branch = self.target
 
3503
        else:
 
3504
            result.target_branch = _override_hook_target
 
3505
        self.source.lock_read()
 
3506
        try:
 
3507
            # We assume that during 'pull' the target repository is closer than
 
3508
            # the source one.
 
3509
            self.source.update_references(self.target)
 
3510
            graph = self.target.repository.get_graph(self.source.repository)
 
3511
            # TODO: Branch formats should have a flag that indicates 
 
3512
            # that revno's are expensive, and pull() should honor that flag.
 
3513
            # -- JRV20090506
 
3514
            result.old_revno, result.old_revid = \
 
3515
                self.target.last_revision_info()
 
3516
            self._update_revisions(stop_revision, overwrite=overwrite,
 
3517
                graph=graph)
 
3518
            # TODO: The old revid should be specified when merging tags, 
 
3519
            # so a tags implementation that versions tags can only 
 
3520
            # pull in the most recent changes. -- JRV20090506
 
3521
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
 
3522
                overwrite, ignore_master=not merge_tags_to_master)
 
3523
            result.new_revno, result.new_revid = self.target.last_revision_info()
 
3524
            if _hook_master:
 
3525
                result.master_branch = _hook_master
 
3526
                result.local_branch = result.target_branch
 
3527
            else:
 
3528
                result.master_branch = result.target_branch
 
3529
                result.local_branch = None
 
3530
            if run_hooks:
 
3531
                for hook in Branch.hooks['post_pull']:
 
3532
                    hook(result)
 
3533
        finally:
 
3534
            self.source.unlock()
 
3535
        return result
 
3536
 
 
3537
 
 
3538
InterBranch.register_optimiser(GenericInterBranch)