~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Aaron Bentley
  • Date: 2012-07-13 19:32:33 UTC
  • mto: This revision was merged to the branch mainline in revision 6540.
  • Revision ID: aaron@aaronbentley.com-20120713193233-l6y0l0twwhd3wmka
Switch to much simpler implementation of restore_uncommitted.

Show diffs side-by-side

added added

removed removed

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