~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Ian Clatworthy
  • Date: 2007-12-17 04:49:20 UTC
  • mfrom: (3089.3.17 bzr.ug-tweaks)
  • mto: This revision was merged to the branch mainline in revision 3120.
  • Revision ID: ian.clatworthy@internode.on.net-20071217044920-8fjh9v6m1t93c8dc
Move material out of User Guide into User Reference (Ian Clatworthy)

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