/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
4110.2.5 by Martin Pool
Deprecate passing pbs in to fetch()
1
# Copyright (C) 2005, 2006, 2007, 2008, 2009 Canonical Ltd
1553.5.70 by Martin Pool
doc
2
#
1 by mbp at sourcefrog
import from baz patch-364
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.
1553.5.70 by Martin Pool
doc
7
#
1 by mbp at sourcefrog
import from baz patch-364
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.
1553.5.70 by Martin Pool
doc
12
#
1 by mbp at sourcefrog
import from baz patch-364
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
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1 by mbp at sourcefrog
import from baz patch-364
16
17
3577.1.1 by Andrew Bennetts
Cherry-pick TipChangeRejected changes from pre-branch-tip-changed-hook loom.
18
import sys
19
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
20
from bzrlib.lazy_import import lazy_import
21
lazy_import(globals(), """
3221.13.2 by Robert Collins
Add a shallow parameter to bzrdir.sprout, which involved fixing a lateny bug in pack to pack fetching with ghost discovery.
22
from itertools import chain
1551.8.4 by Aaron Bentley
Tweak import style
23
from bzrlib import (
1911.2.7 by John Arbash Meinel
[merge] bzr.dev 1924
24
        bzrdir,
25
        cache_utf8,
2120.6.9 by James Henstridge
Fixes for issues brought up in John's review
26
        config as _mod_config,
2592.3.113 by Robert Collins
Various -Devil checks in branch.py.
27
        debug,
1911.2.7 by John Arbash Meinel
[merge] bzr.dev 1924
28
        errors,
29
        lockdir,
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
30
        lockable_files,
3287.6.8 by Robert Collins
Reduce code duplication as per review.
31
        repository,
1996.3.12 by John Arbash Meinel
Change how 'revision' is imported to avoid problems later
32
        revision as _mod_revision,
4110.2.5 by Martin Pool
Deprecate passing pbs in to fetch()
33
        symbol_versioning,
1911.2.9 by John Arbash Meinel
Fix accidental import removal
34
        transport,
2418.5.5 by John Arbash Meinel
Add some tests and an api for revision_id_to_dotted_revno
35
        tsort,
1551.8.4 by Aaron Bentley
Tweak import style
36
        ui,
1911.2.7 by John Arbash Meinel
[merge] bzr.dev 1924
37
        urlutils,
1551.8.4 by Aaron Bentley
Tweak import style
38
        )
3236.1.2 by Michael Hudson
clean up branch.py imports
39
from bzrlib.config import BranchConfig
3735.1.2 by Robert Collins
Remove 1.5 series dev formats and document development2 a little better.
40
from bzrlib.repofmt.pack_repo import RepositoryFormatKnitPack5RichRoot
2220.2.11 by mbp at sourcefrog
Get tag tests working again, stored in the Branch
41
from bzrlib.tag import (
2220.2.20 by Martin Pool
Tag methods now available through Branch.tags.add_tag, etc
42
    BasicTags,
43
    DisabledTags,
2220.2.11 by mbp at sourcefrog
Get tag tests working again, stored in the Branch
44
    )
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
45
""")
46
1534.4.28 by Robert Collins
first cut at merge from integration.
47
from bzrlib.decorators import needs_read_lock, needs_write_lock
4119.3.2 by Robert Collins
Migrate existing hooks over to the new HookPoint infrastructure.
48
from bzrlib.hooks import HookPoint, Hooks
4000.5.1 by Jelmer Vernooij
Add InterBranch.
49
from bzrlib.inter import InterObject
4032.3.1 by Robert Collins
Add a BranchFormat.network_name() method as preparation for creating branches via RPC calls.
50
from bzrlib import registry
3407.2.11 by Martin Pool
Deprecate Branch.abspath
51
from bzrlib.symbol_versioning import (
52
    deprecated_in,
53
    deprecated_method,
54
    )
3200.1.1 by James Westby
Make pull --quiet more quiet. Fixes #185907.
55
from bzrlib.trace import mutter, mutter_callsite, note, is_quiet
1104 by Martin Pool
- Add a simple UIFactory
56
1094 by Martin Pool
- merge aaron's merge improvements 999..1008
57
1186 by Martin Pool
- start implementing v5 format; Branch refuses to operate on old branches
58
BZR_BRANCH_FORMAT_4 = "Bazaar-NG branch, format 0.0.4\n"
59
BZR_BRANCH_FORMAT_5 = "Bazaar-NG branch, format 5\n"
2255.2.230 by Robert Collins
Update tree format signatures to mention introducing bzr version.
60
BZR_BRANCH_FORMAT_6 = "Bazaar Branch Format 6 (bzr 0.15)\n"
1185.70.3 by Martin Pool
Various updates to make storage branch mergeable:
61
62
63
# TODO: Maybe include checks for common corruption of newlines, etc?
1 by mbp at sourcefrog
import from baz patch-364
64
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
65
# TODO: Some operations like log might retrieve the same revisions
66
# repeatedly to calculate deltas.  We could perhaps have a weakref
1223 by Martin Pool
- store inventories in weave
67
# cache in memory to make this faster.  In general anything can be
1185.65.29 by Robert Collins
Implement final review suggestions.
68
# cached in memory between lock and unlock operations. .. nb thats
69
# what the transaction identity map provides
416 by Martin Pool
- bzr log and bzr root now accept an http URL
70
1442.1.63 by Robert Collins
Remove self.lock_*...finally: self.unlock() dead chickens from branch.py.
71
1 by mbp at sourcefrog
import from baz patch-364
72
######################################################################
73
# branch objects
74
558 by Martin Pool
- All top-level classes inherit from object
75
class Branch(object):
1 by mbp at sourcefrog
import from baz patch-364
76
    """Branch holding a history of revisions.
77
343 by Martin Pool
doc
78
    base
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
79
        Base directory/url of the branch.
2245.1.1 by Robert Collins
New Branch hooks facility, with one initial hook 'set_rh' which triggers
80
2245.1.2 by Robert Collins
Remove the static DefaultHooks method from Branch, replacing it with a derived dict BranchHooks object, which is easier to use and provides a place to put the policy-checking add method discussed on list.
81
    hooks: An instance of BranchHooks.
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
82
    """
1534.4.1 by Robert Collins
Allow parameterisation of the branch initialisation for bzrlib.
83
    # this is really an instance variable - FIXME move it there
84
    # - RBC 20060112
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
85
    base = None
86
87
    def __init__(self, *ignored, **ignored_too):
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
88
        self.tags = self._format.make_tags(self)
2375.1.3 by Andrew Bennetts
Don't use Branch.get_transaction to cache revision history.
89
        self._revision_history_cache = None
2418.5.6 by John Arbash Meinel
Cache the revision_id => revno map as appropriate.
90
        self._revision_id_to_revno_cache = None
3949.2.6 by Ian Clatworthy
review feedback from jam
91
        self._partial_revision_id_to_revno_cache = {}
3441.5.27 by Andrew Bennetts
Tweaks suggested by John's review: rename _check_if_descendant_or_diverged, move caching last_revision_info into base Branch, better use of lock decorators.
92
        self._last_revision_info_cache = None
3949.3.4 by Ian Clatworthy
jam feedback: start & stop limits; simple caching
93
        self._merge_sorted_revisions_cache = None
3221.11.11 by Robert Collins
Ensure opening a stacked branch gives a ready to use repository.
94
        self._open_hook()
3681.1.1 by Robert Collins
Create a new hook Branch.open. (Robert Collins)
95
        hooks = Branch.hooks['open']
96
        for hook in hooks:
97
            hook(self)
3221.11.11 by Robert Collins
Ensure opening a stacked branch gives a ready to use repository.
98
99
    def _open_hook(self):
100
        """Called by init to allow simpler extension of the base class."""
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
101
4226.1.3 by Robert Collins
Lift Branch.set_stacked_on_url up from BzrBranch7.
102
    def _activate_fallback_location(self, url):
103
        """Activate the branch/repository from url as a fallback repository."""
104
        self.repository.add_fallback_repository(
105
            self._get_fallback_repository(url))
106
1687.1.8 by Robert Collins
Teach Branch about break_lock.
107
    def break_lock(self):
108
        """Break a lock if one is present from another instance.
109
110
        Uses the ui factory to ask for confirmation if the lock may be from
111
        an active process.
112
113
        This will probe the repository for its lock as well.
114
        """
115
        self.control_files.break_lock()
116
        self.repository.break_lock()
1687.1.10 by Robert Collins
Branch.break_lock should handle bound branches too
117
        master = self.get_master_branch()
118
        if master is not None:
119
            master.break_lock()
1687.1.8 by Robert Collins
Teach Branch about break_lock.
120
4226.1.3 by Robert Collins
Lift Branch.set_stacked_on_url up from BzrBranch7.
121
    def _check_stackable_repo(self):
122
        if not self.repository._format.supports_external_lookups:
123
            raise errors.UnstackableRepositoryFormat(self.repository._format,
124
                self.repository.base)
125
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
126
    @staticmethod
2806.2.2 by Vincent Ladeuil
Fix #128076 and #131396 by reusing bound branch transport.
127
    def open(base, _unsupported=False, possible_transports=None):
1815.1.1 by Jelmer Vernooij
Fix copy-pasted comment.
128
        """Open the branch rooted at base.
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
129
1815.1.1 by Jelmer Vernooij
Fix copy-pasted comment.
130
        For instance, if the branch is at URL/.bzr/branch,
131
        Branch.open(URL) -> a Branch instance.
1534.4.7 by Robert Collins
Move downlevel check up to the Branch.open logic, removing it from the Branch constructor and deprecating relax_version_check to the same.
132
        """
2806.2.2 by Vincent Ladeuil
Fix #128076 and #131396 by reusing bound branch transport.
133
        control = bzrdir.BzrDir.open(base, _unsupported,
134
                                     possible_transports=possible_transports)
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
135
        return control.open_branch(_unsupported)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
136
137
    @staticmethod
2485.8.35 by Vincent Ladeuil
Fix pull multiple connections.
138
    def open_from_transport(transport, _unsupported=False):
139
        """Open the branch rooted at transport"""
140
        control = bzrdir.BzrDir.open_from_transport(transport, _unsupported)
141
        return control.open_branch(_unsupported)
142
143
    @staticmethod
2485.8.37 by Vincent Ladeuil
Fix merge multiple connections. Test suite *not* passing (sftp
144
    def open_containing(url, possible_transports=None):
1185.1.41 by Robert Collins
massive patch from Alexander Belchenko - many PEP8 fixes, removes unused function uuid
145
        """Open an existing branch which contains url.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
146
1185.1.41 by Robert Collins
massive patch from Alexander Belchenko - many PEP8 fixes, removes unused function uuid
147
        This probes for a branch at url, and searches upwards from there.
1185.17.2 by Martin Pool
[pick] avoid problems in fetching when .bzr is not listable
148
149
        Basically we keep looking up until we find the control directory or
150
        run into the root.  If there isn't one, raises NotBranchError.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
151
        If there is one and it is either an unrecognised format or an unsupported
1534.4.22 by Robert Collins
update TODOs and move abstract methods that were misplaced on BzrBranchFormat5 to Branch.
152
        format, UnknownFormatError or UnsupportedFormatError are raised.
1442.1.64 by Robert Collins
Branch.open_containing now returns a tuple (Branch, relative-path).
153
        If there is one, it is returned, along with the unused portion of url.
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
154
        """
2485.8.37 by Vincent Ladeuil
Fix merge multiple connections. Test suite *not* passing (sftp
155
        control, relpath = bzrdir.BzrDir.open_containing(url,
156
                                                         possible_transports)
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
157
        return control.open_branch(), relpath
1534.4.1 by Robert Collins
Allow parameterisation of the branch initialisation for bzrlib.
158
4032.3.5 by Robert Collins
Move BzrBranch._push_should_merge_tags to Branch.
159
    def _push_should_merge_tags(self):
160
        """Should _basic_push merge this branch's tags into the target?
161
162
        The default implementation returns False if this branch has no tags,
163
        and True the rest of the time.  Subclasses may override this.
164
        """
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
165
        return self.supports_tags() and self.tags.get_tag_dict()
4032.3.5 by Robert Collins
Move BzrBranch._push_should_merge_tags to Branch.
166
1770.2.9 by Aaron Bentley
Add Branch.get_config, update BranchConfig() callers
167
    def get_config(self):
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
168
        return BranchConfig(self)
1770.2.9 by Aaron Bentley
Add Branch.get_config, update BranchConfig() callers
169
4226.1.3 by Robert Collins
Lift Branch.set_stacked_on_url up from BzrBranch7.
170
    def _get_fallback_repository(self, url):
171
        """Get the repository we fallback to at url."""
172
        url = urlutils.join(self.base, url)
173
        a_bzrdir = bzrdir.BzrDir.open(url,
4226.1.4 by Robert Collins
Simplify code in RemoteBranch to use helpers from Branch.
174
            possible_transports=[self.bzrdir.root_transport])
4226.1.3 by Robert Collins
Lift Branch.set_stacked_on_url up from BzrBranch7.
175
        return a_bzrdir.open_branch().repository
176
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
177
    def _get_tags_bytes(self):
178
        """Get the bytes of a serialised tags dict.
179
180
        Note that not all branches support tags, nor do all use the same tags
181
        logic: this method is specific to BasicTags. Other tag implementations
182
        may use the same method name and behave differently, safely, because
183
        of the double-dispatch via
184
        format.make_tags->tags_instance->get_tags_dict.
185
186
        :return: The bytes of the tags file.
187
        :seealso: Branch._set_tags_bytes.
188
        """
189
        return self._transport.get_bytes('tags')
190
3815.3.4 by Marius Kruger
When doing a `commit --local`, don't try to connect to the master branch.
191
    def _get_nick(self, local=False, possible_transports=None):
3565.6.7 by Marius Kruger
* checkouts now use master nick when no explicit nick is set.
192
        config = self.get_config()
3815.3.4 by Marius Kruger
When doing a `commit --local`, don't try to connect to the master branch.
193
        # explicit overrides master, but don't look for master if local is True
194
        if not local and not config.has_explicit_nickname():
3565.6.10 by Marius Kruger
Silently fall back to local implicit nick if the master is unavailable
195
            try:
196
                master = self.get_master_branch(possible_transports)
197
                if master is not None:
198
                    # return the master branch value
3815.3.3 by Marius Kruger
apply Martin's fix for #293440
199
                    return master.nick
3565.6.10 by Marius Kruger
Silently fall back to local implicit nick if the master is unavailable
200
            except errors.BzrError, e:
201
                # Silently fall back to local implicit nick if the master is
202
                # unavailable
203
                mutter("Could not connect to bound branch, "
204
                    "falling back to local nick.\n " + str(e))
3565.6.7 by Marius Kruger
* checkouts now use master nick when no explicit nick is set.
205
        return config.get_nickname()
1185.35.11 by Aaron Bentley
Added support for branch nicks
206
207
    def _set_nick(self, nick):
1551.15.35 by Aaron Bentley
Warn when setting config values that will be masked (#122286)
208
        self.get_config().set_user_option('nickname', nick, warn_masked=True)
1185.35.11 by Aaron Bentley
Added support for branch nicks
209
210
    nick = property(_get_nick, _set_nick)
1694.2.6 by Martin Pool
[merge] bzr.dev
211
212
    def is_locked(self):
1910.3.2 by Andrew Bennetts
Improve some NotImplementedErrors.
213
        raise NotImplementedError(self.is_locked)
1694.2.6 by Martin Pool
[merge] bzr.dev
214
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
215
    def _lefthand_history(self, revision_id, last_rev=None,
216
                          other_branch=None):
217
        if 'evil' in debug.debug_flags:
218
            mutter_callsite(4, "_lefthand_history scales with history.")
219
        # stop_revision must be a descendant of last_revision
220
        graph = self.repository.get_graph()
221
        if last_rev is not None:
222
            if not graph.is_ancestor(last_rev, revision_id):
223
                # our previous tip is not merged into stop_revision
224
                raise errors.DivergedBranches(self, other_branch)
225
        # make a new revision history from the graph
226
        parents_map = graph.get_parent_map([revision_id])
227
        if revision_id not in parents_map:
228
            raise errors.NoSuchRevision(self, revision_id)
229
        current_rev_id = revision_id
230
        new_history = []
231
        check_not_reserved_id = _mod_revision.check_not_reserved_id
232
        # Do not include ghosts or graph origin in revision_history
233
        while (current_rev_id in parents_map and
234
               len(parents_map[current_rev_id]) > 0):
235
            check_not_reserved_id(current_rev_id)
236
            new_history.append(current_rev_id)
237
            current_rev_id = parents_map[current_rev_id][0]
238
            parents_map = graph.get_parent_map([current_rev_id])
239
        new_history.reverse()
240
        return new_history
241
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
242
    def lock_write(self):
1910.3.2 by Andrew Bennetts
Improve some NotImplementedErrors.
243
        raise NotImplementedError(self.lock_write)
1694.2.6 by Martin Pool
[merge] bzr.dev
244
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
245
    def lock_read(self):
1910.3.2 by Andrew Bennetts
Improve some NotImplementedErrors.
246
        raise NotImplementedError(self.lock_read)
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
247
248
    def unlock(self):
1910.3.2 by Andrew Bennetts
Improve some NotImplementedErrors.
249
        raise NotImplementedError(self.unlock)
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
250
1185.70.3 by Martin Pool
Various updates to make storage branch mergeable:
251
    def peek_lock_mode(self):
252
        """Return lock mode for the Branch: 'r', 'w' or None"""
1185.70.6 by Martin Pool
review fixups from John
253
        raise NotImplementedError(self.peek_lock_mode)
1185.70.3 by Martin Pool
Various updates to make storage branch mergeable:
254
1694.2.6 by Martin Pool
[merge] bzr.dev
255
    def get_physical_lock_status(self):
1910.3.2 by Andrew Bennetts
Improve some NotImplementedErrors.
256
        raise NotImplementedError(self.get_physical_lock_status)
1694.2.6 by Martin Pool
[merge] bzr.dev
257
2418.5.12 by John Arbash Meinel
Move functions from BzrBranch to base Branch object.
258
    @needs_read_lock
3949.2.6 by Ian Clatworthy
review feedback from jam
259
    def dotted_revno_to_revision_id(self, revno, _cache_reverse=False):
3949.2.1 by Ian Clatworthy
Branch.dotted_revno_to_revision_id API
260
        """Return the revision_id for a dotted revno.
261
262
        :param revno: a tuple like (1,) or (1,1,2)
3949.2.4 by Ian Clatworthy
add top level revno cache
263
        :param _cache_reverse: a private parameter enabling storage
264
           of the reverse mapping in a top level cache. (This should
265
           only be done in selective circumstances as we want to
266
           avoid having the mapping cached multiple times.)
3949.2.1 by Ian Clatworthy
Branch.dotted_revno_to_revision_id API
267
        :return: the revision_id
268
        :raises errors.NoSuchRevision: if the revno doesn't exist
269
        """
3949.2.6 by Ian Clatworthy
review feedback from jam
270
        rev_id = self._do_dotted_revno_to_revision_id(revno)
271
        if _cache_reverse:
272
            self._partial_revision_id_to_revno_cache[rev_id] = revno
3949.2.4 by Ian Clatworthy
add top level revno cache
273
        return rev_id
3949.2.1 by Ian Clatworthy
Branch.dotted_revno_to_revision_id API
274
3949.2.6 by Ian Clatworthy
review feedback from jam
275
    def _do_dotted_revno_to_revision_id(self, revno):
3949.2.1 by Ian Clatworthy
Branch.dotted_revno_to_revision_id API
276
        """Worker function for dotted_revno_to_revision_id.
277
278
        Subclasses should override this if they wish to
279
        provide a more efficient implementation.
280
        """
281
        if len(revno) == 1:
282
            return self.get_rev_id(revno[0])
283
        revision_id_to_revno = self.get_revision_id_to_revno_map()
3949.2.6 by Ian Clatworthy
review feedback from jam
284
        revision_ids = [revision_id for revision_id, this_revno
285
                        in revision_id_to_revno.iteritems()
286
                        if revno == this_revno]
287
        if len(revision_ids) == 1:
288
            return revision_ids[0]
3949.2.1 by Ian Clatworthy
Branch.dotted_revno_to_revision_id API
289
        else:
290
            revno_str = '.'.join(map(str, revno))
291
            raise errors.NoSuchRevision(self, revno_str)
292
293
    @needs_read_lock
3949.2.3 by Ian Clatworthy
add Branch.revision_id_to_dotted_revno()
294
    def revision_id_to_dotted_revno(self, revision_id):
295
        """Given a revision id, return its dotted revno.
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
296
3949.2.3 by Ian Clatworthy
add Branch.revision_id_to_dotted_revno()
297
        :return: a tuple like (1,) or (400,1,3).
298
        """
3949.2.6 by Ian Clatworthy
review feedback from jam
299
        return self._do_revision_id_to_dotted_revno(revision_id)
3949.2.3 by Ian Clatworthy
add Branch.revision_id_to_dotted_revno()
300
3949.2.6 by Ian Clatworthy
review feedback from jam
301
    def _do_revision_id_to_dotted_revno(self, revision_id):
3949.2.3 by Ian Clatworthy
add Branch.revision_id_to_dotted_revno()
302
        """Worker function for revision_id_to_revno."""
3949.2.4 by Ian Clatworthy
add top level revno cache
303
        # Try the caches if they are loaded
3949.2.6 by Ian Clatworthy
review feedback from jam
304
        result = self._partial_revision_id_to_revno_cache.get(revision_id)
305
        if result is not None:
306
            return result
307
        if self._revision_id_to_revno_cache:
3949.2.3 by Ian Clatworthy
add Branch.revision_id_to_dotted_revno()
308
            result = self._revision_id_to_revno_cache.get(revision_id)
3949.2.6 by Ian Clatworthy
review feedback from jam
309
            if result is None:
310
                raise errors.NoSuchRevision(self, revision_id)
311
        # Try the mainline as it's optimised
312
        try:
313
            revno = self.revision_id_to_revno(revision_id)
314
            return (revno,)
315
        except errors.NoSuchRevision:
316
            # We need to load and use the full revno map after all
317
            result = self.get_revision_id_to_revno_map().get(revision_id)
318
            if result is None:
319
                raise errors.NoSuchRevision(self, revision_id)
3949.2.3 by Ian Clatworthy
add Branch.revision_id_to_dotted_revno()
320
        return result
321
3949.2.7 by Ian Clatworthy
fix accidental needs_read_lock removal
322
    @needs_read_lock
2418.5.12 by John Arbash Meinel
Move functions from BzrBranch to base Branch object.
323
    def get_revision_id_to_revno_map(self):
324
        """Return the revision_id => dotted revno map.
325
326
        This will be regenerated on demand, but will be cached.
327
328
        :return: A dictionary mapping revision_id => dotted revno.
329
            This dictionary should not be modified by the caller.
330
        """
331
        if self._revision_id_to_revno_cache is not None:
332
            mapping = self._revision_id_to_revno_cache
333
        else:
334
            mapping = self._gen_revno_map()
335
            self._cache_revision_id_to_revno(mapping)
336
        # TODO: jam 20070417 Since this is being cached, should we be returning
337
        #       a copy?
338
        # I would rather not, and instead just declare that users should not
339
        # modify the return value.
340
        return mapping
341
342
    def _gen_revno_map(self):
343
        """Create a new mapping from revision ids to dotted revnos.
344
345
        Dotted revnos are generated based on the current tip in the revision
346
        history.
347
        This is the worker function for get_revision_id_to_revno_map, which
348
        just caches the return value.
349
350
        :return: A dictionary mapping revision_id => dotted revno.
351
        """
3949.3.1 by Ian Clatworthy
introduce Branch.merge_sorted_revisions API
352
        revision_id_to_revno = dict((rev_id, revno)
3949.3.4 by Ian Clatworthy
jam feedback: start & stop limits; simple caching
353
            for rev_id, depth, revno, end_of_merge
354
             in self.iter_merge_sorted_revisions())
3949.3.1 by Ian Clatworthy
introduce Branch.merge_sorted_revisions API
355
        return revision_id_to_revno
356
357
    @needs_read_lock
3949.3.4 by Ian Clatworthy
jam feedback: start & stop limits; simple caching
358
    def iter_merge_sorted_revisions(self, start_revision_id=None,
3960.3.1 by Ian Clatworthy
add stop_rule to Branch.iter_merge_sorted_revisions()
359
            stop_revision_id=None, stop_rule='exclude', direction='reverse'):
3949.3.2 by Ian Clatworthy
feedback from jam
360
        """Walk the revisions for a branch in merge sorted order.
3949.3.1 by Ian Clatworthy
introduce Branch.merge_sorted_revisions API
361
3949.3.8 by Ian Clatworthy
feedback from poolie
362
        Merge sorted order is the output from a merge-aware,
363
        topological sort, i.e. all parents come before their
364
        children going forward; the opposite for reverse.
365
3949.3.4 by Ian Clatworthy
jam feedback: start & stop limits; simple caching
366
        :param start_revision_id: the revision_id to begin walking from.
367
            If None, the branch tip is used.
368
        :param stop_revision_id: the revision_id to terminate the walk
3960.3.1 by Ian Clatworthy
add stop_rule to Branch.iter_merge_sorted_revisions()
369
            after. If None, the rest of history is included.
370
        :param stop_rule: if stop_revision_id is not None, the precise rule
371
            to use for termination:
372
            * 'exclude' - leave the stop revision out of the result (default)
373
            * 'include' - the stop revision is the last item in the result
374
            * 'with-merges' - include the stop revision and all of its
375
              merged revisions in the result
3949.3.3 by Ian Clatworthy
simplify the meaning of forward to be appropriate to this layer
376
        :param direction: either 'reverse' or 'forward':
3949.3.4 by Ian Clatworthy
jam feedback: start & stop limits; simple caching
377
            * reverse means return the start_revision_id first, i.e.
378
              start at the most recent revision and go backwards in history
3949.3.3 by Ian Clatworthy
simplify the meaning of forward to be appropriate to this layer
379
            * forward returns tuples in the opposite order to reverse.
380
              Note in particular that forward does *not* do any intelligent
381
              ordering w.r.t. depth as some clients of this API may like.
3949.3.8 by Ian Clatworthy
feedback from poolie
382
              (If required, that ought to be done at higher layers.)
383
384
        :return: an iterator over (revision_id, depth, revno, end_of_merge)
385
            tuples where:
386
387
            * revision_id: the unique id of the revision
388
            * depth: How many levels of merging deep this node has been
389
              found.
390
            * revno_sequence: This field provides a sequence of
391
              revision numbers for all revisions. The format is:
392
              (REVNO, BRANCHNUM, BRANCHREVNO). BRANCHNUM is the number of the
393
              branch that the revno is on. From left to right the REVNO numbers
394
              are the sequence numbers within that branch of the revision.
395
            * end_of_merge: When True the next node (earlier in history) is
396
              part of a different merge.
3949.3.1 by Ian Clatworthy
introduce Branch.merge_sorted_revisions API
397
        """
3949.3.4 by Ian Clatworthy
jam feedback: start & stop limits; simple caching
398
        # Note: depth and revno values are in the context of the branch so
399
        # we need the full graph to get stable numbers, regardless of the
400
        # start_revision_id.
401
        if self._merge_sorted_revisions_cache is None:
402
            last_revision = self.last_revision()
3949.3.6 by Ian Clatworthy
feedback from beuno
403
            graph = self.repository.get_graph()
404
            parent_map = dict(((key, value) for key, value in
405
                     graph.iter_ancestry([last_revision]) if value is not None))
406
            revision_graph = repository._strip_NULL_ghosts(parent_map)
3949.3.7 by Ian Clatworthy
drop seqnum from in-memory cache
407
            revs = tsort.merge_sort(revision_graph, last_revision, None,
408
                generate_revno=True)
409
            # Drop the sequence # before caching
410
            self._merge_sorted_revisions_cache = [r[1:] for r in revs]
3949.3.6 by Ian Clatworthy
feedback from beuno
411
3949.3.4 by Ian Clatworthy
jam feedback: start & stop limits; simple caching
412
        filtered = self._filter_merge_sorted_revisions(
413
            self._merge_sorted_revisions_cache, start_revision_id,
3960.3.1 by Ian Clatworthy
add stop_rule to Branch.iter_merge_sorted_revisions()
414
            stop_revision_id, stop_rule)
3949.3.2 by Ian Clatworthy
feedback from jam
415
        if direction == 'reverse':
3949.3.4 by Ian Clatworthy
jam feedback: start & stop limits; simple caching
416
            return filtered
3949.3.2 by Ian Clatworthy
feedback from jam
417
        if direction == 'forward':
3949.3.4 by Ian Clatworthy
jam feedback: start & stop limits; simple caching
418
            return reversed(list(filtered))
3949.3.2 by Ian Clatworthy
feedback from jam
419
        else:
420
            raise ValueError('invalid direction %r' % direction)
2418.5.12 by John Arbash Meinel
Move functions from BzrBranch to base Branch object.
421
3949.3.4 by Ian Clatworthy
jam feedback: start & stop limits; simple caching
422
    def _filter_merge_sorted_revisions(self, merge_sorted_revisions,
3960.3.1 by Ian Clatworthy
add stop_rule to Branch.iter_merge_sorted_revisions()
423
        start_revision_id, stop_revision_id, stop_rule):
3949.3.7 by Ian Clatworthy
drop seqnum from in-memory cache
424
        """Iterate over an inclusive range of sorted revisions."""
3949.3.4 by Ian Clatworthy
jam feedback: start & stop limits; simple caching
425
        rev_iter = iter(merge_sorted_revisions)
426
        if start_revision_id is not None:
3949.3.7 by Ian Clatworthy
drop seqnum from in-memory cache
427
            for rev_id, depth, revno, end_of_merge in rev_iter:
3949.3.4 by Ian Clatworthy
jam feedback: start & stop limits; simple caching
428
                if rev_id != start_revision_id:
429
                    continue
430
                else:
3936.3.30 by Ian Clatworthy
use iter_merge_sorted_revisions() with stop_range feature
431
                    # The decision to include the start or not
432
                    # depends on the stop_rule if a stop is provided
433
                    rev_iter = chain(
434
                        iter([(rev_id, depth, revno, end_of_merge)]),
435
                        rev_iter)
3949.3.4 by Ian Clatworthy
jam feedback: start & stop limits; simple caching
436
                    break
3960.3.1 by Ian Clatworthy
add stop_rule to Branch.iter_merge_sorted_revisions()
437
        if stop_revision_id is None:
438
            for rev_id, depth, revno, end_of_merge in rev_iter:
439
                yield rev_id, depth, revno, end_of_merge
440
        elif stop_rule == 'exclude':
441
            for rev_id, depth, revno, end_of_merge in rev_iter:
442
                if rev_id == stop_revision_id:
443
                    return
444
                yield rev_id, depth, revno, end_of_merge
445
        elif stop_rule == 'include':
446
            for rev_id, depth, revno, end_of_merge in rev_iter:
447
                yield rev_id, depth, revno, end_of_merge
448
                if rev_id == stop_revision_id:
449
                    return
450
        elif stop_rule == 'with-merges':
3960.3.4 by Ian Clatworthy
implement with-merges by checking for left-hand parent, not depth
451
            stop_rev = self.repository.get_revision(stop_revision_id)
452
            if stop_rev.parent_ids:
453
                left_parent = stop_rev.parent_ids[0]
454
            else:
455
                left_parent = _mod_revision.NULL_REVISION
3960.3.1 by Ian Clatworthy
add stop_rule to Branch.iter_merge_sorted_revisions()
456
            for rev_id, depth, revno, end_of_merge in rev_iter:
3960.3.4 by Ian Clatworthy
implement with-merges by checking for left-hand parent, not depth
457
                if rev_id == left_parent:
3960.3.1 by Ian Clatworthy
add stop_rule to Branch.iter_merge_sorted_revisions()
458
                    return
459
                yield rev_id, depth, revno, end_of_merge
460
        else:
461
            raise ValueError('invalid stop_rule %r' % stop_rule)
3949.3.4 by Ian Clatworthy
jam feedback: start & stop limits; simple caching
462
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
463
    def leave_lock_in_place(self):
464
        """Tell this branch object not to release the physical lock when this
465
        object is unlocked.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
466
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
467
        If lock_write doesn't return a token, then this method is not supported.
468
        """
469
        self.control_files.leave_in_place()
470
471
    def dont_leave_lock_in_place(self):
472
        """Tell this branch object to release the physical lock when this
473
        object is unlocked, even if it didn't originally acquire it.
474
475
        If lock_write doesn't return a token, then this method is not supported.
476
        """
477
        self.control_files.dont_leave_in_place()
478
1587.1.6 by Robert Collins
Update bound branch implementation to 0.8.
479
    def bind(self, other):
480
        """Bind the local branch the other branch.
481
482
        :param other: The branch to bind to
483
        :type other: Branch
484
        """
485
        raise errors.UpgradeRequired(self.base)
486
1534.1.31 by Robert Collins
Deprecated fetch.fetch and fetch.greedy_fetch for branch.fetch, and move the Repository.fetch internals to InterRepo and InterWeaveRepo.
487
    @needs_write_lock
488
    def fetch(self, from_branch, last_revision=None, pb=None):
489
        """Copy revisions from from_branch into this branch.
490
491
        :param from_branch: Where to copy from.
492
        :param last_revision: What revision to stop at (None for at the end
493
                              of the branch.
494
        :param pb: An optional progress bar to use.
4065.1.1 by Robert Collins
Change the return value of fetch() to None.
495
        :return: None
1534.1.31 by Robert Collins
Deprecated fetch.fetch and fetch.greedy_fetch for branch.fetch, and move the Repository.fetch internals to InterRepo and InterWeaveRepo.
496
        """
497
        if self.base == from_branch.base:
1558.4.11 by Aaron Bentley
Allow merge against self, make fetching self a noop
498
            return (0, [])
4110.2.5 by Martin Pool
Deprecate passing pbs in to fetch()
499
        if pb is not None:
500
            symbol_versioning.warn(
501
                symbol_versioning.deprecated_in((1, 14, 0))
502
                % "pb parameter to fetch()")
1534.1.31 by Robert Collins
Deprecated fetch.fetch and fetch.greedy_fetch for branch.fetch, and move the Repository.fetch internals to InterRepo and InterWeaveRepo.
503
        from_branch.lock_read()
504
        try:
505
            if last_revision is None:
2230.3.9 by Aaron Bentley
Fix most fetch tests
506
                last_revision = from_branch.last_revision()
3240.1.7 by Aaron Bentley
Update from review comments
507
                last_revision = _mod_revision.ensure_null(last_revision)
1534.1.31 by Robert Collins
Deprecated fetch.fetch and fetch.greedy_fetch for branch.fetch, and move the Repository.fetch internals to InterRepo and InterWeaveRepo.
508
            return self.repository.fetch(from_branch.repository,
509
                                         revision_id=last_revision,
4110.2.5 by Martin Pool
Deprecate passing pbs in to fetch()
510
                                         pb=pb)
1534.1.31 by Robert Collins
Deprecated fetch.fetch and fetch.greedy_fetch for branch.fetch, and move the Repository.fetch internals to InterRepo and InterWeaveRepo.
511
        finally:
512
            from_branch.unlock()
513
1587.1.6 by Robert Collins
Update bound branch implementation to 0.8.
514
    def get_bound_location(self):
1558.7.6 by Aaron Bentley
Fixed typo (Olaf Conradi)
515
        """Return the URL of the branch we are bound to.
1587.1.6 by Robert Collins
Update bound branch implementation to 0.8.
516
517
        Older format branches cannot bind, please be sure to use a metadir
518
        branch.
519
        """
520
        return None
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
521
2230.3.31 by Aaron Bentley
Implement re-binding previously-bound branches
522
    def get_old_bound_location(self):
523
        """Return the URL of the branch we used to be bound to
524
        """
525
        raise errors.UpgradeRequired(self.base)
526
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
527
    def get_commit_builder(self, parents, config=None, timestamp=None,
528
                           timezone=None, committer=None, revprops=None,
1740.3.7 by Jelmer Vernooij
Move committer, log, revprops, timestamp and timezone to CommitBuilder.
529
                           revision_id=None):
530
        """Obtain a CommitBuilder for this branch.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
531
1740.3.7 by Jelmer Vernooij
Move committer, log, revprops, timestamp and timezone to CommitBuilder.
532
        :param parents: Revision ids of the parents of the new revision.
533
        :param config: Optional configuration to use.
534
        :param timestamp: Optional timestamp recorded for commit.
535
        :param timezone: Optional timezone for timestamp.
536
        :param committer: Optional committer to set for commit.
537
        :param revprops: Optional dictionary of revision properties.
538
        :param revision_id: Optional revision id.
539
        """
540
541
        if config is None:
1770.2.9 by Aaron Bentley
Add Branch.get_config, update BranchConfig() callers
542
            config = self.get_config()
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
543
2246.1.3 by Robert Collins
New branch hooks: post_push, post_pull, post_commit, post_uncommit. These
544
        return self.repository.get_commit_builder(self, parents, config,
1740.3.7 by Jelmer Vernooij
Move committer, log, revprops, timestamp and timezone to CommitBuilder.
545
            timestamp, timezone, committer, revprops, revision_id)
1587.1.6 by Robert Collins
Update bound branch implementation to 0.8.
546
2810.2.1 by Martin Pool
merge vincent and cleanup
547
    def get_master_branch(self, possible_transports=None):
1587.1.6 by Robert Collins
Update bound branch implementation to 0.8.
548
        """Return the branch we are bound to.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
549
1587.1.6 by Robert Collins
Update bound branch implementation to 0.8.
550
        :return: Either a Branch, or None
551
        """
552
        return None
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
553
1770.3.2 by Jelmer Vernooij
Move BzrBranch.get_revision_delta() to Branch.get_revision_delta() as it is generic.
554
    def get_revision_delta(self, revno):
555
        """Return the delta for one revision.
556
557
        The delta is relative to its mainline predecessor, or the
558
        empty tree for revision 1.
559
        """
560
        rh = self.revision_history()
561
        if not (1 <= revno <= len(rh)):
3236.1.2 by Michael Hudson
clean up branch.py imports
562
            raise errors.InvalidRevisionNumber(revno)
1770.3.2 by Jelmer Vernooij
Move BzrBranch.get_revision_delta() to Branch.get_revision_delta() as it is generic.
563
        return self.repository.get_revision_delta(rh[revno-1])
564
3537.3.1 by Martin Pool
Rename branch.get_stacked_on to get_stacked_on_url
565
    def get_stacked_on_url(self):
3221.11.2 by Robert Collins
Create basic stackable branch facility.
566
        """Get the URL this branch is stacked against.
567
568
        :raises NotStacked: If the branch is not stacked.
569
        :raises UnstackableBranchFormat: If the branch does not support
570
            stacking.
571
        """
3537.3.1 by Martin Pool
Rename branch.get_stacked_on to get_stacked_on_url
572
        raise NotImplementedError(self.get_stacked_on_url)
3221.11.2 by Robert Collins
Create basic stackable branch facility.
573
1185.50.9 by John Arbash Meinel
[bug 3632] Matthieu Moy- bzr cat should default to last revision
574
    def print_file(self, file, revision_id):
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
575
        """Print `file` to stdout."""
1910.3.2 by Andrew Bennetts
Improve some NotImplementedErrors.
576
        raise NotImplementedError(self.print_file)
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
577
578
    def set_revision_history(self, rev_history):
1910.3.2 by Andrew Bennetts
Improve some NotImplementedErrors.
579
        raise NotImplementedError(self.set_revision_history)
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
580
3537.3.3 by Martin Pool
Rename Branch.set_stacked_on to set_stacked_on_url
581
    def set_stacked_on_url(self, url):
3221.18.1 by Ian Clatworthy
tweaks by ianc during review
582
        """Set the URL this branch is stacked against.
3221.11.2 by Robert Collins
Create basic stackable branch facility.
583
584
        :raises UnstackableBranchFormat: If the branch does not support
585
            stacking.
586
        :raises UnstackableRepositoryFormat: If the repository does not support
587
            stacking.
588
        """
4226.1.3 by Robert Collins
Lift Branch.set_stacked_on_url up from BzrBranch7.
589
        if not self._format.supports_stacking():
590
            raise errors.UnstackableBranchFormat(self._format, self.base)
591
        self._check_stackable_repo()
592
        if not url:
593
            try:
594
                old_url = self.get_stacked_on_url()
595
            except (errors.NotStacked, errors.UnstackableBranchFormat,
596
                errors.UnstackableRepositoryFormat):
597
                return
598
            url = ''
599
            # repositories don't offer an interface to remove fallback
600
            # repositories today; take the conceptually simpler option and just
601
            # reopen it.
602
            self.repository = self.bzrdir.find_repository()
603
            # for every revision reference the branch has, ensure it is pulled
604
            # in.
605
            source_repository = self._get_fallback_repository(old_url)
606
            for revision_id in chain([self.last_revision()],
607
                self.tags.get_reverse_tag_dict()):
608
                self.repository.fetch(source_repository, revision_id,
609
                    find_ghosts=True)
610
        else:
611
            self._activate_fallback_location(url)
612
        # write this out after the repository is stacked to avoid setting a
613
        # stacked config that doesn't work.
614
        self._set_config_location('stacked_on_location', url)
615
3221.11.2 by Robert Collins
Create basic stackable branch facility.
616
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
617
    def _set_tags_bytes(self, bytes):
618
        """Mirror method for _get_tags_bytes.
619
620
        :seealso: Branch._get_tags_bytes.
621
        """
4084.2.2 by Robert Collins
Review feedback.
622
        return _run_with_write_locked_target(self, self._transport.put_bytes,
623
            'tags', bytes)
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
624
2375.1.3 by Andrew Bennetts
Don't use Branch.get_transaction to cache revision history.
625
    def _cache_revision_history(self, rev_history):
626
        """Set the cached revision history to rev_history.
627
628
        The revision_history method will use this cache to avoid regenerating
629
        the revision history.
630
631
        This API is semi-public; it only for use by subclasses, all other code
632
        should consider it to be private.
633
        """
634
        self._revision_history_cache = rev_history
635
2418.5.6 by John Arbash Meinel
Cache the revision_id => revno map as appropriate.
636
    def _cache_revision_id_to_revno(self, revision_id_to_revno):
637
        """Set the cached revision_id => revno map to revision_id_to_revno.
638
639
        This API is semi-public; it only for use by subclasses, all other code
640
        should consider it to be private.
641
        """
642
        self._revision_id_to_revno_cache = revision_id_to_revno
643
2375.1.6 by Andrew Bennetts
Rename _clear_cached_data to _clear_cached_state.
644
    def _clear_cached_state(self):
2375.1.5 by Andrew Bennetts
Deal with review comments from Robert:
645
        """Clear any cached data on this branch, e.g. cached revision history.
2375.1.3 by Andrew Bennetts
Don't use Branch.get_transaction to cache revision history.
646
647
        This means the next call to revision_history will need to call
648
        _gen_revision_history.
649
650
        This API is semi-public; it only for use by subclasses, all other code
651
        should consider it to be private.
652
        """
653
        self._revision_history_cache = None
2418.5.6 by John Arbash Meinel
Cache the revision_id => revno map as appropriate.
654
        self._revision_id_to_revno_cache = None
3441.5.27 by Andrew Bennetts
Tweaks suggested by John's review: rename _check_if_descendant_or_diverged, move caching last_revision_info into base Branch, better use of lock decorators.
655
        self._last_revision_info_cache = None
3949.3.4 by Ian Clatworthy
jam feedback: start & stop limits; simple caching
656
        self._merge_sorted_revisions_cache = None
2375.1.3 by Andrew Bennetts
Don't use Branch.get_transaction to cache revision history.
657
658
    def _gen_revision_history(self):
659
        """Return sequence of revision hashes on to this branch.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
660
2375.1.3 by Andrew Bennetts
Don't use Branch.get_transaction to cache revision history.
661
        Unlike revision_history, this method always regenerates or rereads the
662
        revision history, i.e. it does not cache the result, so repeated calls
663
        may be expensive.
664
2375.1.5 by Andrew Bennetts
Deal with review comments from Robert:
665
        Concrete subclasses should override this instead of revision_history so
666
        that subclasses do not need to deal with caching logic.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
667
2375.1.3 by Andrew Bennetts
Don't use Branch.get_transaction to cache revision history.
668
        This API is semi-public; it only for use by subclasses, all other code
669
        should consider it to be private.
670
        """
671
        raise NotImplementedError(self._gen_revision_history)
672
673
    @needs_read_lock
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
674
    def revision_history(self):
2592.3.113 by Robert Collins
Various -Devil checks in branch.py.
675
        """Return sequence of revision ids on this branch.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
676
2375.1.3 by Andrew Bennetts
Don't use Branch.get_transaction to cache revision history.
677
        This method will cache the revision history for as long as it is safe to
678
        do so.
679
        """
2592.3.113 by Robert Collins
Various -Devil checks in branch.py.
680
        if 'evil' in debug.debug_flags:
681
            mutter_callsite(3, "revision_history scales with history.")
2375.1.3 by Andrew Bennetts
Don't use Branch.get_transaction to cache revision history.
682
        if self._revision_history_cache is not None:
2375.1.5 by Andrew Bennetts
Deal with review comments from Robert:
683
            history = self._revision_history_cache
684
        else:
685
            history = self._gen_revision_history()
686
            self._cache_revision_history(history)
2375.1.3 by Andrew Bennetts
Don't use Branch.get_transaction to cache revision history.
687
        return list(history)
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
688
689
    def revno(self):
690
        """Return current revision number for this branch.
691
692
        That is equivalent to the number of revisions committed to
693
        this branch.
694
        """
3066.1.1 by John Arbash Meinel
Make the default Branch.revno() implementation just be a thunk to last_revision_info.
695
        return self.last_revision_info()[0]
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
696
1587.1.6 by Robert Collins
Update bound branch implementation to 0.8.
697
    def unbind(self):
698
        """Older format branches cannot bind or unbind."""
699
        raise errors.UpgradeRequired(self.base)
700
2230.3.40 by Aaron Bentley
Rename strict_revision_history to append_revisions_only
701
    def set_append_revisions_only(self, enabled):
702
        """Older format branches are never restricted to append-only"""
2230.3.32 by Aaron Bentley
Implement strict history policy
703
        raise errors.UpgradeRequired(self.base)
704
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
705
    def last_revision(self):
3211.2.1 by Robert Collins
* Creating a new branch no longer tries to read the entire revision-history
706
        """Return last revision id, or NULL_REVISION."""
707
        return self.last_revision_info()[1]
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
708
3441.5.27 by Andrew Bennetts
Tweaks suggested by John's review: rename _check_if_descendant_or_diverged, move caching last_revision_info into base Branch, better use of lock decorators.
709
    @needs_read_lock
2249.4.1 by Wouter van Heyst
New Branch.last_revision_info method, this is being done to allow
710
    def last_revision_info(self):
711
        """Return information about the last revision.
712
3441.5.27 by Andrew Bennetts
Tweaks suggested by John's review: rename _check_if_descendant_or_diverged, move caching last_revision_info into base Branch, better use of lock decorators.
713
        :return: A tuple (revno, revision_id).
2249.4.1 by Wouter van Heyst
New Branch.last_revision_info method, this is being done to allow
714
        """
3441.5.27 by Andrew Bennetts
Tweaks suggested by John's review: rename _check_if_descendant_or_diverged, move caching last_revision_info into base Branch, better use of lock decorators.
715
        if self._last_revision_info_cache is None:
716
            self._last_revision_info_cache = self._last_revision_info()
717
        return self._last_revision_info_cache
718
719
    def _last_revision_info(self):
2249.4.1 by Wouter van Heyst
New Branch.last_revision_info method, this is being done to allow
720
        rh = self.revision_history()
721
        revno = len(rh)
722
        if revno:
723
            return (revno, rh[-1])
724
        else:
725
            return (0, _mod_revision.NULL_REVISION)
726
3445.2.1 by John Arbash Meinel
Add tests for Branch.missing_revisions and deprecate it.
727
    @deprecated_method(deprecated_in((1, 6, 0)))
1505.1.21 by John Arbash Meinel
Removing changes for bound branch by invading set-revision-history.
728
    def missing_revisions(self, other, stop_revision=None):
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
729
        """Return a list of new revisions that would perfectly fit.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
730
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
731
        If self and other have not diverged, return a list of the revisions
732
        present in other, but missing from self.
733
        """
734
        self_history = self.revision_history()
735
        self_len = len(self_history)
1505.1.21 by John Arbash Meinel
Removing changes for bound branch by invading set-revision-history.
736
        other_history = other.revision_history()
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
737
        other_len = len(other_history)
738
        common_index = min(self_len, other_len) -1
739
        if common_index >= 0 and \
740
            self_history[common_index] != other_history[common_index]:
3236.1.2 by Michael Hudson
clean up branch.py imports
741
            raise errors.DivergedBranches(self, other)
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
742
743
        if stop_revision is None:
744
            stop_revision = other_len
745
        else:
746
            if stop_revision > other_len:
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
747
                raise errors.NoSuchRevision(self, stop_revision)
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
748
        return other_history[self_len:stop_revision]
1185.66.1 by Aaron Bentley
Merged from mainline
749
3465.1.1 by Jelmer Vernooij
Move implementation of update_revisions() from BzrBranch to Branch as it only uses publib functions.
750
    @needs_write_lock
3445.1.8 by John Arbash Meinel
Clarity tweaks recommended by Ian
751
    def update_revisions(self, other, stop_revision=None, overwrite=False,
752
                         graph=None):
1505.1.16 by John Arbash Meinel
[merge] robertc's integration, updated tests to check for retcode=3
753
        """Pull in new perfect-fit revisions.
754
755
        :param other: Another Branch to pull from
756
        :param stop_revision: Updated until the given revision
3445.1.8 by John Arbash Meinel
Clarity tweaks recommended by Ian
757
        :param overwrite: Always set the branch pointer, rather than checking
758
            to see if it is a proper descendant.
759
        :param graph: A Graph object that can be used to query history
760
            information. This can be None.
1505.1.16 by John Arbash Meinel
[merge] robertc's integration, updated tests to check for retcode=3
761
        :return: None
762
        """
4000.5.1 by Jelmer Vernooij
Add InterBranch.
763
        return InterBranch.get(other, self).update_revisions(stop_revision,
764
            overwrite, graph)
3465.1.1 by Jelmer Vernooij
Move implementation of update_revisions() from BzrBranch to Branch as it only uses publib functions.
765
4048.2.2 by Jelmer Vernooij
New Branch.import_last_Revision_info() function used to pull revisions into the master branch during commit.
766
    def import_last_revision_info(self, source_repo, revno, revid):
767
        """Set the last revision info, importing from another repo if necessary.
768
4048.2.4 by Jelmer Vernooij
Fix whitespace.
769
        This is used by the bound branch code to upload a revision to
4048.2.2 by Jelmer Vernooij
New Branch.import_last_Revision_info() function used to pull revisions into the master branch during commit.
770
        the master branch first before updating the tip of the local branch.
771
772
        :param source_repo: Source repository to optionally fetch from
773
        :param revno: Revision number of the new tip
774
        :param revid: Revision id of the new tip
775
        """
776
        if not self.repository.has_same_location(source_repo):
777
            self.repository.fetch(source_repo, revision_id=revid)
778
        self.set_last_revision_info(revno, revid)
779
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
780
    def revision_id_to_revno(self, revision_id):
781
        """Given a revision id, return its revno"""
2598.5.1 by Aaron Bentley
Start eliminating the use of None to indicate null revision
782
        if _mod_revision.is_null(revision_id):
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
783
            return 0
784
        history = self.revision_history()
785
        try:
786
            return history.index(revision_id) + 1
787
        except ValueError:
2418.5.5 by John Arbash Meinel
Add some tests and an api for revision_id_to_dotted_revno
788
            raise errors.NoSuchRevision(self, revision_id)
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
789
790
    def get_rev_id(self, revno, history=None):
791
        """Find the revision id of the specified revno."""
792
        if revno == 0:
2598.5.10 by Aaron Bentley
Return NULL_REVISION instead of None for the null revision
793
            return _mod_revision.NULL_REVISION
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
794
        if history is None:
795
            history = self.revision_history()
1948.4.1 by John Arbash Meinel
Update number parsers to raise InvalidRevisionSpec. Update revno: itself so it supports negative numbers
796
        if revno <= 0 or revno > len(history):
2418.5.5 by John Arbash Meinel
Add some tests and an api for revision_id_to_dotted_revno
797
            raise errors.NoSuchRevision(self, revno)
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
798
        return history[revno - 1]
799
2817.4.3 by Vincent Ladeuil
Add tests for commit, reuse master branch transport.
800
    def pull(self, source, overwrite=False, stop_revision=None,
3489.2.4 by Andrew Bennetts
Fix all tests broken by fixing make_branch_and_tree.
801
             possible_transports=None, _override_hook_target=None):
2245.2.1 by Robert Collins
Split branch pushing out of branch pulling.
802
        """Mirror source into this branch.
803
804
        This branch is considered to be 'local', having low latency.
2297.1.1 by Martin Pool
Pull now returns a PullResult rather than just an integer.
805
806
        :returns: PullResult instance
2245.2.1 by Robert Collins
Split branch pushing out of branch pulling.
807
        """
1910.3.2 by Andrew Bennetts
Improve some NotImplementedErrors.
808
        raise NotImplementedError(self.pull)
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
809
2245.2.1 by Robert Collins
Split branch pushing out of branch pulling.
810
    def push(self, target, overwrite=False, stop_revision=None):
811
        """Mirror this branch into target.
812
813
        This branch is considered to be 'local', having low latency.
814
        """
815
        raise NotImplementedError(self.push)
816
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
817
    def basis_tree(self):
1852.5.1 by Robert Collins
Deprecate EmptyTree in favour of using Repository.revision_tree.
818
        """Return `Tree` object for last revision."""
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
819
        return self.repository.revision_tree(self.last_revision())
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
820
821
    def get_parent(self):
822
        """Return the parent location of the branch.
823
4031.1.1 by Alexander Belchenko
Parent location is not used as default for push.
824
        This is the default location for pull/missing.  The usual
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
825
        pattern is that the user can override it by specifying a
826
        location.
827
        """
4078.2.1 by Robert Collins
Add a Branch.get_parent remote call for RemoteBranch.
828
        parent = self._get_parent_location()
829
        if parent is None:
830
            return parent
831
        # This is an old-format absolute path to a local branch
832
        # turn it into a url
833
        if parent.startswith('/'):
834
            parent = urlutils.local_path_to_url(parent.decode('utf8'))
835
        try:
836
            return urlutils.join(self.base[:-1], parent)
837
        except errors.InvalidURLJoin, e:
838
            raise errors.InaccessibleParent(parent, self.base)
839
840
    def _get_parent_location(self):
841
        raise NotImplementedError(self._get_parent_location)
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
842
1551.12.44 by Aaron Bentley
Add (set|get)_public_branch
843
    def _set_config_location(self, name, url, config=None,
844
                             make_relative=False):
845
        if config is None:
846
            config = self.get_config()
847
        if url is None:
848
            url = ''
849
        elif make_relative:
850
            url = urlutils.relative_url(self.base, url)
1551.15.35 by Aaron Bentley
Warn when setting config values that will be masked (#122286)
851
        config.set_user_option(name, url, warn_masked=True)
1551.12.44 by Aaron Bentley
Add (set|get)_public_branch
852
853
    def _get_config_location(self, name, config=None):
854
        if config is None:
855
            config = self.get_config()
856
        location = config.get_user_option(name)
857
        if location == '':
858
            location = None
859
        return location
860
1804.1.1 by Aaron Bentley
Add support for submit location to bundles
861
    def get_submit_branch(self):
862
        """Return the submit location of the branch.
863
864
        This is the default location for bundle.  The usual
865
        pattern is that the user can override it by specifying a
866
        location.
867
        """
868
        return self.get_config().get_user_option('submit_branch')
869
870
    def set_submit_branch(self, location):
871
        """Return the submit location of the branch.
872
873
        This is the default location for bundle.  The usual
874
        pattern is that the user can override it by specifying a
875
        location.
876
        """
1551.15.35 by Aaron Bentley
Warn when setting config values that will be masked (#122286)
877
        self.get_config().set_user_option('submit_branch', location,
878
            warn_masked=True)
1804.1.1 by Aaron Bentley
Add support for submit location to bundles
879
1551.12.44 by Aaron Bentley
Add (set|get)_public_branch
880
    def get_public_branch(self):
881
        """Return the public location of the branch.
882
883
        This is is used by merge directives.
884
        """
885
        return self._get_config_location('public_branch')
886
887
    def set_public_branch(self, location):
888
        """Return the submit location of the branch.
889
890
        This is the default location for bundle.  The usual
891
        pattern is that the user can override it by specifying a
892
        location.
893
        """
894
        self._set_config_location('public_branch', location)
895
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
896
    def get_push_location(self):
897
        """Return the None or the location to push this branch to."""
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
898
        push_loc = self.get_config().get_user_option('push_location')
899
        return push_loc
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
900
901
    def set_push_location(self, location):
902
        """Set a new push location for this branch."""
1910.3.2 by Andrew Bennetts
Improve some NotImplementedErrors.
903
        raise NotImplementedError(self.set_push_location)
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
904
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
905
    def _run_post_change_branch_tip_hooks(self, old_revno, old_revid):
906
        """Run the post_change_branch_tip hooks."""
907
        hooks = Branch.hooks['post_change_branch_tip']
908
        if not hooks:
909
            return
910
        new_revno, new_revid = self.last_revision_info()
911
        params = ChangeBranchTipParams(
912
            self, old_revno, new_revno, old_revid, new_revid)
913
        for hook in hooks:
914
            hook(params)
915
916
    def _run_pre_change_branch_tip_hooks(self, new_revno, new_revid):
917
        """Run the pre_change_branch_tip hooks."""
918
        hooks = Branch.hooks['pre_change_branch_tip']
919
        if not hooks:
920
            return
921
        old_revno, old_revid = self.last_revision_info()
922
        params = ChangeBranchTipParams(
923
            self, old_revno, new_revno, old_revid, new_revid)
924
        for hook in hooks:
925
            try:
926
                hook(params)
927
            except errors.TipChangeRejected:
928
                raise
929
            except Exception:
930
                exc_info = sys.exc_info()
931
                hook_name = Branch.hooks.get_hook_name(hook)
932
                raise errors.HookFailed(
933
                    'pre_change_branch_tip', hook_name, exc_info)
934
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
935
    def set_parent(self, url):
1910.3.2 by Andrew Bennetts
Improve some NotImplementedErrors.
936
        raise NotImplementedError(self.set_parent)
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
937
1587.1.10 by Robert Collins
update updates working tree and branch together.
938
    @needs_write_lock
939
    def update(self):
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
940
        """Synchronise this branch with the master branch if any.
1587.1.10 by Robert Collins
update updates working tree and branch together.
941
942
        :return: None or the last_revision pivoted out during the update.
943
        """
944
        return None
945
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
946
    def check_revno(self, revno):
947
        """\
948
        Check whether a revno corresponds to any revision.
949
        Zero (the NULL revision) is considered valid.
950
        """
951
        if revno != 0:
952
            self.check_real_revno(revno)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
953
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
954
    def check_real_revno(self, revno):
955
        """\
956
        Check whether a revno corresponds to a real revision.
957
        Zero (the NULL revision) is considered invalid
958
        """
959
        if revno < 1 or revno > self.revno():
3236.1.2 by Michael Hudson
clean up branch.py imports
960
            raise errors.InvalidRevisionNumber(revno)
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
961
962
    @needs_read_lock
4050.1.1 by Robert Collins
Fix race condition with branch hooks during cloning when the new branch is stacked.
963
    def clone(self, to_bzrdir, revision_id=None, repository_policy=None):
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
964
        """Clone this branch into to_bzrdir preserving all semantic values.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
965
4044.1.1 by Robert Collins
Create Branch.create_clone_on_transport helper method to combine bzr and branch creation for push.
966
        Most API users will want 'create_clone_on_transport', which creates a
967
        new bzrdir and branch on the fly.
968
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
969
        revision_id: if not None, the revision history in the new branch will
970
                     be truncated to end with revision_id.
971
        """
3650.5.1 by Aaron Bentley
Fix push to use clone all the time.
972
        result = to_bzrdir.create_branch()
4050.1.1 by Robert Collins
Fix race condition with branch hooks during cloning when the new branch is stacked.
973
        if repository_policy is not None:
974
            repository_policy.configure_branch(result)
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
975
        self.copy_content_into(result, revision_id=revision_id)
976
        return  result
977
978
    @needs_read_lock
4070.3.1 by Robert Collins
Alter branch sprouting with an alternate fix for stacked branches that does not require multiple copy_content_into and set_parent calls, reducing IO and round trips.
979
    def sprout(self, to_bzrdir, revision_id=None, repository_policy=None):
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
980
        """Create a new line of development from the branch, into to_bzrdir.
3650.2.1 by Aaron Bentley
Fix sprout to honour cloning format
981
982
        to_bzrdir controls the branch format.
983
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
984
        revision_id: if not None, the revision history in the new branch will
985
                     be truncated to end with revision_id.
986
        """
3650.2.1 by Aaron Bentley
Fix sprout to honour cloning format
987
        result = to_bzrdir.create_branch()
4070.3.1 by Robert Collins
Alter branch sprouting with an alternate fix for stacked branches that does not require multiple copy_content_into and set_parent calls, reducing IO and round trips.
988
        if repository_policy is not None:
989
            repository_policy.configure_branch(result)
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
990
        self.copy_content_into(result, revision_id=revision_id)
991
        result.set_parent(self.bzrdir.root_transport.base)
992
        return result
993
2230.3.18 by Aaron Bentley
Handle history sync as a special operation
994
    def _synchronize_history(self, destination, revision_id):
2230.3.35 by Aaron Bentley
Add documentation for synchonize_history
995
        """Synchronize last revision and revision history between branches.
996
997
        This version is most efficient when the destination is also a
3834.3.1 by Andrew Bennetts
Get rid of revision_history() call during copy_content_into.
998
        BzrBranch6, but works for BzrBranch5, as long as the destination's
999
        repository contains all the lefthand ancestors of the intended
1000
        last_revision.  If not, set_last_revision_info will fail.
2230.3.35 by Aaron Bentley
Add documentation for synchonize_history
1001
1002
        :param destination: The branch to copy the history into
1003
        :param revision_id: The revision-id to truncate history at.  May
1004
          be None to copy complete history.
1005
        """
3834.3.1 by Andrew Bennetts
Get rid of revision_history() call during copy_content_into.
1006
        source_revno, source_revision_id = self.last_revision_info()
1007
        if revision_id is None:
1008
            revno, revision_id = source_revno, source_revision_id
1009
        elif source_revision_id == revision_id:
1010
            # we know the revno without needing to walk all of history
1011
            revno = source_revno
3650.3.3 by Aaron Bentley
fix sprout
1012
        else:
3834.3.1 by Andrew Bennetts
Get rid of revision_history() call during copy_content_into.
1013
            # To figure out the revno for a random revision, we need to build
1014
            # the revision history, and count its length.
1015
            # We don't care about the order, just how long it is.
1016
            # Alternatively, we could start at the current location, and count
1017
            # backwards. But there is no guarantee that we will find it since
1018
            # it may be a merged revision.
1019
            revno = len(list(self.repository.iter_reverse_revision_history(
1020
                                                                revision_id)))
1021
        destination.set_last_revision_info(revno, revision_id)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1022
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1023
    @needs_read_lock
1024
    def copy_content_into(self, destination, revision_id=None):
1025
        """Copy the content of self into destination.
1026
1027
        revision_id: if not None, the revision history in the new branch will
1028
                     be truncated to end with revision_id.
1029
        """
2230.3.18 by Aaron Bentley
Handle history sync as a special operation
1030
        self._synchronize_history(destination, revision_id)
1864.7.2 by John Arbash Meinel
Test that we copy the parent across properly (if it is available)
1031
        try:
1032
            parent = self.get_parent()
1033
        except errors.InaccessibleParent, e:
1034
            mutter('parent was not accessible to copy: %s', e)
1035
        else:
1036
            if parent:
1037
                destination.set_parent(parent)
4032.3.3 by Robert Collins
Use the same logic push does to avoid tags operations when pushing new branches.
1038
        if self._push_should_merge_tags():
1039
            self.tags.merge_to(destination.tags)
1185.66.1 by Aaron Bentley
Merged from mainline
1040
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
1041
    @needs_read_lock
1042
    def check(self):
1043
        """Check consistency of the branch.
1044
1045
        In particular this checks that revisions given in the revision-history
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1046
        do actually match up in the revision graph, and that they're all
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
1047
        present in the repository.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1048
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
1049
        Callers will typically also want to check the repository.
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
1050
1051
        :return: A BranchCheckResult.
1052
        """
1053
        mainline_parent_id = None
3389.2.1 by John Arbash Meinel
Add code to 'bzr check' to detect when the mainline history is inconsistent.
1054
        last_revno, last_revision_id = self.last_revision_info()
1055
        real_rev_history = list(self.repository.iter_reverse_revision_history(
1056
                                last_revision_id))
1057
        real_rev_history.reverse()
1058
        if len(real_rev_history) != last_revno:
1059
            raise errors.BzrCheckError('revno does not match len(mainline)'
1060
                ' %s != %s' % (last_revno, len(real_rev_history)))
1061
        # TODO: We should probably also check that real_rev_history actually
1062
        #       matches self.revision_history()
1063
        for revision_id in real_rev_history:
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
1064
            try:
1065
                revision = self.repository.get_revision(revision_id)
1066
            except errors.NoSuchRevision, e:
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
1067
                raise errors.BzrCheckError("mainline revision {%s} not in repository"
1068
                            % revision_id)
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
1069
            # In general the first entry on the revision history has no parents.
1070
            # But it's not illegal for it to have parents listed; this can happen
1071
            # in imports from Arch when the parents weren't reachable.
1072
            if mainline_parent_id is not None:
1073
                if mainline_parent_id not in revision.parent_ids:
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
1074
                    raise errors.BzrCheckError("previous revision {%s} not listed among "
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
1075
                                        "parents of {%s}"
1076
                                        % (mainline_parent_id, revision_id))
1077
            mainline_parent_id = revision_id
1078
        return BranchCheckResult(self)
1079
1910.2.39 by Aaron Bentley
Fix checkout bug
1080
    def _get_checkout_format(self):
1081
        """Return the most suitable metadir for a checkout of this branch.
2018.5.87 by Andrew Bennetts
Make make_branch_and_tree fall back to creating a local checkout if the transport doesn't support working trees, allowing several more Remote tests to pass.
1082
        Weaves are used if this branch's repository uses weaves.
1910.2.39 by Aaron Bentley
Fix checkout bug
1083
        """
2018.5.89 by Andrew Bennetts
Fix thinko in _get_checkout_format; checkouts for RemoteBranches should be in the default bzrdir/repo format, of course. Thanks Robert.
1084
        if isinstance(self.bzrdir, bzrdir.BzrDirPreSplitOut):
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
1085
            from bzrlib.repofmt import weaverepo
1910.2.39 by Aaron Bentley
Fix checkout bug
1086
            format = bzrdir.BzrDirMetaFormat1()
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
1087
            format.repository_format = weaverepo.RepositoryFormat7()
1910.2.39 by Aaron Bentley
Fix checkout bug
1088
        else:
2100.3.21 by Aaron Bentley
Work on checking out by-reference trees
1089
            format = self.repository.bzrdir.checkout_metadir()
2370.3.2 by John Arbash Meinel
Use BzrDir.set_branch_format() rather than setting it directly.
1090
            format.set_branch_format(self._format)
1910.2.39 by Aaron Bentley
Fix checkout bug
1091
        return format
1092
4044.1.1 by Robert Collins
Create Branch.create_clone_on_transport helper method to combine bzr and branch creation for push.
1093
    def create_clone_on_transport(self, to_transport, revision_id=None,
1094
        stacked_on=None):
1095
        """Create a clone of this branch and its bzrdir.
1096
1097
        :param to_transport: The transport to clone onto.
1098
        :param revision_id: The revision id to use as tip in the new branch.
1099
            If None the tip is obtained from this branch.
1100
        :param stacked_on: An optional URL to stack the clone on.
1101
        """
4044.1.2 by Robert Collins
Reinstate the TODO comment about bzrdir.clone_on_transport.
1102
        # XXX: Fix the bzrdir API to allow getting the branch back from the
1103
        # clone call. Or something. 20090224 RBC/spiv.
4044.1.1 by Robert Collins
Create Branch.create_clone_on_transport helper method to combine bzr and branch creation for push.
1104
        dir_to = self.bzrdir.clone_on_transport(to_transport,
1105
            revision_id=revision_id, stacked_on=stacked_on)
1106
        return dir_to.open_branch()
1107
2245.2.1 by Robert Collins
Split branch pushing out of branch pulling.
1108
    def create_checkout(self, to_location, revision_id=None,
3136.1.3 by Aaron Bentley
Implement hard-link support for branch and checkout
1109
                        lightweight=False, accelerator_tree=None,
1110
                        hardlink=False):
1551.8.3 by Aaron Bentley
Make create_checkout_convenience a Branch method
1111
        """Create a checkout of a branch.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1112
1551.8.3 by Aaron Bentley
Make create_checkout_convenience a Branch method
1113
        :param to_location: The url to produce the checkout at
1114
        :param revision_id: The revision to check out
1551.8.5 by Aaron Bentley
Change name to create_checkout
1115
        :param lightweight: If True, produce a lightweight checkout, otherwise,
1551.8.3 by Aaron Bentley
Make create_checkout_convenience a Branch method
1116
        produce a bound branch (heavyweight checkout)
3123.5.17 by Aaron Bentley
Update docs
1117
        :param accelerator_tree: A tree which can be used for retrieving file
1118
            contents more quickly than the revision tree, i.e. a workingtree.
1119
            The revision tree will be used for cases where accelerator_tree's
1120
            content is different.
3136.1.3 by Aaron Bentley
Implement hard-link support for branch and checkout
1121
        :param hardlink: If true, hard-link files from accelerator_tree,
1122
            where possible.
1551.8.3 by Aaron Bentley
Make create_checkout_convenience a Branch method
1123
        :return: The tree of the created checkout
1124
        """
1910.2.39 by Aaron Bentley
Fix checkout bug
1125
        t = transport.get_transport(to_location)
2475.3.3 by John Arbash Meinel
Change calls to try/mkdir('.')/except FileExists to ensure_base()
1126
        t.ensure_base()
1551.8.3 by Aaron Bentley
Make create_checkout_convenience a Branch method
1127
        if lightweight:
2100.3.26 by Aaron Bentley
checkout type is maintained for subtrees
1128
            format = self._get_checkout_format()
1129
            checkout = format.initialize_on_transport(t)
2955.5.3 by Vincent Ladeuil
Fix second unwanted connection by providing the right branch to create_checkout.
1130
            from_branch = BranchReferenceFormat().initialize(checkout, self)
1551.8.3 by Aaron Bentley
Make create_checkout_convenience a Branch method
1131
        else:
1910.2.39 by Aaron Bentley
Fix checkout bug
1132
            format = self._get_checkout_format()
1551.8.3 by Aaron Bentley
Make create_checkout_convenience a Branch method
1133
            checkout_branch = bzrdir.BzrDir.create_branch_convenience(
1910.2.39 by Aaron Bentley
Fix checkout bug
1134
                to_location, force_new_tree=False, format=format)
1551.8.3 by Aaron Bentley
Make create_checkout_convenience a Branch method
1135
            checkout = checkout_branch.bzrdir
1136
            checkout_branch.bind(self)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1137
            # pull up to the specified revision_id to set the initial
1997.1.5 by Robert Collins
``Branch.bind(other_branch)`` no longer takes a write lock on the
1138
            # branch tip correctly, and seed it with history.
1139
            checkout_branch.pull(self, stop_revision=revision_id)
2955.5.3 by Vincent Ladeuil
Fix second unwanted connection by providing the right branch to create_checkout.
1140
            from_branch=None
1141
        tree = checkout.create_workingtree(revision_id,
3123.5.2 by Aaron Bentley
Allow checkout --files_from
1142
                                           from_branch=from_branch,
3136.1.3 by Aaron Bentley
Implement hard-link support for branch and checkout
1143
                                           accelerator_tree=accelerator_tree,
1144
                                           hardlink=hardlink)
2255.2.226 by Robert Collins
Get merge_nested finally working: change nested tree iterators to take file_ids, and ensure the right branch is connected to in the merge logic. May not be suitable for shared repositories yet.
1145
        basis_tree = tree.basis_tree()
1146
        basis_tree.lock_read()
1147
        try:
1148
            for path, file_id in basis_tree.iter_references():
1149
                reference_parent = self.reference_parent(file_id, path)
1150
                reference_parent.create_checkout(tree.abspath(path),
1151
                    basis_tree.get_reference_revision(file_id, path),
1152
                    lightweight)
1153
        finally:
1154
            basis_tree.unlock()
2100.3.21 by Aaron Bentley
Work on checking out by-reference trees
1155
        return tree
1551.8.3 by Aaron Bentley
Make create_checkout_convenience a Branch method
1156
3389.2.3 by John Arbash Meinel
Add Branch.reconcile() functionality.
1157
    @needs_write_lock
1158
    def reconcile(self, thorough=True):
1159
        """Make sure the data stored in this branch is consistent."""
1160
        from bzrlib.reconcile import BranchReconciler
1161
        reconciler = BranchReconciler(self, thorough=thorough)
1162
        reconciler.reconcile()
1163
        return reconciler
1164
2100.3.23 by Aaron Bentley
Nested checkouts kinda work
1165
    def reference_parent(self, file_id, path):
2100.3.29 by Aaron Bentley
Get merge working initially
1166
        """Return the parent branch for a tree-reference file_id
1167
        :param file_id: The file_id of the tree reference
1168
        :param path: The path of the file_id in the tree
1169
        :return: A branch associated with the file_id
1170
        """
1171
        # FIXME should provide multiple branches, based on config
2100.3.23 by Aaron Bentley
Nested checkouts kinda work
1172
        return Branch.open(self.bzrdir.root_transport.clone(path).base)
1173
2220.2.30 by Martin Pool
split out tag-merging code and add some tests
1174
    def supports_tags(self):
1175
        return self._format.supports_tags()
1176
3441.5.27 by Andrew Bennetts
Tweaks suggested by John's review: rename _check_if_descendant_or_diverged, move caching last_revision_info into base Branch, better use of lock decorators.
1177
    def _check_if_descendant_or_diverged(self, revision_a, revision_b, graph,
1178
                                         other_branch):
3441.5.18 by Andrew Bennetts
Fix some test failures.
1179
        """Ensure that revision_b is a descendant of revision_a.
1180
1181
        This is a helper function for update_revisions.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1182
3441.5.18 by Andrew Bennetts
Fix some test failures.
1183
        :raises: DivergedBranches if revision_b has diverged from revision_a.
1184
        :returns: True if revision_b is a descendant of revision_a.
1185
        """
1186
        relation = self._revision_relations(revision_a, revision_b, graph)
1187
        if relation == 'b_descends_from_a':
1188
            return True
1189
        elif relation == 'diverged':
1190
            raise errors.DivergedBranches(self, other_branch)
1191
        elif relation == 'a_descends_from_b':
1192
            return False
1193
        else:
3577.1.1 by Andrew Bennetts
Cherry-pick TipChangeRejected changes from pre-branch-tip-changed-hook loom.
1194
            raise AssertionError("invalid relation: %r" % (relation,))
3441.5.18 by Andrew Bennetts
Fix some test failures.
1195
1196
    def _revision_relations(self, revision_a, revision_b, graph):
1197
        """Determine the relationship between two revisions.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1198
3441.5.18 by Andrew Bennetts
Fix some test failures.
1199
        :returns: One of: 'a_descends_from_b', 'b_descends_from_a', 'diverged'
1200
        """
1201
        heads = graph.heads([revision_a, revision_b])
1202
        if heads == set([revision_b]):
1203
            return 'b_descends_from_a'
1204
        elif heads == set([revision_a, revision_b]):
1205
            # These branches have diverged
1206
            return 'diverged'
1207
        elif heads == set([revision_a]):
1208
            return 'a_descends_from_b'
1209
        else:
3577.1.1 by Andrew Bennetts
Cherry-pick TipChangeRejected changes from pre-branch-tip-changed-hook loom.
1210
            raise AssertionError("invalid heads: %r" % (heads,))
3441.5.18 by Andrew Bennetts
Fix some test failures.
1211
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1212
1213
class BranchFormat(object):
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
1214
    """An encapsulation of the initialization and open routines for a format.
1215
1216
    Formats provide three things:
1217
     * An initialization routine,
1218
     * a format string,
1219
     * an open routine.
1220
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1221
    Formats are placed in an dict by their format string for reference
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
1222
    during branch opening. Its not required that these be instances, they
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1223
    can be classes themselves with class methods - it simply depends on
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
1224
    whether state is needed for a given format or not.
1225
1226
    Once a format is deprecated, just deprecate the initialize and open
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1227
    methods on the format class. Do not deprecate the object, as the
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
1228
    object will be created every time regardless.
1229
    """
1230
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1231
    _default_format = None
1232
    """The default format used for new branches."""
1233
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
1234
    _formats = {}
1235
    """The known formats."""
1236
2363.5.5 by Aaron Bentley
add info.describe_format
1237
    def __eq__(self, other):
1238
        return self.__class__ is other.__class__
1239
1240
    def __ne__(self, other):
1241
        return not (self == other)
1242
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
1243
    @classmethod
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1244
    def find_format(klass, a_bzrdir):
1245
        """Return the format for the branch object in a_bzrdir."""
1246
        try:
1247
            transport = a_bzrdir.get_branch_transport(None)
1248
            format_string = transport.get("format").read()
1249
            return klass._formats[format_string]
3236.1.2 by Michael Hudson
clean up branch.py imports
1250
        except errors.NoSuchFile:
1251
            raise errors.NotBranchError(path=transport.base)
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1252
        except KeyError:
3246.3.2 by Daniel Watkins
Modified uses of errors.UnknownFormatError.
1253
            raise errors.UnknownFormatError(format=format_string, kind='branch')
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1254
1255
    @classmethod
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1256
    def get_default_format(klass):
1257
        """Return the current default format."""
1258
        return klass._default_format
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
1259
2414.2.1 by Andrew Bennetts
Some miscellaneous new APIs, tests and other changes from the hpss branch.
1260
    def get_reference(self, a_bzrdir):
1261
        """Get the target reference of the branch in a_bzrdir.
1262
1263
        format probing must have been completed before calling
1264
        this method - it is assumed that the format of the branch
1265
        in a_bzrdir is correct.
1266
1267
        :param a_bzrdir: The bzrdir to get the branch data from.
1268
        :return: None if the branch is not a reference branch.
1269
        """
1270
        return None
1271
3078.2.1 by Ian Clatworthy
Refactor switch to support heavyweight checkouts
1272
    @classmethod
1273
    def set_reference(self, a_bzrdir, to_branch):
1274
        """Set the target reference of the branch in a_bzrdir.
1275
1276
        format probing must have been completed before calling
1277
        this method - it is assumed that the format of the branch
1278
        in a_bzrdir is correct.
1279
1280
        :param a_bzrdir: The bzrdir to set the branch reference for.
1281
        :param to_branch: branch that the checkout is to reference
1282
        """
1283
        raise NotImplementedError(self.set_reference)
1284
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
1285
    def get_format_string(self):
1286
        """Return the ASCII format string that identifies this format."""
1287
        raise NotImplementedError(self.get_format_string)
1288
1624.3.19 by Olaf Conradi
New call get_format_description to give a user-friendly description of a
1289
    def get_format_description(self):
1290
        """Return the short format description for this format."""
2258.1.1 by Robert Collins
Move info branch statistics gathering into the repository to allow smart server optimisation (Robert Collins).
1291
        raise NotImplementedError(self.get_format_description)
1624.3.19 by Olaf Conradi
New call get_format_description to give a user-friendly description of a
1292
2230.3.37 by Aaron Bentley
Refactor BranchFormat._initialize_helper out of BzrBranchFormat[4-6]
1293
    def _initialize_helper(self, a_bzrdir, utf8_files, lock_type='metadir',
1294
                           set_format=True):
1295
        """Initialize a branch in a bzrdir, with specified files
1296
1297
        :param a_bzrdir: The bzrdir to initialize the branch in
1298
        :param utf8_files: The files to create as a list of
1299
            (filename, content) tuples
1300
        :param set_format: If True, set the format with
1301
            self.get_format_string.  (BzrBranch4 has its format set
1302
            elsewhere)
1303
        :return: a branch in this format
1304
        """
1305
        mutter('creating branch %r in %s', self, a_bzrdir.transport.base)
1306
        branch_transport = a_bzrdir.get_branch_transport(self)
1307
        lock_map = {
1308
            'metadir': ('lock', lockdir.LockDir),
1309
            'branch4': ('branch-lock', lockable_files.TransportLock),
1310
        }
1311
        lock_name, lock_class = lock_map[lock_type]
1312
        control_files = lockable_files.LockableFiles(branch_transport,
1313
            lock_name, lock_class)
1314
        control_files.create_lock()
1315
        control_files.lock_write()
1316
        if set_format:
3407.2.5 by Martin Pool
Deprecate LockableFiles.put_utf8
1317
            utf8_files += [('format', self.get_format_string())]
2230.3.37 by Aaron Bentley
Refactor BranchFormat._initialize_helper out of BzrBranchFormat[4-6]
1318
        try:
3407.2.5 by Martin Pool
Deprecate LockableFiles.put_utf8
1319
            for (filename, content) in utf8_files:
1320
                branch_transport.put_bytes(
1321
                    filename, content,
3407.2.18 by Martin Pool
BzrDir takes responsibility for default file/dir modes
1322
                    mode=a_bzrdir._get_file_mode())
2230.3.37 by Aaron Bentley
Refactor BranchFormat._initialize_helper out of BzrBranchFormat[4-6]
1323
        finally:
1324
            control_files.unlock()
1325
        return self.open(a_bzrdir, _found=True)
1326
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1327
    def initialize(self, a_bzrdir):
1328
        """Create a branch of this format in a_bzrdir."""
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
1329
        raise NotImplementedError(self.initialize)
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
1330
1534.4.7 by Robert Collins
Move downlevel check up to the Branch.open logic, removing it from the Branch constructor and deprecating relax_version_check to the same.
1331
    def is_supported(self):
1332
        """Is this format supported?
1333
1334
        Supported formats can be initialized and opened.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1335
        Unsupported formats may not support initialization or committing or
1534.4.7 by Robert Collins
Move downlevel check up to the Branch.open logic, removing it from the Branch constructor and deprecating relax_version_check to the same.
1336
        some other features depending on the reason for not being supported.
1337
        """
1338
        return True
1339
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
1340
    def make_tags(self, branch):
1341
        """Create a tags object for branch.
1342
1343
        This method is on BranchFormat, because BranchFormats are reflected
1344
        over the wire via network_name(), whereas full Branch instances require
1345
        multiple VFS method calls to operate at all.
1346
1347
        The default implementation returns a disabled-tags instance.
1348
1349
        Note that it is normal for branch to be a RemoteBranch when using tags
1350
        on a RemoteBranch.
1351
        """
1352
        return DisabledTags(branch)
1353
4032.3.1 by Robert Collins
Add a BranchFormat.network_name() method as preparation for creating branches via RPC calls.
1354
    def network_name(self):
1355
        """A simple byte string uniquely identifying this format for RPC calls.
1356
1357
        MetaDir branch formats use their disk format string to identify the
1358
        repository over the wire. All in one formats such as bzr < 0.8, and
1359
        foreign formats like svn/git and hg should use some marker which is
1360
        unique and immutable.
1361
        """
1362
        raise NotImplementedError(self.network_name)
1363
4160.2.6 by Andrew Bennetts
Add ignore_fallbacks flag.
1364
    def open(self, a_bzrdir, _found=False, ignore_fallbacks=False):
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1365
        """Return the branch object for a_bzrdir
1366
4160.2.12 by Andrew Bennetts
Improve docstrings and remove a line of cruft.
1367
        :param a_bzrdir: A BzrDir that contains a branch.
1368
        :param _found: a private parameter, do not use it. It is used to
1369
            indicate if format probing has already be done.
1370
        :param ignore_fallbacks: when set, no fallback branches will be opened
1371
            (if there are any).  Default is to open fallbacks.
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1372
        """
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1373
        raise NotImplementedError(self.open)
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
1374
1375
    @classmethod
1376
    def register_format(klass, format):
4032.3.1 by Robert Collins
Add a BranchFormat.network_name() method as preparation for creating branches via RPC calls.
1377
        """Register a metadir format."""
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
1378
        klass._formats[format.get_format_string()] = format
4075.2.1 by Robert Collins
Audit and make sure we are registering network_name's as factories, not instances.
1379
        # Metadir formats have a network name of their format string, and get
1380
        # registered as class factories.
1381
        network_format_registry.register(format.get_format_string(), format.__class__)
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
1382
1534.4.7 by Robert Collins
Move downlevel check up to the Branch.open logic, removing it from the Branch constructor and deprecating relax_version_check to the same.
1383
    @classmethod
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1384
    def set_default_format(klass, format):
1385
        klass._default_format = format
1386
3575.2.2 by Martin Pool
branch --stacked should force a stacked format
1387
    def supports_stacking(self):
1388
        """True if this format records a stacked-on branch."""
1389
        return False
1390
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1391
    @classmethod
1534.4.7 by Robert Collins
Move downlevel check up to the Branch.open logic, removing it from the Branch constructor and deprecating relax_version_check to the same.
1392
    def unregister_format(klass, format):
1393
        del klass._formats[format.get_format_string()]
1394
1553.4.8 by Michael Ellerman
Define __str__ for BranchFormat, just return the format string with the
1395
    def __str__(self):
4032.3.2 by Robert Collins
Create and use a RPC call to create branches on bzr servers rather than using VFS calls.
1396
        return self.get_format_description().rstrip()
1553.4.8 by Michael Ellerman
Define __str__ for BranchFormat, just return the format string with the
1397
2220.2.10 by Martin Pool
(broken) start moving things to branches
1398
    def supports_tags(self):
1399
        """True if this format supports tags stored in the branch"""
1400
        return False  # by default
1401
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
1402
2370.4.1 by Robert Collins
New SmartServer hooks facility. There are two initial hooks documented
1403
class BranchHooks(Hooks):
2245.1.3 by Robert Collins
Add install_hook to the BranchHooks class as the official means for installing a hook.
1404
    """A dictionary mapping hook name to a list of callables for branch hooks.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1405
2245.1.3 by Robert Collins
Add install_hook to the BranchHooks class as the official means for installing a hook.
1406
    e.g. ['set_rh'] Is the list of items to be called when the
1407
    set_revision_history function is invoked.
1408
    """
1409
1410
    def __init__(self):
1411
        """Create the default hooks.
1412
1413
        These are all empty initially, because by default nothing should get
1414
        notified.
1415
        """
2370.4.1 by Robert Collins
New SmartServer hooks facility. There are two initial hooks documented
1416
        Hooks.__init__(self)
4119.3.2 by Robert Collins
Migrate existing hooks over to the new HookPoint infrastructure.
1417
        self.create_hook(HookPoint('set_rh',
1418
            "Invoked whenever the revision history has been set via "
1419
            "set_revision_history. The api signature is (branch, "
1420
            "revision_history), and the branch will be write-locked. "
1421
            "The set_rh hook can be expensive for bzr to trigger, a better "
1422
            "hook to use is Branch.post_change_branch_tip.", (0, 15), None))
1423
        self.create_hook(HookPoint('open',
1424
            "Called with the Branch object that has been opened after a "
1425
            "branch is opened.", (1, 8), None))
1426
        self.create_hook(HookPoint('post_push',
1427
            "Called after a push operation completes. post_push is called "
4053.3.4 by Jelmer Vernooij
Update branch hooks documentation.
1428
            "with a bzrlib.branch.BranchPushResult object and only runs in the "
4119.3.2 by Robert Collins
Migrate existing hooks over to the new HookPoint infrastructure.
1429
            "bzr client.", (0, 15), None))
1430
        self.create_hook(HookPoint('post_pull',
1431
            "Called after a pull operation completes. post_pull is called "
1432
            "with a bzrlib.branch.PullResult object and only runs in the "
1433
            "bzr client.", (0, 15), None))
1434
        self.create_hook(HookPoint('pre_commit',
1435
            "Called after a commit is calculated but before it is is "
1436
            "completed. pre_commit is called with (local, master, old_revno, "
1437
            "old_revid, future_revno, future_revid, tree_delta, future_tree"
1438
            "). old_revid is NULL_REVISION for the first commit to a branch, "
1439
            "tree_delta is a TreeDelta object describing changes from the "
1440
            "basis revision. hooks MUST NOT modify this delta. "
1441
            " future_tree is an in-memory tree obtained from "
1442
            "CommitBuilder.revision_tree() and hooks MUST NOT modify this "
1443
            "tree.", (0,91), None))
1444
        self.create_hook(HookPoint('post_commit',
1445
            "Called in the bzr client after a commit has completed. "
1446
            "post_commit is called with (local, master, old_revno, old_revid, "
1447
            "new_revno, new_revid). old_revid is NULL_REVISION for the first "
1448
            "commit to a branch.", (0, 15), None))
1449
        self.create_hook(HookPoint('post_uncommit',
1450
            "Called in the bzr client after an uncommit completes. "
1451
            "post_uncommit is called with (local, master, old_revno, "
1452
            "old_revid, new_revno, new_revid) where local is the local branch "
1453
            "or None, master is the target branch, and an empty branch "
1454
            "recieves new_revno of 0, new_revid of None.", (0, 15), None))
1455
        self.create_hook(HookPoint('pre_change_branch_tip',
1456
            "Called in bzr client and server before a change to the tip of a "
1457
            "branch is made. pre_change_branch_tip is called with a "
1458
            "bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
1459
            "commit, uncommit will all trigger this hook.", (1, 6), None))
1460
        self.create_hook(HookPoint('post_change_branch_tip',
1461
            "Called in bzr client and server after a change to the tip of a "
1462
            "branch is made. post_change_branch_tip is called with a "
1463
            "bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
1464
            "commit, uncommit will all trigger this hook.", (1, 4), None))
1465
        self.create_hook(HookPoint('transform_fallback_location',
1466
            "Called when a stacked branch is activating its fallback "
1467
            "locations. transform_fallback_location is called with (branch, "
1468
            "url), and should return a new url. Returning the same url "
1469
            "allows it to be used as-is, returning a different one can be "
1470
            "used to cause the branch to stack on a closer copy of that "
1471
            "fallback_location. Note that the branch cannot have history "
1472
            "accessing methods called on it during this hook because the "
1473
            "fallback locations have not been activated. When there are "
1474
            "multiple hooks installed for transform_fallback_location, "
1475
            "all are called with the url returned from the previous hook."
1476
            "The order is however undefined.", (1, 9), None))
2245.1.3 by Robert Collins
Add install_hook to the BranchHooks class as the official means for installing a hook.
1477
1478
1479
# install the default hooks into the Branch class.
1480
Branch.hooks = BranchHooks()
1481
1482
3323.2.1 by Ian Clatworthy
first cut at post_change_branch_tip hook
1483
class ChangeBranchTipParams(object):
1484
    """Object holding parameters passed to *_change_branch_tip hooks.
3331.1.5 by James Henstridge
Put revno before revid in method arguments to match last_revision_info()
1485
3331.1.7 by James Henstridge
Make the branch a member of the ChangeBranchTipParams object.
1486
    There are 5 fields that hooks may wish to access:
3331.1.5 by James Henstridge
Put revno before revid in method arguments to match last_revision_info()
1487
3331.1.13 by James Henstridge
Use last_revision_info() to retrieve the new revision number and ID.
1488
    :ivar branch: the branch being changed
1489
    :ivar old_revno: revision number before the change
1490
    :ivar new_revno: revision number after the change
1491
    :ivar old_revid: revision id before the change
1492
    :ivar new_revid: revision id after the change
3331.1.5 by James Henstridge
Put revno before revid in method arguments to match last_revision_info()
1493
3323.2.1 by Ian Clatworthy
first cut at post_change_branch_tip hook
1494
    The revid fields are strings. The revno fields are integers.
1495
    """
1496
3331.1.7 by James Henstridge
Make the branch a member of the ChangeBranchTipParams object.
1497
    def __init__(self, branch, old_revno, new_revno, old_revid, new_revid):
3323.2.1 by Ian Clatworthy
first cut at post_change_branch_tip hook
1498
        """Create a group of ChangeBranchTip parameters.
1499
3331.1.7 by James Henstridge
Make the branch a member of the ChangeBranchTipParams object.
1500
        :param branch: The branch being changed.
3331.1.5 by James Henstridge
Put revno before revid in method arguments to match last_revision_info()
1501
        :param old_revno: Revision number before the change.
1502
        :param new_revno: Revision number after the change.
3323.2.1 by Ian Clatworthy
first cut at post_change_branch_tip hook
1503
        :param old_revid: Tip revision id before the change.
1504
        :param new_revid: Tip revision id after the change.
1505
        """
3331.1.7 by James Henstridge
Make the branch a member of the ChangeBranchTipParams object.
1506
        self.branch = branch
3331.1.5 by James Henstridge
Put revno before revid in method arguments to match last_revision_info()
1507
        self.old_revno = old_revno
1508
        self.new_revno = new_revno
3323.2.1 by Ian Clatworthy
first cut at post_change_branch_tip hook
1509
        self.old_revid = old_revid
1510
        self.new_revid = new_revid
1511
3517.2.3 by Andrew Bennetts
Better tests for {pre,post}_change_branch_tip hooks.
1512
    def __eq__(self, other):
1513
        return self.__dict__ == other.__dict__
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1514
3517.2.3 by Andrew Bennetts
Better tests for {pre,post}_change_branch_tip hooks.
1515
    def __repr__(self):
1516
        return "<%s of %s from (%s, %s) to (%s, %s)>" % (
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1517
            self.__class__.__name__, self.branch,
3517.2.3 by Andrew Bennetts
Better tests for {pre,post}_change_branch_tip hooks.
1518
            self.old_revno, self.old_revid, self.new_revno, self.new_revid)
1519
3323.2.1 by Ian Clatworthy
first cut at post_change_branch_tip hook
1520
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1521
class BzrBranchFormat4(BranchFormat):
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
1522
    """Bzr branch format 4.
1523
1524
    This format has:
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1525
     - a revision-history file.
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1526
     - a branch-lock lock file [ to be shared with the bzrdir ]
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1527
    """
1528
1624.3.19 by Olaf Conradi
New call get_format_description to give a user-friendly description of a
1529
    def get_format_description(self):
1530
        """See BranchFormat.get_format_description()."""
1531
        return "Branch format 4"
1532
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1533
    def initialize(self, a_bzrdir):
1534
        """Create a branch of this format in a_bzrdir."""
1535
        utf8_files = [('revision-history', ''),
1536
                      ('branch-name', ''),
1537
                      ]
2230.3.37 by Aaron Bentley
Refactor BranchFormat._initialize_helper out of BzrBranchFormat[4-6]
1538
        return self._initialize_helper(a_bzrdir, utf8_files,
1539
                                       lock_type='branch4', set_format=False)
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1540
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1541
    def __init__(self):
1542
        super(BzrBranchFormat4, self).__init__()
1543
        self._matchingbzrdir = bzrdir.BzrDirFormat6()
1544
4032.3.1 by Robert Collins
Add a BranchFormat.network_name() method as preparation for creating branches via RPC calls.
1545
    def network_name(self):
1546
        """The network name for this format is the control dirs disk label."""
1547
        return self._matchingbzrdir.get_format_string()
1548
4160.2.6 by Andrew Bennetts
Add ignore_fallbacks flag.
1549
    def open(self, a_bzrdir, _found=False, ignore_fallbacks=False):
4160.2.12 by Andrew Bennetts
Improve docstrings and remove a line of cruft.
1550
        """See BranchFormat.open()."""
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1551
        if not _found:
1552
            # we are being called directly and must probe.
1553
            raise NotImplementedError
1554
        return BzrBranch(_format=self,
1534.5.3 by Robert Collins
Make format 4/5/6 branches share a single LockableFiles instance across wt/branch/repository.
1555
                         _control_files=a_bzrdir._control_files,
1534.6.4 by Robert Collins
Creating or opening a branch will use the repository if the format supports that.
1556
                         a_bzrdir=a_bzrdir,
1557
                         _repository=a_bzrdir.open_repository())
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1558
1553.4.8 by Michael Ellerman
Define __str__ for BranchFormat, just return the format string with the
1559
    def __str__(self):
1560
        return "Bazaar-NG branch format 4"
1561
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1562
3221.11.2 by Robert Collins
Create basic stackable branch facility.
1563
class BranchFormatMetadir(BranchFormat):
1564
    """Common logic for meta-dir based branch formats."""
1565
1566
    def _branch_class(self):
1567
        """What class to instantiate on open calls."""
1568
        raise NotImplementedError(self._branch_class)
1569
4032.3.1 by Robert Collins
Add a BranchFormat.network_name() method as preparation for creating branches via RPC calls.
1570
    def network_name(self):
1571
        """A simple byte string uniquely identifying this format for RPC calls.
1572
1573
        Metadir branch formats use their format string.
1574
        """
1575
        return self.get_format_string()
1576
4160.2.6 by Andrew Bennetts
Add ignore_fallbacks flag.
1577
    def open(self, a_bzrdir, _found=False, ignore_fallbacks=False):
4160.2.12 by Andrew Bennetts
Improve docstrings and remove a line of cruft.
1578
        """See BranchFormat.open()."""
3221.11.2 by Robert Collins
Create basic stackable branch facility.
1579
        if not _found:
1580
            format = BranchFormat.find_format(a_bzrdir)
3221.13.3 by Ian Clatworthy
Merge bzr.dev r3466
1581
            if format.__class__ != self.__class__:
1582
                raise AssertionError("wrong format %r found for %r" %
1583
                    (format, self))
3221.11.2 by Robert Collins
Create basic stackable branch facility.
1584
        try:
1585
            transport = a_bzrdir.get_branch_transport(None)
1586
            control_files = lockable_files.LockableFiles(transport, 'lock',
1587
                                                         lockdir.LockDir)
1588
            return self._branch_class()(_format=self,
1589
                              _control_files=control_files,
1590
                              a_bzrdir=a_bzrdir,
4160.2.6 by Andrew Bennetts
Add ignore_fallbacks flag.
1591
                              _repository=a_bzrdir.find_repository(),
1592
                              ignore_fallbacks=ignore_fallbacks)
3221.13.3 by Ian Clatworthy
Merge bzr.dev r3466
1593
        except errors.NoSuchFile:
1594
            raise errors.NotBranchError(path=transport.base)
3221.11.2 by Robert Collins
Create basic stackable branch facility.
1595
1596
    def __init__(self):
1597
        super(BranchFormatMetadir, self).__init__()
1598
        self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
3834.5.2 by John Arbash Meinel
Track down the various BranchFormats that weren't setting the branch format as part of the _matchingbzrdir format.
1599
        self._matchingbzrdir.set_branch_format(self)
3221.11.2 by Robert Collins
Create basic stackable branch facility.
1600
1601
    def supports_tags(self):
1602
        return True
1603
1604
1605
class BzrBranchFormat5(BranchFormatMetadir):
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1606
    """Bzr branch format 5.
1607
1608
    This format has:
1609
     - a revision-history file.
1610
     - a format string
1553.5.71 by Martin Pool
Change branch format 5 to use LockDirs, not transport locks
1611
     - a lock dir guarding the branch itself
1612
     - all of this stored in a branch/ subdirectory
1534.6.4 by Robert Collins
Creating or opening a branch will use the repository if the format supports that.
1613
     - works with shared repositories.
1553.5.71 by Martin Pool
Change branch format 5 to use LockDirs, not transport locks
1614
1615
    This format is new in bzr 0.8.
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1616
    """
1617
3221.11.2 by Robert Collins
Create basic stackable branch facility.
1618
    def _branch_class(self):
1619
        return BzrBranch5
1620
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1621
    def get_format_string(self):
1622
        """See BranchFormat.get_format_string()."""
1623
        return "Bazaar-NG branch format 5\n"
1624.3.19 by Olaf Conradi
New call get_format_description to give a user-friendly description of a
1624
1625
    def get_format_description(self):
1626
        """See BranchFormat.get_format_description()."""
1627
        return "Branch format 5"
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1628
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1629
    def initialize(self, a_bzrdir):
1630
        """Create a branch of this format in a_bzrdir."""
1631
        utf8_files = [('revision-history', ''),
1632
                      ('branch-name', ''),
1633
                      ]
2230.3.37 by Aaron Bentley
Refactor BranchFormat._initialize_helper out of BzrBranchFormat[4-6]
1634
        return self._initialize_helper(a_bzrdir, utf8_files)
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1635
3221.11.2 by Robert Collins
Create basic stackable branch facility.
1636
    def supports_tags(self):
1637
        return False
1638
1639
1640
class BzrBranchFormat6(BranchFormatMetadir):
2696.3.1 by Martin Pool
(broken) start switching format to dirstate-tags
1641
    """Branch format with last-revision and tags.
2230.3.12 by Aaron Bentley
Clean up trailing whitespace
1642
2230.3.38 by Aaron Bentley
Update docs per Martin's suggestion
1643
    Unlike previous formats, this has no explicit revision history. Instead,
1644
    this just stores the last-revision, and the left-hand history leading
1645
    up to there is the history.
1646
1647
    This format was introduced in bzr 0.15
2696.3.1 by Martin Pool
(broken) start switching format to dirstate-tags
1648
    and became the default in 0.91.
2230.3.1 by Aaron Bentley
Get branch6 creation working
1649
    """
1650
3221.11.2 by Robert Collins
Create basic stackable branch facility.
1651
    def _branch_class(self):
1652
        return BzrBranch6
1653
2230.3.1 by Aaron Bentley
Get branch6 creation working
1654
    def get_format_string(self):
1655
        """See BranchFormat.get_format_string()."""
2255.2.230 by Robert Collins
Update tree format signatures to mention introducing bzr version.
1656
        return "Bazaar Branch Format 6 (bzr 0.15)\n"
2230.3.1 by Aaron Bentley
Get branch6 creation working
1657
1658
    def get_format_description(self):
1659
        """See BranchFormat.get_format_description()."""
1660
        return "Branch format 6"
1661
1662
    def initialize(self, a_bzrdir):
1663
        """Create a branch of this format in a_bzrdir."""
2230.3.51 by Aaron Bentley
Store revno for Branch6, set_last_revision -> set_last_revision_info
1664
        utf8_files = [('last-revision', '0 null:\n'),
2220.2.28 by Martin Pool
Integrate tags with Branch6:
1665
                      ('branch.conf', ''),
1666
                      ('tags', ''),
2230.3.1 by Aaron Bentley
Get branch6 creation working
1667
                      ]
2230.3.37 by Aaron Bentley
Refactor BranchFormat._initialize_helper out of BzrBranchFormat[4-6]
1668
        return self._initialize_helper(a_bzrdir, utf8_files)
2230.3.1 by Aaron Bentley
Get branch6 creation working
1669
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
1670
    def make_tags(self, branch):
1671
        """See bzrlib.branch.BranchFormat.make_tags()."""
1672
        return BasicTags(branch)
1673
1674
3221.11.2 by Robert Collins
Create basic stackable branch facility.
1675
1676
class BzrBranchFormat7(BranchFormatMetadir):
1677
    """Branch format with last-revision, tags, and a stacked location pointer.
1678
1679
    The stacked location pointer is passed down to the repository and requires
1680
    a repository format with supports_external_lookups = True.
1681
3221.13.6 by Ian Clatworthy
update BzrBranch7 format to say 1.6, not 1.3
1682
    This format was introduced in bzr 1.6.
3221.11.2 by Robert Collins
Create basic stackable branch facility.
1683
    """
1684
1685
    def _branch_class(self):
1686
        return BzrBranch7
1687
1688
    def get_format_string(self):
1689
        """See BranchFormat.get_format_string()."""
3221.13.6 by Ian Clatworthy
update BzrBranch7 format to say 1.6, not 1.3
1690
        return "Bazaar Branch Format 7 (needs bzr 1.6)\n"
3221.11.2 by Robert Collins
Create basic stackable branch facility.
1691
1692
    def get_format_description(self):
1693
        """See BranchFormat.get_format_description()."""
1694
        return "Branch format 7"
1695
1696
    def initialize(self, a_bzrdir):
1697
        """Create a branch of this format in a_bzrdir."""
1698
        utf8_files = [('last-revision', '0 null:\n'),
1699
                      ('branch.conf', ''),
1700
                      ('tags', ''),
1701
                      ]
1702
        return self._initialize_helper(a_bzrdir, utf8_files)
2220.2.27 by Martin Pool
Start adding tags to Branch6
1703
3221.12.1 by Robert Collins
Backport development1 format (stackable packs) to before-shallow-branches.
1704
    def __init__(self):
3221.11.7 by Robert Collins
Merge in real stacked repository work.
1705
        super(BzrBranchFormat7, self).__init__()
3221.12.1 by Robert Collins
Backport development1 format (stackable packs) to before-shallow-branches.
1706
        self._matchingbzrdir.repository_format = \
3735.1.2 by Robert Collins
Remove 1.5 series dev formats and document development2 a little better.
1707
            RepositoryFormatKnitPack5RichRoot()
3221.12.1 by Robert Collins
Backport development1 format (stackable packs) to before-shallow-branches.
1708
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
1709
    def make_tags(self, branch):
1710
        """See bzrlib.branch.BranchFormat.make_tags()."""
1711
        return BasicTags(branch)
1712
3575.2.2 by Martin Pool
branch --stacked should force a stacked format
1713
    def supports_stacking(self):
1714
        return True
1715
2230.3.1 by Aaron Bentley
Get branch6 creation working
1716
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1717
class BranchReferenceFormat(BranchFormat):
1718
    """Bzr branch reference format.
1719
1720
    Branch references are used in implementing checkouts, they
1721
    act as an alias to the real branch which is at some other url.
1722
1723
    This format has:
1724
     - A location file
1725
     - a format string
1726
    """
1727
1728
    def get_format_string(self):
1729
        """See BranchFormat.get_format_string()."""
1730
        return "Bazaar-NG Branch Reference Format 1\n"
1624.3.19 by Olaf Conradi
New call get_format_description to give a user-friendly description of a
1731
1732
    def get_format_description(self):
1733
        """See BranchFormat.get_format_description()."""
1734
        return "Checkout reference format 1"
2955.5.2 by Vincent Ladeuil
Fix first unwanted connection.
1735
2414.2.1 by Andrew Bennetts
Some miscellaneous new APIs, tests and other changes from the hpss branch.
1736
    def get_reference(self, a_bzrdir):
1737
        """See BranchFormat.get_reference()."""
1738
        transport = a_bzrdir.get_branch_transport(None)
1739
        return transport.get('location').read()
1740
3078.2.1 by Ian Clatworthy
Refactor switch to support heavyweight checkouts
1741
    def set_reference(self, a_bzrdir, to_branch):
1742
        """See BranchFormat.set_reference()."""
1743
        transport = a_bzrdir.get_branch_transport(None)
1744
        location = transport.put_bytes('location', to_branch.base)
1745
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1746
    def initialize(self, a_bzrdir, target_branch=None):
1747
        """Create a branch of this format in a_bzrdir."""
1748
        if target_branch is None:
1749
            # this format does not implement branch itself, thus the implicit
1750
            # creation contract must see it as uninitializable
1751
            raise errors.UninitializableFormat(self)
1752
        mutter('creating branch reference in %s', a_bzrdir.transport.base)
1753
        branch_transport = a_bzrdir.get_branch_transport(self)
1955.3.9 by John Arbash Meinel
Find more occurrances of put() and replace with put_file or put_bytes
1754
        branch_transport.put_bytes('location',
1955.3.25 by John Arbash Meinel
apply a FIXME
1755
            target_branch.bzrdir.root_transport.base)
1955.3.9 by John Arbash Meinel
Find more occurrances of put() and replace with put_file or put_bytes
1756
        branch_transport.put_bytes('format', self.get_format_string())
2955.5.2 by Vincent Ladeuil
Fix first unwanted connection.
1757
        return self.open(
1758
            a_bzrdir, _found=True,
1759
            possible_transports=[target_branch.bzrdir.root_transport])
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1760
1761
    def __init__(self):
1762
        super(BranchReferenceFormat, self).__init__()
1763
        self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
3834.5.2 by John Arbash Meinel
Track down the various BranchFormats that weren't setting the branch format as part of the _matchingbzrdir format.
1764
        self._matchingbzrdir.set_branch_format(self)
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1765
1766
    def _make_reference_clone_function(format, a_branch):
1767
        """Create a clone() routine for a branch dynamically."""
4050.1.3 by Robert Collins
Add missed new parameter for branch reference cloning.
1768
        def clone(to_bzrdir, revision_id=None,
1769
            repository_policy=None):
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1770
            """See Branch.clone()."""
1771
            return format.initialize(to_bzrdir, a_branch)
1772
            # cannot obey revision_id limits when cloning a reference ...
1773
            # FIXME RBC 20060210 either nuke revision_id for clone, or
1774
            # emit some sort of warning/error to the caller ?!
1775
        return clone
1776
2955.5.2 by Vincent Ladeuil
Fix first unwanted connection.
1777
    def open(self, a_bzrdir, _found=False, location=None,
4160.2.6 by Andrew Bennetts
Add ignore_fallbacks flag.
1778
             possible_transports=None, ignore_fallbacks=False):
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1779
        """Return the branch that the branch reference in a_bzrdir points at.
1780
4160.2.12 by Andrew Bennetts
Improve docstrings and remove a line of cruft.
1781
        :param a_bzrdir: A BzrDir that contains a branch.
1782
        :param _found: a private parameter, do not use it. It is used to
1783
            indicate if format probing has already be done.
1784
        :param ignore_fallbacks: when set, no fallback branches will be opened
1785
            (if there are any).  Default is to open fallbacks.
1786
        :param location: The location of the referenced branch.  If
1787
            unspecified, this will be determined from the branch reference in
1788
            a_bzrdir.
1789
        :param possible_transports: An optional reusable transports list.
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1790
        """
1791
        if not _found:
1792
            format = BranchFormat.find_format(a_bzrdir)
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
1793
            if format.__class__ != self.__class__:
1794
                raise AssertionError("wrong format %r found for %r" %
1795
                    (format, self))
2018.6.1 by Robert Collins
Implement a BzrDir.open_branch smart server method for opening a branch without VFS.
1796
        if location is None:
1797
            location = self.get_reference(a_bzrdir)
2955.5.2 by Vincent Ladeuil
Fix first unwanted connection.
1798
        real_bzrdir = bzrdir.BzrDir.open(
1799
            location, possible_transports=possible_transports)
4160.2.6 by Andrew Bennetts
Add ignore_fallbacks flag.
1800
        result = real_bzrdir.open_branch(ignore_fallbacks=ignore_fallbacks)
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1801
        # this changes the behaviour of result.clone to create a new reference
1802
        # rather than a copy of the content of the branch.
1803
        # I did not use a proxy object because that needs much more extensive
1804
        # testing, and we are only changing one behaviour at the moment.
1805
        # If we decide to alter more behaviours - i.e. the implicit nickname
1806
        # then this should be refactored to introduce a tested proxy branch
1807
        # and a subclass of that for use in overriding clone() and ....
1808
        # - RBC 20060210
1809
        result.clone = self._make_reference_clone_function(result)
1810
        return result
1811
1812
4032.3.1 by Robert Collins
Add a BranchFormat.network_name() method as preparation for creating branches via RPC calls.
1813
network_format_registry = registry.FormatRegistry()
1814
"""Registry of formats indexed by their network name.
1815
4070.2.1 by Robert Collins
Add a BzrDirFormat.network_name.
1816
The network name for a branch format is an identifier that can be used when
4032.3.1 by Robert Collins
Add a BranchFormat.network_name() method as preparation for creating branches via RPC calls.
1817
referring to formats with smart server operations. See
1818
BranchFormat.network_name() for more detail.
1819
"""
1820
1821
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1822
# formats which have no format string are not discoverable
1823
# and not independently creatable, so are not registered.
2696.3.3 by Martin Pool
Start setting the default format to dirstate-tags
1824
__format5 = BzrBranchFormat5()
1825
__format6 = BzrBranchFormat6()
3221.11.2 by Robert Collins
Create basic stackable branch facility.
1826
__format7 = BzrBranchFormat7()
2696.3.3 by Martin Pool
Start setting the default format to dirstate-tags
1827
BranchFormat.register_format(__format5)
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1828
BranchFormat.register_format(BranchReferenceFormat())
2696.3.3 by Martin Pool
Start setting the default format to dirstate-tags
1829
BranchFormat.register_format(__format6)
3221.11.2 by Robert Collins
Create basic stackable branch facility.
1830
BranchFormat.register_format(__format7)
2696.3.3 by Martin Pool
Start setting the default format to dirstate-tags
1831
BranchFormat.set_default_format(__format6)
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1832
_legacy_formats = [BzrBranchFormat4(),
4032.3.1 by Robert Collins
Add a BranchFormat.network_name() method as preparation for creating branches via RPC calls.
1833
    ]
1834
network_format_registry.register(
4075.2.1 by Robert Collins
Audit and make sure we are registering network_name's as factories, not instances.
1835
    _legacy_formats[0].network_name(), _legacy_formats[0].__class__)
4032.3.1 by Robert Collins
Add a BranchFormat.network_name() method as preparation for creating branches via RPC calls.
1836
1534.4.5 by Robert Collins
Turn branch format.open into a factory.
1837
1495.1.5 by Jelmer Vernooij
Rename NativeBranch -> BzrBranch
1838
class BzrBranch(Branch):
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
1839
    """A branch stored in the actual filesystem.
1840
1841
    Note that it's "local" in the context of the filesystem; it doesn't
1842
    really matter if it's on an nfs/smb/afs/coda/... share, as long as
1843
    it's writable, and can be accessed via the normal filesystem API.
3407.2.13 by Martin Pool
Remove indirection through control_files to get transports
1844
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1845
    :ivar _transport: Transport for file operations on this branch's
3407.2.13 by Martin Pool
Remove indirection through control_files to get transports
1846
        control files, typically pointing to the .bzr/branch directory.
1847
    :ivar repository: Repository for this branch.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1848
    :ivar base: The url of the base directory for this branch; the one
3407.2.13 by Martin Pool
Remove indirection through control_files to get transports
1849
        containing the .bzr directory.
1 by mbp at sourcefrog
import from baz patch-364
1850
    """
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1851
2367.2.1 by Robert Collins
Remove bzrlib 0.8 compatability where it was making the code unclear or messy. (Robert Collins)
1852
    def __init__(self, _format=None,
4160.2.6 by Andrew Bennetts
Add ignore_fallbacks flag.
1853
                 _control_files=None, a_bzrdir=None, _repository=None,
1854
                 ignore_fallbacks=False):
2367.2.1 by Robert Collins
Remove bzrlib 0.8 compatability where it was making the code unclear or messy. (Robert Collins)
1855
        """Create new branch object at a particular location."""
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1856
        if a_bzrdir is None:
2367.2.1 by Robert Collins
Remove bzrlib 0.8 compatability where it was making the code unclear or messy. (Robert Collins)
1857
            raise ValueError('a_bzrdir must be supplied')
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1858
        else:
1859
            self.bzrdir = a_bzrdir
2220.2.16 by mbp at sourcefrog
Make Branch._transport be the branch's control file transport
1860
        self._base = self.bzrdir.transport.clone('..').base
3446.1.1 by Martin Pool
merge further LockableFile deprecations
1861
        # XXX: We should be able to just do
1862
        #   self.base = self.bzrdir.root_transport.base
1863
        # but this does not quite work yet -- mbp 20080522
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1864
        self._format = _format
1534.4.28 by Robert Collins
first cut at merge from integration.
1865
        if _control_files is None:
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
1866
            raise ValueError('BzrBranch _control_files is None')
1534.4.28 by Robert Collins
first cut at merge from integration.
1867
        self.control_files = _control_files
2220.2.16 by mbp at sourcefrog
Make Branch._transport be the branch's control file transport
1868
        self._transport = _control_files._transport
1534.6.4 by Robert Collins
Creating or opening a branch will use the repository if the format supports that.
1869
        self.repository = _repository
3221.11.11 by Robert Collins
Ensure opening a stacked branch gives a ready to use repository.
1870
        Branch.__init__(self)
1534.4.1 by Robert Collins
Allow parameterisation of the branch initialisation for bzrlib.
1871
1 by mbp at sourcefrog
import from baz patch-364
1872
    def __str__(self):
1185.65.11 by Robert Collins
Disable inheritance for getting at LockableFiles, rather use composition.
1873
        return '%s(%r)' % (self.__class__.__name__, self.base)
1 by mbp at sourcefrog
import from baz patch-364
1874
1875
    __repr__ = __str__
1876
907.1.17 by John Arbash Meinel
Adding a Branch.base property, removing pull_loc()
1877
    def _get_base(self):
2220.2.16 by mbp at sourcefrog
Make Branch._transport be the branch's control file transport
1878
        """Returns the directory containing the control directory."""
1185.69.2 by John Arbash Meinel
Changed LockableFiles to take the root directory directly. Moved mode information into LockableFiles instead of Branch
1879
        return self._base
907.1.17 by John Arbash Meinel
Adding a Branch.base property, removing pull_loc()
1880
1442.1.5 by Robert Collins
Give branch.base a docstring.
1881
    base = property(_get_base, doc="The URL for the root of this branch.")
578 by Martin Pool
- start to move toward Branch.lock and unlock methods,
1882
1694.2.6 by Martin Pool
[merge] bzr.dev
1883
    def is_locked(self):
1884
        return self.control_files.is_locked()
1885
2018.5.142 by Andrew Bennetts
Change Branch.lock_token to only accept and receive the branch lock token (rather than the branch and repo lock tokens).
1886
    def lock_write(self, token=None):
1887
        repo_token = self.repository.lock_write()
1711.8.1 by John Arbash Meinel
Branch.lock_read/lock_write/unlock should handle failures
1888
        try:
2018.5.142 by Andrew Bennetts
Change Branch.lock_token to only accept and receive the branch lock token (rather than the branch and repo lock tokens).
1889
            token = self.control_files.lock_write(token=token)
1711.8.1 by John Arbash Meinel
Branch.lock_read/lock_write/unlock should handle failures
1890
        except:
1711.8.3 by John Arbash Meinel
Branch should lock Repository before it locks self, and unlock self before Repository
1891
            self.repository.unlock()
1711.8.1 by John Arbash Meinel
Branch.lock_read/lock_write/unlock should handle failures
1892
            raise
2018.5.142 by Andrew Bennetts
Change Branch.lock_token to only accept and receive the branch lock token (rather than the branch and repo lock tokens).
1893
        return token
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
1894
1185.65.3 by Aaron Bentley
Fixed locking-- all tests pass
1895
    def lock_read(self):
1711.8.3 by John Arbash Meinel
Branch should lock Repository before it locks self, and unlock self before Repository
1896
        self.repository.lock_read()
1711.8.1 by John Arbash Meinel
Branch.lock_read/lock_write/unlock should handle failures
1897
        try:
1711.8.3 by John Arbash Meinel
Branch should lock Repository before it locks self, and unlock self before Repository
1898
            self.control_files.lock_read()
1711.8.1 by John Arbash Meinel
Branch.lock_read/lock_write/unlock should handle failures
1899
        except:
1711.8.3 by John Arbash Meinel
Branch should lock Repository before it locks self, and unlock self before Repository
1900
            self.repository.unlock()
1711.8.1 by John Arbash Meinel
Branch.lock_read/lock_write/unlock should handle failures
1901
            raise
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
1902
1903
    def unlock(self):
1185.65.11 by Robert Collins
Disable inheritance for getting at LockableFiles, rather use composition.
1904
        # TODO: test for failed two phase locks. This is known broken.
1687.1.8 by Robert Collins
Teach Branch about break_lock.
1905
        try:
1711.8.3 by John Arbash Meinel
Branch should lock Repository before it locks self, and unlock self before Repository
1906
            self.control_files.unlock()
1687.1.8 by Robert Collins
Teach Branch about break_lock.
1907
        finally:
1711.8.3 by John Arbash Meinel
Branch should lock Repository before it locks self, and unlock self before Repository
1908
            self.repository.unlock()
2375.1.3 by Andrew Bennetts
Don't use Branch.get_transaction to cache revision history.
1909
        if not self.control_files.is_locked():
1910
            # we just released the lock
2375.1.6 by Andrew Bennetts
Rename _clear_cached_data to _clear_cached_state.
1911
            self._clear_cached_state()
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1912
1185.70.3 by Martin Pool
Various updates to make storage branch mergeable:
1913
    def peek_lock_mode(self):
1914
        if self.control_files._lock_count == 0:
1915
            return None
1916
        else:
1917
            return self.control_files._lock_mode
1918
1694.2.6 by Martin Pool
[merge] bzr.dev
1919
    def get_physical_lock_status(self):
1920
        return self.control_files.get_physical_lock_status()
1921
1442.1.63 by Robert Collins
Remove self.lock_*...finally: self.unlock() dead chickens from branch.py.
1922
    @needs_read_lock
1185.50.9 by John Arbash Meinel
[bug 3632] Matthieu Moy- bzr cat should default to last revision
1923
    def print_file(self, file, revision_id):
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
1924
        """See Branch.print_file."""
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
1925
        return self.repository.print_file(file, revision_id)
1442.1.63 by Robert Collins
Remove self.lock_*...finally: self.unlock() dead chickens from branch.py.
1926
2230.3.49 by Aaron Bentley
Fix cache updating
1927
    def _write_revision_history(self, history):
1928
        """Factored out of set_revision_history.
1929
1930
        This performs the actual writing to disk.
1931
        It is intended to be called by BzrBranch5.set_revision_history."""
3407.2.7 by Martin Pool
Deprecate LockableFiles.put_utf8 and put_bytes.
1932
        self._transport.put_bytes(
1933
            'revision-history', '\n'.join(history),
3407.2.18 by Martin Pool
BzrDir takes responsibility for default file/dir modes
1934
            mode=self.bzrdir._get_file_mode())
2230.3.49 by Aaron Bentley
Fix cache updating
1935
1442.1.68 by Robert Collins
'bzr pull' now accepts '--clobber'.
1936
    @needs_write_lock
1937
    def set_revision_history(self, rev_history):
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
1938
        """See Branch.set_revision_history."""
2592.3.113 by Robert Collins
Various -Devil checks in branch.py.
1939
        if 'evil' in debug.debug_flags:
1940
            mutter_callsite(3, "set_revision_history scales with history.")
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1941
        check_not_reserved_id = _mod_revision.check_not_reserved_id
1942
        for rev_id in rev_history:
1943
            check_not_reserved_id(rev_id)
3577.1.2 by Andrew Bennetts
If there are no post_change_branch_tip hooks to run in set_revision_history, don't calculate last_revision_info().
1944
        if Branch.hooks['post_change_branch_tip']:
1945
            # Don't calculate the last_revision_info() if there are no hooks
1946
            # that will use it.
1947
            old_revno, old_revid = self.last_revision_info()
3577.1.1 by Andrew Bennetts
Cherry-pick TipChangeRejected changes from pre-branch-tip-changed-hook loom.
1948
        if len(rev_history) == 0:
1949
            revid = _mod_revision.NULL_REVISION
1950
        else:
1951
            revid = rev_history[-1]
1952
        self._run_pre_change_branch_tip_hooks(len(rev_history), revid)
2230.3.49 by Aaron Bentley
Fix cache updating
1953
        self._write_revision_history(rev_history)
3060.3.1 by Lukáš Lalinský
Cache last_revision_info in BzrBranch6, since this is often called multiple times within one lock and we don't want to read the file over and over again.
1954
        self._clear_cached_state()
2375.1.3 by Andrew Bennetts
Don't use Branch.get_transaction to cache revision history.
1955
        self._cache_revision_history(rev_history)
2245.1.1 by Robert Collins
New Branch hooks facility, with one initial hook 'set_rh' which triggers
1956
        for hook in Branch.hooks['set_rh']:
1957
            hook(self, rev_history)
3577.1.2 by Andrew Bennetts
If there are no post_change_branch_tip hooks to run in set_revision_history, don't calculate last_revision_info().
1958
        if Branch.hooks['post_change_branch_tip']:
1959
            self._run_post_change_branch_tip_hooks(old_revno, old_revid)
233 by mbp at sourcefrog
- more output from test.sh
1960
3834.3.2 by Andrew Bennetts
Preserve BzrBranch5's _synchronize_history code without affecting Branch or BzrBranch7; add effort test for RemoteBranch.copy_content_into.
1961
    def _synchronize_history(self, destination, revision_id):
1962
        """Synchronize last revision and revision history between branches.
1963
1964
        This version is most efficient when the destination is also a
1965
        BzrBranch5, but works for BzrBranch6 as long as the revision
1966
        history is the true lefthand parent history, and all of the revisions
1967
        are in the destination's repository.  If not, set_revision_history
1968
        will fail.
1969
1970
        :param destination: The branch to copy the history into
1971
        :param revision_id: The revision-id to truncate history at.  May
1972
          be None to copy complete history.
1973
        """
3904.3.6 by Andrew Bennetts
Skip test for two formats, and fix format 5 by avoiding a full history sync with non-format5 branches.
1974
        if not isinstance(destination._format, BzrBranchFormat5):
1975
            super(BzrBranch, self)._synchronize_history(
1976
                destination, revision_id)
1977
            return
3834.3.2 by Andrew Bennetts
Preserve BzrBranch5's _synchronize_history code without affecting Branch or BzrBranch7; add effort test for RemoteBranch.copy_content_into.
1978
        if revision_id == _mod_revision.NULL_REVISION:
1979
            new_history = []
1980
        else:
1981
            new_history = self.revision_history()
1982
        if revision_id is not None and new_history != []:
1983
            try:
1984
                new_history = new_history[:new_history.index(revision_id) + 1]
1985
            except ValueError:
1986
                rev = self.repository.get_revision(revision_id)
1987
                new_history = rev.get_history(self.repository)[1:]
1988
        destination.set_revision_history(new_history)
1989
2230.3.5 by Aaron Bentley
implement set_last revision and clone
1990
    @needs_write_lock
2230.3.51 by Aaron Bentley
Store revno for Branch6, set_last_revision -> set_last_revision_info
1991
    def set_last_revision_info(self, revno, revision_id):
2697.2.4 by Martin Pool
Remove assertions about revno consistency from BzrBranch.set_last_revision_info
1992
        """Set the last revision of this branch.
1993
1994
        The caller is responsible for checking that the revno is correct
1995
        for this revision id.
1996
1997
        It may be possible to set the branch last revision to an id not
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1998
        present in the repository.  However, branches can also be
2697.2.4 by Martin Pool
Remove assertions about revno consistency from BzrBranch.set_last_revision_info
1999
        configured to check constraints on history, in which case this may not
2000
        be permitted.
2001
        """
3331.1.9 by James Henstridge
Call _make_branch_tip_hook_params() after ensure_null()
2002
        revision_id = _mod_revision.ensure_null(revision_id)
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
2003
        # this old format stores the full history, but this api doesn't
2004
        # provide it, so we must generate, and might as well check it's
2005
        # correct
2697.2.5 by Martin Pool
Kill off append_revision
2006
        history = self._lefthand_history(revision_id)
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
2007
        if len(history) != revno:
2008
            raise AssertionError('%d != %d' % (len(history), revno))
2230.3.51 by Aaron Bentley
Store revno for Branch6, set_last_revision -> set_last_revision_info
2009
        self.set_revision_history(history)
2230.3.5 by Aaron Bentley
implement set_last revision and clone
2010
2230.4.1 by Aaron Bentley
Get log as fast branch5
2011
    def _gen_revision_history(self):
3407.2.1 by Martin Pool
Deprecate LockableFiles.get
2012
        history = self._transport.get_bytes('revision-history').split('\n')
2309.4.11 by John Arbash Meinel
Change Branch5._gen_revision_history() to be a bit faster about reading all revisions.
2013
        if history[-1:] == ['']:
2014
            # There shouldn't be a trailing newline, but just in case.
2015
            history.pop()
2230.4.1 by Aaron Bentley
Get log as fast branch5
2016
        return history
2017
2230.3.2 by Aaron Bentley
Get all branch tests passing
2018
    @needs_write_lock
2230.3.12 by Aaron Bentley
Clean up trailing whitespace
2019
    def generate_revision_history(self, revision_id, last_rev=None,
2230.3.2 by Aaron Bentley
Get all branch tests passing
2020
        other_branch=None):
2021
        """Create a new revision history that will finish with revision_id.
2230.3.12 by Aaron Bentley
Clean up trailing whitespace
2022
2230.3.2 by Aaron Bentley
Get all branch tests passing
2023
        :param revision_id: the new tip to use.
2024
        :param last_rev: The previous last_revision. If not None, then this
2025
            must be a ancestory of revision_id, or DivergedBranches is raised.
2026
        :param other_branch: The other branch that DivergedBranches should
2027
            raise with respect to.
2028
        """
2029
        self.set_revision_history(self._lefthand_history(revision_id,
2030
            last_rev, other_branch))
1792.1.1 by Robert Collins
Factor out revision-history synthesis to make it reusable as Branch.generate_revision_history.
2031
1185.33.59 by Martin Pool
[patch] keep a cached basis inventory (Johan Rydberg)
2032
    def basis_tree(self):
2033
        """See Branch.basis_tree."""
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
2034
        return self.repository.revision_tree(self.last_revision())
1185.33.59 by Martin Pool
[patch] keep a cached basis inventory (Johan Rydberg)
2035
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
2036
    @needs_write_lock
2246.1.3 by Robert Collins
New branch hooks: post_push, post_pull, post_commit, post_uncommit. These
2037
    def pull(self, source, overwrite=False, stop_revision=None,
3489.2.4 by Andrew Bennetts
Fix all tests broken by fixing make_branch_and_tree.
2038
             _hook_master=None, run_hooks=True, possible_transports=None,
2039
             _override_hook_target=None):
2246.1.3 by Robert Collins
New branch hooks: post_push, post_pull, post_commit, post_uncommit. These
2040
        """See Branch.pull.
2041
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2042
        :param _hook_master: Private parameter - set the branch to
3489.2.7 by Andrew Bennetts
Update comments and docstrings, add NEWS entry.
2043
            be supplied as the master to pull hooks.
2477.1.2 by Martin Pool
Rename push/pull back to 'run_hooks' (jameinel)
2044
        :param run_hooks: Private parameter - if false, this branch
2045
            is being called because it's the master of the primary branch,
2046
            so it should not run its hooks.
3489.2.7 by Andrew Bennetts
Update comments and docstrings, add NEWS entry.
2047
        :param _override_hook_target: Private parameter - set the branch to be
2048
            supplied as the target_branch to pull hooks.
2246.1.3 by Robert Collins
New branch hooks: post_push, post_pull, post_commit, post_uncommit. These
2049
        """
2297.1.1 by Martin Pool
Pull now returns a PullResult rather than just an integer.
2050
        result = PullResult()
2297.1.6 by Martin Pool
Add docs for Results, give some members cleaner names
2051
        result.source_branch = source
3489.2.4 by Andrew Bennetts
Fix all tests broken by fixing make_branch_and_tree.
2052
        if _override_hook_target is None:
2053
            result.target_branch = self
2054
        else:
2055
            result.target_branch = _override_hook_target
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
2056
        source.lock_read()
2057
        try:
3445.1.6 by John Arbash Meinel
Start using the 'graph' parameter of update_revisions to bias push and pull checking
2058
            # We assume that during 'pull' the local repository is closer than
2059
            # the remote one.
2060
            graph = self.repository.get_graph(source.repository)
2297.1.1 by Martin Pool
Pull now returns a PullResult rather than just an integer.
2061
            result.old_revno, result.old_revid = self.last_revision_info()
3445.1.6 by John Arbash Meinel
Start using the 'graph' parameter of update_revisions to bias push and pull checking
2062
            self.update_revisions(source, stop_revision, overwrite=overwrite,
2063
                                  graph=graph)
2804.3.1 by Lukáš Lalinský
Overwrite conflicting tags by push|pull --overwrite.
2064
            result.tag_conflicts = source.tags.merge_to(self.tags, overwrite)
2297.1.1 by Martin Pool
Pull now returns a PullResult rather than just an integer.
2065
            result.new_revno, result.new_revid = self.last_revision_info()
2297.1.4 by Martin Pool
Push now returns a PushResult rather than just an integer.
2066
            if _hook_master:
2297.1.6 by Martin Pool
Add docs for Results, give some members cleaner names
2067
                result.master_branch = _hook_master
3489.2.4 by Andrew Bennetts
Fix all tests broken by fixing make_branch_and_tree.
2068
                result.local_branch = result.target_branch
2297.1.4 by Martin Pool
Push now returns a PushResult rather than just an integer.
2069
            else:
3489.2.4 by Andrew Bennetts
Fix all tests broken by fixing make_branch_and_tree.
2070
                result.master_branch = result.target_branch
2297.1.6 by Martin Pool
Add docs for Results, give some members cleaner names
2071
                result.local_branch = None
2477.1.2 by Martin Pool
Rename push/pull back to 'run_hooks' (jameinel)
2072
            if run_hooks:
2246.1.3 by Robert Collins
New branch hooks: post_push, post_pull, post_commit, post_uncommit. These
2073
                for hook in Branch.hooks['post_pull']:
2297.1.1 by Martin Pool
Pull now returns a PullResult rather than just an integer.
2074
                    hook(result)
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
2075
        finally:
2076
            source.unlock()
2297.1.1 by Martin Pool
Pull now returns a PullResult rather than just an integer.
2077
        return result
1 by mbp at sourcefrog
import from baz patch-364
2078
2230.3.8 by Aaron Bentley
Abstract mechanism from policy getting/setting parents
2079
    def _get_parent_location(self):
2080
        _locs = ['parent', 'pull', 'x-pull']
2081
        for l in _locs:
2082
            try:
3407.2.1 by Martin Pool
Deprecate LockableFiles.get
2083
                return self._transport.get_bytes(l).strip('\n')
3236.1.2 by Michael Hudson
clean up branch.py imports
2084
            except errors.NoSuchFile:
2230.3.8 by Aaron Bentley
Abstract mechanism from policy getting/setting parents
2085
                pass
2086
        return None
2087
2245.2.1 by Robert Collins
Split branch pushing out of branch pulling.
2088
    @needs_read_lock
2246.1.3 by Robert Collins
New branch hooks: post_push, post_pull, post_commit, post_uncommit. These
2089
    def push(self, target, overwrite=False, stop_revision=None,
2477.1.9 by Martin Pool
Review cleanups from John, mostly docs
2090
             _override_hook_source_branch=None):
2246.1.3 by Robert Collins
New branch hooks: post_push, post_pull, post_commit, post_uncommit. These
2091
        """See Branch.push.
2477.1.2 by Martin Pool
Rename push/pull back to 'run_hooks' (jameinel)
2092
2093
        This is the basic concrete implementation of push()
2477.1.9 by Martin Pool
Review cleanups from John, mostly docs
2094
2095
        :param _override_hook_source_branch: If specified, run
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2096
        the hooks passing this Branch as the source, rather than self.
2477.1.9 by Martin Pool
Review cleanups from John, mostly docs
2097
        This is for use of RemoteBranch, where push is delegated to the
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2098
        underlying vfs-based Branch.
2477.1.2 by Martin Pool
Rename push/pull back to 'run_hooks' (jameinel)
2099
        """
2477.1.3 by Martin Pool
More refactoring of Branch.push into smaller bits
2100
        # TODO: Public option to disable running hooks - should be trivial but
2101
        # needs tests.
3758.1.1 by Andrew Bennetts
Fix #230902 by being more careful not to squash a pre-existing exception when calling foo.unlock()
2102
        return _run_with_write_locked_target(
2103
            target, self._push_with_bound_branches, target, overwrite,
2104
            stop_revision,
2105
            _override_hook_source_branch=_override_hook_source_branch)
2477.1.2 by Martin Pool
Rename push/pull back to 'run_hooks' (jameinel)
2106
2107
    def _push_with_bound_branches(self, target, overwrite,
2477.1.5 by Martin Pool
More cleanups of Branch.push to get the right behaviour with RemoteBranches
2108
            stop_revision,
2109
            _override_hook_source_branch=None):
2477.1.9 by Martin Pool
Review cleanups from John, mostly docs
2110
        """Push from self into target, and into target's master if any.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2111
2112
        This is on the base BzrBranch class even though it doesn't support
2477.1.2 by Martin Pool
Rename push/pull back to 'run_hooks' (jameinel)
2113
        bound branches because the *target* might be bound.
2114
        """
2477.1.5 by Martin Pool
More cleanups of Branch.push to get the right behaviour with RemoteBranches
2115
        def _run_hooks():
2116
            if _override_hook_source_branch:
2117
                result.source_branch = _override_hook_source_branch
2118
            for hook in Branch.hooks['post_push']:
2119
                hook(result)
2120
2477.1.2 by Martin Pool
Rename push/pull back to 'run_hooks' (jameinel)
2121
        bound_location = target.get_bound_location()
2122
        if bound_location and target.base != bound_location:
2477.1.9 by Martin Pool
Review cleanups from John, mostly docs
2123
            # there is a master branch.
2477.1.3 by Martin Pool
More refactoring of Branch.push into smaller bits
2124
            #
2477.1.9 by Martin Pool
Review cleanups from John, mostly docs
2125
            # XXX: Why the second check?  Is it even supported for a branch to
2126
            # be bound to itself? -- mbp 20070507
2477.1.2 by Martin Pool
Rename push/pull back to 'run_hooks' (jameinel)
2127
            master_branch = target.get_master_branch()
2128
            master_branch.lock_write()
2477.1.3 by Martin Pool
More refactoring of Branch.push into smaller bits
2129
            try:
2477.1.2 by Martin Pool
Rename push/pull back to 'run_hooks' (jameinel)
2130
                # push into the master from this branch.
2477.1.3 by Martin Pool
More refactoring of Branch.push into smaller bits
2131
                self._basic_push(master_branch, overwrite, stop_revision)
2132
                # and push into the target branch from this. Note that we push from
2133
                # this branch again, because its considered the highest bandwidth
2134
                # repository.
2135
                result = self._basic_push(target, overwrite, stop_revision)
2136
                result.master_branch = master_branch
2137
                result.local_branch = target
2477.1.5 by Martin Pool
More cleanups of Branch.push to get the right behaviour with RemoteBranches
2138
                _run_hooks()
2477.1.3 by Martin Pool
More refactoring of Branch.push into smaller bits
2139
                return result
2140
            finally:
2477.1.2 by Martin Pool
Rename push/pull back to 'run_hooks' (jameinel)
2141
                master_branch.unlock()
2477.1.3 by Martin Pool
More refactoring of Branch.push into smaller bits
2142
        else:
2143
            # no master branch
2144
            result = self._basic_push(target, overwrite, stop_revision)
2477.1.5 by Martin Pool
More cleanups of Branch.push to get the right behaviour with RemoteBranches
2145
            # TODO: Why set master_branch and local_branch if there's no
2146
            # binding?  Maybe cleaner to just leave them unset? -- mbp
2147
            # 20070504
2477.1.3 by Martin Pool
More refactoring of Branch.push into smaller bits
2148
            result.master_branch = target
2149
            result.local_branch = None
2477.1.5 by Martin Pool
More cleanups of Branch.push to get the right behaviour with RemoteBranches
2150
            _run_hooks()
2477.1.3 by Martin Pool
More refactoring of Branch.push into smaller bits
2151
            return result
2152
2153
    def _basic_push(self, target, overwrite, stop_revision):
2154
        """Basic implementation of push without bound branches or hooks.
2155
2156
        Must be called with self read locked and target write locked.
2157
        """
4053.3.1 by Jelmer Vernooij
Rename PushResult to BranchPushResult.
2158
        result = BranchPushResult()
2297.1.6 by Martin Pool
Add docs for Results, give some members cleaner names
2159
        result.source_branch = self
2160
        result.target_branch = target
3441.5.13 by Andrew Bennetts
Remove unnecessary extra lock_write in _basic_push.
2161
        result.old_revno, result.old_revid = target.last_revision_info()
3703.3.1 by Andrew Bennetts
Skip unnecessary work in BzrBranch._basic_push.
2162
        if result.old_revid != self.last_revision():
2163
            # We assume that during 'push' this repository is closer than
2164
            # the target.
2165
            graph = self.repository.get_graph(target.repository)
2166
            target.update_revisions(self, stop_revision, overwrite=overwrite,
2167
                                    graph=graph)
3703.3.5 by Andrew Bennetts
Allow subclasses to control if _basic_push can skip tag merging.
2168
        if self._push_should_merge_tags():
3703.3.1 by Andrew Bennetts
Skip unnecessary work in BzrBranch._basic_push.
2169
            result.tag_conflicts = self.tags.merge_to(target.tags, overwrite)
3441.5.13 by Andrew Bennetts
Remove unnecessary extra lock_write in _basic_push.
2170
        result.new_revno, result.new_revid = target.last_revision_info()
2171
        return result
2245.2.1 by Robert Collins
Split branch pushing out of branch pulling.
2172
3537.3.1 by Martin Pool
Rename branch.get_stacked_on to get_stacked_on_url
2173
    def get_stacked_on_url(self):
3221.11.2 by Robert Collins
Create basic stackable branch facility.
2174
        raise errors.UnstackableBranchFormat(self._format, self.base)
2175
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
2176
    def set_push_location(self, location):
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
2177
        """See Branch.set_push_location."""
2120.6.4 by James Henstridge
add support for specifying policy when storing options
2178
        self.get_config().set_user_option(
2120.6.9 by James Henstridge
Fixes for issues brought up in John's review
2179
            'push_location', location,
2180
            store=_mod_config.STORE_LOCATION_NORECURSE)
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
2181
1442.1.63 by Robert Collins
Remove self.lock_*...finally: self.unlock() dead chickens from branch.py.
2182
    @needs_write_lock
1150 by Martin Pool
- add new Branch.set_parent and tests
2183
    def set_parent(self, url):
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
2184
        """See Branch.set_parent."""
1150 by Martin Pool
- add new Branch.set_parent and tests
2185
        # TODO: Maybe delete old location files?
1185.65.29 by Robert Collins
Implement final review suggestions.
2186
        # URLs should never be unicode, even on the local fs,
2187
        # FIXUP this and get_parent in a future branch format bump:
3388.2.3 by Martin Pool
Fix up more uses of LockableFiles.get_utf8 in tests
2188
        # read and rewrite the file. RBC 20060125
2230.3.8 by Aaron Bentley
Abstract mechanism from policy getting/setting parents
2189
        if url is not None:
1685.1.71 by Wouter van Heyst
change branch.{get,set}_parent to store a relative path but return full urls
2190
            if isinstance(url, unicode):
3407.2.3 by Martin Pool
Branch and Repository use their own ._transport rather than going through .control_files
2191
                try:
1685.1.71 by Wouter van Heyst
change branch.{get,set}_parent to store a relative path but return full urls
2192
                    url = url.encode('ascii')
2193
                except UnicodeEncodeError:
2418.5.5 by John Arbash Meinel
Add some tests and an api for revision_id_to_dotted_revno
2194
                    raise errors.InvalidURL(url,
1685.1.71 by Wouter van Heyst
change branch.{get,set}_parent to store a relative path but return full urls
2195
                        "Urls must be 7-bit ascii, "
2196
                        "use bzrlib.urlutils.escape")
1685.1.70 by Wouter van Heyst
working on get_parent, set_parent and relative urls, broken
2197
            url = urlutils.relative_url(self.base, url)
2230.3.8 by Aaron Bentley
Abstract mechanism from policy getting/setting parents
2198
        self._set_parent_location(url)
2199
2200
    def _set_parent_location(self, url):
2201
        if url is None:
3407.2.3 by Martin Pool
Branch and Repository use their own ._transport rather than going through .control_files
2202
            self._transport.delete('parent')
2230.3.8 by Aaron Bentley
Abstract mechanism from policy getting/setting parents
2203
        else:
3407.2.3 by Martin Pool
Branch and Repository use their own ._transport rather than going through .control_files
2204
            self._transport.put_bytes('parent', url + '\n',
3407.2.18 by Martin Pool
BzrDir takes responsibility for default file/dir modes
2205
                mode=self.bzrdir._get_file_mode())
1150 by Martin Pool
- add new Branch.set_parent and tests
2206
1587.1.6 by Robert Collins
Update bound branch implementation to 0.8.
2207
2208
class BzrBranch5(BzrBranch):
2806.2.2 by Vincent Ladeuil
Fix #128076 and #131396 by reusing bound branch transport.
2209
    """A format 5 branch. This supports new features over plain branches.
1587.1.6 by Robert Collins
Update bound branch implementation to 0.8.
2210
2211
    It has support for a master_branch which is the data for bound branches.
2212
    """
2213
1442.1.63 by Robert Collins
Remove self.lock_*...finally: self.unlock() dead chickens from branch.py.
2214
    @needs_write_lock
2246.1.3 by Robert Collins
New branch hooks: post_push, post_pull, post_commit, post_uncommit. These
2215
    def pull(self, source, overwrite=False, stop_revision=None,
3489.2.4 by Andrew Bennetts
Fix all tests broken by fixing make_branch_and_tree.
2216
             run_hooks=True, possible_transports=None,
2217
             _override_hook_target=None):
2477.1.9 by Martin Pool
Review cleanups from John, mostly docs
2218
        """Pull from source into self, updating my master if any.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2219
2477.1.2 by Martin Pool
Rename push/pull back to 'run_hooks' (jameinel)
2220
        :param run_hooks: Private parameter - if false, this branch
2221
            is being called because it's the master of the primary branch,
2222
            so it should not run its hooks.
2246.1.3 by Robert Collins
New branch hooks: post_push, post_pull, post_commit, post_uncommit. These
2223
        """
1587.1.6 by Robert Collins
Update bound branch implementation to 0.8.
2224
        bound_location = self.get_bound_location()
2246.1.3 by Robert Collins
New branch hooks: post_push, post_pull, post_commit, post_uncommit. These
2225
        master_branch = None
2226
        if bound_location and source.base != bound_location:
1587.1.6 by Robert Collins
Update bound branch implementation to 0.8.
2227
            # not pulling from master, so we need to update master.
2817.4.3 by Vincent Ladeuil
Add tests for commit, reuse master branch transport.
2228
            master_branch = self.get_master_branch(possible_transports)
2246.1.3 by Robert Collins
New branch hooks: post_push, post_pull, post_commit, post_uncommit. These
2229
            master_branch.lock_write()
2230
        try:
2231
            if master_branch:
2232
                # pull from source into master.
2233
                master_branch.pull(source, overwrite, stop_revision,
2477.1.2 by Martin Pool
Rename push/pull back to 'run_hooks' (jameinel)
2234
                    run_hooks=False)
2246.1.3 by Robert Collins
New branch hooks: post_push, post_pull, post_commit, post_uncommit. These
2235
            return super(BzrBranch5, self).pull(source, overwrite,
2236
                stop_revision, _hook_master=master_branch,
3489.2.4 by Andrew Bennetts
Fix all tests broken by fixing make_branch_and_tree.
2237
                run_hooks=run_hooks,
2238
                _override_hook_target=_override_hook_target)
2246.1.3 by Robert Collins
New branch hooks: post_push, post_pull, post_commit, post_uncommit. These
2239
        finally:
2240
            if master_branch:
2241
                master_branch.unlock()
2245.2.1 by Robert Collins
Split branch pushing out of branch pulling.
2242
1505.1.3 by John Arbash Meinel
(broken) Adding more tests, and some functionality
2243
    def get_bound_location(self):
1185.66.8 by Aaron Bentley
Applied Jelmer's patch to make clone a branch operation
2244
        try:
3388.2.1 by Martin Pool
Deprecate LockableFiles.get_utf8
2245
            return self._transport.get_bytes('bound')[:-1]
1587.1.6 by Robert Collins
Update bound branch implementation to 0.8.
2246
        except errors.NoSuchFile:
1505.1.3 by John Arbash Meinel
(broken) Adding more tests, and some functionality
2247
            return None
1185.66.8 by Aaron Bentley
Applied Jelmer's patch to make clone a branch operation
2248
2249
    @needs_read_lock
2806.2.2 by Vincent Ladeuil
Fix #128076 and #131396 by reusing bound branch transport.
2250
    def get_master_branch(self, possible_transports=None):
1505.1.24 by John Arbash Meinel
Updated commit to handle bound branches. Included test to handle commit after merge
2251
        """Return the branch we are bound to.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2252
1505.1.24 by John Arbash Meinel
Updated commit to handle bound branches. Included test to handle commit after merge
2253
        :return: Either a Branch, or None
1587.1.6 by Robert Collins
Update bound branch implementation to 0.8.
2254
1759.2.2 by Jelmer Vernooij
Revert some of my spelling fixes and fix some typos after review by Aaron.
2255
        This could memoise the branch, but if thats done
1587.1.6 by Robert Collins
Update bound branch implementation to 0.8.
2256
        it must be revalidated on each new lock.
1759.2.2 by Jelmer Vernooij
Revert some of my spelling fixes and fix some typos after review by Aaron.
2257
        So for now we just don't memoise it.
1587.1.6 by Robert Collins
Update bound branch implementation to 0.8.
2258
        # RBC 20060304 review this decision.
1505.1.24 by John Arbash Meinel
Updated commit to handle bound branches. Included test to handle commit after merge
2259
        """
2260
        bound_loc = self.get_bound_location()
2261
        if not bound_loc:
2262
            return None
1587.1.6 by Robert Collins
Update bound branch implementation to 0.8.
2263
        try:
2806.2.2 by Vincent Ladeuil
Fix #128076 and #131396 by reusing bound branch transport.
2264
            return Branch.open(bound_loc,
2265
                               possible_transports=possible_transports)
1587.1.6 by Robert Collins
Update bound branch implementation to 0.8.
2266
        except (errors.NotBranchError, errors.ConnectionError), e:
2267
            raise errors.BoundBranchConnectionFailure(
2268
                    self, bound_loc, e)
1505.1.24 by John Arbash Meinel
Updated commit to handle bound branches. Included test to handle commit after merge
2269
1505.1.3 by John Arbash Meinel
(broken) Adding more tests, and some functionality
2270
    @needs_write_lock
2271
    def set_bound_location(self, location):
1505.1.27 by John Arbash Meinel
Adding tests against an sftp branch.
2272
        """Set the target where this branch is bound to.
2273
2274
        :param location: URL to the target branch
2275
        """
1505.1.25 by John Arbash Meinel
Updated pull. Now all paths which call set_revision_history maintain the branch invariant. All tests pass.
2276
        if location:
3446.1.1 by Martin Pool
merge further LockableFile deprecations
2277
            self._transport.put_bytes('bound', location+'\n',
2278
                mode=self.bzrdir._get_file_mode())
1185.64.2 by Goffredo Baroncelli
- implemented some suggestion by Robert Collins
2279
        else:
1505.1.25 by John Arbash Meinel
Updated pull. Now all paths which call set_revision_history maintain the branch invariant. All tests pass.
2280
            try:
3407.2.3 by Martin Pool
Branch and Repository use their own ._transport rather than going through .control_files
2281
                self._transport.delete('bound')
3236.1.2 by Michael Hudson
clean up branch.py imports
2282
            except errors.NoSuchFile:
1505.1.25 by John Arbash Meinel
Updated pull. Now all paths which call set_revision_history maintain the branch invariant. All tests pass.
2283
                return False
2284
            return True
1505.1.3 by John Arbash Meinel
(broken) Adding more tests, and some functionality
2285
2286
    @needs_write_lock
2287
    def bind(self, other):
1997.1.5 by Robert Collins
``Branch.bind(other_branch)`` no longer takes a write lock on the
2288
        """Bind this branch to the branch other.
1505.1.3 by John Arbash Meinel
(broken) Adding more tests, and some functionality
2289
1997.1.5 by Robert Collins
``Branch.bind(other_branch)`` no longer takes a write lock on the
2290
        This does not push or pull data between the branches, though it does
2291
        check for divergence to raise an error when the branches are not
2292
        either the same, or one a prefix of the other. That behaviour may not
2293
        be useful, so that check may be removed in future.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2294
1505.1.3 by John Arbash Meinel
(broken) Adding more tests, and some functionality
2295
        :param other: The branch to bind to
2296
        :type other: Branch
1185.64.2 by Goffredo Baroncelli
- implemented some suggestion by Robert Collins
2297
        """
1505.1.24 by John Arbash Meinel
Updated commit to handle bound branches. Included test to handle commit after merge
2298
        # TODO: jam 20051230 Consider checking if the target is bound
2299
        #       It is debatable whether you should be able to bind to
2300
        #       a branch which is itself bound.
2301
        #       Committing is obviously forbidden,
2302
        #       but binding itself may not be.
2303
        #       Since we *have* to check at commit time, we don't
2304
        #       *need* to check here
1997.1.5 by Robert Collins
``Branch.bind(other_branch)`` no longer takes a write lock on the
2305
2306
        # we want to raise diverged if:
2307
        # last_rev is not in the other_last_rev history, AND
2308
        # other_last_rev is not in our history, and do it without pulling
2309
        # history around
1505.1.3 by John Arbash Meinel
(broken) Adding more tests, and some functionality
2310
        self.set_bound_location(other.base)
1505.1.2 by John Arbash Meinel
(broken) working on implementing bound branches.
2311
1505.1.5 by John Arbash Meinel
Added a test for the unbind command.
2312
    @needs_write_lock
2313
    def unbind(self):
2314
        """If bound, unbind"""
1505.1.25 by John Arbash Meinel
Updated pull. Now all paths which call set_revision_history maintain the branch invariant. All tests pass.
2315
        return self.set_bound_location(None)
1185.66.8 by Aaron Bentley
Applied Jelmer's patch to make clone a branch operation
2316
1587.1.10 by Robert Collins
update updates working tree and branch together.
2317
    @needs_write_lock
2806.2.2 by Vincent Ladeuil
Fix #128076 and #131396 by reusing bound branch transport.
2318
    def update(self, possible_transports=None):
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2319
        """Synchronise this branch with the master branch if any.
1587.1.10 by Robert Collins
update updates working tree and branch together.
2320
2321
        :return: None or the last_revision that was pivoted out during the
2322
                 update.
2323
        """
2806.2.2 by Vincent Ladeuil
Fix #128076 and #131396 by reusing bound branch transport.
2324
        master = self.get_master_branch(possible_transports)
1587.1.10 by Robert Collins
update updates working tree and branch together.
2325
        if master is not None:
2653.2.4 by Aaron Bentley
Remove get_ancestry usage from branch
2326
            old_tip = _mod_revision.ensure_null(self.last_revision())
1587.1.10 by Robert Collins
update updates working tree and branch together.
2327
            self.pull(master, overwrite=True)
2653.2.4 by Aaron Bentley
Remove get_ancestry usage from branch
2328
            if self.repository.get_graph().is_ancestor(old_tip,
2329
                _mod_revision.ensure_null(self.last_revision())):
1587.1.10 by Robert Collins
update updates working tree and branch together.
2330
                return None
2331
            return old_tip
2332
        return None
2333
1534.4.1 by Robert Collins
Allow parameterisation of the branch initialisation for bzrlib.
2334
3221.11.2 by Robert Collins
Create basic stackable branch facility.
2335
class BzrBranch7(BzrBranch5):
3517.4.7 by Martin Pool
doc
2336
    """A branch with support for a fallback repository."""
3221.11.2 by Robert Collins
Create basic stackable branch facility.
2337
3221.11.11 by Robert Collins
Ensure opening a stacked branch gives a ready to use repository.
2338
    def _open_hook(self):
4160.2.6 by Andrew Bennetts
Add ignore_fallbacks flag.
2339
        if self._ignore_fallbacks:
2340
            return
3221.11.11 by Robert Collins
Ensure opening a stacked branch gives a ready to use repository.
2341
        try:
3537.3.1 by Martin Pool
Rename branch.get_stacked_on to get_stacked_on_url
2342
            url = self.get_stacked_on_url()
3221.11.11 by Robert Collins
Ensure opening a stacked branch gives a ready to use repository.
2343
        except (errors.UnstackableRepositoryFormat, errors.NotStacked,
2344
            errors.UnstackableBranchFormat):
2345
            pass
2346
        else:
3770.2.1 by Michael Hudson
test and feature
2347
            for hook in Branch.hooks['transform_fallback_location']:
2348
                url = hook(self, url)
3770.2.3 by Michael Hudson
check for None being returned for a hook
2349
                if url is None:
2350
                    hook_name = Branch.hooks.get_hook_name(hook)
2351
                    raise AssertionError(
2352
                        "'transform_fallback_location' hook %s returned "
2353
                        "None, not a URL." % hook_name)
3221.11.11 by Robert Collins
Ensure opening a stacked branch gives a ready to use repository.
2354
            self._activate_fallback_location(url)
2355
4160.2.8 by Andrew Bennetts
Slightly less messy BzrBranch7.__init__.
2356
    def __init__(self, *args, **kwargs):
2357
        self._ignore_fallbacks = kwargs.get('ignore_fallbacks', False)
2358
        super(BzrBranch7, self).__init__(*args, **kwargs)
3060.3.1 by Lukáš Lalinský
Cache last_revision_info in BzrBranch6, since this is often called multiple times within one lock and we don't want to read the file over and over again.
2359
        self._last_revision_info_cache = None
3298.2.10 by Aaron Bentley
Refactor partial history code
2360
        self._partial_revision_history_cache = []
3060.3.1 by Lukáš Lalinský
Cache last_revision_info in BzrBranch6, since this is often called multiple times within one lock and we don't want to read the file over and over again.
2361
2362
    def _clear_cached_state(self):
3221.13.3 by Ian Clatworthy
Merge bzr.dev r3466
2363
        super(BzrBranch7, self)._clear_cached_state()
3060.3.1 by Lukáš Lalinský
Cache last_revision_info in BzrBranch6, since this is often called multiple times within one lock and we don't want to read the file over and over again.
2364
        self._last_revision_info_cache = None
3298.2.10 by Aaron Bentley
Refactor partial history code
2365
        self._partial_revision_history_cache = []
3060.3.1 by Lukáš Lalinský
Cache last_revision_info in BzrBranch6, since this is often called multiple times within one lock and we don't want to read the file over and over again.
2366
3298.2.10 by Aaron Bentley
Refactor partial history code
2367
    def _last_revision_info(self):
3407.2.3 by Martin Pool
Branch and Repository use their own ._transport rather than going through .control_files
2368
        revision_string = self._transport.get_bytes('last-revision')
3298.2.10 by Aaron Bentley
Refactor partial history code
2369
        revno, revision_id = revision_string.rstrip('\n').split(' ', 1)
2370
        revision_id = cache_utf8.get_cached_utf8(revision_id)
2371
        revno = int(revno)
2372
        return revno, revision_id
2373
2230.3.51 by Aaron Bentley
Store revno for Branch6, set_last_revision -> set_last_revision_info
2374
    def _write_last_revision_info(self, revno, revision_id):
2230.3.49 by Aaron Bentley
Fix cache updating
2375
        """Simply write out the revision id, with no checks.
2376
2230.3.51 by Aaron Bentley
Store revno for Branch6, set_last_revision -> set_last_revision_info
2377
        Use set_last_revision_info to perform this safely.
2230.3.49 by Aaron Bentley
Fix cache updating
2378
2379
        Does not update the revision_history cache.
2230.3.51 by Aaron Bentley
Store revno for Branch6, set_last_revision -> set_last_revision_info
2380
        Intended to be called by set_last_revision_info and
2381
        _write_revision_history.
2230.3.49 by Aaron Bentley
Fix cache updating
2382
        """
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
2383
        revision_id = _mod_revision.ensure_null(revision_id)
2230.3.51 by Aaron Bentley
Store revno for Branch6, set_last_revision -> set_last_revision_info
2384
        out_string = '%d %s\n' % (revno, revision_id)
3407.2.7 by Martin Pool
Deprecate LockableFiles.put_utf8 and put_bytes.
2385
        self._transport.put_bytes('last-revision', out_string,
3407.2.18 by Martin Pool
BzrDir takes responsibility for default file/dir modes
2386
            mode=self.bzrdir._get_file_mode())
2230.3.2 by Aaron Bentley
Get all branch tests passing
2387
2230.3.49 by Aaron Bentley
Fix cache updating
2388
    @needs_write_lock
2230.3.51 by Aaron Bentley
Store revno for Branch6, set_last_revision -> set_last_revision_info
2389
    def set_last_revision_info(self, revno, revision_id):
3331.1.9 by James Henstridge
Call _make_branch_tip_hook_params() after ensure_null()
2390
        revision_id = _mod_revision.ensure_null(revision_id)
3331.1.13 by James Henstridge
Use last_revision_info() to retrieve the new revision number and ID.
2391
        old_revno, old_revid = self.last_revision_info()
2230.3.49 by Aaron Bentley
Fix cache updating
2392
        if self._get_append_revisions_only():
2393
            self._check_history_violation(revision_id)
3517.2.1 by Andrew Bennetts
Quick draft of pre_change_branch_tip hook.
2394
        self._run_pre_change_branch_tip_hooks(revno, revision_id)
2230.3.51 by Aaron Bentley
Store revno for Branch6, set_last_revision -> set_last_revision_info
2395
        self._write_last_revision_info(revno, revision_id)
2375.1.6 by Andrew Bennetts
Rename _clear_cached_data to _clear_cached_state.
2396
        self._clear_cached_state()
3060.3.1 by Lukáš Lalinský
Cache last_revision_info in BzrBranch6, since this is often called multiple times within one lock and we don't want to read the file over and over again.
2397
        self._last_revision_info_cache = revno, revision_id
3331.1.13 by James Henstridge
Use last_revision_info() to retrieve the new revision number and ID.
2398
        self._run_post_change_branch_tip_hooks(old_revno, old_revid)
2230.3.49 by Aaron Bentley
Fix cache updating
2399
3834.3.2 by Andrew Bennetts
Preserve BzrBranch5's _synchronize_history code without affecting Branch or BzrBranch7; add effort test for RemoteBranch.copy_content_into.
2400
    def _synchronize_history(self, destination, revision_id):
2401
        """Synchronize last revision and revision history between branches.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2402
3834.3.2 by Andrew Bennetts
Preserve BzrBranch5's _synchronize_history code without affecting Branch or BzrBranch7; add effort test for RemoteBranch.copy_content_into.
2403
        :see: Branch._synchronize_history
2404
        """
2405
        # XXX: The base Branch has a fast implementation of this method based
2406
        # on set_last_revision_info, but BzrBranch/BzrBranch5 have a slower one
2407
        # that uses set_revision_history.  This class inherits from BzrBranch5,
2408
        # but wants the fast implementation, so it calls
2409
        # Branch._synchronize_history directly.
2410
        Branch._synchronize_history(self, destination, revision_id)
2411
2230.3.32 by Aaron Bentley
Implement strict history policy
2412
    def _check_history_violation(self, revision_id):
2598.5.4 by Aaron Bentley
Restore original Branch.last_revision behavior, fix bits that care
2413
        last_revision = _mod_revision.ensure_null(self.last_revision())
2598.5.2 by Aaron Bentley
Got all tests passing with Branch returning 'null:' for null revision
2414
        if _mod_revision.is_null(last_revision):
2230.3.32 by Aaron Bentley
Implement strict history policy
2415
            return
2416
        if last_revision not in self._lefthand_history(revision_id):
2230.3.40 by Aaron Bentley
Rename strict_revision_history to append_revisions_only
2417
            raise errors.AppendRevisionsOnlyViolation(self.base)
2230.3.32 by Aaron Bentley
Implement strict history policy
2418
2230.4.1 by Aaron Bentley
Get log as fast branch5
2419
    def _gen_revision_history(self):
2230.3.2 by Aaron Bentley
Get all branch tests passing
2420
        """Generate the revision history from last revision
2421
        """
3495.2.1 by Aaron Bentley
Tolerate ghosts in mainline (#235055)
2422
        last_revno, last_revision = self.last_revision_info()
2423
        self._extend_partial_history(stop_index=last_revno-1)
3298.2.10 by Aaron Bentley
Refactor partial history code
2424
        return list(reversed(self._partial_revision_history_cache))
2425
3298.2.12 by Aaron Bentley
Add Branch6.revision_id_to_revno
2426
    def _extend_partial_history(self, stop_index=None, stop_revision=None):
3298.2.10 by Aaron Bentley
Refactor partial history code
2427
        """Extend the partial history to include a given index
2428
3298.3.1 by Aaron Bentley
Make stop_revision optional for extend_partial_history
2429
        If a stop_index is supplied, stop when that index has been reached.
3298.2.17 by Aaron Bentley
Update from review
2430
        If a stop_revision is supplied, stop when that revision is
2431
        encountered.  Otherwise, stop when the beginning of history is
2432
        reached.
3298.2.10 by Aaron Bentley
Refactor partial history code
2433
3298.2.17 by Aaron Bentley
Update from review
2434
        :param stop_index: The index which should be present.  When it is
2435
            present, history extension will stop.
2436
        :param revision_id: The revision id which should be present.  When
2437
            it is encountered, history extension will stop.
3298.2.10 by Aaron Bentley
Refactor partial history code
2438
        """
2439
        repo = self.repository
2440
        if len(self._partial_revision_history_cache) == 0:
2441
            iterator = repo.iter_reverse_revision_history(self.last_revision())
3060.3.6 by Lukáš Lalinský
Implement partial history cache in BzrBranch6.
2442
        else:
3298.2.10 by Aaron Bentley
Refactor partial history code
2443
            start_revision = self._partial_revision_history_cache[-1]
2444
            iterator = repo.iter_reverse_revision_history(start_revision)
2445
            #skip the last revision in the list
3298.3.3 by Aaron Bentley
Update from review
2446
            next_revision = iterator.next()
3298.2.10 by Aaron Bentley
Refactor partial history code
2447
        for revision_id in iterator:
2448
            self._partial_revision_history_cache.append(revision_id)
3298.2.12 by Aaron Bentley
Add Branch6.revision_id_to_revno
2449
            if (stop_index is not None and
2450
                len(self._partial_revision_history_cache) > stop_index):
2451
                break
2452
            if revision_id == stop_revision:
3298.2.10 by Aaron Bentley
Refactor partial history code
2453
                break
2230.3.2 by Aaron Bentley
Get all branch tests passing
2454
2230.3.49 by Aaron Bentley
Fix cache updating
2455
    def _write_revision_history(self, history):
2456
        """Factored out of set_revision_history.
2457
2458
        This performs the actual writing to disk, with format-specific checks.
2459
        It is intended to be called by BzrBranch5.set_revision_history.
2460
        """
2230.3.2 by Aaron Bentley
Get all branch tests passing
2461
        if len(history) == 0:
2230.3.49 by Aaron Bentley
Fix cache updating
2462
            last_revision = 'null:'
2230.3.2 by Aaron Bentley
Get all branch tests passing
2463
        else:
2230.3.44 by Aaron Bentley
Change asserts to specific errors for left-hand history violations
2464
            if history != self._lefthand_history(history[-1]):
2465
                raise errors.NotLefthandHistory(history)
2230.3.49 by Aaron Bentley
Fix cache updating
2466
            last_revision = history[-1]
2467
        if self._get_append_revisions_only():
2468
            self._check_history_violation(last_revision)
2230.3.51 by Aaron Bentley
Store revno for Branch6, set_last_revision -> set_last_revision_info
2469
        self._write_last_revision_info(len(history), last_revision)
2230.3.1 by Aaron Bentley
Get branch6 creation working
2470
2230.3.36 by Aaron Bentley
Refactor getting/setting locations with config
2471
    @needs_write_lock
2472
    def _set_parent_location(self, url):
2473
        """Set the parent branch"""
2474
        self._set_config_location('parent_location', url, make_relative=True)
2230.3.3 by Aaron Bentley
Add more config testing
2475
2476
    @needs_read_lock
2230.3.8 by Aaron Bentley
Abstract mechanism from policy getting/setting parents
2477
    def _get_parent_location(self):
2230.3.3 by Aaron Bentley
Add more config testing
2478
        """Set the parent branch"""
2230.3.36 by Aaron Bentley
Refactor getting/setting locations with config
2479
        return self._get_config_location('parent_location')
2230.3.3 by Aaron Bentley
Add more config testing
2480
2481
    def set_push_location(self, location):
2482
        """See Branch.set_push_location."""
2230.3.36 by Aaron Bentley
Refactor getting/setting locations with config
2483
        self._set_config_location('push_location', location)
2230.3.3 by Aaron Bentley
Add more config testing
2484
2485
    def set_bound_location(self, location):
2486
        """See Branch.set_push_location."""
2230.3.7 by Aaron Bentley
Fix binding return values
2487
        result = None
2230.3.31 by Aaron Bentley
Implement re-binding previously-bound branches
2488
        config = self.get_config()
2230.3.6 by Aaron Bentley
work in progress bind stuff
2489
        if location is None:
2230.3.31 by Aaron Bentley
Implement re-binding previously-bound branches
2490
            if config.get_user_option('bound') != 'True':
2230.3.7 by Aaron Bentley
Fix binding return values
2491
                return False
2230.3.31 by Aaron Bentley
Implement re-binding previously-bound branches
2492
            else:
1551.15.35 by Aaron Bentley
Warn when setting config values that will be masked (#122286)
2493
                config.set_user_option('bound', 'False', warn_masked=True)
2230.3.31 by Aaron Bentley
Implement re-binding previously-bound branches
2494
                return True
2495
        else:
2230.3.36 by Aaron Bentley
Refactor getting/setting locations with config
2496
            self._set_config_location('bound_location', location,
2497
                                      config=config)
1551.15.35 by Aaron Bentley
Warn when setting config values that will be masked (#122286)
2498
            config.set_user_option('bound', 'True', warn_masked=True)
2230.3.31 by Aaron Bentley
Implement re-binding previously-bound branches
2499
        return True
2500
2501
    def _get_bound_location(self, bound):
2502
        """Return the bound location in the config file.
2503
2504
        Return None if the bound parameter does not match"""
2505
        config = self.get_config()
2506
        config_bound = (config.get_user_option('bound') == 'True')
2507
        if config_bound != bound:
2508
            return None
2230.3.36 by Aaron Bentley
Refactor getting/setting locations with config
2509
        return self._get_config_location('bound_location', config=config)
2230.3.3 by Aaron Bentley
Add more config testing
2510
2230.3.31 by Aaron Bentley
Implement re-binding previously-bound branches
2511
    def get_bound_location(self):
2512
        """See Branch.set_push_location."""
2513
        return self._get_bound_location(True)
2514
2515
    def get_old_bound_location(self):
2516
        """See Branch.get_old_bound_location"""
2517
        return self._get_bound_location(False)
2518
3537.3.1 by Martin Pool
Rename branch.get_stacked_on to get_stacked_on_url
2519
    def get_stacked_on_url(self):
3691.2.12 by Martin Pool
Add test for coping without Branch.get_stacked_on_url
2520
        # you can always ask for the URL; but you might not be able to use it
2521
        # if the repo can't support stacking.
2522
        ## self._check_stackable_repo()
3221.18.2 by Ian Clatworthy
store stacked-on location in branch.conf
2523
        stacked_url = self._get_config_location('stacked_on_location')
2524
        if stacked_url is None:
3221.11.6 by Robert Collins
Stackable branch fixes.
2525
            raise errors.NotStacked(self)
2526
        return stacked_url
3221.11.2 by Robert Collins
Create basic stackable branch facility.
2527
2230.3.40 by Aaron Bentley
Rename strict_revision_history to append_revisions_only
2528
    def set_append_revisions_only(self, enabled):
2529
        if enabled:
2230.3.32 by Aaron Bentley
Implement strict history policy
2530
            value = 'True'
2531
        else:
2532
            value = 'False'
1551.15.35 by Aaron Bentley
Warn when setting config values that will be masked (#122286)
2533
        self.get_config().set_user_option('append_revisions_only', value,
2534
            warn_masked=True)
2230.3.32 by Aaron Bentley
Implement strict history policy
2535
2230.3.40 by Aaron Bentley
Rename strict_revision_history to append_revisions_only
2536
    def _get_append_revisions_only(self):
2537
        value = self.get_config().get_user_option('append_revisions_only')
2538
        return value == 'True'
2230.3.32 by Aaron Bentley
Implement strict history policy
2539
3240.1.2 by Aaron Bentley
Add write lock
2540
    @needs_write_lock
3240.1.1 by Aaron Bentley
Avoid doing Branch._lefthand_history twice
2541
    def generate_revision_history(self, revision_id, last_rev=None,
2542
                                  other_branch=None):
3240.1.6 by Aaron Bentley
Update docs
2543
        """See BzrBranch5.generate_revision_history"""
3240.1.1 by Aaron Bentley
Avoid doing Branch._lefthand_history twice
2544
        history = self._lefthand_history(revision_id, last_rev, other_branch)
2545
        revno = len(history)
2546
        self.set_last_revision_info(revno, revision_id)
2547
3060.3.3 by Lukáš Lalinský
Make RevisionSpec_revid and RevisionSpec_revno not load the whole revision history.
2548
    @needs_read_lock
3060.3.2 by Lukáš Lalinský
Make RevisionSpec_last not load the whole history.
2549
    def get_rev_id(self, revno, history=None):
2550
        """Find the revision id of the specified revno."""
2551
        if revno == 0:
2552
            return _mod_revision.NULL_REVISION
2553
2554
        last_revno, last_revision_id = self.last_revision_info()
2555
        if revno <= 0 or revno > last_revno:
2556
            raise errors.NoSuchRevision(self, revno)
2557
2558
        if history is not None:
3298.3.3 by Aaron Bentley
Update from review
2559
            return history[revno - 1]
3060.3.2 by Lukáš Lalinský
Make RevisionSpec_last not load the whole history.
2560
3298.2.10 by Aaron Bentley
Refactor partial history code
2561
        index = last_revno - revno
3298.3.2 by Aaron Bentley
Catch history mismatch, cleanup
2562
        if len(self._partial_revision_history_cache) <= index:
2563
            self._extend_partial_history(stop_index=index)
3298.2.10 by Aaron Bentley
Refactor partial history code
2564
        if len(self._partial_revision_history_cache) > index:
2565
            return self._partial_revision_history_cache[index]
3060.3.6 by Lukáš Lalinský
Implement partial history cache in BzrBranch6.
2566
        else:
3298.2.10 by Aaron Bentley
Refactor partial history code
2567
            raise errors.NoSuchRevision(self, revno)
3060.3.2 by Lukáš Lalinský
Make RevisionSpec_last not load the whole history.
2568
3298.2.12 by Aaron Bentley
Add Branch6.revision_id_to_revno
2569
    @needs_read_lock
2570
    def revision_id_to_revno(self, revision_id):
2571
        """Given a revision id, return its revno"""
2572
        if _mod_revision.is_null(revision_id):
2573
            return 0
2574
        try:
2575
            index = self._partial_revision_history_cache.index(revision_id)
2576
        except ValueError:
2577
            self._extend_partial_history(stop_revision=revision_id)
2578
            index = len(self._partial_revision_history_cache) - 1
2579
            if self._partial_revision_history_cache[index] != revision_id:
2580
                raise errors.NoSuchRevision(self, revision_id)
2581
        return self.revno() - index
2582
2230.3.34 by Aaron Bentley
cleanup
2583
3221.11.2 by Robert Collins
Create basic stackable branch facility.
2584
class BzrBranch6(BzrBranch7):
2585
    """See BzrBranchFormat6 for the capabilities of this branch.
2586
3221.18.1 by Ian Clatworthy
tweaks by ianc during review
2587
    This subclass of BzrBranch7 disables the new features BzrBranch7 added,
2588
    i.e. stacking.
3221.11.2 by Robert Collins
Create basic stackable branch facility.
2589
    """
2590
3537.3.1 by Martin Pool
Rename branch.get_stacked_on to get_stacked_on_url
2591
    def get_stacked_on_url(self):
3221.11.2 by Robert Collins
Create basic stackable branch facility.
2592
        raise errors.UnstackableBranchFormat(self._format, self.base)
2593
2594
2297.1.1 by Martin Pool
Pull now returns a PullResult rather than just an integer.
2595
######################################################################
2596
# results of operations
2597
2220.2.37 by Martin Pool
Report conflicting tags from push.
2598
2599
class _Result(object):
2600
2601
    def _show_tag_conficts(self, to_file):
2602
        if not getattr(self, 'tag_conflicts', None):
2603
            return
2604
        to_file.write('Conflicting tags:\n')
2605
        for name, value1, value2 in self.tag_conflicts:
2606
            to_file.write('    %s\n' % (name, ))
2607
2608
2609
class PullResult(_Result):
2297.1.6 by Martin Pool
Add docs for Results, give some members cleaner names
2610
    """Result of a Branch.pull operation.
2611
2612
    :ivar old_revno: Revision number before pull.
2613
    :ivar new_revno: Revision number after pull.
2614
    :ivar old_revid: Tip revision id before pull.
2615
    :ivar new_revid: Tip revision id after pull.
4119.3.2 by Robert Collins
Migrate existing hooks over to the new HookPoint infrastructure.
2616
    :ivar source_branch: Source (local) branch object. (read locked)
3482.1.1 by John Arbash Meinel
Fix bug #238149, RemoteBranch.pull needs to return the _real_branch's pull result.
2617
    :ivar master_branch: Master branch of the target, or the target if no
2618
        Master
2619
    :ivar local_branch: target branch if there is a Master, else None
4119.3.2 by Robert Collins
Migrate existing hooks over to the new HookPoint infrastructure.
2620
    :ivar target_branch: Target/destination branch object. (write locked)
3482.1.1 by John Arbash Meinel
Fix bug #238149, RemoteBranch.pull needs to return the _real_branch's pull result.
2621
    :ivar tag_conflicts: A list of tag conflicts, see BasicTags.merge_to
2297.1.6 by Martin Pool
Add docs for Results, give some members cleaner names
2622
    """
2297.1.1 by Martin Pool
Pull now returns a PullResult rather than just an integer.
2623
2297.1.3 by Martin Pool
PullResult can pretend to be an int for api compatibility with old .pull()
2624
    def __int__(self):
2297.1.4 by Martin Pool
Push now returns a PushResult rather than just an integer.
2625
        # DEPRECATED: pull used to return the change in revno
2626
        return self.new_revno - self.old_revno
2627
2220.2.39 by Martin Pool
Pull also merges tags and warns if they conflict
2628
    def report(self, to_file):
3200.1.1 by James Westby
Make pull --quiet more quiet. Fixes #185907.
2629
        if not is_quiet():
2630
            if self.old_revid == self.new_revid:
2631
                to_file.write('No revisions to pull.\n')
2632
            else:
2633
                to_file.write('Now on revision %d.\n' % self.new_revno)
2220.2.39 by Martin Pool
Pull also merges tags and warns if they conflict
2634
        self._show_tag_conficts(to_file)
2635
2297.1.4 by Martin Pool
Push now returns a PushResult rather than just an integer.
2636
4053.3.1 by Jelmer Vernooij
Rename PushResult to BranchPushResult.
2637
class BranchPushResult(_Result):
2297.1.6 by Martin Pool
Add docs for Results, give some members cleaner names
2638
    """Result of a Branch.push operation.
2639
4119.3.2 by Robert Collins
Migrate existing hooks over to the new HookPoint infrastructure.
2640
    :ivar old_revno: Revision number (eg 10) of the target before push.
2641
    :ivar new_revno: Revision number (eg 12) of the target after push.
2642
    :ivar old_revid: Tip revision id (eg joe@foo.com-1234234-aoeua34) of target
2643
        before the push.
2644
    :ivar new_revid: Tip revision id (eg joe@foo.com-5676566-boa234a) of target
2645
        after the push.
2646
    :ivar source_branch: Source branch object that the push was from. This is
2647
        read locked, and generally is a local (and thus low latency) branch.
2648
    :ivar master_branch: If target is a bound branch, the master branch of
2649
        target, or target itself. Always write locked.
2650
    :ivar target_branch: The direct Branch where data is being sent (write
2651
        locked).
2652
    :ivar local_branch: If the target is a bound branch this will be the
2653
        target, otherwise it will be None.
2297.1.6 by Martin Pool
Add docs for Results, give some members cleaner names
2654
    """
2297.1.4 by Martin Pool
Push now returns a PushResult rather than just an integer.
2655
2656
    def __int__(self):
2657
        # DEPRECATED: push used to return the change in revno
2297.1.3 by Martin Pool
PullResult can pretend to be an int for api compatibility with old .pull()
2658
        return self.new_revno - self.old_revno
2297.1.1 by Martin Pool
Pull now returns a PullResult rather than just an integer.
2659
2220.2.37 by Martin Pool
Report conflicting tags from push.
2660
    def report(self, to_file):
2661
        """Write a human-readable description of the result."""
2662
        if self.old_revid == self.new_revid:
3978.2.2 by Jelmer Vernooij
Write status messages during push to stderr rather than stdout.
2663
            note('No new revisions to push.')
2220.2.37 by Martin Pool
Report conflicting tags from push.
2664
        else:
3978.2.2 by Jelmer Vernooij
Write status messages during push to stderr rather than stdout.
2665
            note('Pushed up to revision %d.' % self.new_revno)
2220.2.37 by Martin Pool
Report conflicting tags from push.
2666
        self._show_tag_conficts(to_file)
2667
2297.1.1 by Martin Pool
Pull now returns a PullResult rather than just an integer.
2668
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
2669
class BranchCheckResult(object):
2670
    """Results of checking branch consistency.
2671
2672
    :see: Branch.check
2673
    """
2674
2675
    def __init__(self, branch):
2676
        self.branch = branch
2677
2678
    def report_results(self, verbose):
2679
        """Report the check results via trace.note.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2680
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
2681
        :param verbose: Requests more detailed display of what was checked,
2682
            if any.
2683
        """
2684
        note('checked branch %s format %s',
2685
             self.branch.base,
2686
             self.branch._format)
2687
2688
2230.3.29 by Aaron Bentley
Implement conversion to branch 6
2689
class Converter5to6(object):
2690
    """Perform an in-place upgrade of format 5 to format 6"""
2691
2692
    def convert(self, branch):
2693
        # Data for 5 and 6 can peacefully coexist.
2694
        format = BzrBranchFormat6()
2695
        new_branch = format.open(branch.bzrdir, _found=True)
2696
2697
        # Copy source data into target
3331.1.15 by Andrew Bennetts
Use _write_last_revision_info rather than set_last_revision_info in Converter5to6, because we just want to write the last-revision file, not trigger hooks with half-converted branches.
2698
        new_branch._write_last_revision_info(*branch.last_revision_info())
2230.3.29 by Aaron Bentley
Implement conversion to branch 6
2699
        new_branch.set_parent(branch.get_parent())
2700
        new_branch.set_bound_location(branch.get_bound_location())
2701
        new_branch.set_push_location(branch.get_push_location())
2702
2220.2.43 by Martin Pool
Should clear tag file when upgrading format 5 to 6 to prevent warning
2703
        # New branch has no tags by default
2704
        new_branch.tags._set_tag_dict({})
2705
2230.3.29 by Aaron Bentley
Implement conversion to branch 6
2706
        # Copying done; now update target format
3407.2.5 by Martin Pool
Deprecate LockableFiles.put_utf8
2707
        new_branch._transport.put_bytes('format',
2708
            format.get_format_string(),
3407.2.18 by Martin Pool
BzrDir takes responsibility for default file/dir modes
2709
            mode=new_branch.bzrdir._get_file_mode())
2230.3.29 by Aaron Bentley
Implement conversion to branch 6
2710
2711
        # Clean up old files
3407.2.13 by Martin Pool
Remove indirection through control_files to get transports
2712
        new_branch._transport.delete('revision-history')
2230.3.29 by Aaron Bentley
Implement conversion to branch 6
2713
        try:
2714
            branch.set_parent(None)
3236.1.2 by Michael Hudson
clean up branch.py imports
2715
        except errors.NoSuchFile:
2230.3.29 by Aaron Bentley
Implement conversion to branch 6
2716
            pass
2717
        branch.set_bound_location(None)
3221.11.4 by Robert Collins
Add a converter for format 7 branches.
2718
2719
2720
class Converter6to7(object):
2721
    """Perform an in-place upgrade of format 6 to format 7"""
2722
2723
    def convert(self, branch):
3221.11.5 by Robert Collins
Correctly handle multi-step branch upgrades.
2724
        format = BzrBranchFormat7()
3221.18.2 by Ian Clatworthy
store stacked-on location in branch.conf
2725
        branch._set_config_location('stacked_on_location', '')
3221.11.4 by Robert Collins
Add a converter for format 7 branches.
2726
        # update target format
3221.13.5 by Ian Clatworthy
fix LockableFiles deprecations
2727
        branch._transport.put_bytes('format', format.get_format_string())
3758.1.1 by Andrew Bennetts
Fix #230902 by being more careful not to squash a pre-existing exception when calling foo.unlock()
2728
2729
2730
2731
def _run_with_write_locked_target(target, callable, *args, **kwargs):
2732
    """Run ``callable(*args, **kwargs)``, write-locking target for the
2733
    duration.
2734
2735
    _run_with_write_locked_target will attempt to release the lock it acquires.
2736
2737
    If an exception is raised by callable, then that exception *will* be
2738
    propagated, even if the unlock attempt raises its own error.  Thus
2739
    _run_with_write_locked_target should be preferred to simply doing::
2740
2741
        target.lock_write()
2742
        try:
2743
            return callable(*args, **kwargs)
2744
        finally:
2745
            target.unlock()
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2746
3758.1.1 by Andrew Bennetts
Fix #230902 by being more careful not to squash a pre-existing exception when calling foo.unlock()
2747
    """
2748
    # This is very similar to bzrlib.decorators.needs_write_lock.  Perhaps they
2749
    # should share code?
2750
    target.lock_write()
2751
    try:
2752
        result = callable(*args, **kwargs)
2753
    except:
2754
        exc_info = sys.exc_info()
2755
        try:
2756
            target.unlock()
2757
        finally:
2758
            raise exc_info[0], exc_info[1], exc_info[2]
2759
    else:
2760
        target.unlock()
2761
        return result
4000.5.1 by Jelmer Vernooij
Add InterBranch.
2762
2763
2764
class InterBranch(InterObject):
2765
    """This class represents operations taking place between two branches.
2766
2767
    Its instances have methods like pull() and push() and contain
2768
    references to the source and target repositories these operations
2769
    can be carried out on.
2770
    """
2771
2772
    _optimisers = []
2773
    """The available optimised InterBranch types."""
2774
4000.5.3 by Jelmer Vernooij
Add tests for InterBranch.
2775
    @staticmethod
4000.5.5 by Jelmer Vernooij
Allow InterBranch implementations to set different from and to Branch formats for testing.
2776
    def _get_branch_formats_to_test():
2777
        """Return a tuple with the Branch formats to use when testing."""
2778
        raise NotImplementedError(self._get_branch_formats_to_test)
4000.5.3 by Jelmer Vernooij
Add tests for InterBranch.
2779
4000.5.1 by Jelmer Vernooij
Add InterBranch.
2780
    def update_revisions(self, stop_revision=None, overwrite=False,
2781
                         graph=None):
2782
        """Pull in new perfect-fit revisions.
2783
2784
        :param stop_revision: Updated until the given revision
2785
        :param overwrite: Always set the branch pointer, rather than checking
2786
            to see if it is a proper descendant.
2787
        :param graph: A Graph object that can be used to query history
2788
            information. This can be None.
2789
        :return: None
2790
        """
2791
        raise NotImplementedError(self.update_revisions)
2792
2793
2794
class GenericInterBranch(InterBranch):
2795
    """InterBranch implementation that uses public Branch functions.
2796
    """
2797
4000.5.3 by Jelmer Vernooij
Add tests for InterBranch.
2798
    @staticmethod
4000.5.5 by Jelmer Vernooij
Allow InterBranch implementations to set different from and to Branch formats for testing.
2799
    def _get_branch_formats_to_test():
2800
        return BranchFormat._default_format, BranchFormat._default_format
4000.5.3 by Jelmer Vernooij
Add tests for InterBranch.
2801
4000.5.1 by Jelmer Vernooij
Add InterBranch.
2802
    def update_revisions(self, stop_revision=None, overwrite=False,
2803
        graph=None):
2804
        """See InterBranch.update_revisions()."""
2805
        self.source.lock_read()
2806
        try:
2807
            other_revno, other_last_revision = self.source.last_revision_info()
2808
            stop_revno = None # unknown
2809
            if stop_revision is None:
2810
                stop_revision = other_last_revision
2811
                if _mod_revision.is_null(stop_revision):
2812
                    # if there are no commits, we're done.
2813
                    return
2814
                stop_revno = other_revno
2815
2816
            # what's the current last revision, before we fetch [and change it
2817
            # possibly]
2818
            last_rev = _mod_revision.ensure_null(self.target.last_revision())
2819
            # we fetch here so that we don't process data twice in the common
2820
            # case of having something to pull, and so that the check for
2821
            # already merged can operate on the just fetched graph, which will
2822
            # be cached in memory.
2823
            self.target.fetch(self.source, stop_revision)
2824
            # Check to see if one is an ancestor of the other
2825
            if not overwrite:
2826
                if graph is None:
2827
                    graph = self.target.repository.get_graph()
2828
                if self.target._check_if_descendant_or_diverged(
2829
                        stop_revision, last_rev, graph, self.source):
2830
                    # stop_revision is a descendant of last_rev, but we aren't
2831
                    # overwriting, so we're done.
2832
                    return
2833
            if stop_revno is None:
2834
                if graph is None:
2835
                    graph = self.target.repository.get_graph()
2836
                this_revno, this_last_revision = \
2837
                        self.target.last_revision_info()
2838
                stop_revno = graph.find_distance_to_null(stop_revision,
2839
                                [(other_last_revision, other_revno),
2840
                                 (this_last_revision, this_revno)])
2841
            self.target.set_last_revision_info(stop_revno, stop_revision)
2842
        finally:
2843
            self.source.unlock()
2844
2845
    @classmethod
2846
    def is_compatible(self, source, target):
2847
        # GenericBranch uses the public API, so always compatible
2848
        return True
2849
2850
2851
InterBranch.register_optimiser(GenericInterBranch)