/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: Martin Packman
  • Date: 2011-11-29 16:14:12 UTC
  • mto: This revision was merged to the branch mainline in revision 6327.
  • Revision ID: martin.packman@canonical.com-20111129161412-mx4yu5mg6xsaty46
Require the dulwich package when using py2exe with the git plugin enabled

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