/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
70 by mbp at sourcefrog
Prepare for smart recursive add.
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.
7
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.
12
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
26
1 by mbp at sourcefrog
import from baz patch-364
27
28
import bzrlib
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
29
import bzrlib.bzrdir as bzrdir
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
30
from bzrlib.config import TreeConfig
1534.4.28 by Robert Collins
first cut at merge from integration.
31
from bzrlib.decorators import needs_read_lock, needs_write_lock
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
32
from bzrlib.delta import compare_trees
33
import bzrlib.errors as errors
34
from bzrlib.errors import (BzrError, InvalidRevisionNumber, InvalidRevisionId,
35
                           NoSuchRevision, HistoryMissing, NotBranchError,
1534.4.3 by Robert Collins
Implement BranchTestProviderAdapter, so tests now run across all branch formats.
36
                           DivergedBranches, LockError, 
37
                           UninitializableFormat,
38
                           UnlistableStore,
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
39
                           UnlistableBranch, NoSuchFile, NotVersionedError,
40
                           NoWorkingTree)
1185.65.15 by Robert Collins
Merge from integration.
41
import bzrlib.inventory as inventory
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
42
from bzrlib.inventory import Inventory
1185.65.14 by Robert Collins
Merge from aaron. Whee, we are synced. Yay. Begone the foul demons of merge conflicts.
43
from bzrlib.lockable_files import LockableFiles
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
1185.65.14 by Robert Collins
Merge from aaron. Whee, we are synced. Yay. Begone the foul demons of merge conflicts.
53
from bzrlib.revision import (Revision, is_ancestor, get_intervening_revisions)
1393.2.1 by John Arbash Meinel
Merged in split-storage-2 branch. Need to cleanup a little bit more still.
54
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.
55
from bzrlib.symbol_versioning import *
1417.1.6 by Robert Collins
introduce transactions for grouping actions done to and with branches
56
import bzrlib.transactions as transactions
1393.2.4 by John Arbash Meinel
All tests pass.
57
from bzrlib.transport import Transport, get_transport
1185.65.15 by Robert Collins
Merge from integration.
58
from bzrlib.tree import EmptyTree, RevisionTree
1185.65.11 by Robert Collins
Disable inheritance for getting at LockableFiles, rather use composition.
59
import bzrlib.ui
1189 by Martin Pool
- BROKEN: partial support for commit into weave
60
import bzrlib.xml5
1104 by Martin Pool
- Add a simple UIFactory
61
1094 by Martin Pool
- merge aaron's merge improvements 999..1008
62
1186 by Martin Pool
- start implementing v5 format; Branch refuses to operate on old branches
63
BZR_BRANCH_FORMAT_4 = "Bazaar-NG branch, format 0.0.4\n"
64
BZR_BRANCH_FORMAT_5 = "Bazaar-NG branch, format 5\n"
1429 by Robert Collins
merge in niemeyers prefixed-store patch
65
BZR_BRANCH_FORMAT_6 = "Bazaar-NG branch, format 6\n"
1185.70.3 by Martin Pool
Various updates to make storage branch mergeable:
66
67
68
# TODO: Maybe include checks for common corruption of newlines, etc?
1 by mbp at sourcefrog
import from baz patch-364
69
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
70
# TODO: Some operations like log might retrieve the same revisions
71
# repeatedly to calculate deltas.  We could perhaps have a weakref
1223 by Martin Pool
- store inventories in weave
72
# cache in memory to make this faster.  In general anything can be
1185.65.29 by Robert Collins
Implement final review suggestions.
73
# cached in memory between lock and unlock operations. .. nb thats
74
# what the transaction identity map provides
416 by Martin Pool
- bzr log and bzr root now accept an http URL
75
1442.1.63 by Robert Collins
Remove self.lock_*...finally: self.unlock() dead chickens from branch.py.
76
1 by mbp at sourcefrog
import from baz patch-364
77
######################################################################
78
# branch objects
79
558 by Martin Pool
- All top-level classes inherit from object
80
class Branch(object):
1 by mbp at sourcefrog
import from baz patch-364
81
    """Branch holding a history of revisions.
82
343 by Martin Pool
doc
83
    base
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
84
        Base directory/url of the branch.
85
    """
1534.4.1 by Robert Collins
Allow parameterisation of the branch initialisation for bzrlib.
86
    # this is really an instance variable - FIXME move it there
87
    # - RBC 20060112
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
88
    base = None
89
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
90
    @staticmethod
91
    def create(base):
92
        """Construct the current default format branch in a_bzrdir.
93
94
        This creates the current default BzrDir format, and if that 
95
        supports multiple Branch formats, then the default Branch format
96
        will take effect.
97
        """
98
        print "not usable until we have repositories"
99
        raise NotImplementedError("not usable right now")
100
        return bzrdir.BzrDir.create(base)
1534.4.1 by Robert Collins
Allow parameterisation of the branch initialisation for bzrlib.
101
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
102
    def __init__(self, *ignored, **ignored_too):
103
        raise NotImplementedError('The Branch class is abstract')
104
105
    @staticmethod
1393.1.2 by Martin Pool
- better representation in Branch factories of opening old formats
106
    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.
107
        """Open a branch which may be of an old format."""
108
        return Branch.open(base, _unsupported=True)
1393.1.2 by Martin Pool
- better representation in Branch factories of opening old formats
109
        
110
    @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.
111
    def open(base, _unsupported=False):
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
112
        """Open the repository rooted at base.
113
114
        For instance, if the repository is at URL/.bzr/repository,
115
        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.
116
        """
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
117
        control = bzrdir.BzrDir.open(base, _unsupported)
118
        return control.open_branch()
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
119
120
    @staticmethod
1185.2.8 by Lalo Martins
creating the new branch constructors
121
    def open_containing(url):
1185.1.41 by Robert Collins
massive patch from Alexander Belchenko - many PEP8 fixes, removes unused function uuid
122
        """Open an existing branch which contains url.
123
        
124
        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
125
126
        Basically we keep looking up until we find the control directory or
127
        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.
128
        If there is one and it is either an unrecognised format or an unsupported 
129
        format, UnknownFormatError or UnsupportedFormatError are raised.
1442.1.64 by Robert Collins
Branch.open_containing now returns a tuple (Branch, relative-path).
130
        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.
131
        """
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
132
        control, relpath = bzrdir.BzrDir.open_containing(url)
133
        return control.open_branch(), relpath
1534.4.1 by Robert Collins
Allow parameterisation of the branch initialisation for bzrlib.
134
135
    @staticmethod
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
136
    @deprecated_function(zero_eight)
137
    def initialize(base):
138
        """Create a new working tree and branch, rooted at 'base' (url)
139
        """
140
        # imported here to prevent scope creep as this is going.
141
        from bzrlib.workingtree import WorkingTree
142
        return WorkingTree.create_standalone(safe_unicode(base)).branch
143
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
144
    def setup_caching(self, cache_root):
145
        """Subclasses that care about caching should override this, and set
146
        up cached stores located under cache_root.
147
        """
1185.70.6 by Martin Pool
review fixups from John
148
        # seems to be unused, 2006-01-13 mbp
149
        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
150
        self.cache_root = cache_root
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
151
1185.35.11 by Aaron Bentley
Added support for branch nicks
152
    def _get_nick(self):
153
        cfg = self.tree_config()
1530.1.3 by Robert Collins
transport implementations now tested consistently.
154
        return cfg.get_option(u"nickname", default=self.base.split('/')[-2])
1185.35.11 by Aaron Bentley
Added support for branch nicks
155
156
    def _set_nick(self, nick):
157
        cfg = self.tree_config()
158
        cfg.set_option(nick, "nickname")
159
        assert cfg.get_option("nickname") == nick
160
161
    nick = property(_get_nick, _set_nick)
162
        
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
163
    def lock_write(self):
164
        raise NotImplementedError('lock_write is abstract')
165
        
166
    def lock_read(self):
167
        raise NotImplementedError('lock_read is abstract')
168
169
    def unlock(self):
170
        raise NotImplementedError('unlock is abstract')
171
1185.70.3 by Martin Pool
Various updates to make storage branch mergeable:
172
    def peek_lock_mode(self):
173
        """Return lock mode for the Branch: 'r', 'w' or None"""
1185.70.6 by Martin Pool
review fixups from John
174
        raise NotImplementedError(self.peek_lock_mode)
1185.70.3 by Martin Pool
Various updates to make storage branch mergeable:
175
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
176
    def abspath(self, name):
177
        """Return absolute filename for something in the branch
178
        
179
        XXX: Robert Collins 20051017 what is this used for? why is it a branch
180
        method and not a tree method.
181
        """
182
        raise NotImplementedError('abspath is abstract')
183
184
    def get_root_id(self):
185
        """Return the id of this branches root"""
186
        raise NotImplementedError('get_root_id is abstract')
187
1185.50.9 by John Arbash Meinel
[bug 3632] Matthieu Moy- bzr cat should default to last revision
188
    def print_file(self, file, revision_id):
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
189
        """Print `file` to stdout."""
190
        raise NotImplementedError('print_file is abstract')
191
192
    def append_revision(self, *revision_ids):
193
        raise NotImplementedError('append_revision is abstract')
194
195
    def set_revision_history(self, rev_history):
196
        raise NotImplementedError('set_revision_history is abstract')
197
198
    def revision_history(self):
199
        """Return sequence of revision hashes on to this branch."""
200
        raise NotImplementedError('revision_history is abstract')
201
202
    def revno(self):
203
        """Return current revision number for this branch.
204
205
        That is equivalent to the number of revisions committed to
206
        this branch.
207
        """
208
        return len(self.revision_history())
209
210
    def last_revision(self):
211
        """Return last patch hash, or None if no history."""
212
        ph = self.revision_history()
213
        if ph:
214
            return ph[-1]
215
        else:
216
            return None
217
218
    def missing_revisions(self, other, stop_revision=None, diverged_ok=False):
219
        """Return a list of new revisions that would perfectly fit.
220
        
221
        If self and other have not diverged, return a list of the revisions
222
        present in other, but missing from self.
223
1534.4.36 by Robert Collins
Finish deprecating Branch.working_tree()
224
        >>> from bzrlib.workingtree import WorkingTree
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
225
        >>> bzrlib.trace.silent = True
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
226
        >>> d1 = bzrdir.ScratchDir()
227
        >>> br1 = d1.open_branch()
1534.4.36 by Robert Collins
Finish deprecating Branch.working_tree()
228
        >>> wt1 = WorkingTree(br1.base, br1)
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
229
        >>> d2 = bzrdir.ScratchDir()
230
        >>> br2 = d2.open_branch()
1534.4.36 by Robert Collins
Finish deprecating Branch.working_tree()
231
        >>> wt2 = WorkingTree(br2.base, br2)
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
232
        >>> br1.missing_revisions(br2)
233
        []
1534.4.36 by Robert Collins
Finish deprecating Branch.working_tree()
234
        >>> wt2.commit("lala!", rev_id="REVISION-ID-1")
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
235
        >>> br1.missing_revisions(br2)
236
        [u'REVISION-ID-1']
237
        >>> br2.missing_revisions(br1)
238
        []
1534.4.36 by Robert Collins
Finish deprecating Branch.working_tree()
239
        >>> wt1.commit("lala!", rev_id="REVISION-ID-1")
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
240
        >>> br1.missing_revisions(br2)
241
        []
1534.4.36 by Robert Collins
Finish deprecating Branch.working_tree()
242
        >>> wt2.commit("lala!", rev_id="REVISION-ID-2A")
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
243
        >>> br1.missing_revisions(br2)
244
        [u'REVISION-ID-2A']
1534.4.36 by Robert Collins
Finish deprecating Branch.working_tree()
245
        >>> wt1.commit("lala!", rev_id="REVISION-ID-2B")
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
246
        >>> br1.missing_revisions(br2)
247
        Traceback (most recent call last):
1185.56.1 by Michael Ellerman
Simplify handling of DivergedBranches in cmd_pull()
248
        DivergedBranches: These branches have diverged.  Try merge.
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
249
        """
250
        self_history = self.revision_history()
251
        self_len = len(self_history)
252
        other_history = other.revision_history()
253
        other_len = len(other_history)
254
        common_index = min(self_len, other_len) -1
255
        if common_index >= 0 and \
256
            self_history[common_index] != other_history[common_index]:
257
            raise DivergedBranches(self, other)
258
259
        if stop_revision is None:
260
            stop_revision = other_len
261
        else:
262
            assert isinstance(stop_revision, int)
263
            if stop_revision > other_len:
264
                raise bzrlib.errors.NoSuchRevision(self, stop_revision)
265
        return other_history[self_len:stop_revision]
1185.66.1 by Aaron Bentley
Merged from mainline
266
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
267
    def update_revisions(self, other, stop_revision=None):
268
        """Pull in new perfect-fit revisions."""
269
        raise NotImplementedError('update_revisions is abstract')
270
271
    def pullable_revisions(self, other, stop_revision):
272
        raise NotImplementedError('pullable_revisions is abstract')
273
        
274
    def revision_id_to_revno(self, revision_id):
275
        """Given a revision id, return its revno"""
276
        if revision_id is None:
277
            return 0
278
        history = self.revision_history()
279
        try:
280
            return history.index(revision_id) + 1
281
        except ValueError:
282
            raise bzrlib.errors.NoSuchRevision(self, revision_id)
283
284
    def get_rev_id(self, revno, history=None):
285
        """Find the revision id of the specified revno."""
286
        if revno == 0:
287
            return None
288
        if history is None:
289
            history = self.revision_history()
290
        elif revno <= 0 or revno > len(history):
291
            raise bzrlib.errors.NoSuchRevision(self, revno)
292
        return history[revno - 1]
293
294
    def pull(self, source, overwrite=False):
295
        raise NotImplementedError('pull is abstract')
296
297
    def basis_tree(self):
298
        """Return `Tree` object for last revision.
299
300
        If there are no revisions yet, return an `EmptyTree`.
301
        """
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
302
        return self.repository.revision_tree(self.last_revision())
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
303
304
    def rename_one(self, from_rel, to_rel):
305
        """Rename one file.
306
307
        This can change the directory or the filename or both.
308
        """
309
        raise NotImplementedError('rename_one is abstract')
310
311
    def move(self, from_paths, to_name):
312
        """Rename files.
313
314
        to_name must exist as a versioned directory.
315
316
        If to_name exists and is a directory, the files are moved into
317
        it, keeping their old names.  If it is a directory, 
318
319
        Note that to_name is only the last component of the new name;
320
        this doesn't change the directory.
321
322
        This returns a list of (from_path, to_path) pairs for each
323
        entry that is moved.
324
        """
325
        raise NotImplementedError('move is abstract')
326
327
    def get_parent(self):
328
        """Return the parent location of the branch.
329
330
        This is the default location for push/pull/missing.  The usual
331
        pattern is that the user can override it by specifying a
332
        location.
333
        """
334
        raise NotImplementedError('get_parent is abstract')
335
336
    def get_push_location(self):
337
        """Return the None or the location to push this branch to."""
338
        raise NotImplementedError('get_push_location is abstract')
339
340
    def set_push_location(self, location):
341
        """Set a new push location for this branch."""
342
        raise NotImplementedError('set_push_location is abstract')
343
344
    def set_parent(self, url):
345
        raise NotImplementedError('set_parent is abstract')
346
347
    def check_revno(self, revno):
348
        """\
349
        Check whether a revno corresponds to any revision.
350
        Zero (the NULL revision) is considered valid.
351
        """
352
        if revno != 0:
353
            self.check_real_revno(revno)
354
            
355
    def check_real_revno(self, revno):
356
        """\
357
        Check whether a revno corresponds to a real revision.
358
        Zero (the NULL revision) is considered invalid
359
        """
360
        if revno < 1 or revno > self.revno():
361
            raise InvalidRevisionNumber(revno)
362
        
1534.4.34 by Robert Collins
Fix remaining uses of deprecated apis within bzrlib.
363
    def clone(self, to_location, revision=None, basis_branch=None, to_branch_format=None):
1185.66.8 by Aaron Bentley
Applied Jelmer's patch to make clone a branch operation
364
        """Copy this branch into the existing directory to_location.
365
366
        Returns the newly created branch object.
367
368
        revision
369
            If not None, only revisions up to this point will be copied.
370
            The head of the new branch will be that revision.  Must be a
371
            revid or None.
372
    
373
        to_location -- The destination directory; must either exist and be 
374
            empty, or not exist, in which case it is created.
375
    
376
        basis_branch
377
            A local branch to copy revisions from, related to this branch. 
378
            This is used when branching from a remote (slow) branch, and we have
379
            a local branch that might contain some relevant revisions.
380
    
381
        to_branch_type
382
            Branch type of destination branch
383
        """
1534.4.28 by Robert Collins
first cut at merge from integration.
384
        from bzrlib.workingtree import WorkingTree
1185.66.8 by Aaron Bentley
Applied Jelmer's patch to make clone a branch operation
385
        assert isinstance(to_location, basestring)
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
386
        segments = to_location.split('/')
387
        if segments and segments[-1] not in ('', '.'):
388
            parent = '/'.join(segments[:-1])
389
            t = get_transport(parent)
390
            try:
391
                t.mkdir(segments[-1])
392
            except errors.FileExists:
393
                pass
1534.4.34 by Robert Collins
Fix remaining uses of deprecated apis within bzrlib.
394
        if to_branch_format is None:
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
395
            # use the default
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
396
            br_to = bzrdir.BzrDir.create_branch_and_repo(to_location)
1534.4.34 by Robert Collins
Fix remaining uses of deprecated apis within bzrlib.
397
        else:
398
            br_to = to_branch_format.initialize(to_location)
1185.66.8 by Aaron Bentley
Applied Jelmer's patch to make clone a branch operation
399
        mutter("copy branch from %s to %s", self, br_to)
400
        if revision is None:
401
            revision = self.last_revision()
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
402
        if basis_branch is not None:
403
            basis_branch.repository.push_stores(br_to.repository,
404
                                                revision=revision)
1185.66.8 by Aaron Bentley
Applied Jelmer's patch to make clone a branch operation
405
        br_to.update_revisions(self, stop_revision=revision)
406
        br_to.set_parent(self.base)
407
        mutter("copied")
408
        return br_to
1185.66.1 by Aaron Bentley
Merged from mainline
409
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
410
411
class BranchFormat(object):
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
412
    """An encapsulation of the initialization and open routines for a format.
413
414
    Formats provide three things:
415
     * An initialization routine,
416
     * a format string,
417
     * an open routine.
418
419
    Formats are placed in an dict by their format string for reference 
420
    during branch opening. Its not required that these be instances, they
421
    can be classes themselves with class methods - it simply depends on 
422
    whether state is needed for a given format or not.
423
424
    Once a format is deprecated, just deprecate the initialize and open
425
    methods on the format class. Do not deprecate the object, as the 
426
    object will be created every time regardless.
427
    """
428
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
429
    _default_format = None
430
    """The default format used for new branches."""
431
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
432
    _formats = {}
433
    """The known formats."""
434
435
    @classmethod
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
436
    def get_default_format(klass):
437
        """Return the current default format."""
438
        return klass._default_format
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
439
440
    def get_format_string(self):
441
        """Return the ASCII format string that identifies this format."""
442
        raise NotImplementedError(self.get_format_string)
443
444
    def _find_modes(self, t):
445
        """Determine the appropriate modes for files and directories.
446
        
447
        FIXME: When this merges into, or from storage,
448
        this code becomes delgatable to a LockableFiles instance.
449
450
        For now its cribbed and returns (dir_mode, file_mode)
451
        """
452
        try:
453
            st = t.stat('.')
454
        except errors.TransportNotPossible:
455
            dir_mode = 0755
456
            file_mode = 0644
457
        else:
458
            dir_mode = st.st_mode & 07777
459
            # Remove the sticky and execute bits for files
460
            file_mode = dir_mode & ~07111
461
        if not BzrBranch._set_dir_mode:
462
            dir_mode = None
463
        if not BzrBranch._set_file_mode:
464
            file_mode = None
465
        return dir_mode, file_mode
466
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
467
    def initialize(self, a_bzrdir):
468
        """Create a branch of this format in a_bzrdir."""
469
        mutter('creating branch in %s', a_bzrdir.transport.base)
470
        utf8_files = [('revision-history', ''),
1534.4.28 by Robert Collins
first cut at merge from integration.
471
                      ('branch-name', ''),
472
                      ]
473
        
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
474
        control_files = LockableFiles(a_bzrdir.transport, 'branch-lock')
1534.4.28 by Robert Collins
first cut at merge from integration.
475
        control_files.lock_write()
476
        try:
477
            for file, content in utf8_files:
478
                control_files.put_utf8(file, content)
479
        finally:
480
            control_files.unlock()
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
481
        return self.open(a_bzrdir, _found=True)
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
482
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.
483
    def is_supported(self):
484
        """Is this format supported?
485
486
        Supported formats can be initialized and opened.
487
        Unsupported formats may not support initialization or committing or 
488
        some other features depending on the reason for not being supported.
489
        """
490
        return True
491
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
492
    def open(self, a_bzrdir, _found=False):
493
        """Return the branch object for a_bzrdir
494
495
        _found is a private parameter, do not use it. It is used to indicate
496
               if format probing has already be done.
497
        """
498
        if not _found:
499
            # we are being called directly and must probe.
500
            raise NotImplementedError
501
        return BzrBranch(a_bzrdir.transport.clone('..'), _format=self, a_bzrdir=a_bzrdir)
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
502
503
    @classmethod
504
    def register_format(klass, format):
505
        klass._formats[format.get_format_string()] = format
506
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.
507
    @classmethod
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
508
    def set_default_format(klass, format):
509
        klass._default_format = format
510
511
    @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.
512
    def unregister_format(klass, format):
513
        assert klass._formats[format.get_format_string()] is format
514
        del klass._formats[format.get_format_string()]
515
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
516
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
517
class BzrBranchFormat4(BranchFormat):
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
518
    """Bzr branch format 4.
519
520
    This format has:
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
521
     - a revision-history file.
522
    """
523
524
    def __init__(self):
525
        super(BzrBranchFormat4, self).__init__()
526
        self._matchingbzrdir = bzrdir.BzrDirFormat6()
527
528
# formats which have no format string are not discoverable
529
# and not independently creatable, so are not registered.
530
# __default_format = BranchFormatXXX()
531
# BranchFormat.register_format(__default_format)
532
# BranchFormat.set_default_format(__default_format)
533
_legacy_formats = [BzrBranchFormat4(),
534
                   ]
1534.4.5 by Robert Collins
Turn branch format.open into a factory.
535
1495.1.5 by Jelmer Vernooij
Rename NativeBranch -> BzrBranch
536
class BzrBranch(Branch):
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
537
    """A branch stored in the actual filesystem.
538
539
    Note that it's "local" in the context of the filesystem; it doesn't
540
    really matter if it's on an nfs/smb/afs/coda/... share, as long as
541
    it's writable, and can be accessed via the normal filesystem API.
578 by Martin Pool
- start to move toward Branch.lock and unlock methods,
542
1 by mbp at sourcefrog
import from baz patch-364
543
    """
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
544
    # We actually expect this class to be somewhat short-lived; part of its
545
    # purpose is to try to isolate what bits of the branch logic are tied to
546
    # filesystem access, so that in a later step, we can extricate them to
547
    # a separarte ("storage") class.
1223 by Martin Pool
- store inventories in weave
548
    _inventory_weave = None
353 by Martin Pool
- Per-branch locks in read and write modes.
549
    
897 by Martin Pool
- merge john's revision-naming code
550
    # Map some sort of prefix into a namespace
551
    # stuff like "revno:10", "revid:", etc.
552
    # This should match a prefix with a function which accepts
553
    REVISION_NAMESPACES = {}
554
1534.4.32 by Robert Collins
Rename deprecated_nonce to DEPRECATED_PARAMETER
555
    def __init__(self, transport, init=DEPRECATED_PARAMETER,
556
                 relax_version_check=DEPRECATED_PARAMETER, _format=None,
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
557
                 _control_files=None, a_bzrdir=None):
1 by mbp at sourcefrog
import from baz patch-364
558
        """Create new branch object at a particular location.
559
907.1.2 by John Arbash Meinel
Working on making Branch() do all of it's work over a Transport.
560
        transport -- A Transport object, defining how to access files.
62 by mbp at sourcefrog
- new find_branch_root function; based on suggestion from aaron
561
        
254 by Martin Pool
- Doc cleanups from Magnus Therning
562
        init -- If True, create new control files in a previously
1 by mbp at sourcefrog
import from baz patch-364
563
             unversioned directory.  If False, the branch must already
564
             be versioned.
565
1293 by Martin Pool
- add Branch constructor option to relax version check
566
        relax_version_check -- If true, the usual check for the branch
567
            version is not applied.  This is intended only for
568
            upgrade/recovery type use; it's not guaranteed that
569
            all operations will work on old format branches.
1 by mbp at sourcefrog
import from baz patch-364
570
        """
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
571
        self.bzrdir = a_bzrdir
907.1.8 by John Arbash Meinel
Changed the format for abspath. Updated branch to use a hidden _transport
572
        self._transport = transport
1534.4.28 by Robert Collins
first cut at merge from integration.
573
        self._base = self._transport.base
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
574
        self._format = _format
1534.4.28 by Robert Collins
first cut at merge from integration.
575
        if _control_files is None:
576
            _control_files = LockableFiles(self._transport.clone(bzrlib.BZRDIR),
1185.69.2 by John Arbash Meinel
Changed LockableFiles to take the root directory directly. Moved mode information into LockableFiles instead of Branch
577
                                           'branch-lock')
1534.4.28 by Robert Collins
first cut at merge from integration.
578
        self.control_files = _control_files
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
579
        if deprecated_passed(init):
580
            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.
581
                 "deprecated as of bzr 0.8. Please use Branch.create().",
582
                 DeprecationWarning,
583
                 stacklevel=2)
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
584
            if init:
585
                # this is slower than before deprecation, oh well never mind.
586
                # -> its deprecated.
587
                self._initialize(transport.base)
1534.4.28 by Robert Collins
first cut at merge from integration.
588
        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.
589
        if deprecated_passed(relax_version_check):
590
            warn("BzrBranch.__init__(..., relax_version_check=XXX_: The "
591
                 "relax_version_check parameter is deprecated as of bzr 0.8. "
592
                 "Please use Branch.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.
593
                 "open() method.",
594
                 DeprecationWarning,
595
                 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.
596
            if (not relax_version_check
1534.4.8 by Robert Collins
Unfuck upgrade.
597
                and not self._branch_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.
598
                raise errors.UnsupportedFormatError(
599
                        'sorry, branch format %r not supported' % fmt,
600
                        ['use a different bzr version',
601
                         'or remove the .bzr directory'
602
                         ' and "bzr init" again'])
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
603
        self.repository = self.bzrdir.open_repository()
1534.4.1 by Robert Collins
Allow parameterisation of the branch initialisation for bzrlib.
604
1 by mbp at sourcefrog
import from baz patch-364
605
    def __str__(self):
1185.65.11 by Robert Collins
Disable inheritance for getting at LockableFiles, rather use composition.
606
        return '%s(%r)' % (self.__class__.__name__, self.base)
1 by mbp at sourcefrog
import from baz patch-364
607
608
    __repr__ = __str__
609
578 by Martin Pool
- start to move toward Branch.lock and unlock methods,
610
    def __del__(self):
907.1.23 by John Arbash Meinel
Branch objects now automatically create Cached stores if the protocol is_remote.
611
        # TODO: It might be best to do this somewhere else,
612
        # but it is nice for a Branch object to automatically
613
        # cache it's information.
614
        # Alternatively, we could have the Transport objects cache requests
615
        # See the earlier discussion about how major objects (like Branch)
616
        # should never expect their __del__ function to run.
1185.70.6 by Martin Pool
review fixups from John
617
        # 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
618
        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.
619
            try:
620
                shutil.rmtree(self.cache_root)
621
            except:
622
                pass
623
            self.cache_root = None
624
907.1.17 by John Arbash Meinel
Adding a Branch.base property, removing pull_loc()
625
    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
626
        return self._base
907.1.17 by John Arbash Meinel
Adding a Branch.base property, removing pull_loc()
627
1442.1.5 by Robert Collins
Give branch.base a docstring.
628
    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,
629
1417.1.6 by Robert Collins
introduce transactions for grouping actions done to and with branches
630
    def _finish_transaction(self):
631
        """Exit the current transaction."""
1185.65.13 by Robert Collins
Merge from integration
632
        return self.control_files._finish_transaction()
1417.1.6 by Robert Collins
introduce transactions for grouping actions done to and with branches
633
634
    def get_transaction(self):
1185.65.13 by Robert Collins
Merge from integration
635
        """Return the current active transaction.
636
637
        If no transaction is active, this returns a passthrough object
638
        for which all data is immediately flushed and no caching happens.
639
        """
640
        # this is an explicit function so that we can do tricky stuff
641
        # when the storage in rev_storage is elsewhere.
642
        # we probably need to hook the two 'lock a location' and 
643
        # 'have a transaction' together more delicately, so that
644
        # we can have two locks (branch and storage) and one transaction
645
        # ... and finishing the transaction unlocks both, but unlocking
646
        # does not. - RBC 20051121
647
        return self.control_files.get_transaction()
648
649
    def _set_transaction(self, transaction):
1417.1.6 by Robert Collins
introduce transactions for grouping actions done to and with branches
650
        """Set a new active transaction."""
1185.65.13 by Robert Collins
Merge from integration
651
        return self.control_files._set_transaction(transaction)
353 by Martin Pool
- Per-branch locks in read and write modes.
652
67 by mbp at sourcefrog
use abspath() for the function that makes an absolute
653
    def abspath(self, name):
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
654
        """See Branch.abspath."""
1185.65.11 by Robert Collins
Disable inheritance for getting at LockableFiles, rather use composition.
655
        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.
656
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.
657
    def _check_format(self, format):
1534.4.8 by Robert Collins
Unfuck upgrade.
658
        """Identify the branch format if needed.
1 by mbp at sourcefrog
import from baz patch-364
659
1534.4.8 by Robert Collins
Unfuck upgrade.
660
        The format is stored as a reference to the format object in
1187 by Martin Pool
- improved check for branch version
661
        self._branch_format for code that needs to check it later.
1 by mbp at sourcefrog
import from baz patch-364
662
1534.4.5 by Robert Collins
Turn branch format.open into a factory.
663
        The format parameter is either None or the branch format class
664
        used to open this branch.
163 by mbp at sourcefrog
merge win32 portability fixes
665
        """
1534.4.5 by Robert Collins
Turn branch format.open into a factory.
666
        if format is None:
667
            format = BzrBranchFormat.find_format(self._transport)
1534.4.8 by Robert Collins
Unfuck upgrade.
668
        self._branch_format = format
669
        mutter("got branch format %s", self._branch_format)
907.1.2 by John Arbash Meinel
Working on making Branch() do all of it's work over a Transport.
670
1508.1.15 by Robert Collins
Merge from mpool.
671
    @needs_read_lock
909 by Martin Pool
- merge John's code to give the tree root an explicit file id
672
    def get_root_id(self):
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
673
        """See Branch.get_root_id."""
1534.4.28 by Robert Collins
first cut at merge from integration.
674
        tree = self.repository.revision_tree(self.last_revision())
675
        return tree.inventory.root.file_id
1 by mbp at sourcefrog
import from baz patch-364
676
1185.65.3 by Aaron Bentley
Fixed locking-- all tests pass
677
    def lock_write(self):
1185.65.11 by Robert Collins
Disable inheritance for getting at LockableFiles, rather use composition.
678
        # TODO: test for failed two phase locks. This is known broken.
679
        self.control_files.lock_write()
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
680
        self.repository.lock_write()
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
681
1185.65.3 by Aaron Bentley
Fixed locking-- all tests pass
682
    def lock_read(self):
1185.65.11 by Robert Collins
Disable inheritance for getting at LockableFiles, rather use composition.
683
        # TODO: test for failed two phase locks. This is known broken.
684
        self.control_files.lock_read()
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
685
        self.repository.lock_read()
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
686
687
    def unlock(self):
1185.65.11 by Robert Collins
Disable inheritance for getting at LockableFiles, rather use composition.
688
        # TODO: test for failed two phase locks. This is known broken.
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
689
        self.repository.unlock()
1185.65.11 by Robert Collins
Disable inheritance for getting at LockableFiles, rather use composition.
690
        self.control_files.unlock()
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
691
1185.70.3 by Martin Pool
Various updates to make storage branch mergeable:
692
    def peek_lock_mode(self):
693
        if self.control_files._lock_count == 0:
694
            return None
695
        else:
696
            return self.control_files._lock_mode
697
1442.1.63 by Robert Collins
Remove self.lock_*...finally: self.unlock() dead chickens from branch.py.
698
    @needs_read_lock
1185.50.9 by John Arbash Meinel
[bug 3632] Matthieu Moy- bzr cat should default to last revision
699
    def print_file(self, file, revision_id):
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
700
        """See Branch.print_file."""
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
701
        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.
702
703
    @needs_write_lock
905 by Martin Pool
- merge aaron's append_multiple.patch
704
    def append_revision(self, *revision_ids):
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
705
        """See Branch.append_revision."""
905 by Martin Pool
- merge aaron's append_multiple.patch
706
        for revision_id in revision_ids:
707
            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.
708
        rev_history = self.revision_history()
709
        rev_history.extend(revision_ids)
1442.1.68 by Robert Collins
'bzr pull' now accepts '--clobber'.
710
        self.set_revision_history(rev_history)
711
712
    @needs_write_lock
713
    def set_revision_history(self, rev_history):
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
714
        """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.
715
        self.control_files.put_utf8(
1185.65.11 by Robert Collins
Disable inheritance for getting at LockableFiles, rather use composition.
716
            'revision-history', '\n'.join(rev_history))
233 by mbp at sourcefrog
- more output from test.sh
717
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
718
    def get_revision_delta(self, revno):
719
        """Return the delta for one revision.
720
721
        The delta is relative to its mainline predecessor, or the
722
        empty tree for revision 1.
723
        """
724
        assert isinstance(revno, int)
725
        rh = self.revision_history()
726
        if not (1 <= revno <= len(rh)):
727
            raise InvalidRevisionNumber(revno)
728
729
        # revno is 1-based; list is 0-based
730
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
731
        new_tree = self.repository.revision_tree(rh[revno-1])
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
732
        if revno == 1:
733
            old_tree = EmptyTree()
734
        else:
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
735
            old_tree = self.repository.revision_tree(rh[revno-2])
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
736
        return compare_trees(old_tree, new_tree)
737
1442.1.63 by Robert Collins
Remove self.lock_*...finally: self.unlock() dead chickens from branch.py.
738
    @needs_read_lock
1 by mbp at sourcefrog
import from baz patch-364
739
    def revision_history(self):
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
740
        """See Branch.revision_history."""
1185.65.11 by Robert Collins
Disable inheritance for getting at LockableFiles, rather use composition.
741
        # FIXME are transactions bound to control files ? RBC 20051121
1442.1.63 by Robert Collins
Remove self.lock_*...finally: self.unlock() dead chickens from branch.py.
742
        transaction = self.get_transaction()
743
        history = transaction.map.find_revision_history()
744
        if history is not None:
745
            mutter("cache hit for revision-history in %s", self)
1417.1.12 by Robert Collins
cache revision history during read transactions
746
            return list(history)
1442.1.63 by Robert Collins
Remove self.lock_*...finally: self.unlock() dead chickens from branch.py.
747
        history = [l.rstrip('\r\n') for l in
1185.65.29 by Robert Collins
Implement final review suggestions.
748
                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.
749
        transaction.map.add_revision_history(history)
750
        # this call is disabled because revision_history is 
751
        # not really an object yet, and the transaction is for objects.
752
        # transaction.register_clean(history, precious=True)
753
        return list(history)
1 by mbp at sourcefrog
import from baz patch-364
754
974.1.28 by aaron.bentley at utoronto
factored install_revisions out of update_revisions, updated test cases for greedy_fetch
755
    def update_revisions(self, other, stop_revision=None):
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
756
        """See Branch.update_revisions."""
974.1.33 by aaron.bentley at utoronto
Added greedy_fetch to update_revisions
757
        from bzrlib.fetch import greedy_fetch
974.1.75 by Aaron Bentley
Sped up pull by copying locally first
758
        if stop_revision is None:
1390 by Robert Collins
pair programming worx... merge integration and weave
759
            stop_revision = other.last_revision()
1185.12.44 by abentley
Restored branch convergence to bzr pull
760
        ### Should this be checking is_ancestor instead of revision_history?
1441 by Robert Collins
tests passing is a good idea - move the branch open in cmd_branch to ensure this, and remove noise from the test suite
761
        if (stop_revision is not None and 
762
            stop_revision in self.revision_history()):
1440 by Robert Collins
further tuning of pull, do not do a local merge or fetch at all, if the remote branch is no newer than we are
763
            return
1260 by Martin Pool
- some updates for fetch/update function
764
        greedy_fetch(to_branch=self, from_branch=other,
1261 by Martin Pool
- new method Branch.has_revision
765
                     revision=stop_revision)
1185.12.44 by abentley
Restored branch convergence to bzr pull
766
        pullable_revs = self.pullable_revisions(other, stop_revision)
1185.12.45 by abentley
Cleanups for pull
767
        if len(pullable_revs) > 0:
1261 by Martin Pool
- new method Branch.has_revision
768
            self.append_revision(*pullable_revs)
1185.12.44 by abentley
Restored branch convergence to bzr pull
769
770
    def pullable_revisions(self, other, stop_revision):
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
771
        """See Branch.pullable_revisions."""
1185.12.44 by abentley
Restored branch convergence to bzr pull
772
        other_revno = other.revision_id_to_revno(stop_revision)
773
        try:
774
            return self.missing_revisions(other, other_revno)
775
        except DivergedBranches, e:
776
            try:
777
                pullable_revs = get_intervening_revisions(self.last_revision(),
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
778
                                                          stop_revision, 
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
779
                                                          self.repository)
1185.12.44 by abentley
Restored branch convergence to bzr pull
780
                assert self.last_revision() not in pullable_revs
781
                return pullable_revs
782
            except bzrlib.errors.NotAncestor:
783
                if is_ancestor(self.last_revision(), stop_revision, self):
784
                    return []
785
                else:
786
                    raise e
787
        
1185.33.59 by Martin Pool
[patch] keep a cached basis inventory (Johan Rydberg)
788
    def basis_tree(self):
789
        """See Branch.basis_tree."""
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
790
        return self.repository.revision_tree(self.last_revision())
1185.33.59 by Martin Pool
[patch] keep a cached basis inventory (Johan Rydberg)
791
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
792
    @deprecated_method(zero_eight)
1 by mbp at sourcefrog
import from baz patch-364
793
    def working_tree(self):
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
794
        """Create a Working tree object for this branch."""
1185.2.2 by Lalo Martins
cleaning up and refactoring the branch module.
795
        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.
796
        from bzrlib.transport.local import LocalTransport
1534.4.28 by Robert Collins
first cut at merge from integration.
797
        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.
798
            not isinstance(self._transport, LocalTransport)):
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
799
            raise NoWorkingTree(self.base)
1457.1.1 by Robert Collins
rather than getting the branch inventory, WorkingTree can use the whole Branch, or make its own.
800
        return WorkingTree(self.base, branch=self)
1 by mbp at sourcefrog
import from baz patch-364
801
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
802
    @needs_write_lock
803
    def pull(self, source, overwrite=False):
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
804
        """See Branch.pull."""
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
805
        source.lock_read()
806
        try:
1185.33.44 by Martin Pool
[patch] show number of revisions pushed/pulled/merged (Robey Pointer)
807
            old_count = len(self.revision_history())
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
808
            try:
809
                self.update_revisions(source)
810
            except DivergedBranches:
811
                if not overwrite:
812
                    raise
1185.50.5 by John Arbash Meinel
pull --overwrite should always overwrite, not just if diverged. (Test case from Robey Pointer)
813
            if overwrite:
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
814
                self.set_revision_history(source.revision_history())
1185.33.44 by Martin Pool
[patch] show number of revisions pushed/pulled/merged (Robey Pointer)
815
            new_count = len(self.revision_history())
816
            return new_count - old_count
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
817
        finally:
818
            source.unlock()
1 by mbp at sourcefrog
import from baz patch-364
819
1149 by Martin Pool
- make get_parent() be a method of Branch; add simple tests for it
820
    def get_parent(self):
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
821
        """See Branch.get_parent."""
1149 by Martin Pool
- make get_parent() be a method of Branch; add simple tests for it
822
        import errno
823
        _locs = ['parent', 'pull', 'x-pull']
824
        for l in _locs:
825
            try:
1185.65.29 by Robert Collins
Implement final review suggestions.
826
                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.
827
            except NoSuchFile:
828
                pass
1149 by Martin Pool
- make get_parent() be a method of Branch; add simple tests for it
829
        return None
830
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
831
    def get_push_location(self):
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
832
        """See Branch.get_push_location."""
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
833
        config = bzrlib.config.BranchConfig(self)
834
        push_loc = config.get_user_option('push_location')
835
        return push_loc
836
837
    def set_push_location(self, location):
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
838
        """See Branch.set_push_location."""
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
839
        config = bzrlib.config.LocationConfig(self.base)
840
        config.set_user_option('push_location', location)
841
1442.1.63 by Robert Collins
Remove self.lock_*...finally: self.unlock() dead chickens from branch.py.
842
    @needs_write_lock
1150 by Martin Pool
- add new Branch.set_parent and tests
843
    def set_parent(self, url):
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
844
        """See Branch.set_parent."""
1150 by Martin Pool
- add new Branch.set_parent and tests
845
        # TODO: Maybe delete old location files?
1185.65.29 by Robert Collins
Implement final review suggestions.
846
        # URLs should never be unicode, even on the local fs,
847
        # FIXUP this and get_parent in a future branch format bump:
848
        # read and rewrite the file, and have the new format code read
849
        # using .get not .get_utf8. RBC 20060125
850
        self.control_files.put_utf8('parent', url + '\n')
1150 by Martin Pool
- add new Branch.set_parent and tests
851
1185.35.11 by Aaron Bentley
Added support for branch nicks
852
    def tree_config(self):
853
        return TreeConfig(self)
854
1185.66.8 by Aaron Bentley
Applied Jelmer's patch to make clone a branch operation
855
    def _get_truncated_history(self, revision_id):
856
        history = self.revision_history()
857
        if revision_id is None:
858
            return history
859
        try:
860
            idx = history.index(revision_id)
861
        except ValueError:
862
            raise InvalidRevisionId(revision_id=revision, branch=self)
863
        return history[:idx+1]
864
865
    @needs_read_lock
866
    def _clone_weave(self, to_location, revision=None, basis_branch=None):
1534.4.28 by Robert Collins
first cut at merge from integration.
867
        # prevent leakage
868
        from bzrlib.workingtree import WorkingTree
1185.66.8 by Aaron Bentley
Applied Jelmer's patch to make clone a branch operation
869
        assert isinstance(to_location, basestring)
870
        if basis_branch is not None:
871
            note("basis_branch is not supported for fast weave copy yet.")
872
873
        history = self._get_truncated_history(revision)
874
        if not bzrlib.osutils.lexists(to_location):
875
            os.mkdir(to_location)
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
876
        bzrdir_to = self.bzrdir._format.initialize(to_location)
877
        self.repository.clone(bzrdir_to)
878
        branch_to = bzrdir_to.create_branch()
1185.66.8 by Aaron Bentley
Applied Jelmer's patch to make clone a branch operation
879
        mutter("copy branch from %s to %s", self, branch_to)
880
1185.65.15 by Robert Collins
Merge from integration.
881
        # FIXME duplicate code with base .clone().
1534.4.28 by Robert Collins
first cut at merge from integration.
882
        # .. would template method be useful here?  RBC 20051207
1185.66.8 by Aaron Bentley
Applied Jelmer's patch to make clone a branch operation
883
        branch_to.set_parent(self.base)
1185.65.15 by Robert Collins
Merge from integration.
884
        branch_to.append_revision(*history)
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
885
        WorkingTree.create(branch_to, branch_to.base)
1185.66.8 by Aaron Bentley
Applied Jelmer's patch to make clone a branch operation
886
        mutter("copied")
887
        return branch_to
888
889
    def clone(self, to_location, revision=None, basis_branch=None, to_branch_type=None):
1534.4.28 by Robert Collins
first cut at merge from integration.
890
        print "FIXME: clone via create and fetch is probably faster when versioned file comes in."
1534.4.34 by Robert Collins
Fix remaining uses of deprecated apis within bzrlib.
891
        if (to_branch_type is None
892
            and self.repository.weave_store.listable()
893
            and self.repository.revision_store.listable()):
1185.66.8 by Aaron Bentley
Applied Jelmer's patch to make clone a branch operation
894
            return self._clone_weave(to_location, revision, basis_branch)
1534.4.34 by Robert Collins
Fix remaining uses of deprecated apis within bzrlib.
895
        else:
896
            return Branch.clone(self, to_location, revision, basis_branch, to_branch_type)
1185.35.11 by Aaron Bentley
Added support for branch nicks
897
1534.4.1 by Robert Collins
Allow parameterisation of the branch initialisation for bzrlib.
898
1534.4.3 by Robert Collins
Implement BranchTestProviderAdapter, so tests now run across all branch formats.
899
class BranchTestProviderAdapter(object):
900
    """A tool to generate a suite testing multiple branch formats at once.
901
902
    This is done by copying the test once for each transport and injecting
903
    the transport_server, transport_readonly_server, and branch_format
904
    classes into each copy. Each copy is also given a new id() to make it
905
    easy to identify.
906
    """
907
908
    def __init__(self, transport_server, transport_readonly_server, formats):
909
        self._transport_server = transport_server
910
        self._transport_readonly_server = transport_readonly_server
911
        self._formats = formats
912
    
913
    def adapt(self, test):
914
        result = TestSuite()
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
915
        for branch_format, bzrdir_format in self._formats:
1534.4.3 by Robert Collins
Implement BranchTestProviderAdapter, so tests now run across all branch formats.
916
            new_test = deepcopy(test)
917
            new_test.transport_server = self._transport_server
918
            new_test.transport_readonly_server = self._transport_readonly_server
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
919
            new_test.bzrdir_format = bzrdir_format
920
            new_test.branch_format = branch_format
1534.4.3 by Robert Collins
Implement BranchTestProviderAdapter, so tests now run across all branch formats.
921
            def make_new_test_id():
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
922
                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.
923
                return lambda: new_id
924
            new_test.id = make_new_test_id()
925
            result.addTest(new_test)
926
        return result
927
928
1 by mbp at sourcefrog
import from baz patch-364
929
######################################################################
930
# predicates
931
932
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
933
@deprecated_function(zero_eight)
934
def ScratchBranch(*args, **kwargs):
935
    """See bzrlib.bzrdir.ScratchDir."""
936
    d = ScratchDir(*args, **kwargs)
937
    return d.open_branch()
938
939
940
@deprecated_function(zero_eight)
941
def is_control_file(*args, **kwargs):
942
    """See bzrlib.workingtree.is_control_file."""
943
    return bzrlib.workingtree.is_control_file(*args, **kwargs)