/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1
# Copyright (C) 2005, 2006 Canonical Ltd
1553.5.70 by Martin Pool
doc
2
#
1 by mbp at sourcefrog
import from baz patch-364
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
1553.5.70 by Martin Pool
doc
7
#
1 by mbp at sourcefrog
import from baz patch-364
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
1553.5.70 by Martin Pool
doc
12
#
1 by mbp at sourcefrog
import from baz patch-364
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
17
1534.4.3 by Robert Collins
Implement BranchTestProviderAdapter, so tests now run across all branch formats.
18
from copy import deepcopy
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
19
from cStringIO import StringIO
20
import errno
21
import os
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
22
import shutil
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
23
import sys
1534.4.3 by Robert Collins
Implement BranchTestProviderAdapter, so tests now run across all branch formats.
24
from unittest import TestSuite
1372 by Martin Pool
- avoid converting inventories to/from StringIO
25
from warnings import warn
1553.5.70 by Martin Pool
doc
26
1 by mbp at sourcefrog
import from baz patch-364
27
import bzrlib
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
28
import bzrlib.bzrdir as bzrdir
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
29
from bzrlib.config import TreeConfig
1534.4.28 by Robert Collins
first cut at merge from integration.
30
from bzrlib.decorators import needs_read_lock, needs_write_lock
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
31
from bzrlib.delta import compare_trees
32
import bzrlib.errors as errors
33
from bzrlib.errors import (BzrError, InvalidRevisionNumber, InvalidRevisionId,
34
                           NoSuchRevision, HistoryMissing, NotBranchError,
1551.1.1 by Martin Pool
[merge] branch-formats branch, and reconcile changes
35
                           DivergedBranches, LockError,
1534.4.3 by Robert Collins
Implement BranchTestProviderAdapter, so tests now run across all branch formats.
36
                           UninitializableFormat,
37
                           UnlistableStore,
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
38
                           UnlistableBranch, NoSuchFile, NotVersionedError,
39
                           NoWorkingTree)
1185.65.15 by Robert Collins
Merge from integration.
40
import bzrlib.inventory as inventory
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
41
from bzrlib.inventory import Inventory
1553.5.63 by Martin Pool
Lock type is now mandatory for LockableFiles constructor
42
from bzrlib.lockable_files import LockableFiles, TransportLock
1553.5.71 by Martin Pool
Change branch format 5 to use LockDirs, not transport locks
43
from bzrlib.lockdir import LockDir
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
44
from bzrlib.osutils import (isdir, quotefn,
1185.31.32 by John Arbash Meinel
Updated the bzr sourcecode to use bzrlib.osutils.pathjoin rather than os.path.join to enforce internal use of / instead of \
45
                            rename, splitpath, sha_file,
1534.4.1 by Robert Collins
Allow parameterisation of the branch initialisation for bzrlib.
46
                            file_kind, abspath, normpath, pathjoin,
47
                            safe_unicode,
48
                            )
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
49
from bzrlib.textui import show_status
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
50
from bzrlib.trace import mutter, note
51
from bzrlib.tree import EmptyTree, RevisionTree
1534.4.28 by Robert Collins
first cut at merge from integration.
52
from bzrlib.repository import Repository
1534.1.31 by Robert Collins
Deprecated fetch.fetch and fetch.greedy_fetch for branch.fetch, and move the Repository.fetch internals to InterRepo and InterWeaveRepo.
53
from bzrlib.revision import (
54
                             get_intervening_revisions,
55
                             is_ancestor,
56
                             NULL_REVISION,
57
                             Revision,
58
                             )
1393.2.1 by John Arbash Meinel
Merged in split-storage-2 branch. Need to cleanup a little bit more still.
59
from bzrlib.store import copy_all
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
60
from bzrlib.symbol_versioning import *
1417.1.6 by Robert Collins
introduce transactions for grouping actions done to and with branches
61
import bzrlib.transactions as transactions
1393.2.4 by John Arbash Meinel
All tests pass.
62
from bzrlib.transport import Transport, get_transport
1185.65.15 by Robert Collins
Merge from integration.
63
from bzrlib.tree import EmptyTree, RevisionTree
1185.65.11 by Robert Collins
Disable inheritance for getting at LockableFiles, rather use composition.
64
import bzrlib.ui
1189 by Martin Pool
- BROKEN: partial support for commit into weave
65
import bzrlib.xml5
1104 by Martin Pool
- Add a simple UIFactory
66
1094 by Martin Pool
- merge aaron's merge improvements 999..1008
67
1186 by Martin Pool
- start implementing v5 format; Branch refuses to operate on old branches
68
BZR_BRANCH_FORMAT_4 = "Bazaar-NG branch, format 0.0.4\n"
69
BZR_BRANCH_FORMAT_5 = "Bazaar-NG branch, format 5\n"
1429 by Robert Collins
merge in niemeyers prefixed-store patch
70
BZR_BRANCH_FORMAT_6 = "Bazaar-NG branch, format 6\n"
1185.70.3 by Martin Pool
Various updates to make storage branch mergeable:
71
72
73
# TODO: Maybe include checks for common corruption of newlines, etc?
1 by mbp at sourcefrog
import from baz patch-364
74
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
75
# TODO: Some operations like log might retrieve the same revisions
76
# repeatedly to calculate deltas.  We could perhaps have a weakref
1223 by Martin Pool
- store inventories in weave
77
# cache in memory to make this faster.  In general anything can be
1185.65.29 by Robert Collins
Implement final review suggestions.
78
# cached in memory between lock and unlock operations. .. nb thats
79
# what the transaction identity map provides
416 by Martin Pool
- bzr log and bzr root now accept an http URL
80
1442.1.63 by Robert Collins
Remove self.lock_*...finally: self.unlock() dead chickens from branch.py.
81
1 by mbp at sourcefrog
import from baz patch-364
82
######################################################################
83
# branch objects
84
558 by Martin Pool
- All top-level classes inherit from object
85
class Branch(object):
1 by mbp at sourcefrog
import from baz patch-364
86
    """Branch holding a history of revisions.
87
343 by Martin Pool
doc
88
    base
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
89
        Base directory/url of the branch.
90
    """
1534.4.1 by Robert Collins
Allow parameterisation of the branch initialisation for bzrlib.
91
    # this is really an instance variable - FIXME move it there
92
    # - RBC 20060112
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
93
    base = None
94
95
    def __init__(self, *ignored, **ignored_too):
96
        raise NotImplementedError('The Branch class is abstract')
97
98
    @staticmethod
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
99
    @deprecated_method(zero_eight)
1393.1.2 by Martin Pool
- better representation in Branch factories of opening old formats
100
    def open_downlevel(base):
1534.4.7 by Robert Collins
Move downlevel check up to the Branch.open logic, removing it from the Branch constructor and deprecating relax_version_check to the same.
101
        """Open a branch which may be of an old format."""
102
        return Branch.open(base, _unsupported=True)
1393.1.2 by Martin Pool
- better representation in Branch factories of opening old formats
103
        
104
    @staticmethod
1534.4.7 by Robert Collins
Move downlevel check up to the Branch.open logic, removing it from the Branch constructor and deprecating relax_version_check to the same.
105
    def open(base, _unsupported=False):
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
106
        """Open the repository rooted at base.
107
108
        For instance, if the repository is at URL/.bzr/repository,
109
        Repository.open(URL) -> a Repository instance.
1534.4.7 by Robert Collins
Move downlevel check up to the Branch.open logic, removing it from the Branch constructor and deprecating relax_version_check to the same.
110
        """
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
111
        control = bzrdir.BzrDir.open(base, _unsupported)
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
112
        return control.open_branch(_unsupported)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
113
114
    @staticmethod
1185.2.8 by Lalo Martins
creating the new branch constructors
115
    def open_containing(url):
1185.1.41 by Robert Collins
massive patch from Alexander Belchenko - many PEP8 fixes, removes unused function uuid
116
        """Open an existing branch which contains url.
117
        
118
        This probes for a branch at url, and searches upwards from there.
1185.17.2 by Martin Pool
[pick] avoid problems in fetching when .bzr is not listable
119
120
        Basically we keep looking up until we find the control directory or
121
        run into the root.  If there isn't one, raises NotBranchError.
1534.4.22 by Robert Collins
update TODOs and move abstract methods that were misplaced on BzrBranchFormat5 to Branch.
122
        If there is one and it is either an unrecognised format or an unsupported 
123
        format, UnknownFormatError or UnsupportedFormatError are raised.
1442.1.64 by Robert Collins
Branch.open_containing now returns a tuple (Branch, relative-path).
124
        If there is one, it is returned, along with the unused portion of url.
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
125
        """
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
126
        control, relpath = bzrdir.BzrDir.open_containing(url)
127
        return control.open_branch(), relpath
1534.4.1 by Robert Collins
Allow parameterisation of the branch initialisation for bzrlib.
128
129
    @staticmethod
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
130
    @deprecated_function(zero_eight)
131
    def initialize(base):
132
        """Create a new working tree and branch, rooted at 'base' (url)
1551.1.2 by Martin Pool
Deprecation warnings for popular APIs that will change in BzrDir
133
134
        NOTE: This will soon be deprecated in favour of creation
135
        through a BzrDir.
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
136
        """
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
137
        return bzrdir.BzrDir.create_standalone_workingtree(base).branch
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
138
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
139
    def setup_caching(self, cache_root):
140
        """Subclasses that care about caching should override this, and set
141
        up cached stores located under cache_root.
142
        """
1185.70.6 by Martin Pool
review fixups from John
143
        # seems to be unused, 2006-01-13 mbp
144
        warn('%s is deprecated' % self.setup_caching)
1400.1.1 by Robert Collins
implement a basic test for the ui branch command from http servers
145
        self.cache_root = cache_root
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
146
1185.35.11 by Aaron Bentley
Added support for branch nicks
147
    def _get_nick(self):
148
        cfg = self.tree_config()
1530.1.3 by Robert Collins
transport implementations now tested consistently.
149
        return cfg.get_option(u"nickname", default=self.base.split('/')[-2])
1185.35.11 by Aaron Bentley
Added support for branch nicks
150
151
    def _set_nick(self, nick):
152
        cfg = self.tree_config()
153
        cfg.set_option(nick, "nickname")
154
        assert cfg.get_option("nickname") == nick
155
156
    nick = property(_get_nick, _set_nick)
1624.3.34 by Olaf Conradi
Add initial support for showing locking information in bzr info.
157
158
    def is_locked(self):
159
        raise NotImplementedError('is_locked is abstract')
160
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
161
    def lock_write(self):
162
        raise NotImplementedError('lock_write is abstract')
1624.3.34 by Olaf Conradi
Add initial support for showing locking information in bzr info.
163
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
164
    def lock_read(self):
165
        raise NotImplementedError('lock_read is abstract')
166
167
    def unlock(self):
168
        raise NotImplementedError('unlock is abstract')
169
1185.70.3 by Martin Pool
Various updates to make storage branch mergeable:
170
    def peek_lock_mode(self):
171
        """Return lock mode for the Branch: 'r', 'w' or None"""
1185.70.6 by Martin Pool
review fixups from John
172
        raise NotImplementedError(self.peek_lock_mode)
1185.70.3 by Martin Pool
Various updates to make storage branch mergeable:
173
1624.3.36 by Olaf Conradi
Rename is_transport_locked() to get_physical_lock_status() as the
174
    def get_physical_lock_status(self):
175
        raise NotImplementedError('get_physical_lock_status is abstract')
176
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
177
    def abspath(self, name):
178
        """Return absolute filename for something in the branch
179
        
180
        XXX: Robert Collins 20051017 what is this used for? why is it a branch
181
        method and not a tree method.
182
        """
183
        raise NotImplementedError('abspath is abstract')
184
1587.1.6 by Robert Collins
Update bound branch implementation to 0.8.
185
    def bind(self, other):
186
        """Bind the local branch the other branch.
187
188
        :param other: The branch to bind to
189
        :type other: Branch
190
        """
191
        raise errors.UpgradeRequired(self.base)
192
1534.1.31 by Robert Collins
Deprecated fetch.fetch and fetch.greedy_fetch for branch.fetch, and move the Repository.fetch internals to InterRepo and InterWeaveRepo.
193
    @needs_write_lock
194
    def fetch(self, from_branch, last_revision=None, pb=None):
195
        """Copy revisions from from_branch into this branch.
196
197
        :param from_branch: Where to copy from.
198
        :param last_revision: What revision to stop at (None for at the end
199
                              of the branch.
200
        :param pb: An optional progress bar to use.
201
202
        Returns the copied revision count and the failed revisions in a tuple:
203
        (copied, failures).
204
        """
205
        if self.base == from_branch.base:
1558.4.11 by Aaron Bentley
Allow merge against self, make fetching self a noop
206
            return (0, [])
1534.1.31 by Robert Collins
Deprecated fetch.fetch and fetch.greedy_fetch for branch.fetch, and move the Repository.fetch internals to InterRepo and InterWeaveRepo.
207
        if pb is None:
1594.1.3 by Robert Collins
Fixup pb usage to use nested_progress_bar.
208
            nested_pb = bzrlib.ui.ui_factory.nested_progress_bar()
209
            pb = nested_pb
210
        else:
211
            nested_pb = None
1534.1.31 by Robert Collins
Deprecated fetch.fetch and fetch.greedy_fetch for branch.fetch, and move the Repository.fetch internals to InterRepo and InterWeaveRepo.
212
213
        from_branch.lock_read()
214
        try:
215
            if last_revision is None:
216
                pb.update('get source history')
217
                from_history = from_branch.revision_history()
218
                if from_history:
219
                    last_revision = from_history[-1]
220
                else:
221
                    # no history in the source branch
222
                    last_revision = NULL_REVISION
223
            return self.repository.fetch(from_branch.repository,
224
                                         revision_id=last_revision,
1594.1.3 by Robert Collins
Fixup pb usage to use nested_progress_bar.
225
                                         pb=nested_pb)
1534.1.31 by Robert Collins
Deprecated fetch.fetch and fetch.greedy_fetch for branch.fetch, and move the Repository.fetch internals to InterRepo and InterWeaveRepo.
226
        finally:
1594.1.3 by Robert Collins
Fixup pb usage to use nested_progress_bar.
227
            if nested_pb is not None:
228
                nested_pb.finished()
1534.1.31 by Robert Collins
Deprecated fetch.fetch and fetch.greedy_fetch for branch.fetch, and move the Repository.fetch internals to InterRepo and InterWeaveRepo.
229
            from_branch.unlock()
230
1587.1.6 by Robert Collins
Update bound branch implementation to 0.8.
231
    def get_bound_location(self):
1558.7.6 by Aaron Bentley
Fixed typo (Olaf Conradi)
232
        """Return the URL of the branch we are bound to.
1587.1.6 by Robert Collins
Update bound branch implementation to 0.8.
233
234
        Older format branches cannot bind, please be sure to use a metadir
235
        branch.
236
        """
237
        return None
238
239
    def get_master_branch(self):
240
        """Return the branch we are bound to.
241
        
242
        :return: Either a Branch, or None
243
        """
244
        return None
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
245
246
    def get_root_id(self):
247
        """Return the id of this branches root"""
248
        raise NotImplementedError('get_root_id is abstract')
249
1185.50.9 by John Arbash Meinel
[bug 3632] Matthieu Moy- bzr cat should default to last revision
250
    def print_file(self, file, revision_id):
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
251
        """Print `file` to stdout."""
252
        raise NotImplementedError('print_file is abstract')
253
254
    def append_revision(self, *revision_ids):
255
        raise NotImplementedError('append_revision is abstract')
256
257
    def set_revision_history(self, rev_history):
258
        raise NotImplementedError('set_revision_history is abstract')
259
260
    def revision_history(self):
261
        """Return sequence of revision hashes on to this branch."""
262
        raise NotImplementedError('revision_history is abstract')
263
264
    def revno(self):
265
        """Return current revision number for this branch.
266
267
        That is equivalent to the number of revisions committed to
268
        this branch.
269
        """
270
        return len(self.revision_history())
271
1587.1.6 by Robert Collins
Update bound branch implementation to 0.8.
272
    def unbind(self):
273
        """Older format branches cannot bind or unbind."""
274
        raise errors.UpgradeRequired(self.base)
275
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
276
    def last_revision(self):
277
        """Return last patch hash, or None if no history."""
278
        ph = self.revision_history()
279
        if ph:
280
            return ph[-1]
281
        else:
282
            return None
283
1505.1.21 by John Arbash Meinel
Removing changes for bound branch by invading set-revision-history.
284
    def missing_revisions(self, other, stop_revision=None):
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
285
        """Return a list of new revisions that would perfectly fit.
286
        
287
        If self and other have not diverged, return a list of the revisions
288
        present in other, but missing from self.
289
1534.4.36 by Robert Collins
Finish deprecating Branch.working_tree()
290
        >>> from bzrlib.workingtree import WorkingTree
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
291
        >>> bzrlib.trace.silent = True
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
292
        >>> d1 = bzrdir.ScratchDir()
293
        >>> br1 = d1.open_branch()
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
294
        >>> wt1 = d1.open_workingtree()
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
295
        >>> d2 = bzrdir.ScratchDir()
296
        >>> br2 = d2.open_branch()
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
297
        >>> wt2 = d2.open_workingtree()
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
298
        >>> br1.missing_revisions(br2)
299
        []
1534.4.36 by Robert Collins
Finish deprecating Branch.working_tree()
300
        >>> wt2.commit("lala!", rev_id="REVISION-ID-1")
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
301
        >>> br1.missing_revisions(br2)
302
        [u'REVISION-ID-1']
303
        >>> br2.missing_revisions(br1)
304
        []
1534.4.36 by Robert Collins
Finish deprecating Branch.working_tree()
305
        >>> wt1.commit("lala!", rev_id="REVISION-ID-1")
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
306
        >>> br1.missing_revisions(br2)
307
        []
1534.4.36 by Robert Collins
Finish deprecating Branch.working_tree()
308
        >>> wt2.commit("lala!", rev_id="REVISION-ID-2A")
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
309
        >>> br1.missing_revisions(br2)
310
        [u'REVISION-ID-2A']
1534.4.36 by Robert Collins
Finish deprecating Branch.working_tree()
311
        >>> wt1.commit("lala!", rev_id="REVISION-ID-2B")
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
312
        >>> br1.missing_revisions(br2)
313
        Traceback (most recent call last):
1185.56.1 by Michael Ellerman
Simplify handling of DivergedBranches in cmd_pull()
314
        DivergedBranches: These branches have diverged.  Try merge.
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
315
        """
316
        self_history = self.revision_history()
317
        self_len = len(self_history)
1505.1.21 by John Arbash Meinel
Removing changes for bound branch by invading set-revision-history.
318
        other_history = other.revision_history()
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
319
        other_len = len(other_history)
320
        common_index = min(self_len, other_len) -1
321
        if common_index >= 0 and \
322
            self_history[common_index] != other_history[common_index]:
323
            raise DivergedBranches(self, other)
324
325
        if stop_revision is None:
326
            stop_revision = other_len
327
        else:
328
            assert isinstance(stop_revision, int)
329
            if stop_revision > other_len:
330
                raise bzrlib.errors.NoSuchRevision(self, stop_revision)
331
        return other_history[self_len:stop_revision]
1185.66.1 by Aaron Bentley
Merged from mainline
332
1505.1.21 by John Arbash Meinel
Removing changes for bound branch by invading set-revision-history.
333
    def update_revisions(self, other, stop_revision=None):
1505.1.16 by John Arbash Meinel
[merge] robertc's integration, updated tests to check for retcode=3
334
        """Pull in new perfect-fit revisions.
335
336
        :param other: Another Branch to pull from
337
        :param stop_revision: Updated until the given revision
338
        :return: None
339
        """
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
340
        raise NotImplementedError('update_revisions is abstract')
341
342
    def revision_id_to_revno(self, revision_id):
343
        """Given a revision id, return its revno"""
344
        if revision_id is None:
345
            return 0
346
        history = self.revision_history()
347
        try:
348
            return history.index(revision_id) + 1
349
        except ValueError:
350
            raise bzrlib.errors.NoSuchRevision(self, revision_id)
351
352
    def get_rev_id(self, revno, history=None):
353
        """Find the revision id of the specified revno."""
354
        if revno == 0:
355
            return None
356
        if history is None:
357
            history = self.revision_history()
358
        elif revno <= 0 or revno > len(history):
359
            raise bzrlib.errors.NoSuchRevision(self, revno)
360
        return history[revno - 1]
361
1185.76.1 by Erik BÃ¥gfors
Support for --revision in pull
362
    def pull(self, source, overwrite=False, stop_revision=None):
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
363
        raise NotImplementedError('pull is abstract')
364
365
    def basis_tree(self):
366
        """Return `Tree` object for last revision.
367
368
        If there are no revisions yet, return an `EmptyTree`.
369
        """
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
370
        return self.repository.revision_tree(self.last_revision())
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
371
372
    def rename_one(self, from_rel, to_rel):
373
        """Rename one file.
374
375
        This can change the directory or the filename or both.
376
        """
377
        raise NotImplementedError('rename_one is abstract')
378
379
    def move(self, from_paths, to_name):
380
        """Rename files.
381
382
        to_name must exist as a versioned directory.
383
384
        If to_name exists and is a directory, the files are moved into
385
        it, keeping their old names.  If it is a directory, 
386
387
        Note that to_name is only the last component of the new name;
388
        this doesn't change the directory.
389
390
        This returns a list of (from_path, to_path) pairs for each
391
        entry that is moved.
392
        """
393
        raise NotImplementedError('move is abstract')
394
395
    def get_parent(self):
396
        """Return the parent location of the branch.
397
398
        This is the default location for push/pull/missing.  The usual
399
        pattern is that the user can override it by specifying a
400
        location.
401
        """
402
        raise NotImplementedError('get_parent is abstract')
403
404
    def get_push_location(self):
405
        """Return the None or the location to push this branch to."""
406
        raise NotImplementedError('get_push_location is abstract')
407
408
    def set_push_location(self, location):
409
        """Set a new push location for this branch."""
410
        raise NotImplementedError('set_push_location is abstract')
411
412
    def set_parent(self, url):
413
        raise NotImplementedError('set_parent is abstract')
414
1587.1.10 by Robert Collins
update updates working tree and branch together.
415
    @needs_write_lock
416
    def update(self):
417
        """Synchronise this branch with the master branch if any. 
418
419
        :return: None or the last_revision pivoted out during the update.
420
        """
421
        return None
422
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
423
    def check_revno(self, revno):
424
        """\
425
        Check whether a revno corresponds to any revision.
426
        Zero (the NULL revision) is considered valid.
427
        """
428
        if revno != 0:
429
            self.check_real_revno(revno)
430
            
431
    def check_real_revno(self, revno):
432
        """\
433
        Check whether a revno corresponds to a real revision.
434
        Zero (the NULL revision) is considered invalid
435
        """
436
        if revno < 1 or revno > self.revno():
437
            raise InvalidRevisionNumber(revno)
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
438
439
    @needs_read_lock
440
    def clone(self, *args, **kwargs):
441
        """Clone this branch into to_bzrdir preserving all semantic values.
442
        
443
        revision_id: if not None, the revision history in the new branch will
444
                     be truncated to end with revision_id.
445
        """
446
        # for API compatability, until 0.8 releases we provide the old api:
447
        # def clone(self, to_location, revision=None, basis_branch=None, to_branch_format=None):
448
        # after 0.8 releases, the *args and **kwargs should be changed:
449
        # def clone(self, to_bzrdir, revision_id=None):
450
        if (kwargs.get('to_location', None) or
451
            kwargs.get('revision', None) or
452
            kwargs.get('basis_branch', None) or
453
            (len(args) and isinstance(args[0], basestring))):
454
            # backwards compatability api:
455
            warn("Branch.clone() has been deprecated for BzrDir.clone() from"
456
                 " bzrlib 0.8.", DeprecationWarning, stacklevel=3)
457
            # get basis_branch
458
            if len(args) > 2:
459
                basis_branch = args[2]
460
            else:
461
                basis_branch = kwargs.get('basis_branch', None)
462
            if basis_branch:
463
                basis = basis_branch.bzrdir
464
            else:
465
                basis = None
466
            # get revision
467
            if len(args) > 1:
468
                revision_id = args[1]
469
            else:
470
                revision_id = kwargs.get('revision', None)
471
            # get location
472
            if len(args):
473
                url = args[0]
474
            else:
475
                # no default to raise if not provided.
476
                url = kwargs.get('to_location')
477
            return self.bzrdir.clone(url,
478
                                     revision_id=revision_id,
479
                                     basis=basis).open_branch()
480
        # new cleaner api.
481
        # generate args by hand 
482
        if len(args) > 1:
483
            revision_id = args[1]
484
        else:
485
            revision_id = kwargs.get('revision_id', None)
486
        if len(args):
487
            to_bzrdir = args[0]
488
        else:
489
            # no default to raise if not provided.
490
            to_bzrdir = kwargs.get('to_bzrdir')
491
        result = self._format.initialize(to_bzrdir)
492
        self.copy_content_into(result, revision_id=revision_id)
493
        return  result
494
495
    @needs_read_lock
496
    def sprout(self, to_bzrdir, revision_id=None):
497
        """Create a new line of development from the branch, into to_bzrdir.
498
        
499
        revision_id: if not None, the revision history in the new branch will
500
                     be truncated to end with revision_id.
501
        """
502
        result = self._format.initialize(to_bzrdir)
503
        self.copy_content_into(result, revision_id=revision_id)
504
        result.set_parent(self.bzrdir.root_transport.base)
505
        return result
506
507
    @needs_read_lock
508
    def copy_content_into(self, destination, revision_id=None):
509
        """Copy the content of self into destination.
510
511
        revision_id: if not None, the revision history in the new branch will
512
                     be truncated to end with revision_id.
513
        """
514
        new_history = self.revision_history()
515
        if revision_id is not None:
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
516
            try:
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
517
                new_history = new_history[:new_history.index(revision_id) + 1]
518
            except ValueError:
519
                rev = self.repository.get_revision(revision_id)
520
                new_history = rev.get_history(self.repository)[1:]
521
        destination.set_revision_history(new_history)
522
        parent = self.get_parent()
523
        if parent:
524
            destination.set_parent(parent)
1185.66.1 by Aaron Bentley
Merged from mainline
525
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
526
527
class BranchFormat(object):
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
528
    """An encapsulation of the initialization and open routines for a format.
529
530
    Formats provide three things:
531
     * An initialization routine,
532
     * a format string,
533
     * an open routine.
534
535
    Formats are placed in an dict by their format string for reference 
536
    during branch opening. Its not required that these be instances, they
537
    can be classes themselves with class methods - it simply depends on 
538
    whether state is needed for a given format or not.
539
540
    Once a format is deprecated, just deprecate the initialize and open
541
    methods on the format class. Do not deprecate the object, as the 
542
    object will be created every time regardless.
543
    """
544
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
545
    _default_format = None
546
    """The default format used for new branches."""
547
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
548
    _formats = {}
549
    """The known formats."""
550
551
    @classmethod
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
552
    def find_format(klass, a_bzrdir):
553
        """Return the format for the branch object in a_bzrdir."""
554
        try:
555
            transport = a_bzrdir.get_branch_transport(None)
556
            format_string = transport.get("format").read()
557
            return klass._formats[format_string]
558
        except NoSuchFile:
559
            raise NotBranchError(path=transport.base)
560
        except KeyError:
561
            raise errors.UnknownFormatError(format_string)
562
563
    @classmethod
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
564
    def get_default_format(klass):
565
        """Return the current default format."""
566
        return klass._default_format
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
567
568
    def get_format_string(self):
569
        """Return the ASCII format string that identifies this format."""
570
        raise NotImplementedError(self.get_format_string)
571
1624.3.19 by Olaf Conradi
New call get_format_description to give a user-friendly description of a
572
    def get_format_description(self):
573
        """Return the short format description for this format."""
574
        raise NotImplementedError(self.get_format_string)
575
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
576
    def initialize(self, a_bzrdir):
577
        """Create a branch of this format in a_bzrdir."""
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
578
        raise NotImplementedError(self.initialized)
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
579
1534.4.7 by Robert Collins
Move downlevel check up to the Branch.open logic, removing it from the Branch constructor and deprecating relax_version_check to the same.
580
    def is_supported(self):
581
        """Is this format supported?
582
583
        Supported formats can be initialized and opened.
584
        Unsupported formats may not support initialization or committing or 
585
        some other features depending on the reason for not being supported.
586
        """
587
        return True
588
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
589
    def open(self, a_bzrdir, _found=False):
590
        """Return the branch object for a_bzrdir
591
592
        _found is a private parameter, do not use it. It is used to indicate
593
               if format probing has already be done.
594
        """
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
595
        raise NotImplementedError(self.open)
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
596
597
    @classmethod
598
    def register_format(klass, format):
599
        klass._formats[format.get_format_string()] = format
600
1534.4.7 by Robert Collins
Move downlevel check up to the Branch.open logic, removing it from the Branch constructor and deprecating relax_version_check to the same.
601
    @classmethod
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
602
    def set_default_format(klass, format):
603
        klass._default_format = format
604
605
    @classmethod
1534.4.7 by Robert Collins
Move downlevel check up to the Branch.open logic, removing it from the Branch constructor and deprecating relax_version_check to the same.
606
    def unregister_format(klass, format):
607
        assert klass._formats[format.get_format_string()] is format
608
        del klass._formats[format.get_format_string()]
609
1553.4.8 by Michael Ellerman
Define __str__ for BranchFormat, just return the format string with the
610
    def __str__(self):
611
        return self.get_format_string().rstrip()
612
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
613
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
614
class BzrBranchFormat4(BranchFormat):
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
615
    """Bzr branch format 4.
616
617
    This format has:
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
618
     - a revision-history file.
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
619
     - a branch-lock lock file [ to be shared with the bzrdir ]
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
620
    """
621
1624.3.19 by Olaf Conradi
New call get_format_description to give a user-friendly description of a
622
    def get_format_description(self):
623
        """See BranchFormat.get_format_description()."""
624
        return "Branch format 4"
625
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
626
    def initialize(self, a_bzrdir):
627
        """Create a branch of this format in a_bzrdir."""
628
        mutter('creating branch in %s', a_bzrdir.transport.base)
629
        branch_transport = a_bzrdir.get_branch_transport(self)
630
        utf8_files = [('revision-history', ''),
631
                      ('branch-name', ''),
632
                      ]
1553.5.63 by Martin Pool
Lock type is now mandatory for LockableFiles constructor
633
        control_files = LockableFiles(branch_transport, 'branch-lock',
634
                                      TransportLock)
635
        control_files.create_lock()
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
636
        control_files.lock_write()
637
        try:
638
            for file, content in utf8_files:
639
                control_files.put_utf8(file, content)
640
        finally:
641
            control_files.unlock()
642
        return self.open(a_bzrdir, _found=True)
643
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
644
    def __init__(self):
645
        super(BzrBranchFormat4, self).__init__()
646
        self._matchingbzrdir = bzrdir.BzrDirFormat6()
647
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
648
    def open(self, a_bzrdir, _found=False):
649
        """Return the branch object for a_bzrdir
650
651
        _found is a private parameter, do not use it. It is used to indicate
652
               if format probing has already be done.
653
        """
654
        if not _found:
655
            # we are being called directly and must probe.
656
            raise NotImplementedError
657
        return BzrBranch(_format=self,
1534.5.3 by Robert Collins
Make format 4/5/6 branches share a single LockableFiles instance across wt/branch/repository.
658
                         _control_files=a_bzrdir._control_files,
1534.6.4 by Robert Collins
Creating or opening a branch will use the repository if the format supports that.
659
                         a_bzrdir=a_bzrdir,
660
                         _repository=a_bzrdir.open_repository())
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
661
1553.4.8 by Michael Ellerman
Define __str__ for BranchFormat, just return the format string with the
662
    def __str__(self):
663
        return "Bazaar-NG branch format 4"
664
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
665
666
class BzrBranchFormat5(BranchFormat):
667
    """Bzr branch format 5.
668
669
    This format has:
670
     - a revision-history file.
671
     - a format string
1553.5.71 by Martin Pool
Change branch format 5 to use LockDirs, not transport locks
672
     - a lock dir guarding the branch itself
673
     - all of this stored in a branch/ subdirectory
1534.6.4 by Robert Collins
Creating or opening a branch will use the repository if the format supports that.
674
     - works with shared repositories.
1553.5.71 by Martin Pool
Change branch format 5 to use LockDirs, not transport locks
675
676
    This format is new in bzr 0.8.
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
677
    """
678
679
    def get_format_string(self):
680
        """See BranchFormat.get_format_string()."""
681
        return "Bazaar-NG branch format 5\n"
1624.3.19 by Olaf Conradi
New call get_format_description to give a user-friendly description of a
682
683
    def get_format_description(self):
684
        """See BranchFormat.get_format_description()."""
685
        return "Branch format 5"
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
686
        
687
    def initialize(self, a_bzrdir):
688
        """Create a branch of this format in a_bzrdir."""
1553.5.71 by Martin Pool
Change branch format 5 to use LockDirs, not transport locks
689
        mutter('creating branch %r in %s', self, a_bzrdir.transport.base)
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
690
        branch_transport = a_bzrdir.get_branch_transport(self)
691
        utf8_files = [('revision-history', ''),
692
                      ('branch-name', ''),
693
                      ]
1553.5.71 by Martin Pool
Change branch format 5 to use LockDirs, not transport locks
694
        control_files = LockableFiles(branch_transport, 'lock', LockDir)
1553.5.63 by Martin Pool
Lock type is now mandatory for LockableFiles constructor
695
        control_files.create_lock()
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
696
        control_files.lock_write()
697
        control_files.put_utf8('format', self.get_format_string())
698
        try:
699
            for file, content in utf8_files:
700
                control_files.put_utf8(file, content)
701
        finally:
702
            control_files.unlock()
703
        return self.open(a_bzrdir, _found=True, )
704
705
    def __init__(self):
706
        super(BzrBranchFormat5, self).__init__()
707
        self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
708
709
    def open(self, a_bzrdir, _found=False):
710
        """Return the branch object for a_bzrdir
711
712
        _found is a private parameter, do not use it. It is used to indicate
713
               if format probing has already be done.
714
        """
715
        if not _found:
716
            format = BranchFormat.find_format(a_bzrdir)
717
            assert format.__class__ == self.__class__
718
        transport = a_bzrdir.get_branch_transport(None)
1553.5.71 by Martin Pool
Change branch format 5 to use LockDirs, not transport locks
719
        control_files = LockableFiles(transport, 'lock', LockDir)
1587.1.6 by Robert Collins
Update bound branch implementation to 0.8.
720
        return BzrBranch5(_format=self,
721
                          _control_files=control_files,
722
                          a_bzrdir=a_bzrdir,
723
                          _repository=a_bzrdir.find_repository())
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
724
1587.1.14 by Robert Collins
Make bound branch creation happen via 'checkout'
725
    def __str__(self):
726
        return "Bazaar-NG Metadir branch format 5"
727
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
728
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
729
class BranchReferenceFormat(BranchFormat):
730
    """Bzr branch reference format.
731
732
    Branch references are used in implementing checkouts, they
733
    act as an alias to the real branch which is at some other url.
734
735
    This format has:
736
     - A location file
737
     - a format string
738
    """
739
740
    def get_format_string(self):
741
        """See BranchFormat.get_format_string()."""
742
        return "Bazaar-NG Branch Reference Format 1\n"
1624.3.19 by Olaf Conradi
New call get_format_description to give a user-friendly description of a
743
744
    def get_format_description(self):
745
        """See BranchFormat.get_format_description()."""
746
        return "Checkout reference format 1"
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
747
        
748
    def initialize(self, a_bzrdir, target_branch=None):
749
        """Create a branch of this format in a_bzrdir."""
750
        if target_branch is None:
751
            # this format does not implement branch itself, thus the implicit
752
            # creation contract must see it as uninitializable
753
            raise errors.UninitializableFormat(self)
754
        mutter('creating branch reference in %s', a_bzrdir.transport.base)
755
        branch_transport = a_bzrdir.get_branch_transport(self)
756
        # FIXME rbc 20060209 one j-a-ms encoding branch lands this str() cast is not needed.
757
        branch_transport.put('location', StringIO(str(target_branch.bzrdir.root_transport.base)))
758
        branch_transport.put('format', StringIO(self.get_format_string()))
759
        return self.open(a_bzrdir, _found=True)
760
761
    def __init__(self):
762
        super(BranchReferenceFormat, self).__init__()
763
        self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
764
765
    def _make_reference_clone_function(format, a_branch):
766
        """Create a clone() routine for a branch dynamically."""
767
        def clone(to_bzrdir, revision_id=None):
768
            """See Branch.clone()."""
769
            return format.initialize(to_bzrdir, a_branch)
770
            # cannot obey revision_id limits when cloning a reference ...
771
            # FIXME RBC 20060210 either nuke revision_id for clone, or
772
            # emit some sort of warning/error to the caller ?!
773
        return clone
774
775
    def open(self, a_bzrdir, _found=False):
776
        """Return the branch that the branch reference in a_bzrdir points at.
777
778
        _found is a private parameter, do not use it. It is used to indicate
779
               if format probing has already be done.
780
        """
781
        if not _found:
782
            format = BranchFormat.find_format(a_bzrdir)
783
            assert format.__class__ == self.__class__
784
        transport = a_bzrdir.get_branch_transport(None)
785
        real_bzrdir = bzrdir.BzrDir.open(transport.get('location').read())
786
        result = real_bzrdir.open_branch()
787
        # this changes the behaviour of result.clone to create a new reference
788
        # rather than a copy of the content of the branch.
789
        # I did not use a proxy object because that needs much more extensive
790
        # testing, and we are only changing one behaviour at the moment.
791
        # If we decide to alter more behaviours - i.e. the implicit nickname
792
        # then this should be refactored to introduce a tested proxy branch
793
        # and a subclass of that for use in overriding clone() and ....
794
        # - RBC 20060210
795
        result.clone = self._make_reference_clone_function(result)
796
        return result
797
798
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
799
# formats which have no format string are not discoverable
800
# and not independently creatable, so are not registered.
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
801
__default_format = BzrBranchFormat5()
802
BranchFormat.register_format(__default_format)
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
803
BranchFormat.register_format(BranchReferenceFormat())
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
804
BranchFormat.set_default_format(__default_format)
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
805
_legacy_formats = [BzrBranchFormat4(),
806
                   ]
1534.4.5 by Robert Collins
Turn branch format.open into a factory.
807
1495.1.5 by Jelmer Vernooij
Rename NativeBranch -> BzrBranch
808
class BzrBranch(Branch):
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
809
    """A branch stored in the actual filesystem.
810
811
    Note that it's "local" in the context of the filesystem; it doesn't
812
    really matter if it's on an nfs/smb/afs/coda/... share, as long as
813
    it's writable, and can be accessed via the normal filesystem API.
1 by mbp at sourcefrog
import from baz patch-364
814
    """
353 by Martin Pool
- Per-branch locks in read and write modes.
815
    
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
816
    def __init__(self, transport=DEPRECATED_PARAMETER, init=DEPRECATED_PARAMETER,
1534.4.32 by Robert Collins
Rename deprecated_nonce to DEPRECATED_PARAMETER
817
                 relax_version_check=DEPRECATED_PARAMETER, _format=None,
1534.6.4 by Robert Collins
Creating or opening a branch will use the repository if the format supports that.
818
                 _control_files=None, a_bzrdir=None, _repository=None):
1 by mbp at sourcefrog
import from baz patch-364
819
        """Create new branch object at a particular location.
820
907.1.2 by John Arbash Meinel
Working on making Branch() do all of it's work over a Transport.
821
        transport -- A Transport object, defining how to access files.
62 by mbp at sourcefrog
- new find_branch_root function; based on suggestion from aaron
822
        
254 by Martin Pool
- Doc cleanups from Magnus Therning
823
        init -- If True, create new control files in a previously
1 by mbp at sourcefrog
import from baz patch-364
824
             unversioned directory.  If False, the branch must already
825
             be versioned.
826
1293 by Martin Pool
- add Branch constructor option to relax version check
827
        relax_version_check -- If true, the usual check for the branch
828
            version is not applied.  This is intended only for
829
            upgrade/recovery type use; it's not guaranteed that
830
            all operations will work on old format branches.
1 by mbp at sourcefrog
import from baz patch-364
831
        """
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
832
        if a_bzrdir is None:
833
            self.bzrdir = bzrdir.BzrDir.open(transport.base)
834
        else:
835
            self.bzrdir = a_bzrdir
836
        self._transport = self.bzrdir.transport.clone('..')
1534.4.28 by Robert Collins
first cut at merge from integration.
837
        self._base = self._transport.base
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
838
        self._format = _format
1534.4.28 by Robert Collins
first cut at merge from integration.
839
        if _control_files is None:
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
840
            raise BzrBadParameterMissing('_control_files')
1534.4.28 by Robert Collins
first cut at merge from integration.
841
        self.control_files = _control_files
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
842
        if deprecated_passed(init):
843
            warn("BzrBranch.__init__(..., init=XXX): The init parameter is "
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
844
                 "deprecated as of bzr 0.8. Please use Branch.create().",
845
                 DeprecationWarning,
846
                 stacklevel=2)
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
847
            if init:
848
                # this is slower than before deprecation, oh well never mind.
849
                # -> its deprecated.
850
                self._initialize(transport.base)
1534.4.28 by Robert Collins
first cut at merge from integration.
851
        self._check_format(_format)
1534.4.7 by Robert Collins
Move downlevel check up to the Branch.open logic, removing it from the Branch constructor and deprecating relax_version_check to the same.
852
        if deprecated_passed(relax_version_check):
853
            warn("BzrBranch.__init__(..., relax_version_check=XXX_: The "
854
                 "relax_version_check parameter is deprecated as of bzr 0.8. "
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
855
                 "Please use BzrDir.open_downlevel, or a BzrBranchFormat's "
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
856
                 "open() method.",
857
                 DeprecationWarning,
858
                 stacklevel=2)
1534.4.7 by Robert Collins
Move downlevel check up to the Branch.open logic, removing it from the Branch constructor and deprecating relax_version_check to the same.
859
            if (not relax_version_check
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
860
                and not self._format.is_supported()):
1534.4.7 by Robert Collins
Move downlevel check up to the Branch.open logic, removing it from the Branch constructor and deprecating relax_version_check to the same.
861
                raise errors.UnsupportedFormatError(
862
                        'sorry, branch format %r not supported' % fmt,
863
                        ['use a different bzr version',
864
                         'or remove the .bzr directory'
865
                         ' and "bzr init" again'])
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
866
        if deprecated_passed(transport):
867
            warn("BzrBranch.__init__(transport=XXX...): The transport "
868
                 "parameter is deprecated as of bzr 0.8. "
869
                 "Please use Branch.open, or bzrdir.open_branch().",
870
                 DeprecationWarning,
871
                 stacklevel=2)
1534.6.4 by Robert Collins
Creating or opening a branch will use the repository if the format supports that.
872
        self.repository = _repository
1534.4.1 by Robert Collins
Allow parameterisation of the branch initialisation for bzrlib.
873
1 by mbp at sourcefrog
import from baz patch-364
874
    def __str__(self):
1185.65.11 by Robert Collins
Disable inheritance for getting at LockableFiles, rather use composition.
875
        return '%s(%r)' % (self.__class__.__name__, self.base)
1 by mbp at sourcefrog
import from baz patch-364
876
877
    __repr__ = __str__
878
578 by Martin Pool
- start to move toward Branch.lock and unlock methods,
879
    def __del__(self):
907.1.23 by John Arbash Meinel
Branch objects now automatically create Cached stores if the protocol is_remote.
880
        # TODO: It might be best to do this somewhere else,
881
        # but it is nice for a Branch object to automatically
882
        # cache it's information.
883
        # Alternatively, we could have the Transport objects cache requests
884
        # See the earlier discussion about how major objects (like Branch)
885
        # should never expect their __del__ function to run.
1185.70.6 by Martin Pool
review fixups from John
886
        # XXX: cache_root seems to be unused, 2006-01-13 mbp
1185.11.9 by John Arbash Meinel
Most tests pass, some problems with unavailable socket recv
887
        if hasattr(self, 'cache_root') and self.cache_root is not None:
907.1.23 by John Arbash Meinel
Branch objects now automatically create Cached stores if the protocol is_remote.
888
            try:
889
                shutil.rmtree(self.cache_root)
890
            except:
891
                pass
892
            self.cache_root = None
893
907.1.17 by John Arbash Meinel
Adding a Branch.base property, removing pull_loc()
894
    def _get_base(self):
1185.69.2 by John Arbash Meinel
Changed LockableFiles to take the root directory directly. Moved mode information into LockableFiles instead of Branch
895
        return self._base
907.1.17 by John Arbash Meinel
Adding a Branch.base property, removing pull_loc()
896
1442.1.5 by Robert Collins
Give branch.base a docstring.
897
    base = property(_get_base, doc="The URL for the root of this branch.")
578 by Martin Pool
- start to move toward Branch.lock and unlock methods,
898
1417.1.6 by Robert Collins
introduce transactions for grouping actions done to and with branches
899
    def _finish_transaction(self):
900
        """Exit the current transaction."""
1185.65.13 by Robert Collins
Merge from integration
901
        return self.control_files._finish_transaction()
1417.1.6 by Robert Collins
introduce transactions for grouping actions done to and with branches
902
903
    def get_transaction(self):
1185.65.13 by Robert Collins
Merge from integration
904
        """Return the current active transaction.
905
906
        If no transaction is active, this returns a passthrough object
907
        for which all data is immediately flushed and no caching happens.
908
        """
909
        # this is an explicit function so that we can do tricky stuff
910
        # when the storage in rev_storage is elsewhere.
911
        # we probably need to hook the two 'lock a location' and 
912
        # 'have a transaction' together more delicately, so that
913
        # we can have two locks (branch and storage) and one transaction
914
        # ... and finishing the transaction unlocks both, but unlocking
915
        # does not. - RBC 20051121
916
        return self.control_files.get_transaction()
917
918
    def _set_transaction(self, transaction):
1417.1.6 by Robert Collins
introduce transactions for grouping actions done to and with branches
919
        """Set a new active transaction."""
1185.65.13 by Robert Collins
Merge from integration
920
        return self.control_files._set_transaction(transaction)
353 by Martin Pool
- Per-branch locks in read and write modes.
921
67 by mbp at sourcefrog
use abspath() for the function that makes an absolute
922
    def abspath(self, name):
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
923
        """See Branch.abspath."""
1185.65.11 by Robert Collins
Disable inheritance for getting at LockableFiles, rather use composition.
924
        return self.control_files._transport.abspath(name)
1185.58.4 by John Arbash Meinel
Added permission checking to Branch, and propogated that change into the stores.
925
1534.4.7 by Robert Collins
Move downlevel check up to the Branch.open logic, removing it from the Branch constructor and deprecating relax_version_check to the same.
926
    def _check_format(self, format):
1534.4.8 by Robert Collins
Unfuck upgrade.
927
        """Identify the branch format if needed.
1 by mbp at sourcefrog
import from baz patch-364
928
1534.4.8 by Robert Collins
Unfuck upgrade.
929
        The format is stored as a reference to the format object in
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
930
        self._format for code that needs to check it later.
1 by mbp at sourcefrog
import from baz patch-364
931
1534.4.5 by Robert Collins
Turn branch format.open into a factory.
932
        The format parameter is either None or the branch format class
933
        used to open this branch.
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
934
935
        FIXME: DELETE THIS METHOD when pre 0.8 support is removed.
163 by mbp at sourcefrog
merge win32 portability fixes
936
        """
1534.4.5 by Robert Collins
Turn branch format.open into a factory.
937
        if format is None:
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
938
            format = BzrBranchFormat.find_format(self.bzrdir)
939
        self._format = format
940
        mutter("got branch format %s", self._format)
907.1.2 by John Arbash Meinel
Working on making Branch() do all of it's work over a Transport.
941
1508.1.15 by Robert Collins
Merge from mpool.
942
    @needs_read_lock
909 by Martin Pool
- merge John's code to give the tree root an explicit file id
943
    def get_root_id(self):
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
944
        """See Branch.get_root_id."""
1534.4.28 by Robert Collins
first cut at merge from integration.
945
        tree = self.repository.revision_tree(self.last_revision())
946
        return tree.inventory.root.file_id
1 by mbp at sourcefrog
import from baz patch-364
947
1624.3.34 by Olaf Conradi
Add initial support for showing locking information in bzr info.
948
    def is_locked(self):
949
        return self.control_files.is_locked()
950
1185.65.3 by Aaron Bentley
Fixed locking-- all tests pass
951
    def lock_write(self):
1185.65.11 by Robert Collins
Disable inheritance for getting at LockableFiles, rather use composition.
952
        # TODO: test for failed two phase locks. This is known broken.
953
        self.control_files.lock_write()
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
954
        self.repository.lock_write()
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
955
1185.65.3 by Aaron Bentley
Fixed locking-- all tests pass
956
    def lock_read(self):
1185.65.11 by Robert Collins
Disable inheritance for getting at LockableFiles, rather use composition.
957
        # TODO: test for failed two phase locks. This is known broken.
958
        self.control_files.lock_read()
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
959
        self.repository.lock_read()
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
960
961
    def unlock(self):
1185.65.11 by Robert Collins
Disable inheritance for getting at LockableFiles, rather use composition.
962
        # TODO: test for failed two phase locks. This is known broken.
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
963
        self.repository.unlock()
1185.65.11 by Robert Collins
Disable inheritance for getting at LockableFiles, rather use composition.
964
        self.control_files.unlock()
1587.1.6 by Robert Collins
Update bound branch implementation to 0.8.
965
        
1185.70.3 by Martin Pool
Various updates to make storage branch mergeable:
966
    def peek_lock_mode(self):
967
        if self.control_files._lock_count == 0:
968
            return None
969
        else:
970
            return self.control_files._lock_mode
971
1624.3.36 by Olaf Conradi
Rename is_transport_locked() to get_physical_lock_status() as the
972
    def get_physical_lock_status(self):
973
        return self.control_files.get_physical_lock_status()
974
1442.1.63 by Robert Collins
Remove self.lock_*...finally: self.unlock() dead chickens from branch.py.
975
    @needs_read_lock
1185.50.9 by John Arbash Meinel
[bug 3632] Matthieu Moy- bzr cat should default to last revision
976
    def print_file(self, file, revision_id):
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
977
        """See Branch.print_file."""
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
978
        return self.repository.print_file(file, revision_id)
1442.1.63 by Robert Collins
Remove self.lock_*...finally: self.unlock() dead chickens from branch.py.
979
980
    @needs_write_lock
905 by Martin Pool
- merge aaron's append_multiple.patch
981
    def append_revision(self, *revision_ids):
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
982
        """See Branch.append_revision."""
905 by Martin Pool
- merge aaron's append_multiple.patch
983
        for revision_id in revision_ids:
984
            mutter("add {%s} to revision-history" % revision_id)
1442.1.63 by Robert Collins
Remove self.lock_*...finally: self.unlock() dead chickens from branch.py.
985
        rev_history = self.revision_history()
986
        rev_history.extend(revision_ids)
1442.1.68 by Robert Collins
'bzr pull' now accepts '--clobber'.
987
        self.set_revision_history(rev_history)
988
989
    @needs_write_lock
990
    def set_revision_history(self, rev_history):
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
991
        """See Branch.set_revision_history."""
1185.65.12 by Robert Collins
Remove the only-used-once put_controlfiles, and change put_controlfile to put and put_utf8.
992
        self.control_files.put_utf8(
1185.65.11 by Robert Collins
Disable inheritance for getting at LockableFiles, rather use composition.
993
            'revision-history', '\n'.join(rev_history))
1563.2.34 by Robert Collins
Remove the commit and rollback transaction methods as misleading, and implement a WriteTransaction
994
        transaction = self.get_transaction()
995
        history = transaction.map.find_revision_history()
996
        if history is not None:
997
            # update the revision history in the identity map.
998
            history[:] = list(rev_history)
999
            # this call is disabled because revision_history is 
1000
            # not really an object yet, and the transaction is for objects.
1001
            # transaction.register_dirty(history)
1002
        else:
1003
            transaction.map.add_revision_history(rev_history)
1004
            # this call is disabled because revision_history is 
1005
            # not really an object yet, and the transaction is for objects.
1006
            # transaction.register_clean(history)
233 by mbp at sourcefrog
- more output from test.sh
1007
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
1008
    def get_revision_delta(self, revno):
1009
        """Return the delta for one revision.
1010
1011
        The delta is relative to its mainline predecessor, or the
1012
        empty tree for revision 1.
1013
        """
1014
        assert isinstance(revno, int)
1015
        rh = self.revision_history()
1016
        if not (1 <= revno <= len(rh)):
1017
            raise InvalidRevisionNumber(revno)
1018
1019
        # revno is 1-based; list is 0-based
1020
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
1021
        new_tree = self.repository.revision_tree(rh[revno-1])
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
1022
        if revno == 1:
1023
            old_tree = EmptyTree()
1024
        else:
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
1025
            old_tree = self.repository.revision_tree(rh[revno-2])
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
1026
        return compare_trees(old_tree, new_tree)
1027
1442.1.63 by Robert Collins
Remove self.lock_*...finally: self.unlock() dead chickens from branch.py.
1028
    @needs_read_lock
1 by mbp at sourcefrog
import from baz patch-364
1029
    def revision_history(self):
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
1030
        """See Branch.revision_history."""
1442.1.63 by Robert Collins
Remove self.lock_*...finally: self.unlock() dead chickens from branch.py.
1031
        transaction = self.get_transaction()
1032
        history = transaction.map.find_revision_history()
1033
        if history is not None:
1034
            mutter("cache hit for revision-history in %s", self)
1417.1.12 by Robert Collins
cache revision history during read transactions
1035
            return list(history)
1442.1.63 by Robert Collins
Remove self.lock_*...finally: self.unlock() dead chickens from branch.py.
1036
        history = [l.rstrip('\r\n') for l in
1185.65.29 by Robert Collins
Implement final review suggestions.
1037
                self.control_files.get_utf8('revision-history').readlines()]
1442.1.63 by Robert Collins
Remove self.lock_*...finally: self.unlock() dead chickens from branch.py.
1038
        transaction.map.add_revision_history(history)
1039
        # this call is disabled because revision_history is 
1040
        # not really an object yet, and the transaction is for objects.
1041
        # transaction.register_clean(history, precious=True)
1042
        return list(history)
1 by mbp at sourcefrog
import from baz patch-364
1043
1649.1.1 by Robert Collins
* 'pull' and 'push' now normalise the revision history, so that any two
1044
    @needs_write_lock
1505.1.21 by John Arbash Meinel
Removing changes for bound branch by invading set-revision-history.
1045
    def update_revisions(self, other, stop_revision=None):
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
1046
        """See Branch.update_revisions."""
1649.1.1 by Robert Collins
* 'pull' and 'push' now normalise the revision history, so that any two
1047
        other.lock_read()
1048
        try:
1049
            if stop_revision is None:
1050
                stop_revision = other.last_revision()
1051
                if stop_revision is None:
1052
                    # if there are no commits, we're done.
1053
                    return
1054
            # whats the current last revision, before we fetch [and change it
1055
            # possibly]
1056
            last_rev = self.last_revision()
1057
            # we fetch here regardless of whether we need to so that we pickup
1058
            # filled in ghosts.
1059
            self.fetch(other, stop_revision)
1060
            my_ancestry = self.repository.get_ancestry(last_rev)
1061
            if stop_revision in my_ancestry:
1062
                # last_revision is a descendant of stop_revision
1063
                return
1064
            # stop_revision must be a descendant of last_revision
1065
            stop_graph = self.repository.get_revision_graph(stop_revision)
1066
            if last_rev is not None and last_rev not in stop_graph:
1067
                # our previous tip is not merged into stop_revision
1068
                raise errors.DivergedBranches(self, other)
1069
            # make a new revision history from the graph
1070
            current_rev_id = stop_revision
1071
            new_history = []
1072
            while current_rev_id not in (None, NULL_REVISION):
1073
                new_history.append(current_rev_id)
1074
                current_rev_id_parents = stop_graph[current_rev_id]
1075
                try:
1076
                    current_rev_id = current_rev_id_parents[0]
1077
                except IndexError:
1078
                    current_rev_id = None
1079
            new_history.reverse()
1080
            self.set_revision_history(new_history)
1081
        finally:
1082
            other.unlock()
1185.12.44 by abentley
Restored branch convergence to bzr pull
1083
1649.1.1 by Robert Collins
* 'pull' and 'push' now normalise the revision history, so that any two
1084
    @deprecated_method(zero_eight)
1505.1.21 by John Arbash Meinel
Removing changes for bound branch by invading set-revision-history.
1085
    def pullable_revisions(self, other, stop_revision):
1649.1.1 by Robert Collins
* 'pull' and 'push' now normalise the revision history, so that any two
1086
        """Please use bzrlib.missing instead."""
1505.1.21 by John Arbash Meinel
Removing changes for bound branch by invading set-revision-history.
1087
        other_revno = other.revision_id_to_revno(stop_revision)
1505.1.10 by John Arbash Meinel
Brought back 'optimized' version, for better errors, cleaned up exception handling.
1088
        try:
1505.1.21 by John Arbash Meinel
Removing changes for bound branch by invading set-revision-history.
1089
            return self.missing_revisions(other, other_revno)
1505.1.10 by John Arbash Meinel
Brought back 'optimized' version, for better errors, cleaned up exception handling.
1090
        except DivergedBranches, e:
1185.12.44 by abentley
Restored branch convergence to bzr pull
1091
            try:
1092
                pullable_revs = get_intervening_revisions(self.last_revision(),
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
1093
                                                          stop_revision, 
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
1094
                                                          self.repository)
1185.12.44 by abentley
Restored branch convergence to bzr pull
1095
                assert self.last_revision() not in pullable_revs
1096
                return pullable_revs
1097
            except bzrlib.errors.NotAncestor:
1098
                if is_ancestor(self.last_revision(), stop_revision, self):
1099
                    return []
1100
                else:
1101
                    raise e
1102
        
1185.33.59 by Martin Pool
[patch] keep a cached basis inventory (Johan Rydberg)
1103
    def basis_tree(self):
1104
        """See Branch.basis_tree."""
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
1105
        return self.repository.revision_tree(self.last_revision())
1185.33.59 by Martin Pool
[patch] keep a cached basis inventory (Johan Rydberg)
1106
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
1107
    @deprecated_method(zero_eight)
1 by mbp at sourcefrog
import from baz patch-364
1108
    def working_tree(self):
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
1109
        """Create a Working tree object for this branch."""
1185.2.2 by Lalo Martins
cleaning up and refactoring the branch module.
1110
        from bzrlib.workingtree import WorkingTree
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
1111
        from bzrlib.transport.local import LocalTransport
1534.4.28 by Robert Collins
first cut at merge from integration.
1112
        if (self.base.find('://') != -1 or 
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
1113
            not isinstance(self._transport, LocalTransport)):
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
1114
            raise NoWorkingTree(self.base)
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
1115
        return self.bzrdir.open_workingtree()
1 by mbp at sourcefrog
import from baz patch-364
1116
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1117
    @needs_write_lock
1185.76.1 by Erik BÃ¥gfors
Support for --revision in pull
1118
    def pull(self, source, overwrite=False, stop_revision=None):
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
1119
        """See Branch.pull."""
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1120
        source.lock_read()
1121
        try:
1185.33.44 by Martin Pool
[patch] show number of revisions pushed/pulled/merged (Robey Pointer)
1122
            old_count = len(self.revision_history())
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1123
            try:
1185.76.1 by Erik BÃ¥gfors
Support for --revision in pull
1124
                self.update_revisions(source,stop_revision)
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1125
            except DivergedBranches:
1126
                if not overwrite:
1127
                    raise
1185.50.5 by John Arbash Meinel
pull --overwrite should always overwrite, not just if diverged. (Test case from Robey Pointer)
1128
            if overwrite:
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1129
                self.set_revision_history(source.revision_history())
1185.33.44 by Martin Pool
[patch] show number of revisions pushed/pulled/merged (Robey Pointer)
1130
            new_count = len(self.revision_history())
1131
            return new_count - old_count
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1132
        finally:
1133
            source.unlock()
1 by mbp at sourcefrog
import from baz patch-364
1134
1149 by Martin Pool
- make get_parent() be a method of Branch; add simple tests for it
1135
    def get_parent(self):
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
1136
        """See Branch.get_parent."""
1149 by Martin Pool
- make get_parent() be a method of Branch; add simple tests for it
1137
        import errno
1138
        _locs = ['parent', 'pull', 'x-pull']
1139
        for l in _locs:
1140
            try:
1185.65.29 by Robert Collins
Implement final review suggestions.
1141
                return self.control_files.get_utf8(l).read().strip('\n')
1185.31.45 by John Arbash Meinel
Refactoring Exceptions found some places where the wrong exception was caught.
1142
            except NoSuchFile:
1143
                pass
1149 by Martin Pool
- make get_parent() be a method of Branch; add simple tests for it
1144
        return None
1145
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1146
    def get_push_location(self):
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
1147
        """See Branch.get_push_location."""
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1148
        config = bzrlib.config.BranchConfig(self)
1149
        push_loc = config.get_user_option('push_location')
1150
        return push_loc
1151
1152
    def set_push_location(self, location):
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
1153
        """See Branch.set_push_location."""
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1154
        config = bzrlib.config.LocationConfig(self.base)
1155
        config.set_user_option('push_location', location)
1156
1442.1.63 by Robert Collins
Remove self.lock_*...finally: self.unlock() dead chickens from branch.py.
1157
    @needs_write_lock
1150 by Martin Pool
- add new Branch.set_parent and tests
1158
    def set_parent(self, url):
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
1159
        """See Branch.set_parent."""
1150 by Martin Pool
- add new Branch.set_parent and tests
1160
        # TODO: Maybe delete old location files?
1185.65.29 by Robert Collins
Implement final review suggestions.
1161
        # URLs should never be unicode, even on the local fs,
1162
        # FIXUP this and get_parent in a future branch format bump:
1163
        # read and rewrite the file, and have the new format code read
1164
        # using .get not .get_utf8. RBC 20060125
1614.2.5 by Olaf Conradi
Added testcase for bzr merge --remember.
1165
        if url is None:
1166
            self.control_files._transport.delete('parent')
1167
        else:
1168
            self.control_files.put_utf8('parent', url + '\n')
1150 by Martin Pool
- add new Branch.set_parent and tests
1169
1185.35.11 by Aaron Bentley
Added support for branch nicks
1170
    def tree_config(self):
1171
        return TreeConfig(self)
1172
1587.1.6 by Robert Collins
Update bound branch implementation to 0.8.
1173
1174
class BzrBranch5(BzrBranch):
1175
    """A format 5 branch. This supports new features over plan branches.
1176
1177
    It has support for a master_branch which is the data for bound branches.
1178
    """
1179
1180
    def __init__(self,
1181
                 _format,
1182
                 _control_files,
1183
                 a_bzrdir,
1184
                 _repository):
1185
        super(BzrBranch5, self).__init__(_format=_format,
1186
                                         _control_files=_control_files,
1187
                                         a_bzrdir=a_bzrdir,
1188
                                         _repository=_repository)
1189
        
1442.1.63 by Robert Collins
Remove self.lock_*...finally: self.unlock() dead chickens from branch.py.
1190
    @needs_write_lock
1587.1.6 by Robert Collins
Update bound branch implementation to 0.8.
1191
    def pull(self, source, overwrite=False, stop_revision=None):
1192
        """Updates branch.pull to be bound branch aware."""
1193
        bound_location = self.get_bound_location()
1194
        if source.base != bound_location:
1195
            # not pulling from master, so we need to update master.
1196
            master_branch = self.get_master_branch()
1197
            if master_branch:
1198
                master_branch.pull(source)
1199
                source = master_branch
1200
        return super(BzrBranch5, self).pull(source, overwrite, stop_revision)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
1201
1505.1.3 by John Arbash Meinel
(broken) Adding more tests, and some functionality
1202
    def get_bound_location(self):
1185.66.8 by Aaron Bentley
Applied Jelmer's patch to make clone a branch operation
1203
        try:
1587.1.6 by Robert Collins
Update bound branch implementation to 0.8.
1204
            return self.control_files.get_utf8('bound').read()[:-1]
1205
        except errors.NoSuchFile:
1505.1.3 by John Arbash Meinel
(broken) Adding more tests, and some functionality
1206
            return None
1185.66.8 by Aaron Bentley
Applied Jelmer's patch to make clone a branch operation
1207
1208
    @needs_read_lock
1505.1.25 by John Arbash Meinel
Updated pull. Now all paths which call set_revision_history maintain the branch invariant. All tests pass.
1209
    def get_master_branch(self):
1505.1.24 by John Arbash Meinel
Updated commit to handle bound branches. Included test to handle commit after merge
1210
        """Return the branch we are bound to.
1211
        
1212
        :return: Either a Branch, or None
1587.1.6 by Robert Collins
Update bound branch implementation to 0.8.
1213
1214
        This could memoise the branch, but if thats done
1215
        it must be revalidated on each new lock.
1216
        So for now we just dont memoise it.
1217
        # RBC 20060304 review this decision.
1505.1.24 by John Arbash Meinel
Updated commit to handle bound branches. Included test to handle commit after merge
1218
        """
1219
        bound_loc = self.get_bound_location()
1220
        if not bound_loc:
1221
            return None
1587.1.6 by Robert Collins
Update bound branch implementation to 0.8.
1222
        try:
1223
            return Branch.open(bound_loc)
1224
        except (errors.NotBranchError, errors.ConnectionError), e:
1225
            raise errors.BoundBranchConnectionFailure(
1226
                    self, bound_loc, e)
1505.1.24 by John Arbash Meinel
Updated commit to handle bound branches. Included test to handle commit after merge
1227
1505.1.3 by John Arbash Meinel
(broken) Adding more tests, and some functionality
1228
    @needs_write_lock
1229
    def set_bound_location(self, location):
1505.1.27 by John Arbash Meinel
Adding tests against an sftp branch.
1230
        """Set the target where this branch is bound to.
1231
1232
        :param location: URL to the target branch
1233
        """
1505.1.25 by John Arbash Meinel
Updated pull. Now all paths which call set_revision_history maintain the branch invariant. All tests pass.
1234
        if location:
1587.1.6 by Robert Collins
Update bound branch implementation to 0.8.
1235
            self.control_files.put_utf8('bound', location+'\n')
1185.64.2 by Goffredo Baroncelli
- implemented some suggestion by Robert Collins
1236
        else:
1505.1.25 by John Arbash Meinel
Updated pull. Now all paths which call set_revision_history maintain the branch invariant. All tests pass.
1237
            try:
1587.1.6 by Robert Collins
Update bound branch implementation to 0.8.
1238
                self.control_files._transport.delete('bound')
1505.1.25 by John Arbash Meinel
Updated pull. Now all paths which call set_revision_history maintain the branch invariant. All tests pass.
1239
            except NoSuchFile:
1240
                return False
1241
            return True
1505.1.3 by John Arbash Meinel
(broken) Adding more tests, and some functionality
1242
1243
    @needs_write_lock
1244
    def bind(self, other):
1245
        """Bind the local branch the other branch.
1246
1247
        :param other: The branch to bind to
1248
        :type other: Branch
1185.64.2 by Goffredo Baroncelli
- implemented some suggestion by Robert Collins
1249
        """
1505.1.24 by John Arbash Meinel
Updated commit to handle bound branches. Included test to handle commit after merge
1250
        # TODO: jam 20051230 Consider checking if the target is bound
1251
        #       It is debatable whether you should be able to bind to
1252
        #       a branch which is itself bound.
1253
        #       Committing is obviously forbidden,
1254
        #       but binding itself may not be.
1255
        #       Since we *have* to check at commit time, we don't
1256
        #       *need* to check here
1587.1.6 by Robert Collins
Update bound branch implementation to 0.8.
1257
        self.pull(other)
1258
1259
        # we are now equal to or a suffix of other.
1505.1.3 by John Arbash Meinel
(broken) Adding more tests, and some functionality
1260
1261
        # Since we have 'pulled' from the remote location,
1262
        # now we should try to pull in the opposite direction
1263
        # in case the local tree has more revisions than the
1264
        # remote one.
1265
        # There may be a different check you could do here
1266
        # rather than actually trying to install revisions remotely.
1267
        # TODO: capture an exception which indicates the remote branch
1268
        #       is not writeable. 
1269
        #       If it is up-to-date, this probably should not be a failure
1587.1.6 by Robert Collins
Update bound branch implementation to 0.8.
1270
        
1271
        # lock other for write so the revision-history syncing cannot race
1272
        other.lock_write()
1273
        try:
1274
            other.pull(self)
1275
            # if this does not error, other now has the same last rev we do
1276
            # it can only error if the pull from other was concurrent with
1277
            # a commit to other from someone else.
1278
1279
            # until we ditch revision-history, we need to sync them up:
1280
            self.set_revision_history(other.revision_history())
1281
            # now other and self are up to date with each other and have the
1282
            # same revision-history.
1283
        finally:
1284
            other.unlock()
1285
1505.1.3 by John Arbash Meinel
(broken) Adding more tests, and some functionality
1286
        self.set_bound_location(other.base)
1505.1.2 by John Arbash Meinel
(broken) working on implementing bound branches.
1287
1505.1.5 by John Arbash Meinel
Added a test for the unbind command.
1288
    @needs_write_lock
1289
    def unbind(self):
1290
        """If bound, unbind"""
1505.1.25 by John Arbash Meinel
Updated pull. Now all paths which call set_revision_history maintain the branch invariant. All tests pass.
1291
        return self.set_bound_location(None)
1185.66.8 by Aaron Bentley
Applied Jelmer's patch to make clone a branch operation
1292
1587.1.10 by Robert Collins
update updates working tree and branch together.
1293
    @needs_write_lock
1294
    def update(self):
1295
        """Synchronise this branch with the master branch if any. 
1296
1297
        :return: None or the last_revision that was pivoted out during the
1298
                 update.
1299
        """
1300
        master = self.get_master_branch()
1301
        if master is not None:
1302
            old_tip = self.last_revision()
1303
            self.pull(master, overwrite=True)
1587.1.11 by Robert Collins
Local commits appear to be working properly.
1304
            if old_tip in self.repository.get_ancestry(self.last_revision()):
1587.1.10 by Robert Collins
update updates working tree and branch together.
1305
                return None
1306
            return old_tip
1307
        return None
1308
1534.4.1 by Robert Collins
Allow parameterisation of the branch initialisation for bzrlib.
1309
1534.4.3 by Robert Collins
Implement BranchTestProviderAdapter, so tests now run across all branch formats.
1310
class BranchTestProviderAdapter(object):
1311
    """A tool to generate a suite testing multiple branch formats at once.
1312
1313
    This is done by copying the test once for each transport and injecting
1314
    the transport_server, transport_readonly_server, and branch_format
1315
    classes into each copy. Each copy is also given a new id() to make it
1316
    easy to identify.
1317
    """
1318
1319
    def __init__(self, transport_server, transport_readonly_server, formats):
1320
        self._transport_server = transport_server
1321
        self._transport_readonly_server = transport_readonly_server
1322
        self._formats = formats
1323
    
1324
    def adapt(self, test):
1325
        result = TestSuite()
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1326
        for branch_format, bzrdir_format in self._formats:
1534.4.3 by Robert Collins
Implement BranchTestProviderAdapter, so tests now run across all branch formats.
1327
            new_test = deepcopy(test)
1328
            new_test.transport_server = self._transport_server
1329
            new_test.transport_readonly_server = self._transport_readonly_server
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1330
            new_test.bzrdir_format = bzrdir_format
1331
            new_test.branch_format = branch_format
1534.4.3 by Robert Collins
Implement BranchTestProviderAdapter, so tests now run across all branch formats.
1332
            def make_new_test_id():
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1333
                new_id = "%s(%s)" % (new_test.id(), branch_format.__class__.__name__)
1534.4.3 by Robert Collins
Implement BranchTestProviderAdapter, so tests now run across all branch formats.
1334
                return lambda: new_id
1335
            new_test.id = make_new_test_id()
1336
            result.addTest(new_test)
1337
        return result
1338
1339
1 by mbp at sourcefrog
import from baz patch-364
1340
######################################################################
1341
# predicates
1342
1343
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1344
@deprecated_function(zero_eight)
1345
def ScratchBranch(*args, **kwargs):
1346
    """See bzrlib.bzrdir.ScratchDir."""
1347
    d = ScratchDir(*args, **kwargs)
1348
    return d.open_branch()
1349
1350
1351
@deprecated_function(zero_eight)
1352
def is_control_file(*args, **kwargs):
1353
    """See bzrlib.workingtree.is_control_file."""
1354
    return bzrlib.workingtree.is_control_file(*args, **kwargs)