~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

Fix test_upgrade defects related to non local or absent working trees.

Show diffs side-by-side

added added

removed removed

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