/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Robert Collins
  • Date: 2006-06-16 17:03:42 UTC
  • mto: (1813.1.1 integration)
  • mto: This revision was merged to the branch mainline in revision 1815.
  • Revision ID: robertc@robertcollins.net-20060616170342-1094ed388f0a9fce
Remove some unused imports.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005, 2006 Canonical Ltd
 
2
#
 
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
 
 
18
from copy import deepcopy
 
19
from cStringIO import StringIO
 
20
import errno
 
21
import os
 
22
import shutil
 
23
import sys
 
24
from unittest import TestSuite
 
25
from warnings import warn
 
26
 
 
27
import bzrlib
 
28
import bzrlib.bzrdir as bzrdir
 
29
from bzrlib.config import TreeConfig
 
30
from bzrlib.decorators import needs_read_lock, needs_write_lock
 
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,
 
35
                           DivergedBranches, LockError,
 
36
                           UninitializableFormat,
 
37
                           UnlistableStore,
 
38
                           UnlistableBranch, NoSuchFile, NotVersionedError,
 
39
                           NoWorkingTree)
 
40
import bzrlib.inventory as inventory
 
41
from bzrlib.inventory import Inventory
 
42
from bzrlib.lockable_files import LockableFiles, TransportLock
 
43
from bzrlib.lockdir import LockDir
 
44
from bzrlib.osutils import (isdir, quotefn,
 
45
                            rename, splitpath, sha_file,
 
46
                            file_kind, abspath, normpath, pathjoin,
 
47
                            safe_unicode,
 
48
                            rmtree,
 
49
                            )
 
50
from bzrlib.repository import Repository
 
51
from bzrlib.revision import (
 
52
                             is_ancestor,
 
53
                             NULL_REVISION,
 
54
                             Revision,
 
55
                             )
 
56
from bzrlib.store import copy_all
 
57
from bzrlib.symbol_versioning import *
 
58
from bzrlib.trace import mutter, note
 
59
import bzrlib.transactions as transactions
 
60
from bzrlib.transport import Transport, get_transport
 
61
from bzrlib.tree import EmptyTree, RevisionTree
 
62
import bzrlib.ui
 
63
import bzrlib.urlutils as urlutils
 
64
import bzrlib.xml5
 
65
 
 
66
 
 
67
BZR_BRANCH_FORMAT_4 = "Bazaar-NG branch, format 0.0.4\n"
 
68
BZR_BRANCH_FORMAT_5 = "Bazaar-NG branch, format 5\n"
 
69
BZR_BRANCH_FORMAT_6 = "Bazaar-NG branch, format 6\n"
 
70
 
 
71
 
 
72
# TODO: Maybe include checks for common corruption of newlines, etc?
 
73
 
 
74
# TODO: Some operations like log might retrieve the same revisions
 
75
# repeatedly to calculate deltas.  We could perhaps have a weakref
 
76
# cache in memory to make this faster.  In general anything can be
 
77
# cached in memory between lock and unlock operations. .. nb thats
 
78
# what the transaction identity map provides
 
79
 
 
80
 
 
81
######################################################################
 
82
# branch objects
 
83
 
 
84
class Branch(object):
 
85
    """Branch holding a history of revisions.
 
86
 
 
87
    base
 
88
        Base directory/url of the branch.
 
89
    """
 
90
    # this is really an instance variable - FIXME move it there
 
91
    # - RBC 20060112
 
92
    base = None
 
93
 
 
94
    def __init__(self, *ignored, **ignored_too):
 
95
        raise NotImplementedError('The Branch class is abstract')
 
96
 
 
97
    def break_lock(self):
 
98
        """Break a lock if one is present from another instance.
 
99
 
 
100
        Uses the ui factory to ask for confirmation if the lock may be from
 
101
        an active process.
 
102
 
 
103
        This will probe the repository for its lock as well.
 
104
        """
 
105
        self.control_files.break_lock()
 
106
        self.repository.break_lock()
 
107
        master = self.get_master_branch()
 
108
        if master is not None:
 
109
            master.break_lock()
 
110
 
 
111
    @staticmethod
 
112
    @deprecated_method(zero_eight)
 
113
    def open_downlevel(base):
 
114
        """Open a branch which may be of an old format."""
 
115
        return Branch.open(base, _unsupported=True)
 
116
        
 
117
    @staticmethod
 
118
    def open(base, _unsupported=False):
 
119
        """Open the repository rooted at base.
 
120
 
 
121
        For instance, if the repository is at URL/.bzr/repository,
 
122
        Repository.open(URL) -> a Repository instance.
 
123
        """
 
124
        control = bzrdir.BzrDir.open(base, _unsupported)
 
125
        return control.open_branch(_unsupported)
 
126
 
 
127
    @staticmethod
 
128
    def open_containing(url):
 
129
        """Open an existing branch which contains url.
 
130
        
 
131
        This probes for a branch at url, and searches upwards from there.
 
132
 
 
133
        Basically we keep looking up until we find the control directory or
 
134
        run into the root.  If there isn't one, raises NotBranchError.
 
135
        If there is one and it is either an unrecognised format or an unsupported 
 
136
        format, UnknownFormatError or UnsupportedFormatError are raised.
 
137
        If there is one, it is returned, along with the unused portion of url.
 
138
        """
 
139
        control, relpath = bzrdir.BzrDir.open_containing(url)
 
140
        return control.open_branch(), relpath
 
141
 
 
142
    @staticmethod
 
143
    @deprecated_function(zero_eight)
 
144
    def initialize(base):
 
145
        """Create a new working tree and branch, rooted at 'base' (url)
 
146
 
 
147
        NOTE: This will soon be deprecated in favour of creation
 
148
        through a BzrDir.
 
149
        """
 
150
        return bzrdir.BzrDir.create_standalone_workingtree(base).branch
 
151
 
 
152
    def setup_caching(self, cache_root):
 
153
        """Subclasses that care about caching should override this, and set
 
154
        up cached stores located under cache_root.
 
155
        """
 
156
        # seems to be unused, 2006-01-13 mbp
 
157
        warn('%s is deprecated' % self.setup_caching)
 
158
        self.cache_root = cache_root
 
159
 
 
160
    def _get_nick(self):
 
161
        cfg = self.tree_config()
 
162
        return cfg.get_option(u"nickname", default=self.base.split('/')[-2])
 
163
 
 
164
    def _set_nick(self, nick):
 
165
        cfg = self.tree_config()
 
166
        cfg.set_option(nick, "nickname")
 
167
        assert cfg.get_option("nickname") == nick
 
168
 
 
169
    nick = property(_get_nick, _set_nick)
 
170
 
 
171
    def is_locked(self):
 
172
        raise NotImplementedError('is_locked is abstract')
 
173
 
 
174
    def lock_write(self):
 
175
        raise NotImplementedError('lock_write is abstract')
 
176
 
 
177
    def lock_read(self):
 
178
        raise NotImplementedError('lock_read is abstract')
 
179
 
 
180
    def unlock(self):
 
181
        raise NotImplementedError('unlock is abstract')
 
182
 
 
183
    def peek_lock_mode(self):
 
184
        """Return lock mode for the Branch: 'r', 'w' or None"""
 
185
        raise NotImplementedError(self.peek_lock_mode)
 
186
 
 
187
    def get_physical_lock_status(self):
 
188
        raise NotImplementedError('get_physical_lock_status is abstract')
 
189
 
 
190
    def abspath(self, name):
 
191
        """Return absolute filename for something in the branch
 
192
        
 
193
        XXX: Robert Collins 20051017 what is this used for? why is it a branch
 
194
        method and not a tree method.
 
195
        """
 
196
        raise NotImplementedError('abspath is abstract')
 
197
 
 
198
    def bind(self, other):
 
199
        """Bind the local branch the other branch.
 
200
 
 
201
        :param other: The branch to bind to
 
202
        :type other: Branch
 
203
        """
 
204
        raise errors.UpgradeRequired(self.base)
 
205
 
 
206
    @needs_write_lock
 
207
    def fetch(self, from_branch, last_revision=None, pb=None):
 
208
        """Copy revisions from from_branch into this branch.
 
209
 
 
210
        :param from_branch: Where to copy from.
 
211
        :param last_revision: What revision to stop at (None for at the end
 
212
                              of the branch.
 
213
        :param pb: An optional progress bar to use.
 
214
 
 
215
        Returns the copied revision count and the failed revisions in a tuple:
 
216
        (copied, failures).
 
217
        """
 
218
        if self.base == from_branch.base:
 
219
            return (0, [])
 
220
        if pb is None:
 
221
            nested_pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
222
            pb = nested_pb
 
223
        else:
 
224
            nested_pb = None
 
225
 
 
226
        from_branch.lock_read()
 
227
        try:
 
228
            if last_revision is None:
 
229
                pb.update('get source history')
 
230
                from_history = from_branch.revision_history()
 
231
                if from_history:
 
232
                    last_revision = from_history[-1]
 
233
                else:
 
234
                    # no history in the source branch
 
235
                    last_revision = NULL_REVISION
 
236
            return self.repository.fetch(from_branch.repository,
 
237
                                         revision_id=last_revision,
 
238
                                         pb=nested_pb)
 
239
        finally:
 
240
            if nested_pb is not None:
 
241
                nested_pb.finished()
 
242
            from_branch.unlock()
 
243
 
 
244
    def get_bound_location(self):
 
245
        """Return the URL of the branch we are bound to.
 
246
 
 
247
        Older format branches cannot bind, please be sure to use a metadir
 
248
        branch.
 
249
        """
 
250
        return None
 
251
    
 
252
    def get_commit_builder(self, parents, config=None, timestamp=None, 
 
253
                           timezone=None, committer=None, revprops=None, 
 
254
                           revision_id=None):
 
255
        """Obtain a CommitBuilder for this branch.
 
256
        
 
257
        :param parents: Revision ids of the parents of the new revision.
 
258
        :param config: Optional configuration to use.
 
259
        :param timestamp: Optional timestamp recorded for commit.
 
260
        :param timezone: Optional timezone for timestamp.
 
261
        :param committer: Optional committer to set for commit.
 
262
        :param revprops: Optional dictionary of revision properties.
 
263
        :param revision_id: Optional revision id.
 
264
        """
 
265
 
 
266
        if config is None:
 
267
            config = bzrlib.config.BranchConfig(self)
 
268
        
 
269
        return self.repository.get_commit_builder(self, parents, config, 
 
270
            timestamp, timezone, committer, revprops, revision_id)
 
271
 
 
272
    def get_master_branch(self):
 
273
        """Return the branch we are bound to.
 
274
        
 
275
        :return: Either a Branch, or None
 
276
        """
 
277
        return None
 
278
 
 
279
    def get_root_id(self):
 
280
        """Return the id of this branches root"""
 
281
        raise NotImplementedError('get_root_id is abstract')
 
282
 
 
283
    def print_file(self, file, revision_id):
 
284
        """Print `file` to stdout."""
 
285
        raise NotImplementedError('print_file is abstract')
 
286
 
 
287
    def append_revision(self, *revision_ids):
 
288
        raise NotImplementedError('append_revision is abstract')
 
289
 
 
290
    def set_revision_history(self, rev_history):
 
291
        raise NotImplementedError('set_revision_history is abstract')
 
292
 
 
293
    def revision_history(self):
 
294
        """Return sequence of revision hashes on to this branch."""
 
295
        raise NotImplementedError('revision_history is abstract')
 
296
 
 
297
    def revno(self):
 
298
        """Return current revision number for this branch.
 
299
 
 
300
        That is equivalent to the number of revisions committed to
 
301
        this branch.
 
302
        """
 
303
        return len(self.revision_history())
 
304
 
 
305
    def unbind(self):
 
306
        """Older format branches cannot bind or unbind."""
 
307
        raise errors.UpgradeRequired(self.base)
 
308
 
 
309
    def last_revision(self):
 
310
        """Return last patch hash, or None if no history."""
 
311
        ph = self.revision_history()
 
312
        if ph:
 
313
            return ph[-1]
 
314
        else:
 
315
            return None
 
316
 
 
317
    def missing_revisions(self, other, stop_revision=None):
 
318
        """Return a list of new revisions that would perfectly fit.
 
319
        
 
320
        If self and other have not diverged, return a list of the revisions
 
321
        present in other, but missing from self.
 
322
 
 
323
        >>> from bzrlib.workingtree import WorkingTree
 
324
        >>> bzrlib.trace.silent = True
 
325
        >>> d1 = bzrdir.ScratchDir()
 
326
        >>> br1 = d1.open_branch()
 
327
        >>> wt1 = d1.open_workingtree()
 
328
        >>> d2 = bzrdir.ScratchDir()
 
329
        >>> br2 = d2.open_branch()
 
330
        >>> wt2 = d2.open_workingtree()
 
331
        >>> br1.missing_revisions(br2)
 
332
        []
 
333
        >>> wt2.commit("lala!", rev_id="REVISION-ID-1")
 
334
        'REVISION-ID-1'
 
335
        >>> br1.missing_revisions(br2)
 
336
        [u'REVISION-ID-1']
 
337
        >>> br2.missing_revisions(br1)
 
338
        []
 
339
        >>> wt1.commit("lala!", rev_id="REVISION-ID-1")
 
340
        'REVISION-ID-1'
 
341
        >>> br1.missing_revisions(br2)
 
342
        []
 
343
        >>> wt2.commit("lala!", rev_id="REVISION-ID-2A")
 
344
        'REVISION-ID-2A'
 
345
        >>> br1.missing_revisions(br2)
 
346
        [u'REVISION-ID-2A']
 
347
        >>> wt1.commit("lala!", rev_id="REVISION-ID-2B")
 
348
        'REVISION-ID-2B'
 
349
        >>> br1.missing_revisions(br2)
 
350
        Traceback (most recent call last):
 
351
        DivergedBranches: These branches have diverged.  Try merge.
 
352
        """
 
353
        self_history = self.revision_history()
 
354
        self_len = len(self_history)
 
355
        other_history = other.revision_history()
 
356
        other_len = len(other_history)
 
357
        common_index = min(self_len, other_len) -1
 
358
        if common_index >= 0 and \
 
359
            self_history[common_index] != other_history[common_index]:
 
360
            raise DivergedBranches(self, other)
 
361
 
 
362
        if stop_revision is None:
 
363
            stop_revision = other_len
 
364
        else:
 
365
            assert isinstance(stop_revision, int)
 
366
            if stop_revision > other_len:
 
367
                raise bzrlib.errors.NoSuchRevision(self, stop_revision)
 
368
        return other_history[self_len:stop_revision]
 
369
 
 
370
    def update_revisions(self, other, stop_revision=None):
 
371
        """Pull in new perfect-fit revisions.
 
372
 
 
373
        :param other: Another Branch to pull from
 
374
        :param stop_revision: Updated until the given revision
 
375
        :return: None
 
376
        """
 
377
        raise NotImplementedError('update_revisions is abstract')
 
378
 
 
379
    def revision_id_to_revno(self, revision_id):
 
380
        """Given a revision id, return its revno"""
 
381
        if revision_id is None:
 
382
            return 0
 
383
        history = self.revision_history()
 
384
        try:
 
385
            return history.index(revision_id) + 1
 
386
        except ValueError:
 
387
            raise bzrlib.errors.NoSuchRevision(self, revision_id)
 
388
 
 
389
    def get_rev_id(self, revno, history=None):
 
390
        """Find the revision id of the specified revno."""
 
391
        if revno == 0:
 
392
            return None
 
393
        if history is None:
 
394
            history = self.revision_history()
 
395
        elif revno <= 0 or revno > len(history):
 
396
            raise bzrlib.errors.NoSuchRevision(self, revno)
 
397
        return history[revno - 1]
 
398
 
 
399
    def pull(self, source, overwrite=False, stop_revision=None):
 
400
        raise NotImplementedError('pull is abstract')
 
401
 
 
402
    def basis_tree(self):
 
403
        """Return `Tree` object for last revision.
 
404
 
 
405
        If there are no revisions yet, return an `EmptyTree`.
 
406
        """
 
407
        return self.repository.revision_tree(self.last_revision())
 
408
 
 
409
    def rename_one(self, from_rel, to_rel):
 
410
        """Rename one file.
 
411
 
 
412
        This can change the directory or the filename or both.
 
413
        """
 
414
        raise NotImplementedError('rename_one is abstract')
 
415
 
 
416
    def move(self, from_paths, to_name):
 
417
        """Rename files.
 
418
 
 
419
        to_name must exist as a versioned directory.
 
420
 
 
421
        If to_name exists and is a directory, the files are moved into
 
422
        it, keeping their old names.  If it is a directory, 
 
423
 
 
424
        Note that to_name is only the last component of the new name;
 
425
        this doesn't change the directory.
 
426
 
 
427
        This returns a list of (from_path, to_path) pairs for each
 
428
        entry that is moved.
 
429
        """
 
430
        raise NotImplementedError('move is abstract')
 
431
 
 
432
    def get_parent(self):
 
433
        """Return the parent location of the branch.
 
434
 
 
435
        This is the default location for push/pull/missing.  The usual
 
436
        pattern is that the user can override it by specifying a
 
437
        location.
 
438
        """
 
439
        raise NotImplementedError('get_parent is abstract')
 
440
 
 
441
    def get_push_location(self):
 
442
        """Return the None or the location to push this branch to."""
 
443
        raise NotImplementedError('get_push_location is abstract')
 
444
 
 
445
    def set_push_location(self, location):
 
446
        """Set a new push location for this branch."""
 
447
        raise NotImplementedError('set_push_location is abstract')
 
448
 
 
449
    def set_parent(self, url):
 
450
        raise NotImplementedError('set_parent is abstract')
 
451
 
 
452
    @needs_write_lock
 
453
    def update(self):
 
454
        """Synchronise this branch with the master branch if any. 
 
455
 
 
456
        :return: None or the last_revision pivoted out during the update.
 
457
        """
 
458
        return None
 
459
 
 
460
    def check_revno(self, revno):
 
461
        """\
 
462
        Check whether a revno corresponds to any revision.
 
463
        Zero (the NULL revision) is considered valid.
 
464
        """
 
465
        if revno != 0:
 
466
            self.check_real_revno(revno)
 
467
            
 
468
    def check_real_revno(self, revno):
 
469
        """\
 
470
        Check whether a revno corresponds to a real revision.
 
471
        Zero (the NULL revision) is considered invalid
 
472
        """
 
473
        if revno < 1 or revno > self.revno():
 
474
            raise InvalidRevisionNumber(revno)
 
475
 
 
476
    @needs_read_lock
 
477
    def clone(self, *args, **kwargs):
 
478
        """Clone this branch into to_bzrdir preserving all semantic values.
 
479
        
 
480
        revision_id: if not None, the revision history in the new branch will
 
481
                     be truncated to end with revision_id.
 
482
        """
 
483
        # for API compatibility, until 0.8 releases we provide the old api:
 
484
        # def clone(self, to_location, revision=None, basis_branch=None, to_branch_format=None):
 
485
        # after 0.8 releases, the *args and **kwargs should be changed:
 
486
        # def clone(self, to_bzrdir, revision_id=None):
 
487
        if (kwargs.get('to_location', None) or
 
488
            kwargs.get('revision', None) or
 
489
            kwargs.get('basis_branch', None) or
 
490
            (len(args) and isinstance(args[0], basestring))):
 
491
            # backwards compatibility api:
 
492
            warn("Branch.clone() has been deprecated for BzrDir.clone() from"
 
493
                 " bzrlib 0.8.", DeprecationWarning, stacklevel=3)
 
494
            # get basis_branch
 
495
            if len(args) > 2:
 
496
                basis_branch = args[2]
 
497
            else:
 
498
                basis_branch = kwargs.get('basis_branch', None)
 
499
            if basis_branch:
 
500
                basis = basis_branch.bzrdir
 
501
            else:
 
502
                basis = None
 
503
            # get revision
 
504
            if len(args) > 1:
 
505
                revision_id = args[1]
 
506
            else:
 
507
                revision_id = kwargs.get('revision', None)
 
508
            # get location
 
509
            if len(args):
 
510
                url = args[0]
 
511
            else:
 
512
                # no default to raise if not provided.
 
513
                url = kwargs.get('to_location')
 
514
            return self.bzrdir.clone(url,
 
515
                                     revision_id=revision_id,
 
516
                                     basis=basis).open_branch()
 
517
        # new cleaner api.
 
518
        # generate args by hand 
 
519
        if len(args) > 1:
 
520
            revision_id = args[1]
 
521
        else:
 
522
            revision_id = kwargs.get('revision_id', None)
 
523
        if len(args):
 
524
            to_bzrdir = args[0]
 
525
        else:
 
526
            # no default to raise if not provided.
 
527
            to_bzrdir = kwargs.get('to_bzrdir')
 
528
        result = self._format.initialize(to_bzrdir)
 
529
        self.copy_content_into(result, revision_id=revision_id)
 
530
        return  result
 
531
 
 
532
    @needs_read_lock
 
533
    def sprout(self, to_bzrdir, revision_id=None):
 
534
        """Create a new line of development from the branch, into to_bzrdir.
 
535
        
 
536
        revision_id: if not None, the revision history in the new branch will
 
537
                     be truncated to end with revision_id.
 
538
        """
 
539
        result = self._format.initialize(to_bzrdir)
 
540
        self.copy_content_into(result, revision_id=revision_id)
 
541
        result.set_parent(self.bzrdir.root_transport.base)
 
542
        return result
 
543
 
 
544
    @needs_read_lock
 
545
    def copy_content_into(self, destination, revision_id=None):
 
546
        """Copy the content of self into destination.
 
547
 
 
548
        revision_id: if not None, the revision history in the new branch will
 
549
                     be truncated to end with revision_id.
 
550
        """
 
551
        new_history = self.revision_history()
 
552
        if revision_id is not None:
 
553
            try:
 
554
                new_history = new_history[:new_history.index(revision_id) + 1]
 
555
            except ValueError:
 
556
                rev = self.repository.get_revision(revision_id)
 
557
                new_history = rev.get_history(self.repository)[1:]
 
558
        destination.set_revision_history(new_history)
 
559
        parent = self.get_parent()
 
560
        if parent:
 
561
            destination.set_parent(parent)
 
562
 
 
563
    @needs_read_lock
 
564
    def check(self):
 
565
        """Check consistency of the branch.
 
566
 
 
567
        In particular this checks that revisions given in the revision-history
 
568
        do actually match up in the revision graph, and that they're all 
 
569
        present in the repository.
 
570
 
 
571
        :return: A BranchCheckResult.
 
572
        """
 
573
        mainline_parent_id = None
 
574
        for revision_id in self.revision_history():
 
575
            try:
 
576
                revision = self.repository.get_revision(revision_id)
 
577
            except errors.NoSuchRevision, e:
 
578
                raise BzrCheckError("mainline revision {%s} not in repository"
 
579
                        % revision_id)
 
580
            # In general the first entry on the revision history has no parents.
 
581
            # But it's not illegal for it to have parents listed; this can happen
 
582
            # in imports from Arch when the parents weren't reachable.
 
583
            if mainline_parent_id is not None:
 
584
                if mainline_parent_id not in revision.parent_ids:
 
585
                    raise BzrCheckError("previous revision {%s} not listed among "
 
586
                                        "parents of {%s}"
 
587
                                        % (mainline_parent_id, revision_id))
 
588
            mainline_parent_id = revision_id
 
589
        return BranchCheckResult(self)
 
590
 
 
591
 
 
592
class BranchFormat(object):
 
593
    """An encapsulation of the initialization and open routines for a format.
 
594
 
 
595
    Formats provide three things:
 
596
     * An initialization routine,
 
597
     * a format string,
 
598
     * an open routine.
 
599
 
 
600
    Formats are placed in an dict by their format string for reference 
 
601
    during branch opening. Its not required that these be instances, they
 
602
    can be classes themselves with class methods - it simply depends on 
 
603
    whether state is needed for a given format or not.
 
604
 
 
605
    Once a format is deprecated, just deprecate the initialize and open
 
606
    methods on the format class. Do not deprecate the object, as the 
 
607
    object will be created every time regardless.
 
608
    """
 
609
 
 
610
    _default_format = None
 
611
    """The default format used for new branches."""
 
612
 
 
613
    _formats = {}
 
614
    """The known formats."""
 
615
 
 
616
    @classmethod
 
617
    def find_format(klass, a_bzrdir):
 
618
        """Return the format for the branch object in a_bzrdir."""
 
619
        try:
 
620
            transport = a_bzrdir.get_branch_transport(None)
 
621
            format_string = transport.get("format").read()
 
622
            return klass._formats[format_string]
 
623
        except NoSuchFile:
 
624
            raise NotBranchError(path=transport.base)
 
625
        except KeyError:
 
626
            raise errors.UnknownFormatError(format_string)
 
627
 
 
628
    @classmethod
 
629
    def get_default_format(klass):
 
630
        """Return the current default format."""
 
631
        return klass._default_format
 
632
 
 
633
    def get_format_string(self):
 
634
        """Return the ASCII format string that identifies this format."""
 
635
        raise NotImplementedError(self.get_format_string)
 
636
 
 
637
    def get_format_description(self):
 
638
        """Return the short format description for this format."""
 
639
        raise NotImplementedError(self.get_format_string)
 
640
 
 
641
    def initialize(self, a_bzrdir):
 
642
        """Create a branch of this format in a_bzrdir."""
 
643
        raise NotImplementedError(self.initialize)
 
644
 
 
645
    def is_supported(self):
 
646
        """Is this format supported?
 
647
 
 
648
        Supported formats can be initialized and opened.
 
649
        Unsupported formats may not support initialization or committing or 
 
650
        some other features depending on the reason for not being supported.
 
651
        """
 
652
        return True
 
653
 
 
654
    def open(self, a_bzrdir, _found=False):
 
655
        """Return the branch object for a_bzrdir
 
656
 
 
657
        _found is a private parameter, do not use it. It is used to indicate
 
658
               if format probing has already be done.
 
659
        """
 
660
        raise NotImplementedError(self.open)
 
661
 
 
662
    @classmethod
 
663
    def register_format(klass, format):
 
664
        klass._formats[format.get_format_string()] = format
 
665
 
 
666
    @classmethod
 
667
    def set_default_format(klass, format):
 
668
        klass._default_format = format
 
669
 
 
670
    @classmethod
 
671
    def unregister_format(klass, format):
 
672
        assert klass._formats[format.get_format_string()] is format
 
673
        del klass._formats[format.get_format_string()]
 
674
 
 
675
    def __str__(self):
 
676
        return self.get_format_string().rstrip()
 
677
 
 
678
 
 
679
class BzrBranchFormat4(BranchFormat):
 
680
    """Bzr branch format 4.
 
681
 
 
682
    This format has:
 
683
     - a revision-history file.
 
684
     - a branch-lock lock file [ to be shared with the bzrdir ]
 
685
    """
 
686
 
 
687
    def get_format_description(self):
 
688
        """See BranchFormat.get_format_description()."""
 
689
        return "Branch format 4"
 
690
 
 
691
    def initialize(self, a_bzrdir):
 
692
        """Create a branch of this format in a_bzrdir."""
 
693
        mutter('creating branch in %s', a_bzrdir.transport.base)
 
694
        branch_transport = a_bzrdir.get_branch_transport(self)
 
695
        utf8_files = [('revision-history', ''),
 
696
                      ('branch-name', ''),
 
697
                      ]
 
698
        control_files = LockableFiles(branch_transport, 'branch-lock',
 
699
                                      TransportLock)
 
700
        control_files.create_lock()
 
701
        control_files.lock_write()
 
702
        try:
 
703
            for file, content in utf8_files:
 
704
                control_files.put_utf8(file, content)
 
705
        finally:
 
706
            control_files.unlock()
 
707
        return self.open(a_bzrdir, _found=True)
 
708
 
 
709
    def __init__(self):
 
710
        super(BzrBranchFormat4, self).__init__()
 
711
        self._matchingbzrdir = bzrdir.BzrDirFormat6()
 
712
 
 
713
    def open(self, a_bzrdir, _found=False):
 
714
        """Return the branch object for a_bzrdir
 
715
 
 
716
        _found is a private parameter, do not use it. It is used to indicate
 
717
               if format probing has already be done.
 
718
        """
 
719
        if not _found:
 
720
            # we are being called directly and must probe.
 
721
            raise NotImplementedError
 
722
        return BzrBranch(_format=self,
 
723
                         _control_files=a_bzrdir._control_files,
 
724
                         a_bzrdir=a_bzrdir,
 
725
                         _repository=a_bzrdir.open_repository())
 
726
 
 
727
    def __str__(self):
 
728
        return "Bazaar-NG branch format 4"
 
729
 
 
730
 
 
731
class BzrBranchFormat5(BranchFormat):
 
732
    """Bzr branch format 5.
 
733
 
 
734
    This format has:
 
735
     - a revision-history file.
 
736
     - a format string
 
737
     - a lock dir guarding the branch itself
 
738
     - all of this stored in a branch/ subdirectory
 
739
     - works with shared repositories.
 
740
 
 
741
    This format is new in bzr 0.8.
 
742
    """
 
743
 
 
744
    def get_format_string(self):
 
745
        """See BranchFormat.get_format_string()."""
 
746
        return "Bazaar-NG branch format 5\n"
 
747
 
 
748
    def get_format_description(self):
 
749
        """See BranchFormat.get_format_description()."""
 
750
        return "Branch format 5"
 
751
        
 
752
    def initialize(self, a_bzrdir):
 
753
        """Create a branch of this format in a_bzrdir."""
 
754
        mutter('creating branch %r in %s', self, a_bzrdir.transport.base)
 
755
        branch_transport = a_bzrdir.get_branch_transport(self)
 
756
        utf8_files = [('revision-history', ''),
 
757
                      ('branch-name', ''),
 
758
                      ]
 
759
        control_files = LockableFiles(branch_transport, 'lock', LockDir)
 
760
        control_files.create_lock()
 
761
        control_files.lock_write()
 
762
        control_files.put_utf8('format', self.get_format_string())
 
763
        try:
 
764
            for file, content in utf8_files:
 
765
                control_files.put_utf8(file, content)
 
766
        finally:
 
767
            control_files.unlock()
 
768
        return self.open(a_bzrdir, _found=True, )
 
769
 
 
770
    def __init__(self):
 
771
        super(BzrBranchFormat5, self).__init__()
 
772
        self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
 
773
 
 
774
    def open(self, a_bzrdir, _found=False):
 
775
        """Return the branch object for a_bzrdir
 
776
 
 
777
        _found is a private parameter, do not use it. It is used to indicate
 
778
               if format probing has already be done.
 
779
        """
 
780
        if not _found:
 
781
            format = BranchFormat.find_format(a_bzrdir)
 
782
            assert format.__class__ == self.__class__
 
783
        transport = a_bzrdir.get_branch_transport(None)
 
784
        control_files = LockableFiles(transport, 'lock', LockDir)
 
785
        return BzrBranch5(_format=self,
 
786
                          _control_files=control_files,
 
787
                          a_bzrdir=a_bzrdir,
 
788
                          _repository=a_bzrdir.find_repository())
 
789
 
 
790
    def __str__(self):
 
791
        return "Bazaar-NG Metadir branch format 5"
 
792
 
 
793
 
 
794
class BranchReferenceFormat(BranchFormat):
 
795
    """Bzr branch reference format.
 
796
 
 
797
    Branch references are used in implementing checkouts, they
 
798
    act as an alias to the real branch which is at some other url.
 
799
 
 
800
    This format has:
 
801
     - A location file
 
802
     - a format string
 
803
    """
 
804
 
 
805
    def get_format_string(self):
 
806
        """See BranchFormat.get_format_string()."""
 
807
        return "Bazaar-NG Branch Reference Format 1\n"
 
808
 
 
809
    def get_format_description(self):
 
810
        """See BranchFormat.get_format_description()."""
 
811
        return "Checkout reference format 1"
 
812
        
 
813
    def initialize(self, a_bzrdir, target_branch=None):
 
814
        """Create a branch of this format in a_bzrdir."""
 
815
        if target_branch is None:
 
816
            # this format does not implement branch itself, thus the implicit
 
817
            # creation contract must see it as uninitializable
 
818
            raise errors.UninitializableFormat(self)
 
819
        mutter('creating branch reference in %s', a_bzrdir.transport.base)
 
820
        branch_transport = a_bzrdir.get_branch_transport(self)
 
821
        # FIXME rbc 20060209 one j-a-ms encoding branch lands this str() cast is not needed.
 
822
        branch_transport.put('location', StringIO(str(target_branch.bzrdir.root_transport.base)))
 
823
        branch_transport.put('format', StringIO(self.get_format_string()))
 
824
        return self.open(a_bzrdir, _found=True)
 
825
 
 
826
    def __init__(self):
 
827
        super(BranchReferenceFormat, self).__init__()
 
828
        self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
 
829
 
 
830
    def _make_reference_clone_function(format, a_branch):
 
831
        """Create a clone() routine for a branch dynamically."""
 
832
        def clone(to_bzrdir, revision_id=None):
 
833
            """See Branch.clone()."""
 
834
            return format.initialize(to_bzrdir, a_branch)
 
835
            # cannot obey revision_id limits when cloning a reference ...
 
836
            # FIXME RBC 20060210 either nuke revision_id for clone, or
 
837
            # emit some sort of warning/error to the caller ?!
 
838
        return clone
 
839
 
 
840
    def open(self, a_bzrdir, _found=False):
 
841
        """Return the branch that the branch reference in a_bzrdir points at.
 
842
 
 
843
        _found is a private parameter, do not use it. It is used to indicate
 
844
               if format probing has already be done.
 
845
        """
 
846
        if not _found:
 
847
            format = BranchFormat.find_format(a_bzrdir)
 
848
            assert format.__class__ == self.__class__
 
849
        transport = a_bzrdir.get_branch_transport(None)
 
850
        real_bzrdir = bzrdir.BzrDir.open(transport.get('location').read())
 
851
        result = real_bzrdir.open_branch()
 
852
        # this changes the behaviour of result.clone to create a new reference
 
853
        # rather than a copy of the content of the branch.
 
854
        # I did not use a proxy object because that needs much more extensive
 
855
        # testing, and we are only changing one behaviour at the moment.
 
856
        # If we decide to alter more behaviours - i.e. the implicit nickname
 
857
        # then this should be refactored to introduce a tested proxy branch
 
858
        # and a subclass of that for use in overriding clone() and ....
 
859
        # - RBC 20060210
 
860
        result.clone = self._make_reference_clone_function(result)
 
861
        return result
 
862
 
 
863
 
 
864
# formats which have no format string are not discoverable
 
865
# and not independently creatable, so are not registered.
 
866
__default_format = BzrBranchFormat5()
 
867
BranchFormat.register_format(__default_format)
 
868
BranchFormat.register_format(BranchReferenceFormat())
 
869
BranchFormat.set_default_format(__default_format)
 
870
_legacy_formats = [BzrBranchFormat4(),
 
871
                   ]
 
872
 
 
873
class BzrBranch(Branch):
 
874
    """A branch stored in the actual filesystem.
 
875
 
 
876
    Note that it's "local" in the context of the filesystem; it doesn't
 
877
    really matter if it's on an nfs/smb/afs/coda/... share, as long as
 
878
    it's writable, and can be accessed via the normal filesystem API.
 
879
    """
 
880
    
 
881
    def __init__(self, transport=DEPRECATED_PARAMETER, init=DEPRECATED_PARAMETER,
 
882
                 relax_version_check=DEPRECATED_PARAMETER, _format=None,
 
883
                 _control_files=None, a_bzrdir=None, _repository=None):
 
884
        """Create new branch object at a particular location.
 
885
 
 
886
        transport -- A Transport object, defining how to access files.
 
887
        
 
888
        init -- If True, create new control files in a previously
 
889
             unversioned directory.  If False, the branch must already
 
890
             be versioned.
 
891
 
 
892
        relax_version_check -- If true, the usual check for the branch
 
893
            version is not applied.  This is intended only for
 
894
            upgrade/recovery type use; it's not guaranteed that
 
895
            all operations will work on old format branches.
 
896
        """
 
897
        if a_bzrdir is None:
 
898
            self.bzrdir = bzrdir.BzrDir.open(transport.base)
 
899
        else:
 
900
            self.bzrdir = a_bzrdir
 
901
        self._transport = self.bzrdir.transport.clone('..')
 
902
        self._base = self._transport.base
 
903
        self._format = _format
 
904
        if _control_files is None:
 
905
            raise BzrBadParameterMissing('_control_files')
 
906
        self.control_files = _control_files
 
907
        if deprecated_passed(init):
 
908
            warn("BzrBranch.__init__(..., init=XXX): The init parameter is "
 
909
                 "deprecated as of bzr 0.8. Please use Branch.create().",
 
910
                 DeprecationWarning,
 
911
                 stacklevel=2)
 
912
            if init:
 
913
                # this is slower than before deprecation, oh well never mind.
 
914
                # -> its deprecated.
 
915
                self._initialize(transport.base)
 
916
        self._check_format(_format)
 
917
        if deprecated_passed(relax_version_check):
 
918
            warn("BzrBranch.__init__(..., relax_version_check=XXX_: The "
 
919
                 "relax_version_check parameter is deprecated as of bzr 0.8. "
 
920
                 "Please use BzrDir.open_downlevel, or a BzrBranchFormat's "
 
921
                 "open() method.",
 
922
                 DeprecationWarning,
 
923
                 stacklevel=2)
 
924
            if (not relax_version_check
 
925
                and not self._format.is_supported()):
 
926
                raise errors.UnsupportedFormatError(
 
927
                        'sorry, branch format %r not supported' % fmt,
 
928
                        ['use a different bzr version',
 
929
                         'or remove the .bzr directory'
 
930
                         ' and "bzr init" again'])
 
931
        if deprecated_passed(transport):
 
932
            warn("BzrBranch.__init__(transport=XXX...): The transport "
 
933
                 "parameter is deprecated as of bzr 0.8. "
 
934
                 "Please use Branch.open, or bzrdir.open_branch().",
 
935
                 DeprecationWarning,
 
936
                 stacklevel=2)
 
937
        self.repository = _repository
 
938
 
 
939
    def __str__(self):
 
940
        return '%s(%r)' % (self.__class__.__name__, self.base)
 
941
 
 
942
    __repr__ = __str__
 
943
 
 
944
    def __del__(self):
 
945
        # TODO: It might be best to do this somewhere else,
 
946
        # but it is nice for a Branch object to automatically
 
947
        # cache it's information.
 
948
        # Alternatively, we could have the Transport objects cache requests
 
949
        # See the earlier discussion about how major objects (like Branch)
 
950
        # should never expect their __del__ function to run.
 
951
        # XXX: cache_root seems to be unused, 2006-01-13 mbp
 
952
        if hasattr(self, 'cache_root') and self.cache_root is not None:
 
953
            try:
 
954
                rmtree(self.cache_root)
 
955
            except:
 
956
                pass
 
957
            self.cache_root = None
 
958
 
 
959
    def _get_base(self):
 
960
        return self._base
 
961
 
 
962
    base = property(_get_base, doc="The URL for the root of this branch.")
 
963
 
 
964
    def _finish_transaction(self):
 
965
        """Exit the current transaction."""
 
966
        return self.control_files._finish_transaction()
 
967
 
 
968
    def get_transaction(self):
 
969
        """Return the current active transaction.
 
970
 
 
971
        If no transaction is active, this returns a passthrough object
 
972
        for which all data is immediately flushed and no caching happens.
 
973
        """
 
974
        # this is an explicit function so that we can do tricky stuff
 
975
        # when the storage in rev_storage is elsewhere.
 
976
        # we probably need to hook the two 'lock a location' and 
 
977
        # 'have a transaction' together more delicately, so that
 
978
        # we can have two locks (branch and storage) and one transaction
 
979
        # ... and finishing the transaction unlocks both, but unlocking
 
980
        # does not. - RBC 20051121
 
981
        return self.control_files.get_transaction()
 
982
 
 
983
    def _set_transaction(self, transaction):
 
984
        """Set a new active transaction."""
 
985
        return self.control_files._set_transaction(transaction)
 
986
 
 
987
    def abspath(self, name):
 
988
        """See Branch.abspath."""
 
989
        return self.control_files._transport.abspath(name)
 
990
 
 
991
    def _check_format(self, format):
 
992
        """Identify the branch format if needed.
 
993
 
 
994
        The format is stored as a reference to the format object in
 
995
        self._format for code that needs to check it later.
 
996
 
 
997
        The format parameter is either None or the branch format class
 
998
        used to open this branch.
 
999
 
 
1000
        FIXME: DELETE THIS METHOD when pre 0.8 support is removed.
 
1001
        """
 
1002
        if format is None:
 
1003
            format = BzrBranchFormat.find_format(self.bzrdir)
 
1004
        self._format = format
 
1005
        mutter("got branch format %s", self._format)
 
1006
 
 
1007
    @needs_read_lock
 
1008
    def get_root_id(self):
 
1009
        """See Branch.get_root_id."""
 
1010
        tree = self.repository.revision_tree(self.last_revision())
 
1011
        return tree.inventory.root.file_id
 
1012
 
 
1013
    def is_locked(self):
 
1014
        return self.control_files.is_locked()
 
1015
 
 
1016
    def lock_write(self):
 
1017
        # TODO: test for failed two phase locks. This is known broken.
 
1018
        self.control_files.lock_write()
 
1019
        self.repository.lock_write()
 
1020
 
 
1021
    def lock_read(self):
 
1022
        # TODO: test for failed two phase locks. This is known broken.
 
1023
        self.control_files.lock_read()
 
1024
        self.repository.lock_read()
 
1025
 
 
1026
    def unlock(self):
 
1027
        # TODO: test for failed two phase locks. This is known broken.
 
1028
        try:
 
1029
            self.repository.unlock()
 
1030
        finally:
 
1031
            self.control_files.unlock()
 
1032
        
 
1033
    def peek_lock_mode(self):
 
1034
        if self.control_files._lock_count == 0:
 
1035
            return None
 
1036
        else:
 
1037
            return self.control_files._lock_mode
 
1038
 
 
1039
    def get_physical_lock_status(self):
 
1040
        return self.control_files.get_physical_lock_status()
 
1041
 
 
1042
    @needs_read_lock
 
1043
    def print_file(self, file, revision_id):
 
1044
        """See Branch.print_file."""
 
1045
        return self.repository.print_file(file, revision_id)
 
1046
 
 
1047
    @needs_write_lock
 
1048
    def append_revision(self, *revision_ids):
 
1049
        """See Branch.append_revision."""
 
1050
        for revision_id in revision_ids:
 
1051
            mutter("add {%s} to revision-history" % revision_id)
 
1052
        rev_history = self.revision_history()
 
1053
        rev_history.extend(revision_ids)
 
1054
        self.set_revision_history(rev_history)
 
1055
 
 
1056
    @needs_write_lock
 
1057
    def set_revision_history(self, rev_history):
 
1058
        """See Branch.set_revision_history."""
 
1059
        self.control_files.put_utf8(
 
1060
            'revision-history', '\n'.join(rev_history))
 
1061
        transaction = self.get_transaction()
 
1062
        history = transaction.map.find_revision_history()
 
1063
        if history is not None:
 
1064
            # update the revision history in the identity map.
 
1065
            history[:] = list(rev_history)
 
1066
            # this call is disabled because revision_history is 
 
1067
            # not really an object yet, and the transaction is for objects.
 
1068
            # transaction.register_dirty(history)
 
1069
        else:
 
1070
            transaction.map.add_revision_history(rev_history)
 
1071
            # this call is disabled because revision_history is 
 
1072
            # not really an object yet, and the transaction is for objects.
 
1073
            # transaction.register_clean(history)
 
1074
 
 
1075
    def get_revision_delta(self, revno):
 
1076
        """Return the delta for one revision.
 
1077
 
 
1078
        The delta is relative to its mainline predecessor, or the
 
1079
        empty tree for revision 1.
 
1080
        """
 
1081
        assert isinstance(revno, int)
 
1082
        rh = self.revision_history()
 
1083
        if not (1 <= revno <= len(rh)):
 
1084
            raise InvalidRevisionNumber(revno)
 
1085
 
 
1086
        # revno is 1-based; list is 0-based
 
1087
 
 
1088
        new_tree = self.repository.revision_tree(rh[revno-1])
 
1089
        if revno == 1:
 
1090
            old_tree = EmptyTree()
 
1091
        else:
 
1092
            old_tree = self.repository.revision_tree(rh[revno-2])
 
1093
        return compare_trees(old_tree, new_tree)
 
1094
 
 
1095
    @needs_read_lock
 
1096
    def revision_history(self):
 
1097
        """See Branch.revision_history."""
 
1098
        transaction = self.get_transaction()
 
1099
        history = transaction.map.find_revision_history()
 
1100
        if history is not None:
 
1101
            mutter("cache hit for revision-history in %s", self)
 
1102
            return list(history)
 
1103
        history = [l.rstrip('\r\n') for l in
 
1104
                self.control_files.get_utf8('revision-history').readlines()]
 
1105
        transaction.map.add_revision_history(history)
 
1106
        # this call is disabled because revision_history is 
 
1107
        # not really an object yet, and the transaction is for objects.
 
1108
        # transaction.register_clean(history, precious=True)
 
1109
        return list(history)
 
1110
 
 
1111
    @needs_write_lock
 
1112
    def update_revisions(self, other, stop_revision=None):
 
1113
        """See Branch.update_revisions."""
 
1114
        other.lock_read()
 
1115
        try:
 
1116
            if stop_revision is None:
 
1117
                stop_revision = other.last_revision()
 
1118
                if stop_revision is None:
 
1119
                    # if there are no commits, we're done.
 
1120
                    return
 
1121
            # whats the current last revision, before we fetch [and change it
 
1122
            # possibly]
 
1123
            last_rev = self.last_revision()
 
1124
            # we fetch here regardless of whether we need to so that we pickup
 
1125
            # filled in ghosts.
 
1126
            self.fetch(other, stop_revision)
 
1127
            my_ancestry = self.repository.get_ancestry(last_rev)
 
1128
            if stop_revision in my_ancestry:
 
1129
                # last_revision is a descendant of stop_revision
 
1130
                return
 
1131
            # stop_revision must be a descendant of last_revision
 
1132
            stop_graph = self.repository.get_revision_graph(stop_revision)
 
1133
            if last_rev is not None and last_rev not in stop_graph:
 
1134
                # our previous tip is not merged into stop_revision
 
1135
                raise errors.DivergedBranches(self, other)
 
1136
            # make a new revision history from the graph
 
1137
            current_rev_id = stop_revision
 
1138
            new_history = []
 
1139
            while current_rev_id not in (None, NULL_REVISION):
 
1140
                new_history.append(current_rev_id)
 
1141
                current_rev_id_parents = stop_graph[current_rev_id]
 
1142
                try:
 
1143
                    current_rev_id = current_rev_id_parents[0]
 
1144
                except IndexError:
 
1145
                    current_rev_id = None
 
1146
            new_history.reverse()
 
1147
            self.set_revision_history(new_history)
 
1148
        finally:
 
1149
            other.unlock()
 
1150
 
 
1151
    def basis_tree(self):
 
1152
        """See Branch.basis_tree."""
 
1153
        return self.repository.revision_tree(self.last_revision())
 
1154
 
 
1155
    @deprecated_method(zero_eight)
 
1156
    def working_tree(self):
 
1157
        """Create a Working tree object for this branch."""
 
1158
        from bzrlib.workingtree import WorkingTree
 
1159
        from bzrlib.transport.local import LocalTransport
 
1160
        if (self.base.find('://') != -1 or 
 
1161
            not isinstance(self._transport, LocalTransport)):
 
1162
            raise NoWorkingTree(self.base)
 
1163
        return self.bzrdir.open_workingtree()
 
1164
 
 
1165
    @needs_write_lock
 
1166
    def pull(self, source, overwrite=False, stop_revision=None):
 
1167
        """See Branch.pull."""
 
1168
        source.lock_read()
 
1169
        try:
 
1170
            old_count = len(self.revision_history())
 
1171
            try:
 
1172
                self.update_revisions(source,stop_revision)
 
1173
            except DivergedBranches:
 
1174
                if not overwrite:
 
1175
                    raise
 
1176
            if overwrite:
 
1177
                self.set_revision_history(source.revision_history())
 
1178
            new_count = len(self.revision_history())
 
1179
            return new_count - old_count
 
1180
        finally:
 
1181
            source.unlock()
 
1182
 
 
1183
    def get_parent(self):
 
1184
        """See Branch.get_parent."""
 
1185
        import errno
 
1186
        _locs = ['parent', 'pull', 'x-pull']
 
1187
        assert self.base[-1] == '/'
 
1188
        for l in _locs:
 
1189
            try:
 
1190
                parent = self.control_files.get(l).read().strip('\n')
 
1191
            except NoSuchFile:
 
1192
                continue
 
1193
            # This is an old-format absolute path to a local branch
 
1194
            # turn it into a url
 
1195
            if parent.startswith('/'):
 
1196
                parent = urlutils.local_path_to_url(parent.decode('utf8'))
 
1197
            return urlutils.join(self.base[:-1], parent)
 
1198
        return None
 
1199
 
 
1200
    def get_push_location(self):
 
1201
        """See Branch.get_push_location."""
 
1202
        config = bzrlib.config.BranchConfig(self)
 
1203
        push_loc = config.get_user_option('push_location')
 
1204
        return push_loc
 
1205
 
 
1206
    def set_push_location(self, location):
 
1207
        """See Branch.set_push_location."""
 
1208
        config = bzrlib.config.LocationConfig(self.base)
 
1209
        config.set_user_option('push_location', location)
 
1210
 
 
1211
    @needs_write_lock
 
1212
    def set_parent(self, url):
 
1213
        """See Branch.set_parent."""
 
1214
        # TODO: Maybe delete old location files?
 
1215
        # URLs should never be unicode, even on the local fs,
 
1216
        # FIXUP this and get_parent in a future branch format bump:
 
1217
        # read and rewrite the file, and have the new format code read
 
1218
        # using .get not .get_utf8. RBC 20060125
 
1219
        if url is None:
 
1220
            self.control_files._transport.delete('parent')
 
1221
        else:
 
1222
            if isinstance(url, unicode):
 
1223
                try: 
 
1224
                    url = url.encode('ascii')
 
1225
                except UnicodeEncodeError:
 
1226
                    raise bzrlib.errors.InvalidURL(url,
 
1227
                        "Urls must be 7-bit ascii, "
 
1228
                        "use bzrlib.urlutils.escape")
 
1229
                    
 
1230
            url = urlutils.relative_url(self.base, url)
 
1231
            self.control_files.put('parent', url + '\n')
 
1232
 
 
1233
    def tree_config(self):
 
1234
        return TreeConfig(self)
 
1235
 
 
1236
 
 
1237
class BzrBranch5(BzrBranch):
 
1238
    """A format 5 branch. This supports new features over plan branches.
 
1239
 
 
1240
    It has support for a master_branch which is the data for bound branches.
 
1241
    """
 
1242
 
 
1243
    def __init__(self,
 
1244
                 _format,
 
1245
                 _control_files,
 
1246
                 a_bzrdir,
 
1247
                 _repository):
 
1248
        super(BzrBranch5, self).__init__(_format=_format,
 
1249
                                         _control_files=_control_files,
 
1250
                                         a_bzrdir=a_bzrdir,
 
1251
                                         _repository=_repository)
 
1252
        
 
1253
    @needs_write_lock
 
1254
    def pull(self, source, overwrite=False, stop_revision=None):
 
1255
        """Updates branch.pull to be bound branch aware."""
 
1256
        bound_location = self.get_bound_location()
 
1257
        if source.base != bound_location:
 
1258
            # not pulling from master, so we need to update master.
 
1259
            master_branch = self.get_master_branch()
 
1260
            if master_branch:
 
1261
                master_branch.pull(source)
 
1262
                source = master_branch
 
1263
        return super(BzrBranch5, self).pull(source, overwrite, stop_revision)
 
1264
 
 
1265
    def get_bound_location(self):
 
1266
        try:
 
1267
            return self.control_files.get_utf8('bound').read()[:-1]
 
1268
        except errors.NoSuchFile:
 
1269
            return None
 
1270
 
 
1271
    @needs_read_lock
 
1272
    def get_master_branch(self):
 
1273
        """Return the branch we are bound to.
 
1274
        
 
1275
        :return: Either a Branch, or None
 
1276
 
 
1277
        This could memoise the branch, but if thats done
 
1278
        it must be revalidated on each new lock.
 
1279
        So for now we just don't memoise it.
 
1280
        # RBC 20060304 review this decision.
 
1281
        """
 
1282
        bound_loc = self.get_bound_location()
 
1283
        if not bound_loc:
 
1284
            return None
 
1285
        try:
 
1286
            return Branch.open(bound_loc)
 
1287
        except (errors.NotBranchError, errors.ConnectionError), e:
 
1288
            raise errors.BoundBranchConnectionFailure(
 
1289
                    self, bound_loc, e)
 
1290
 
 
1291
    @needs_write_lock
 
1292
    def set_bound_location(self, location):
 
1293
        """Set the target where this branch is bound to.
 
1294
 
 
1295
        :param location: URL to the target branch
 
1296
        """
 
1297
        if location:
 
1298
            self.control_files.put_utf8('bound', location+'\n')
 
1299
        else:
 
1300
            try:
 
1301
                self.control_files._transport.delete('bound')
 
1302
            except NoSuchFile:
 
1303
                return False
 
1304
            return True
 
1305
 
 
1306
    @needs_write_lock
 
1307
    def bind(self, other):
 
1308
        """Bind the local branch the other branch.
 
1309
 
 
1310
        :param other: The branch to bind to
 
1311
        :type other: Branch
 
1312
        """
 
1313
        # TODO: jam 20051230 Consider checking if the target is bound
 
1314
        #       It is debatable whether you should be able to bind to
 
1315
        #       a branch which is itself bound.
 
1316
        #       Committing is obviously forbidden,
 
1317
        #       but binding itself may not be.
 
1318
        #       Since we *have* to check at commit time, we don't
 
1319
        #       *need* to check here
 
1320
        self.pull(other)
 
1321
 
 
1322
        # we are now equal to or a suffix of other.
 
1323
 
 
1324
        # Since we have 'pulled' from the remote location,
 
1325
        # now we should try to pull in the opposite direction
 
1326
        # in case the local tree has more revisions than the
 
1327
        # remote one.
 
1328
        # There may be a different check you could do here
 
1329
        # rather than actually trying to install revisions remotely.
 
1330
        # TODO: capture an exception which indicates the remote branch
 
1331
        #       is not writable. 
 
1332
        #       If it is up-to-date, this probably should not be a failure
 
1333
        
 
1334
        # lock other for write so the revision-history syncing cannot race
 
1335
        other.lock_write()
 
1336
        try:
 
1337
            other.pull(self)
 
1338
            # if this does not error, other now has the same last rev we do
 
1339
            # it can only error if the pull from other was concurrent with
 
1340
            # a commit to other from someone else.
 
1341
 
 
1342
            # until we ditch revision-history, we need to sync them up:
 
1343
            self.set_revision_history(other.revision_history())
 
1344
            # now other and self are up to date with each other and have the
 
1345
            # same revision-history.
 
1346
        finally:
 
1347
            other.unlock()
 
1348
 
 
1349
        self.set_bound_location(other.base)
 
1350
 
 
1351
    @needs_write_lock
 
1352
    def unbind(self):
 
1353
        """If bound, unbind"""
 
1354
        return self.set_bound_location(None)
 
1355
 
 
1356
    @needs_write_lock
 
1357
    def update(self):
 
1358
        """Synchronise this branch with the master branch if any. 
 
1359
 
 
1360
        :return: None or the last_revision that was pivoted out during the
 
1361
                 update.
 
1362
        """
 
1363
        master = self.get_master_branch()
 
1364
        if master is not None:
 
1365
            old_tip = self.last_revision()
 
1366
            self.pull(master, overwrite=True)
 
1367
            if old_tip in self.repository.get_ancestry(self.last_revision()):
 
1368
                return None
 
1369
            return old_tip
 
1370
        return None
 
1371
 
 
1372
 
 
1373
class BranchTestProviderAdapter(object):
 
1374
    """A tool to generate a suite testing multiple branch formats at once.
 
1375
 
 
1376
    This is done by copying the test once for each transport and injecting
 
1377
    the transport_server, transport_readonly_server, and branch_format
 
1378
    classes into each copy. Each copy is also given a new id() to make it
 
1379
    easy to identify.
 
1380
    """
 
1381
 
 
1382
    def __init__(self, transport_server, transport_readonly_server, formats):
 
1383
        self._transport_server = transport_server
 
1384
        self._transport_readonly_server = transport_readonly_server
 
1385
        self._formats = formats
 
1386
    
 
1387
    def adapt(self, test):
 
1388
        result = TestSuite()
 
1389
        for branch_format, bzrdir_format in self._formats:
 
1390
            new_test = deepcopy(test)
 
1391
            new_test.transport_server = self._transport_server
 
1392
            new_test.transport_readonly_server = self._transport_readonly_server
 
1393
            new_test.bzrdir_format = bzrdir_format
 
1394
            new_test.branch_format = branch_format
 
1395
            def make_new_test_id():
 
1396
                new_id = "%s(%s)" % (new_test.id(), branch_format.__class__.__name__)
 
1397
                return lambda: new_id
 
1398
            new_test.id = make_new_test_id()
 
1399
            result.addTest(new_test)
 
1400
        return result
 
1401
 
 
1402
 
 
1403
class BranchCheckResult(object):
 
1404
    """Results of checking branch consistency.
 
1405
 
 
1406
    :see: Branch.check
 
1407
    """
 
1408
 
 
1409
    def __init__(self, branch):
 
1410
        self.branch = branch
 
1411
 
 
1412
    def report_results(self, verbose):
 
1413
        """Report the check results via trace.note.
 
1414
        
 
1415
        :param verbose: Requests more detailed display of what was checked,
 
1416
            if any.
 
1417
        """
 
1418
        note('checked branch %s format %s',
 
1419
             self.branch.base,
 
1420
             self.branch._format)
 
1421
 
 
1422
 
 
1423
######################################################################
 
1424
# predicates
 
1425
 
 
1426
 
 
1427
@deprecated_function(zero_eight)
 
1428
def ScratchBranch(*args, **kwargs):
 
1429
    """See bzrlib.bzrdir.ScratchDir."""
 
1430
    d = ScratchDir(*args, **kwargs)
 
1431
    return d.open_branch()
 
1432
 
 
1433
 
 
1434
@deprecated_function(zero_eight)
 
1435
def is_control_file(*args, **kwargs):
 
1436
    """See bzrlib.workingtree.is_control_file."""
 
1437
    return bzrlib.workingtree.is_control_file(*args, **kwargs)