/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: Aaron Bentley
  • Date: 2007-02-09 01:15:10 UTC
  • mto: (2230.3.47 branch6)
  • mto: This revision was merged to the branch mainline in revision 2290.
  • Revision ID: aaron.bentley@utoronto.ca-20070209011510-ta7b7x7w6bagd2gk
Set default serializer to 0.9

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