/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: John Arbash Meinel
  • Date: 2007-04-17 21:19:29 UTC
  • mto: This revision was merged to the branch mainline in revision 2452.
  • Revision ID: john@arbash-meinel.com-20070417211929-rchob1jeahy30cj0
Update annotate.py to use the new helper function.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005, 2006, 2007 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
        tsort,
 
39
        ui,
 
40
        urlutils,
 
41
        )
 
42
from bzrlib.config import BranchConfig, TreeConfig
 
43
from bzrlib.lockable_files import LockableFiles, TransportLock
 
44
from bzrlib.tag import (
 
45
    BasicTags,
 
46
    DisabledTags,
 
47
    )
 
48
""")
 
49
 
 
50
from bzrlib.decorators import needs_read_lock, needs_write_lock
 
51
from bzrlib.errors import (BzrError, BzrCheckError, DivergedBranches,
 
52
                           HistoryMissing, InvalidRevisionId,
 
53
                           InvalidRevisionNumber, LockError, NoSuchFile,
 
54
                           NoSuchRevision, NoWorkingTree, NotVersionedError,
 
55
                           NotBranchError, UninitializableFormat,
 
56
                           UnlistableStore, UnlistableBranch,
 
57
                           )
 
58
from bzrlib.hooks import Hooks
 
59
from bzrlib.symbol_versioning import (deprecated_function,
 
60
                                      deprecated_method,
 
61
                                      DEPRECATED_PARAMETER,
 
62
                                      deprecated_passed,
 
63
                                      zero_eight, zero_nine, zero_sixteen,
 
64
                                      )
 
65
from bzrlib.trace import mutter, note
 
66
 
 
67
 
 
68
BZR_BRANCH_FORMAT_4 = "Bazaar-NG branch, format 0.0.4\n"
 
69
BZR_BRANCH_FORMAT_5 = "Bazaar-NG branch, format 5\n"
 
70
BZR_BRANCH_FORMAT_6 = "Bazaar Branch Format 6 (bzr 0.15)\n"
 
71
 
 
72
 
 
73
# TODO: Maybe include checks for common corruption of newlines, etc?
 
74
 
 
75
# TODO: Some operations like log might retrieve the same revisions
 
76
# repeatedly to calculate deltas.  We could perhaps have a weakref
 
77
# cache in memory to make this faster.  In general anything can be
 
78
# cached in memory between lock and unlock operations. .. nb thats
 
79
# what the transaction identity map provides
 
80
 
 
81
 
 
82
######################################################################
 
83
# branch objects
 
84
 
 
85
class Branch(object):
 
86
    """Branch holding a history of revisions.
 
87
 
 
88
    base
 
89
        Base directory/url of the branch.
 
90
 
 
91
    hooks: An instance of BranchHooks.
 
92
    """
 
93
    # this is really an instance variable - FIXME move it there
 
94
    # - RBC 20060112
 
95
    base = None
 
96
 
 
97
    # override this to set the strategy for storing tags
 
98
    def _make_tags(self):
 
99
        return DisabledTags(self)
 
100
 
 
101
    def __init__(self, *ignored, **ignored_too):
 
102
        self.tags = self._make_tags()
 
103
        self._revision_history_cache = None
 
104
        self._revision_id_to_revno_cache = None
 
105
 
 
106
    def break_lock(self):
 
107
        """Break a lock if one is present from another instance.
 
108
 
 
109
        Uses the ui factory to ask for confirmation if the lock may be from
 
110
        an active process.
 
111
 
 
112
        This will probe the repository for its lock as well.
 
113
        """
 
114
        self.control_files.break_lock()
 
115
        self.repository.break_lock()
 
116
        master = self.get_master_branch()
 
117
        if master is not None:
 
118
            master.break_lock()
 
119
 
 
120
    @staticmethod
 
121
    @deprecated_method(zero_eight)
 
122
    def open_downlevel(base):
 
123
        """Open a branch which may be of an old format."""
 
124
        return Branch.open(base, _unsupported=True)
 
125
        
 
126
    @staticmethod
 
127
    def open(base, _unsupported=False):
 
128
        """Open the branch rooted at base.
 
129
 
 
130
        For instance, if the branch is at URL/.bzr/branch,
 
131
        Branch.open(URL) -> a Branch instance.
 
132
        """
 
133
        control = bzrdir.BzrDir.open(base, _unsupported)
 
134
        return control.open_branch(_unsupported)
 
135
 
 
136
    @staticmethod
 
137
    def open_containing(url):
 
138
        """Open an existing branch which contains url.
 
139
        
 
140
        This probes for a branch at url, and searches upwards from there.
 
141
 
 
142
        Basically we keep looking up until we find the control directory or
 
143
        run into the root.  If there isn't one, raises NotBranchError.
 
144
        If there is one and it is either an unrecognised format or an unsupported 
 
145
        format, UnknownFormatError or UnsupportedFormatError are raised.
 
146
        If there is one, it is returned, along with the unused portion of url.
 
147
        """
 
148
        control, relpath = bzrdir.BzrDir.open_containing(url)
 
149
        return control.open_branch(), relpath
 
150
 
 
151
    @staticmethod
 
152
    @deprecated_function(zero_eight)
 
153
    def initialize(base):
 
154
        """Create a new working tree and branch, rooted at 'base' (url)
 
155
 
 
156
        NOTE: This will soon be deprecated in favour of creation
 
157
        through a BzrDir.
 
158
        """
 
159
        return bzrdir.BzrDir.create_standalone_workingtree(base).branch
 
160
 
 
161
    @deprecated_function(zero_eight)
 
162
    def setup_caching(self, cache_root):
 
163
        """Subclasses that care about caching should override this, and set
 
164
        up cached stores located under cache_root.
 
165
        
 
166
        NOTE: This is unused.
 
167
        """
 
168
        pass
 
169
 
 
170
    def get_config(self):
 
171
        return BranchConfig(self)
 
172
 
 
173
    def _get_nick(self):
 
174
        return self.get_config().get_nickname()
 
175
 
 
176
    def _set_nick(self, nick):
 
177
        self.get_config().set_user_option('nickname', nick)
 
178
 
 
179
    nick = property(_get_nick, _set_nick)
 
180
 
 
181
    def is_locked(self):
 
182
        raise NotImplementedError(self.is_locked)
 
183
 
 
184
    def lock_write(self):
 
185
        raise NotImplementedError(self.lock_write)
 
186
 
 
187
    def lock_read(self):
 
188
        raise NotImplementedError(self.lock_read)
 
189
 
 
190
    def unlock(self):
 
191
        raise NotImplementedError(self.unlock)
 
192
 
 
193
    def peek_lock_mode(self):
 
194
        """Return lock mode for the Branch: 'r', 'w' or None"""
 
195
        raise NotImplementedError(self.peek_lock_mode)
 
196
 
 
197
    def get_physical_lock_status(self):
 
198
        raise NotImplementedError(self.get_physical_lock_status)
 
199
 
 
200
    def leave_lock_in_place(self):
 
201
        """Tell this branch object not to release the physical lock when this
 
202
        object is unlocked.
 
203
        
 
204
        If lock_write doesn't return a token, then this method is not supported.
 
205
        """
 
206
        self.control_files.leave_in_place()
 
207
 
 
208
    def dont_leave_lock_in_place(self):
 
209
        """Tell this branch object to release the physical lock when this
 
210
        object is unlocked, even if it didn't originally acquire it.
 
211
 
 
212
        If lock_write doesn't return a token, then this method is not supported.
 
213
        """
 
214
        self.control_files.dont_leave_in_place()
 
215
 
 
216
    def abspath(self, name):
 
217
        """Return absolute filename for something in the branch
 
218
        
 
219
        XXX: Robert Collins 20051017 what is this used for? why is it a branch
 
220
        method and not a tree method.
 
221
        """
 
222
        raise NotImplementedError(self.abspath)
 
223
 
 
224
    def bind(self, other):
 
225
        """Bind the local branch the other branch.
 
226
 
 
227
        :param other: The branch to bind to
 
228
        :type other: Branch
 
229
        """
 
230
        raise errors.UpgradeRequired(self.base)
 
231
 
 
232
    @needs_write_lock
 
233
    def fetch(self, from_branch, last_revision=None, pb=None):
 
234
        """Copy revisions from from_branch into this branch.
 
235
 
 
236
        :param from_branch: Where to copy from.
 
237
        :param last_revision: What revision to stop at (None for at the end
 
238
                              of the branch.
 
239
        :param pb: An optional progress bar to use.
 
240
 
 
241
        Returns the copied revision count and the failed revisions in a tuple:
 
242
        (copied, failures).
 
243
        """
 
244
        if self.base == from_branch.base:
 
245
            return (0, [])
 
246
        if pb is None:
 
247
            nested_pb = ui.ui_factory.nested_progress_bar()
 
248
            pb = nested_pb
 
249
        else:
 
250
            nested_pb = None
 
251
 
 
252
        from_branch.lock_read()
 
253
        try:
 
254
            if last_revision is None:
 
255
                pb.update('get source history')
 
256
                last_revision = from_branch.last_revision()
 
257
                if last_revision is None:
 
258
                    last_revision = _mod_revision.NULL_REVISION
 
259
            return self.repository.fetch(from_branch.repository,
 
260
                                         revision_id=last_revision,
 
261
                                         pb=nested_pb)
 
262
        finally:
 
263
            if nested_pb is not None:
 
264
                nested_pb.finished()
 
265
            from_branch.unlock()
 
266
 
 
267
    def get_bound_location(self):
 
268
        """Return the URL of the branch we are bound to.
 
269
 
 
270
        Older format branches cannot bind, please be sure to use a metadir
 
271
        branch.
 
272
        """
 
273
        return None
 
274
    
 
275
    def get_old_bound_location(self):
 
276
        """Return the URL of the branch we used to be bound to
 
277
        """
 
278
        raise errors.UpgradeRequired(self.base)
 
279
 
 
280
    def get_commit_builder(self, parents, config=None, timestamp=None, 
 
281
                           timezone=None, committer=None, revprops=None, 
 
282
                           revision_id=None):
 
283
        """Obtain a CommitBuilder for this branch.
 
284
        
 
285
        :param parents: Revision ids of the parents of the new revision.
 
286
        :param config: Optional configuration to use.
 
287
        :param timestamp: Optional timestamp recorded for commit.
 
288
        :param timezone: Optional timezone for timestamp.
 
289
        :param committer: Optional committer to set for commit.
 
290
        :param revprops: Optional dictionary of revision properties.
 
291
        :param revision_id: Optional revision id.
 
292
        """
 
293
 
 
294
        if config is None:
 
295
            config = self.get_config()
 
296
        
 
297
        return self.repository.get_commit_builder(self, parents, config,
 
298
            timestamp, timezone, committer, revprops, revision_id)
 
299
 
 
300
    def get_master_branch(self):
 
301
        """Return the branch we are bound to.
 
302
        
 
303
        :return: Either a Branch, or None
 
304
        """
 
305
        return None
 
306
 
 
307
    def get_revision_delta(self, revno):
 
308
        """Return the delta for one revision.
 
309
 
 
310
        The delta is relative to its mainline predecessor, or the
 
311
        empty tree for revision 1.
 
312
        """
 
313
        assert isinstance(revno, int)
 
314
        rh = self.revision_history()
 
315
        if not (1 <= revno <= len(rh)):
 
316
            raise InvalidRevisionNumber(revno)
 
317
        return self.repository.get_revision_delta(rh[revno-1])
 
318
 
 
319
    @deprecated_method(zero_sixteen)
 
320
    def get_root_id(self):
 
321
        """Return the id of this branches root
 
322
 
 
323
        Deprecated: branches don't have root ids-- trees do.
 
324
        Use basis_tree().get_root_id() instead.
 
325
        """
 
326
        raise NotImplementedError(self.get_root_id)
 
327
 
 
328
    def print_file(self, file, revision_id):
 
329
        """Print `file` to stdout."""
 
330
        raise NotImplementedError(self.print_file)
 
331
 
 
332
    def append_revision(self, *revision_ids):
 
333
        raise NotImplementedError(self.append_revision)
 
334
 
 
335
    def set_revision_history(self, rev_history):
 
336
        raise NotImplementedError(self.set_revision_history)
 
337
 
 
338
    def _cache_revision_history(self, rev_history):
 
339
        """Set the cached revision history to rev_history.
 
340
 
 
341
        The revision_history method will use this cache to avoid regenerating
 
342
        the revision history.
 
343
 
 
344
        This API is semi-public; it only for use by subclasses, all other code
 
345
        should consider it to be private.
 
346
        """
 
347
        self._revision_history_cache = rev_history
 
348
 
 
349
    def _cache_revision_id_to_revno(self, revision_id_to_revno):
 
350
        """Set the cached revision_id => revno map to revision_id_to_revno.
 
351
 
 
352
        This API is semi-public; it only for use by subclasses, all other code
 
353
        should consider it to be private.
 
354
        """
 
355
        self._revision_id_to_revno_cache = revision_id_to_revno
 
356
 
 
357
    def _clear_cached_state(self):
 
358
        """Clear any cached data on this branch, e.g. cached revision history.
 
359
 
 
360
        This means the next call to revision_history will need to call
 
361
        _gen_revision_history.
 
362
 
 
363
        This API is semi-public; it only for use by subclasses, all other code
 
364
        should consider it to be private.
 
365
        """
 
366
        self._revision_history_cache = None
 
367
        self._revision_id_to_revno_cache = None
 
368
 
 
369
    def _gen_revision_history(self):
 
370
        """Return sequence of revision hashes on to this branch.
 
371
        
 
372
        Unlike revision_history, this method always regenerates or rereads the
 
373
        revision history, i.e. it does not cache the result, so repeated calls
 
374
        may be expensive.
 
375
 
 
376
        Concrete subclasses should override this instead of revision_history so
 
377
        that subclasses do not need to deal with caching logic.
 
378
        
 
379
        This API is semi-public; it only for use by subclasses, all other code
 
380
        should consider it to be private.
 
381
        """
 
382
        raise NotImplementedError(self._gen_revision_history)
 
383
 
 
384
    @needs_read_lock
 
385
    def revision_history(self):
 
386
        """Return sequence of revision hashes on to this branch.
 
387
        
 
388
        This method will cache the revision history for as long as it is safe to
 
389
        do so.
 
390
        """
 
391
        if self._revision_history_cache is not None:
 
392
            history = self._revision_history_cache
 
393
        else:
 
394
            history = self._gen_revision_history()
 
395
            self._cache_revision_history(history)
 
396
        return list(history)
 
397
 
 
398
    def revno(self):
 
399
        """Return current revision number for this branch.
 
400
 
 
401
        That is equivalent to the number of revisions committed to
 
402
        this branch.
 
403
        """
 
404
        return len(self.revision_history())
 
405
 
 
406
    def unbind(self):
 
407
        """Older format branches cannot bind or unbind."""
 
408
        raise errors.UpgradeRequired(self.base)
 
409
 
 
410
    def set_append_revisions_only(self, enabled):
 
411
        """Older format branches are never restricted to append-only"""
 
412
        raise errors.UpgradeRequired(self.base)
 
413
 
 
414
    def last_revision(self):
 
415
        """Return last revision id, or None"""
 
416
        ph = self.revision_history()
 
417
        if ph:
 
418
            return ph[-1]
 
419
        else:
 
420
            return None
 
421
 
 
422
    def last_revision_info(self):
 
423
        """Return information about the last revision.
 
424
 
 
425
        :return: A tuple (revno, last_revision_id).
 
426
        """
 
427
        rh = self.revision_history()
 
428
        revno = len(rh)
 
429
        if revno:
 
430
            return (revno, rh[-1])
 
431
        else:
 
432
            return (0, _mod_revision.NULL_REVISION)
 
433
 
 
434
    def missing_revisions(self, other, stop_revision=None):
 
435
        """Return a list of new revisions that would perfectly fit.
 
436
        
 
437
        If self and other have not diverged, return a list of the revisions
 
438
        present in other, but missing from self.
 
439
        """
 
440
        self_history = self.revision_history()
 
441
        self_len = len(self_history)
 
442
        other_history = other.revision_history()
 
443
        other_len = len(other_history)
 
444
        common_index = min(self_len, other_len) -1
 
445
        if common_index >= 0 and \
 
446
            self_history[common_index] != other_history[common_index]:
 
447
            raise DivergedBranches(self, other)
 
448
 
 
449
        if stop_revision is None:
 
450
            stop_revision = other_len
 
451
        else:
 
452
            assert isinstance(stop_revision, int)
 
453
            if stop_revision > other_len:
 
454
                raise errors.NoSuchRevision(self, stop_revision)
 
455
        return other_history[self_len:stop_revision]
 
456
 
 
457
    def update_revisions(self, other, stop_revision=None):
 
458
        """Pull in new perfect-fit revisions.
 
459
 
 
460
        :param other: Another Branch to pull from
 
461
        :param stop_revision: Updated until the given revision
 
462
        :return: None
 
463
        """
 
464
        raise NotImplementedError(self.update_revisions)
 
465
 
 
466
    @needs_read_lock
 
467
    def revision_id_to_dotted_revno(self, revision_id):
 
468
        """Given a revision id, return its dotted revno."""
 
469
        if revision_id in (None, _mod_revision.NULL_REVISION):
 
470
            return (0,)
 
471
        revision_id = osutils.safe_revision_id(revision_id)
 
472
 
 
473
        revision_id_to_revno = self.get_revision_id_to_revno_map()
 
474
        if revision_id not in revision_id_to_revno:
 
475
            raise errors.NoSuchRevision(self, revision_id)
 
476
        return revision_id_to_revno[revision_id]
 
477
 
 
478
    def revision_id_to_revno(self, revision_id):
 
479
        """Given a revision id, return its revno"""
 
480
        if revision_id is None:
 
481
            return 0
 
482
        revision_id = osutils.safe_revision_id(revision_id)
 
483
        history = self.revision_history()
 
484
        try:
 
485
            return history.index(revision_id) + 1
 
486
        except ValueError:
 
487
            raise errors.NoSuchRevision(self, revision_id)
 
488
 
 
489
    def get_rev_id(self, revno, history=None):
 
490
        """Find the revision id of the specified revno."""
 
491
        if revno == 0:
 
492
            return None
 
493
        if history is None:
 
494
            history = self.revision_history()
 
495
        if revno <= 0 or revno > len(history):
 
496
            raise errors.NoSuchRevision(self, revno)
 
497
        return history[revno - 1]
 
498
 
 
499
    def pull(self, source, overwrite=False, stop_revision=None):
 
500
        """Mirror source into this branch.
 
501
 
 
502
        This branch is considered to be 'local', having low latency.
 
503
 
 
504
        :returns: PullResult instance
 
505
        """
 
506
        raise NotImplementedError(self.pull)
 
507
 
 
508
    def push(self, target, overwrite=False, stop_revision=None):
 
509
        """Mirror this branch into target.
 
510
 
 
511
        This branch is considered to be 'local', having low latency.
 
512
        """
 
513
        raise NotImplementedError(self.push)
 
514
 
 
515
    def basis_tree(self):
 
516
        """Return `Tree` object for last revision."""
 
517
        return self.repository.revision_tree(self.last_revision())
 
518
 
 
519
    def rename_one(self, from_rel, to_rel):
 
520
        """Rename one file.
 
521
 
 
522
        This can change the directory or the filename or both.
 
523
        """
 
524
        raise NotImplementedError(self.rename_one)
 
525
 
 
526
    def move(self, from_paths, to_name):
 
527
        """Rename files.
 
528
 
 
529
        to_name must exist as a versioned directory.
 
530
 
 
531
        If to_name exists and is a directory, the files are moved into
 
532
        it, keeping their old names.  If it is a directory, 
 
533
 
 
534
        Note that to_name is only the last component of the new name;
 
535
        this doesn't change the directory.
 
536
 
 
537
        This returns a list of (from_path, to_path) pairs for each
 
538
        entry that is moved.
 
539
        """
 
540
        raise NotImplementedError(self.move)
 
541
 
 
542
    def get_parent(self):
 
543
        """Return the parent location of the branch.
 
544
 
 
545
        This is the default location for push/pull/missing.  The usual
 
546
        pattern is that the user can override it by specifying a
 
547
        location.
 
548
        """
 
549
        raise NotImplementedError(self.get_parent)
 
550
 
 
551
    def _set_config_location(self, name, url, config=None,
 
552
                             make_relative=False):
 
553
        if config is None:
 
554
            config = self.get_config()
 
555
        if url is None:
 
556
            url = ''
 
557
        elif make_relative:
 
558
            url = urlutils.relative_url(self.base, url)
 
559
        config.set_user_option(name, url)
 
560
 
 
561
    def _get_config_location(self, name, config=None):
 
562
        if config is None:
 
563
            config = self.get_config()
 
564
        location = config.get_user_option(name)
 
565
        if location == '':
 
566
            location = None
 
567
        return location
 
568
 
 
569
    def get_submit_branch(self):
 
570
        """Return the submit location of the branch.
 
571
 
 
572
        This is the default location for bundle.  The usual
 
573
        pattern is that the user can override it by specifying a
 
574
        location.
 
575
        """
 
576
        return self.get_config().get_user_option('submit_branch')
 
577
 
 
578
    def set_submit_branch(self, location):
 
579
        """Return the submit location of the branch.
 
580
 
 
581
        This is the default location for bundle.  The usual
 
582
        pattern is that the user can override it by specifying a
 
583
        location.
 
584
        """
 
585
        self.get_config().set_user_option('submit_branch', location)
 
586
 
 
587
    def get_public_branch(self):
 
588
        """Return the public location of the branch.
 
589
 
 
590
        This is is used by merge directives.
 
591
        """
 
592
        return self._get_config_location('public_branch')
 
593
 
 
594
    def set_public_branch(self, location):
 
595
        """Return the submit location of the branch.
 
596
 
 
597
        This is the default location for bundle.  The usual
 
598
        pattern is that the user can override it by specifying a
 
599
        location.
 
600
        """
 
601
        self._set_config_location('public_branch', location)
 
602
 
 
603
    def get_push_location(self):
 
604
        """Return the None or the location to push this branch to."""
 
605
        raise NotImplementedError(self.get_push_location)
 
606
 
 
607
    def set_push_location(self, location):
 
608
        """Set a new push location for this branch."""
 
609
        raise NotImplementedError(self.set_push_location)
 
610
 
 
611
    def set_parent(self, url):
 
612
        raise NotImplementedError(self.set_parent)
 
613
 
 
614
    @needs_write_lock
 
615
    def update(self):
 
616
        """Synchronise this branch with the master branch if any. 
 
617
 
 
618
        :return: None or the last_revision pivoted out during the update.
 
619
        """
 
620
        return None
 
621
 
 
622
    def check_revno(self, revno):
 
623
        """\
 
624
        Check whether a revno corresponds to any revision.
 
625
        Zero (the NULL revision) is considered valid.
 
626
        """
 
627
        if revno != 0:
 
628
            self.check_real_revno(revno)
 
629
            
 
630
    def check_real_revno(self, revno):
 
631
        """\
 
632
        Check whether a revno corresponds to a real revision.
 
633
        Zero (the NULL revision) is considered invalid
 
634
        """
 
635
        if revno < 1 or revno > self.revno():
 
636
            raise InvalidRevisionNumber(revno)
 
637
 
 
638
    @needs_read_lock
 
639
    def clone(self, to_bzrdir, revision_id=None):
 
640
        """Clone this branch into to_bzrdir preserving all semantic values.
 
641
        
 
642
        revision_id: if not None, the revision history in the new branch will
 
643
                     be truncated to end with revision_id.
 
644
        """
 
645
        result = self._format.initialize(to_bzrdir)
 
646
        self.copy_content_into(result, revision_id=revision_id)
 
647
        return  result
 
648
 
 
649
    @needs_read_lock
 
650
    def sprout(self, to_bzrdir, revision_id=None):
 
651
        """Create a new line of development from the branch, into to_bzrdir.
 
652
        
 
653
        revision_id: if not None, the revision history in the new branch will
 
654
                     be truncated to end with revision_id.
 
655
        """
 
656
        result = self._format.initialize(to_bzrdir)
 
657
        self.copy_content_into(result, revision_id=revision_id)
 
658
        result.set_parent(self.bzrdir.root_transport.base)
 
659
        return result
 
660
 
 
661
    def _synchronize_history(self, destination, revision_id):
 
662
        """Synchronize last revision and revision history between branches.
 
663
 
 
664
        This version is most efficient when the destination is also a
 
665
        BzrBranch5, but works for BzrBranch6 as long as the revision
 
666
        history is the true lefthand parent history, and all of the revisions
 
667
        are in the destination's repository.  If not, set_revision_history
 
668
        will fail.
 
669
 
 
670
        :param destination: The branch to copy the history into
 
671
        :param revision_id: The revision-id to truncate history at.  May
 
672
          be None to copy complete history.
 
673
        """
 
674
        new_history = self.revision_history()
 
675
        if revision_id is not None:
 
676
            revision_id = osutils.safe_revision_id(revision_id)
 
677
            try:
 
678
                new_history = new_history[:new_history.index(revision_id) + 1]
 
679
            except ValueError:
 
680
                rev = self.repository.get_revision(revision_id)
 
681
                new_history = rev.get_history(self.repository)[1:]
 
682
        destination.set_revision_history(new_history)
 
683
 
 
684
    @needs_read_lock
 
685
    def copy_content_into(self, destination, revision_id=None):
 
686
        """Copy the content of self into destination.
 
687
 
 
688
        revision_id: if not None, the revision history in the new branch will
 
689
                     be truncated to end with revision_id.
 
690
        """
 
691
        self._synchronize_history(destination, revision_id)
 
692
        try:
 
693
            parent = self.get_parent()
 
694
        except errors.InaccessibleParent, e:
 
695
            mutter('parent was not accessible to copy: %s', e)
 
696
        else:
 
697
            if parent:
 
698
                destination.set_parent(parent)
 
699
        self.tags.merge_to(destination.tags)
 
700
 
 
701
    @needs_read_lock
 
702
    def check(self):
 
703
        """Check consistency of the branch.
 
704
 
 
705
        In particular this checks that revisions given in the revision-history
 
706
        do actually match up in the revision graph, and that they're all 
 
707
        present in the repository.
 
708
        
 
709
        Callers will typically also want to check the repository.
 
710
 
 
711
        :return: A BranchCheckResult.
 
712
        """
 
713
        mainline_parent_id = None
 
714
        for revision_id in self.revision_history():
 
715
            try:
 
716
                revision = self.repository.get_revision(revision_id)
 
717
            except errors.NoSuchRevision, e:
 
718
                raise errors.BzrCheckError("mainline revision {%s} not in repository"
 
719
                            % revision_id)
 
720
            # In general the first entry on the revision history has no parents.
 
721
            # But it's not illegal for it to have parents listed; this can happen
 
722
            # in imports from Arch when the parents weren't reachable.
 
723
            if mainline_parent_id is not None:
 
724
                if mainline_parent_id not in revision.parent_ids:
 
725
                    raise errors.BzrCheckError("previous revision {%s} not listed among "
 
726
                                        "parents of {%s}"
 
727
                                        % (mainline_parent_id, revision_id))
 
728
            mainline_parent_id = revision_id
 
729
        return BranchCheckResult(self)
 
730
 
 
731
    def _get_checkout_format(self):
 
732
        """Return the most suitable metadir for a checkout of this branch.
 
733
        Weaves are used if this branch's repostory uses weaves.
 
734
        """
 
735
        if isinstance(self.bzrdir, bzrdir.BzrDirPreSplitOut):
 
736
            from bzrlib.repofmt import weaverepo
 
737
            format = bzrdir.BzrDirMetaFormat1()
 
738
            format.repository_format = weaverepo.RepositoryFormat7()
 
739
        else:
 
740
            format = self.repository.bzrdir.checkout_metadir()
 
741
            format.set_branch_format(self._format)
 
742
        return format
 
743
 
 
744
    def create_checkout(self, to_location, revision_id=None,
 
745
                        lightweight=False):
 
746
        """Create a checkout of a branch.
 
747
        
 
748
        :param to_location: The url to produce the checkout at
 
749
        :param revision_id: The revision to check out
 
750
        :param lightweight: If True, produce a lightweight checkout, otherwise,
 
751
        produce a bound branch (heavyweight checkout)
 
752
        :return: The tree of the created checkout
 
753
        """
 
754
        t = transport.get_transport(to_location)
 
755
        try:
 
756
            t.mkdir('.')
 
757
        except errors.FileExists:
 
758
            pass
 
759
        if lightweight:
 
760
            format = self._get_checkout_format()
 
761
            checkout = format.initialize_on_transport(t)
 
762
            BranchReferenceFormat().initialize(checkout, self)
 
763
        else:
 
764
            format = self._get_checkout_format()
 
765
            checkout_branch = bzrdir.BzrDir.create_branch_convenience(
 
766
                to_location, force_new_tree=False, format=format)
 
767
            checkout = checkout_branch.bzrdir
 
768
            checkout_branch.bind(self)
 
769
            # pull up to the specified revision_id to set the initial 
 
770
            # branch tip correctly, and seed it with history.
 
771
            checkout_branch.pull(self, stop_revision=revision_id)
 
772
        tree = checkout.create_workingtree(revision_id)
 
773
        basis_tree = tree.basis_tree()
 
774
        basis_tree.lock_read()
 
775
        try:
 
776
            for path, file_id in basis_tree.iter_references():
 
777
                reference_parent = self.reference_parent(file_id, path)
 
778
                reference_parent.create_checkout(tree.abspath(path),
 
779
                    basis_tree.get_reference_revision(file_id, path),
 
780
                    lightweight)
 
781
        finally:
 
782
            basis_tree.unlock()
 
783
        return tree
 
784
 
 
785
    def reference_parent(self, file_id, path):
 
786
        """Return the parent branch for a tree-reference file_id
 
787
        :param file_id: The file_id of the tree reference
 
788
        :param path: The path of the file_id in the tree
 
789
        :return: A branch associated with the file_id
 
790
        """
 
791
        # FIXME should provide multiple branches, based on config
 
792
        return Branch.open(self.bzrdir.root_transport.clone(path).base)
 
793
 
 
794
    def supports_tags(self):
 
795
        return self._format.supports_tags()
 
796
 
 
797
 
 
798
class BranchFormat(object):
 
799
    """An encapsulation of the initialization and open routines for a format.
 
800
 
 
801
    Formats provide three things:
 
802
     * An initialization routine,
 
803
     * a format string,
 
804
     * an open routine.
 
805
 
 
806
    Formats are placed in an dict by their format string for reference 
 
807
    during branch opening. Its not required that these be instances, they
 
808
    can be classes themselves with class methods - it simply depends on 
 
809
    whether state is needed for a given format or not.
 
810
 
 
811
    Once a format is deprecated, just deprecate the initialize and open
 
812
    methods on the format class. Do not deprecate the object, as the 
 
813
    object will be created every time regardless.
 
814
    """
 
815
 
 
816
    _default_format = None
 
817
    """The default format used for new branches."""
 
818
 
 
819
    _formats = {}
 
820
    """The known formats."""
 
821
 
 
822
    @classmethod
 
823
    def find_format(klass, a_bzrdir):
 
824
        """Return the format for the branch object in a_bzrdir."""
 
825
        try:
 
826
            transport = a_bzrdir.get_branch_transport(None)
 
827
            format_string = transport.get("format").read()
 
828
            return klass._formats[format_string]
 
829
        except NoSuchFile:
 
830
            raise NotBranchError(path=transport.base)
 
831
        except KeyError:
 
832
            raise errors.UnknownFormatError(format=format_string)
 
833
 
 
834
    @classmethod
 
835
    def get_default_format(klass):
 
836
        """Return the current default format."""
 
837
        return klass._default_format
 
838
 
 
839
    def get_format_string(self):
 
840
        """Return the ASCII format string that identifies this format."""
 
841
        raise NotImplementedError(self.get_format_string)
 
842
 
 
843
    def get_format_description(self):
 
844
        """Return the short format description for this format."""
 
845
        raise NotImplementedError(self.get_format_description)
 
846
 
 
847
    def _initialize_helper(self, a_bzrdir, utf8_files, lock_type='metadir',
 
848
                           set_format=True):
 
849
        """Initialize a branch in a bzrdir, with specified files
 
850
 
 
851
        :param a_bzrdir: The bzrdir to initialize the branch in
 
852
        :param utf8_files: The files to create as a list of
 
853
            (filename, content) tuples
 
854
        :param set_format: If True, set the format with
 
855
            self.get_format_string.  (BzrBranch4 has its format set
 
856
            elsewhere)
 
857
        :return: a branch in this format
 
858
        """
 
859
        mutter('creating branch %r in %s', self, a_bzrdir.transport.base)
 
860
        branch_transport = a_bzrdir.get_branch_transport(self)
 
861
        lock_map = {
 
862
            'metadir': ('lock', lockdir.LockDir),
 
863
            'branch4': ('branch-lock', lockable_files.TransportLock),
 
864
        }
 
865
        lock_name, lock_class = lock_map[lock_type]
 
866
        control_files = lockable_files.LockableFiles(branch_transport,
 
867
            lock_name, lock_class)
 
868
        control_files.create_lock()
 
869
        control_files.lock_write()
 
870
        if set_format:
 
871
            control_files.put_utf8('format', self.get_format_string())
 
872
        try:
 
873
            for file, content in utf8_files:
 
874
                control_files.put_utf8(file, content)
 
875
        finally:
 
876
            control_files.unlock()
 
877
        return self.open(a_bzrdir, _found=True)
 
878
 
 
879
    def initialize(self, a_bzrdir):
 
880
        """Create a branch of this format in a_bzrdir."""
 
881
        raise NotImplementedError(self.initialize)
 
882
 
 
883
    def is_supported(self):
 
884
        """Is this format supported?
 
885
 
 
886
        Supported formats can be initialized and opened.
 
887
        Unsupported formats may not support initialization or committing or 
 
888
        some other features depending on the reason for not being supported.
 
889
        """
 
890
        return True
 
891
 
 
892
    def open(self, a_bzrdir, _found=False):
 
893
        """Return the branch object for a_bzrdir
 
894
 
 
895
        _found is a private parameter, do not use it. It is used to indicate
 
896
               if format probing has already be done.
 
897
        """
 
898
        raise NotImplementedError(self.open)
 
899
 
 
900
    @classmethod
 
901
    def register_format(klass, format):
 
902
        klass._formats[format.get_format_string()] = format
 
903
 
 
904
    @classmethod
 
905
    def set_default_format(klass, format):
 
906
        klass._default_format = format
 
907
 
 
908
    @classmethod
 
909
    def unregister_format(klass, format):
 
910
        assert klass._formats[format.get_format_string()] is format
 
911
        del klass._formats[format.get_format_string()]
 
912
 
 
913
    def __str__(self):
 
914
        return self.get_format_string().rstrip()
 
915
 
 
916
    def supports_tags(self):
 
917
        """True if this format supports tags stored in the branch"""
 
918
        return False  # by default
 
919
 
 
920
    # XXX: Probably doesn't really belong here -- mbp 20070212
 
921
    def _initialize_control_files(self, a_bzrdir, utf8_files, lock_filename,
 
922
            lock_class):
 
923
        branch_transport = a_bzrdir.get_branch_transport(self)
 
924
        control_files = lockable_files.LockableFiles(branch_transport,
 
925
            lock_filename, lock_class)
 
926
        control_files.create_lock()
 
927
        control_files.lock_write()
 
928
        try:
 
929
            for filename, content in utf8_files:
 
930
                control_files.put_utf8(filename, content)
 
931
        finally:
 
932
            control_files.unlock()
 
933
 
 
934
 
 
935
class BranchHooks(Hooks):
 
936
    """A dictionary mapping hook name to a list of callables for branch hooks.
 
937
    
 
938
    e.g. ['set_rh'] Is the list of items to be called when the
 
939
    set_revision_history function is invoked.
 
940
    """
 
941
 
 
942
    def __init__(self):
 
943
        """Create the default hooks.
 
944
 
 
945
        These are all empty initially, because by default nothing should get
 
946
        notified.
 
947
        """
 
948
        Hooks.__init__(self)
 
949
        # Introduced in 0.15:
 
950
        # invoked whenever the revision history has been set
 
951
        # with set_revision_history. The api signature is
 
952
        # (branch, revision_history), and the branch will
 
953
        # be write-locked.
 
954
        self['set_rh'] = []
 
955
        # invoked after a push operation completes.
 
956
        # the api signature is
 
957
        # (push_result)
 
958
        # containing the members
 
959
        # (source, local, master, old_revno, old_revid, new_revno, new_revid)
 
960
        # where local is the local branch or None, master is the target 
 
961
        # master branch, and the rest should be self explanatory. The source
 
962
        # is read locked and the target branches write locked. Source will
 
963
        # be the local low-latency branch.
 
964
        self['post_push'] = []
 
965
        # invoked after a pull operation completes.
 
966
        # the api signature is
 
967
        # (pull_result)
 
968
        # containing the members
 
969
        # (source, local, master, old_revno, old_revid, new_revno, new_revid)
 
970
        # where local is the local branch or None, master is the target 
 
971
        # master branch, and the rest should be self explanatory. The source
 
972
        # is read locked and the target branches write locked. The local
 
973
        # branch is the low-latency branch.
 
974
        self['post_pull'] = []
 
975
        # invoked after a commit operation completes.
 
976
        # the api signature is 
 
977
        # (local, master, old_revno, old_revid, new_revno, new_revid)
 
978
        # old_revid is NULL_REVISION for the first commit to a branch.
 
979
        self['post_commit'] = []
 
980
        # invoked after a uncommit operation completes.
 
981
        # the api signature is
 
982
        # (local, master, old_revno, old_revid, new_revno, new_revid) where
 
983
        # local is the local branch or None, master is the target branch,
 
984
        # and an empty branch recieves new_revno of 0, new_revid of None.
 
985
        self['post_uncommit'] = []
 
986
 
 
987
 
 
988
# install the default hooks into the Branch class.
 
989
Branch.hooks = BranchHooks()
 
990
 
 
991
 
 
992
class BzrBranchFormat4(BranchFormat):
 
993
    """Bzr branch format 4.
 
994
 
 
995
    This format has:
 
996
     - a revision-history file.
 
997
     - a branch-lock lock file [ to be shared with the bzrdir ]
 
998
    """
 
999
 
 
1000
    def get_format_description(self):
 
1001
        """See BranchFormat.get_format_description()."""
 
1002
        return "Branch format 4"
 
1003
 
 
1004
    def initialize(self, a_bzrdir):
 
1005
        """Create a branch of this format in a_bzrdir."""
 
1006
        utf8_files = [('revision-history', ''),
 
1007
                      ('branch-name', ''),
 
1008
                      ]
 
1009
        return self._initialize_helper(a_bzrdir, utf8_files,
 
1010
                                       lock_type='branch4', set_format=False)
 
1011
 
 
1012
    def __init__(self):
 
1013
        super(BzrBranchFormat4, self).__init__()
 
1014
        self._matchingbzrdir = bzrdir.BzrDirFormat6()
 
1015
 
 
1016
    def open(self, a_bzrdir, _found=False):
 
1017
        """Return the branch object for a_bzrdir
 
1018
 
 
1019
        _found is a private parameter, do not use it. It is used to indicate
 
1020
               if format probing has already be done.
 
1021
        """
 
1022
        if not _found:
 
1023
            # we are being called directly and must probe.
 
1024
            raise NotImplementedError
 
1025
        return BzrBranch(_format=self,
 
1026
                         _control_files=a_bzrdir._control_files,
 
1027
                         a_bzrdir=a_bzrdir,
 
1028
                         _repository=a_bzrdir.open_repository())
 
1029
 
 
1030
    def __str__(self):
 
1031
        return "Bazaar-NG branch format 4"
 
1032
 
 
1033
 
 
1034
class BzrBranchFormat5(BranchFormat):
 
1035
    """Bzr branch format 5.
 
1036
 
 
1037
    This format has:
 
1038
     - a revision-history file.
 
1039
     - a format string
 
1040
     - a lock dir guarding the branch itself
 
1041
     - all of this stored in a branch/ subdirectory
 
1042
     - works with shared repositories.
 
1043
 
 
1044
    This format is new in bzr 0.8.
 
1045
    """
 
1046
 
 
1047
    def get_format_string(self):
 
1048
        """See BranchFormat.get_format_string()."""
 
1049
        return "Bazaar-NG branch format 5\n"
 
1050
 
 
1051
    def get_format_description(self):
 
1052
        """See BranchFormat.get_format_description()."""
 
1053
        return "Branch format 5"
 
1054
        
 
1055
    def initialize(self, a_bzrdir):
 
1056
        """Create a branch of this format in a_bzrdir."""
 
1057
        utf8_files = [('revision-history', ''),
 
1058
                      ('branch-name', ''),
 
1059
                      ]
 
1060
        return self._initialize_helper(a_bzrdir, utf8_files)
 
1061
 
 
1062
    def __init__(self):
 
1063
        super(BzrBranchFormat5, self).__init__()
 
1064
        self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
 
1065
 
 
1066
    def open(self, a_bzrdir, _found=False):
 
1067
        """Return the branch object for a_bzrdir
 
1068
 
 
1069
        _found is a private parameter, do not use it. It is used to indicate
 
1070
               if format probing has already be done.
 
1071
        """
 
1072
        if not _found:
 
1073
            format = BranchFormat.find_format(a_bzrdir)
 
1074
            assert format.__class__ == self.__class__
 
1075
        transport = a_bzrdir.get_branch_transport(None)
 
1076
        control_files = lockable_files.LockableFiles(transport, 'lock',
 
1077
                                                     lockdir.LockDir)
 
1078
        return BzrBranch5(_format=self,
 
1079
                          _control_files=control_files,
 
1080
                          a_bzrdir=a_bzrdir,
 
1081
                          _repository=a_bzrdir.find_repository())
 
1082
 
 
1083
 
 
1084
class BzrBranchFormat6(BzrBranchFormat5):
 
1085
    """Branch format with last-revision
 
1086
 
 
1087
    Unlike previous formats, this has no explicit revision history. Instead,
 
1088
    this just stores the last-revision, and the left-hand history leading
 
1089
    up to there is the history.
 
1090
 
 
1091
    This format was introduced in bzr 0.15
 
1092
    """
 
1093
 
 
1094
    def get_format_string(self):
 
1095
        """See BranchFormat.get_format_string()."""
 
1096
        return "Bazaar Branch Format 6 (bzr 0.15)\n"
 
1097
 
 
1098
    def get_format_description(self):
 
1099
        """See BranchFormat.get_format_description()."""
 
1100
        return "Branch format 6"
 
1101
 
 
1102
    def initialize(self, a_bzrdir):
 
1103
        """Create a branch of this format in a_bzrdir."""
 
1104
        utf8_files = [('last-revision', '0 null:\n'),
 
1105
                      ('branch-name', ''),
 
1106
                      ('branch.conf', ''),
 
1107
                      ('tags', ''),
 
1108
                      ]
 
1109
        return self._initialize_helper(a_bzrdir, utf8_files)
 
1110
 
 
1111
    def open(self, a_bzrdir, _found=False):
 
1112
        """Return the branch object for a_bzrdir
 
1113
 
 
1114
        _found is a private parameter, do not use it. It is used to indicate
 
1115
               if format probing has already be done.
 
1116
        """
 
1117
        if not _found:
 
1118
            format = BranchFormat.find_format(a_bzrdir)
 
1119
            assert format.__class__ == self.__class__
 
1120
        transport = a_bzrdir.get_branch_transport(None)
 
1121
        control_files = lockable_files.LockableFiles(transport, 'lock',
 
1122
                                                     lockdir.LockDir)
 
1123
        return BzrBranch6(_format=self,
 
1124
                          _control_files=control_files,
 
1125
                          a_bzrdir=a_bzrdir,
 
1126
                          _repository=a_bzrdir.find_repository())
 
1127
 
 
1128
    def supports_tags(self):
 
1129
        return True
 
1130
 
 
1131
 
 
1132
class BranchReferenceFormat(BranchFormat):
 
1133
    """Bzr branch reference format.
 
1134
 
 
1135
    Branch references are used in implementing checkouts, they
 
1136
    act as an alias to the real branch which is at some other url.
 
1137
 
 
1138
    This format has:
 
1139
     - A location file
 
1140
     - a format string
 
1141
    """
 
1142
 
 
1143
    def get_format_string(self):
 
1144
        """See BranchFormat.get_format_string()."""
 
1145
        return "Bazaar-NG Branch Reference Format 1\n"
 
1146
 
 
1147
    def get_format_description(self):
 
1148
        """See BranchFormat.get_format_description()."""
 
1149
        return "Checkout reference format 1"
 
1150
        
 
1151
    def initialize(self, a_bzrdir, target_branch=None):
 
1152
        """Create a branch of this format in a_bzrdir."""
 
1153
        if target_branch is None:
 
1154
            # this format does not implement branch itself, thus the implicit
 
1155
            # creation contract must see it as uninitializable
 
1156
            raise errors.UninitializableFormat(self)
 
1157
        mutter('creating branch reference in %s', a_bzrdir.transport.base)
 
1158
        branch_transport = a_bzrdir.get_branch_transport(self)
 
1159
        branch_transport.put_bytes('location',
 
1160
            target_branch.bzrdir.root_transport.base)
 
1161
        branch_transport.put_bytes('format', self.get_format_string())
 
1162
        return self.open(a_bzrdir, _found=True)
 
1163
 
 
1164
    def __init__(self):
 
1165
        super(BranchReferenceFormat, self).__init__()
 
1166
        self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
 
1167
 
 
1168
    def _make_reference_clone_function(format, a_branch):
 
1169
        """Create a clone() routine for a branch dynamically."""
 
1170
        def clone(to_bzrdir, revision_id=None):
 
1171
            """See Branch.clone()."""
 
1172
            return format.initialize(to_bzrdir, a_branch)
 
1173
            # cannot obey revision_id limits when cloning a reference ...
 
1174
            # FIXME RBC 20060210 either nuke revision_id for clone, or
 
1175
            # emit some sort of warning/error to the caller ?!
 
1176
        return clone
 
1177
 
 
1178
    def open(self, a_bzrdir, _found=False):
 
1179
        """Return the branch that the branch reference in a_bzrdir points at.
 
1180
 
 
1181
        _found is a private parameter, do not use it. It is used to indicate
 
1182
               if format probing has already be done.
 
1183
        """
 
1184
        if not _found:
 
1185
            format = BranchFormat.find_format(a_bzrdir)
 
1186
            assert format.__class__ == self.__class__
 
1187
        transport = a_bzrdir.get_branch_transport(None)
 
1188
        real_bzrdir = bzrdir.BzrDir.open(transport.get('location').read())
 
1189
        result = real_bzrdir.open_branch()
 
1190
        # this changes the behaviour of result.clone to create a new reference
 
1191
        # rather than a copy of the content of the branch.
 
1192
        # I did not use a proxy object because that needs much more extensive
 
1193
        # testing, and we are only changing one behaviour at the moment.
 
1194
        # If we decide to alter more behaviours - i.e. the implicit nickname
 
1195
        # then this should be refactored to introduce a tested proxy branch
 
1196
        # and a subclass of that for use in overriding clone() and ....
 
1197
        # - RBC 20060210
 
1198
        result.clone = self._make_reference_clone_function(result)
 
1199
        return result
 
1200
 
 
1201
 
 
1202
# formats which have no format string are not discoverable
 
1203
# and not independently creatable, so are not registered.
 
1204
__default_format = BzrBranchFormat5()
 
1205
BranchFormat.register_format(__default_format)
 
1206
BranchFormat.register_format(BranchReferenceFormat())
 
1207
BranchFormat.register_format(BzrBranchFormat6())
 
1208
BranchFormat.set_default_format(__default_format)
 
1209
_legacy_formats = [BzrBranchFormat4(),
 
1210
                   ]
 
1211
 
 
1212
class BzrBranch(Branch):
 
1213
    """A branch stored in the actual filesystem.
 
1214
 
 
1215
    Note that it's "local" in the context of the filesystem; it doesn't
 
1216
    really matter if it's on an nfs/smb/afs/coda/... share, as long as
 
1217
    it's writable, and can be accessed via the normal filesystem API.
 
1218
    """
 
1219
    
 
1220
    def __init__(self, _format=None,
 
1221
                 _control_files=None, a_bzrdir=None, _repository=None):
 
1222
        """Create new branch object at a particular location."""
 
1223
        Branch.__init__(self)
 
1224
        if a_bzrdir is None:
 
1225
            raise ValueError('a_bzrdir must be supplied')
 
1226
        else:
 
1227
            self.bzrdir = a_bzrdir
 
1228
        # self._transport used to point to the directory containing the
 
1229
        # control directory, but was not used - now it's just the transport
 
1230
        # for the branch control files.  mbp 20070212
 
1231
        self._base = self.bzrdir.transport.clone('..').base
 
1232
        self._format = _format
 
1233
        if _control_files is None:
 
1234
            raise ValueError('BzrBranch _control_files is None')
 
1235
        self.control_files = _control_files
 
1236
        self._transport = _control_files._transport
 
1237
        self.repository = _repository
 
1238
 
 
1239
    def __str__(self):
 
1240
        return '%s(%r)' % (self.__class__.__name__, self.base)
 
1241
 
 
1242
    __repr__ = __str__
 
1243
 
 
1244
    def _get_base(self):
 
1245
        """Returns the directory containing the control directory."""
 
1246
        return self._base
 
1247
 
 
1248
    base = property(_get_base, doc="The URL for the root of this branch.")
 
1249
 
 
1250
    def abspath(self, name):
 
1251
        """See Branch.abspath."""
 
1252
        return self.control_files._transport.abspath(name)
 
1253
 
 
1254
 
 
1255
    @deprecated_method(zero_sixteen)
 
1256
    @needs_read_lock
 
1257
    def get_root_id(self):
 
1258
        """See Branch.get_root_id."""
 
1259
        tree = self.repository.revision_tree(self.last_revision())
 
1260
        return tree.inventory.root.file_id
 
1261
 
 
1262
    def is_locked(self):
 
1263
        return self.control_files.is_locked()
 
1264
 
 
1265
    def lock_write(self, token=None):
 
1266
        repo_token = self.repository.lock_write()
 
1267
        try:
 
1268
            token = self.control_files.lock_write(token=token)
 
1269
        except:
 
1270
            self.repository.unlock()
 
1271
            raise
 
1272
        return token
 
1273
 
 
1274
    def lock_read(self):
 
1275
        self.repository.lock_read()
 
1276
        try:
 
1277
            self.control_files.lock_read()
 
1278
        except:
 
1279
            self.repository.unlock()
 
1280
            raise
 
1281
 
 
1282
    def unlock(self):
 
1283
        # TODO: test for failed two phase locks. This is known broken.
 
1284
        try:
 
1285
            self.control_files.unlock()
 
1286
        finally:
 
1287
            self.repository.unlock()
 
1288
        if not self.control_files.is_locked():
 
1289
            # we just released the lock
 
1290
            self._clear_cached_state()
 
1291
        
 
1292
    def peek_lock_mode(self):
 
1293
        if self.control_files._lock_count == 0:
 
1294
            return None
 
1295
        else:
 
1296
            return self.control_files._lock_mode
 
1297
 
 
1298
    def get_physical_lock_status(self):
 
1299
        return self.control_files.get_physical_lock_status()
 
1300
 
 
1301
    @needs_read_lock
 
1302
    def print_file(self, file, revision_id):
 
1303
        """See Branch.print_file."""
 
1304
        return self.repository.print_file(file, revision_id)
 
1305
 
 
1306
    @needs_write_lock
 
1307
    def append_revision(self, *revision_ids):
 
1308
        """See Branch.append_revision."""
 
1309
        revision_ids = [osutils.safe_revision_id(r) for r in revision_ids]
 
1310
        for revision_id in revision_ids:
 
1311
            _mod_revision.check_not_reserved_id(revision_id)
 
1312
            mutter("add {%s} to revision-history" % revision_id)
 
1313
        rev_history = self.revision_history()
 
1314
        rev_history.extend(revision_ids)
 
1315
        self.set_revision_history(rev_history)
 
1316
 
 
1317
    def _write_revision_history(self, history):
 
1318
        """Factored out of set_revision_history.
 
1319
 
 
1320
        This performs the actual writing to disk.
 
1321
        It is intended to be called by BzrBranch5.set_revision_history."""
 
1322
        self.control_files.put_bytes(
 
1323
            'revision-history', '\n'.join(history))
 
1324
 
 
1325
    @needs_write_lock
 
1326
    def set_revision_history(self, rev_history):
 
1327
        """See Branch.set_revision_history."""
 
1328
        rev_history = [osutils.safe_revision_id(r) for r in rev_history]
 
1329
        self._clear_cached_state()
 
1330
        self._write_revision_history(rev_history)
 
1331
        self._cache_revision_history(rev_history)
 
1332
        for hook in Branch.hooks['set_rh']:
 
1333
            hook(self, rev_history)
 
1334
 
 
1335
    @needs_write_lock
 
1336
    def set_last_revision_info(self, revno, revision_id):
 
1337
        revision_id = osutils.safe_revision_id(revision_id)
 
1338
        history = self._lefthand_history(revision_id)
 
1339
        assert len(history) == revno, '%d != %d' % (len(history), revno)
 
1340
        self.set_revision_history(history)
 
1341
 
 
1342
    def _gen_revision_history(self):
 
1343
        history = self.control_files.get('revision-history').read().split('\n')
 
1344
        if history[-1:] == ['']:
 
1345
            # There shouldn't be a trailing newline, but just in case.
 
1346
            history.pop()
 
1347
        return history
 
1348
 
 
1349
    @needs_read_lock
 
1350
    def get_revision_id_to_revno_map(self):
 
1351
        """Return the revision_id => dotted revno map.
 
1352
 
 
1353
        This will be regenerated on demand, but will be cached.
 
1354
 
 
1355
        :return: A dictionary mapping revision_id => dotted revno.
 
1356
            This dictionary should not be modified by the caller.
 
1357
        """
 
1358
        if self._revision_id_to_revno_cache is not None:
 
1359
            mapping = self._revision_id_to_revno_cache
 
1360
        else:
 
1361
            mapping = self._gen_revno_map()
 
1362
            self._cache_revision_id_to_revno(mapping)
 
1363
        # TODO: jam 20070417 Since this is being cached, should we be returning
 
1364
        #       a copy?
 
1365
        # I would rather not, and instead just declare that users should not
 
1366
        # modify the return value.
 
1367
        return mapping
 
1368
 
 
1369
    def _gen_revno_map(self):
 
1370
        """Generate a mapping from revision ids to dotted revnos.
 
1371
 
 
1372
        :return: A dict mapping revision_ids => dotted revnos
 
1373
        """
 
1374
        last_revision = self.last_revision()
 
1375
        revision_graph = self.repository.get_revision_graph(last_revision)
 
1376
        merge_sorted_revisions = tsort.merge_sort(
 
1377
            revision_graph,
 
1378
            last_revision,
 
1379
            None,
 
1380
            generate_revno=True)
 
1381
        revision_id_to_revno = dict((rev_id, revno)
 
1382
                                    for seq_num, rev_id, depth, revno, end_of_merge
 
1383
                                     in merge_sorted_revisions)
 
1384
        return revision_id_to_revno
 
1385
 
 
1386
    def _lefthand_history(self, revision_id, last_rev=None,
 
1387
                          other_branch=None):
 
1388
        # stop_revision must be a descendant of last_revision
 
1389
        stop_graph = self.repository.get_revision_graph(revision_id)
 
1390
        if last_rev is not None and last_rev not in stop_graph:
 
1391
            # our previous tip is not merged into stop_revision
 
1392
            raise errors.DivergedBranches(self, other_branch)
 
1393
        # make a new revision history from the graph
 
1394
        current_rev_id = revision_id
 
1395
        new_history = []
 
1396
        while current_rev_id not in (None, _mod_revision.NULL_REVISION):
 
1397
            new_history.append(current_rev_id)
 
1398
            current_rev_id_parents = stop_graph[current_rev_id]
 
1399
            try:
 
1400
                current_rev_id = current_rev_id_parents[0]
 
1401
            except IndexError:
 
1402
                current_rev_id = None
 
1403
        new_history.reverse()
 
1404
        return new_history
 
1405
 
 
1406
    @needs_write_lock
 
1407
    def generate_revision_history(self, revision_id, last_rev=None,
 
1408
        other_branch=None):
 
1409
        """Create a new revision history that will finish with revision_id.
 
1410
 
 
1411
        :param revision_id: the new tip to use.
 
1412
        :param last_rev: The previous last_revision. If not None, then this
 
1413
            must be a ancestory of revision_id, or DivergedBranches is raised.
 
1414
        :param other_branch: The other branch that DivergedBranches should
 
1415
            raise with respect to.
 
1416
        """
 
1417
        revision_id = osutils.safe_revision_id(revision_id)
 
1418
        self.set_revision_history(self._lefthand_history(revision_id,
 
1419
            last_rev, other_branch))
 
1420
 
 
1421
    @needs_write_lock
 
1422
    def update_revisions(self, other, stop_revision=None):
 
1423
        """See Branch.update_revisions."""
 
1424
        other.lock_read()
 
1425
        try:
 
1426
            if stop_revision is None:
 
1427
                stop_revision = other.last_revision()
 
1428
                if stop_revision is None:
 
1429
                    # if there are no commits, we're done.
 
1430
                    return
 
1431
            else:
 
1432
                stop_revision = osutils.safe_revision_id(stop_revision)
 
1433
            # whats the current last revision, before we fetch [and change it
 
1434
            # possibly]
 
1435
            last_rev = self.last_revision()
 
1436
            # we fetch here regardless of whether we need to so that we pickup
 
1437
            # filled in ghosts.
 
1438
            self.fetch(other, stop_revision)
 
1439
            my_ancestry = self.repository.get_ancestry(last_rev)
 
1440
            if stop_revision in my_ancestry:
 
1441
                # last_revision is a descendant of stop_revision
 
1442
                return
 
1443
            self.generate_revision_history(stop_revision, last_rev=last_rev,
 
1444
                other_branch=other)
 
1445
        finally:
 
1446
            other.unlock()
 
1447
 
 
1448
    def basis_tree(self):
 
1449
        """See Branch.basis_tree."""
 
1450
        return self.repository.revision_tree(self.last_revision())
 
1451
 
 
1452
    @deprecated_method(zero_eight)
 
1453
    def working_tree(self):
 
1454
        """Create a Working tree object for this branch."""
 
1455
 
 
1456
        from bzrlib.transport.local import LocalTransport
 
1457
        if (self.base.find('://') != -1 or 
 
1458
            not isinstance(self._transport, LocalTransport)):
 
1459
            raise NoWorkingTree(self.base)
 
1460
        return self.bzrdir.open_workingtree()
 
1461
 
 
1462
    @needs_write_lock
 
1463
    def pull(self, source, overwrite=False, stop_revision=None,
 
1464
        _hook_master=None, _run_hooks=True):
 
1465
        """See Branch.pull.
 
1466
 
 
1467
        :param _hook_master: Private parameter - set the branch to 
 
1468
            be supplied as the master to push hooks.
 
1469
        :param _run_hooks: Private parameter - allow disabling of
 
1470
            hooks, used when pushing to a master branch.
 
1471
        """
 
1472
        result = PullResult()
 
1473
        result.source_branch = source
 
1474
        result.target_branch = self
 
1475
        source.lock_read()
 
1476
        try:
 
1477
            result.old_revno, result.old_revid = self.last_revision_info()
 
1478
            try:
 
1479
                self.update_revisions(source, stop_revision)
 
1480
            except DivergedBranches:
 
1481
                if not overwrite:
 
1482
                    raise
 
1483
            if overwrite:
 
1484
                if stop_revision is None:
 
1485
                    stop_revision = source.last_revision()
 
1486
                self.generate_revision_history(stop_revision)
 
1487
            result.tag_conflicts = source.tags.merge_to(self.tags)
 
1488
            result.new_revno, result.new_revid = self.last_revision_info()
 
1489
            if _hook_master:
 
1490
                result.master_branch = _hook_master
 
1491
                result.local_branch = self
 
1492
            else:
 
1493
                result.master_branch = self
 
1494
                result.local_branch = None
 
1495
            if _run_hooks:
 
1496
                for hook in Branch.hooks['post_pull']:
 
1497
                    hook(result)
 
1498
        finally:
 
1499
            source.unlock()
 
1500
        return result
 
1501
 
 
1502
    def _get_parent_location(self):
 
1503
        _locs = ['parent', 'pull', 'x-pull']
 
1504
        for l in _locs:
 
1505
            try:
 
1506
                return self.control_files.get(l).read().strip('\n')
 
1507
            except NoSuchFile:
 
1508
                pass
 
1509
        return None
 
1510
 
 
1511
    @needs_read_lock
 
1512
    def push(self, target, overwrite=False, stop_revision=None,
 
1513
        _hook_master=None, _run_hooks=True):
 
1514
        """See Branch.push.
 
1515
        
 
1516
        :param _hook_master: Private parameter - set the branch to 
 
1517
            be supplied as the master to push hooks.
 
1518
        :param _run_hooks: Private parameter - allow disabling of
 
1519
            hooks, used when pushing to a master branch.
 
1520
        """
 
1521
        result = PushResult()
 
1522
        result.source_branch = self
 
1523
        result.target_branch = target
 
1524
        target.lock_write()
 
1525
        try:
 
1526
            result.old_revno, result.old_revid = target.last_revision_info()
 
1527
            try:
 
1528
                target.update_revisions(self, stop_revision)
 
1529
            except DivergedBranches:
 
1530
                if not overwrite:
 
1531
                    raise
 
1532
            if overwrite:
 
1533
                target.set_revision_history(self.revision_history())
 
1534
            result.tag_conflicts = self.tags.merge_to(target.tags)
 
1535
            result.new_revno, result.new_revid = target.last_revision_info()
 
1536
            if _hook_master:
 
1537
                result.master_branch = _hook_master
 
1538
                result.local_branch = target
 
1539
            else:
 
1540
                result.master_branch = target
 
1541
                result.local_branch = None
 
1542
            if _run_hooks:
 
1543
                for hook in Branch.hooks['post_push']:
 
1544
                    hook(result)
 
1545
        finally:
 
1546
            target.unlock()
 
1547
        return result
 
1548
 
 
1549
    def get_parent(self):
 
1550
        """See Branch.get_parent."""
 
1551
 
 
1552
        assert self.base[-1] == '/'
 
1553
        parent = self._get_parent_location()
 
1554
        if parent is None:
 
1555
            return parent
 
1556
        # This is an old-format absolute path to a local branch
 
1557
        # turn it into a url
 
1558
        if parent.startswith('/'):
 
1559
            parent = urlutils.local_path_to_url(parent.decode('utf8'))
 
1560
        try:
 
1561
            return urlutils.join(self.base[:-1], parent)
 
1562
        except errors.InvalidURLJoin, e:
 
1563
            raise errors.InaccessibleParent(parent, self.base)
 
1564
 
 
1565
    def get_push_location(self):
 
1566
        """See Branch.get_push_location."""
 
1567
        push_loc = self.get_config().get_user_option('push_location')
 
1568
        return push_loc
 
1569
 
 
1570
    def set_push_location(self, location):
 
1571
        """See Branch.set_push_location."""
 
1572
        self.get_config().set_user_option(
 
1573
            'push_location', location,
 
1574
            store=_mod_config.STORE_LOCATION_NORECURSE)
 
1575
 
 
1576
    @needs_write_lock
 
1577
    def set_parent(self, url):
 
1578
        """See Branch.set_parent."""
 
1579
        # TODO: Maybe delete old location files?
 
1580
        # URLs should never be unicode, even on the local fs,
 
1581
        # FIXUP this and get_parent in a future branch format bump:
 
1582
        # read and rewrite the file, and have the new format code read
 
1583
        # using .get not .get_utf8. RBC 20060125
 
1584
        if url is not None:
 
1585
            if isinstance(url, unicode):
 
1586
                try: 
 
1587
                    url = url.encode('ascii')
 
1588
                except UnicodeEncodeError:
 
1589
                    raise errors.InvalidURL(url,
 
1590
                        "Urls must be 7-bit ascii, "
 
1591
                        "use bzrlib.urlutils.escape")
 
1592
            url = urlutils.relative_url(self.base, url)
 
1593
        self._set_parent_location(url)
 
1594
 
 
1595
    def _set_parent_location(self, url):
 
1596
        if url is None:
 
1597
            self.control_files._transport.delete('parent')
 
1598
        else:
 
1599
            assert isinstance(url, str)
 
1600
            self.control_files.put_bytes('parent', url + '\n')
 
1601
 
 
1602
    @deprecated_function(zero_nine)
 
1603
    def tree_config(self):
 
1604
        """DEPRECATED; call get_config instead.  
 
1605
        TreeConfig has become part of BranchConfig."""
 
1606
        return TreeConfig(self)
 
1607
 
 
1608
 
 
1609
class BzrBranch5(BzrBranch):
 
1610
    """A format 5 branch. This supports new features over plan branches.
 
1611
 
 
1612
    It has support for a master_branch which is the data for bound branches.
 
1613
    """
 
1614
 
 
1615
    def __init__(self,
 
1616
                 _format,
 
1617
                 _control_files,
 
1618
                 a_bzrdir,
 
1619
                 _repository):
 
1620
        super(BzrBranch5, self).__init__(_format=_format,
 
1621
                                         _control_files=_control_files,
 
1622
                                         a_bzrdir=a_bzrdir,
 
1623
                                         _repository=_repository)
 
1624
        
 
1625
    @needs_write_lock
 
1626
    def pull(self, source, overwrite=False, stop_revision=None,
 
1627
        _run_hooks=True):
 
1628
        """Extends branch.pull to be bound branch aware.
 
1629
        
 
1630
        :param _run_hooks: Private parameter used to force hook running
 
1631
            off during bound branch double-pushing.
 
1632
        """
 
1633
        bound_location = self.get_bound_location()
 
1634
        master_branch = None
 
1635
        if bound_location and source.base != bound_location:
 
1636
            # not pulling from master, so we need to update master.
 
1637
            master_branch = self.get_master_branch()
 
1638
            master_branch.lock_write()
 
1639
        try:
 
1640
            if master_branch:
 
1641
                # pull from source into master.
 
1642
                master_branch.pull(source, overwrite, stop_revision,
 
1643
                    _run_hooks=False)
 
1644
            return super(BzrBranch5, self).pull(source, overwrite,
 
1645
                stop_revision, _hook_master=master_branch,
 
1646
                _run_hooks=_run_hooks)
 
1647
        finally:
 
1648
            if master_branch:
 
1649
                master_branch.unlock()
 
1650
 
 
1651
    @needs_read_lock
 
1652
    def push(self, target, overwrite=False, stop_revision=None):
 
1653
        """Updates branch.push to be bound branch aware."""
 
1654
        bound_location = target.get_bound_location()
 
1655
        master_branch = None
 
1656
        if bound_location and target.base != bound_location:
 
1657
            # not pushing to master, so we need to update master.
 
1658
            master_branch = target.get_master_branch()
 
1659
            master_branch.lock_write()
 
1660
        try:
 
1661
            if master_branch:
 
1662
                # push into the master from this branch.
 
1663
                super(BzrBranch5, self).push(master_branch, overwrite,
 
1664
                    stop_revision, _run_hooks=False)
 
1665
            # and push into the target branch from this. Note that we push from
 
1666
            # this branch again, because its considered the highest bandwidth
 
1667
            # repository.
 
1668
            return super(BzrBranch5, self).push(target, overwrite,
 
1669
                stop_revision, _hook_master=master_branch)
 
1670
        finally:
 
1671
            if master_branch:
 
1672
                master_branch.unlock()
 
1673
 
 
1674
    def get_bound_location(self):
 
1675
        try:
 
1676
            return self.control_files.get_utf8('bound').read()[:-1]
 
1677
        except errors.NoSuchFile:
 
1678
            return None
 
1679
 
 
1680
    @needs_read_lock
 
1681
    def get_master_branch(self):
 
1682
        """Return the branch we are bound to.
 
1683
        
 
1684
        :return: Either a Branch, or None
 
1685
 
 
1686
        This could memoise the branch, but if thats done
 
1687
        it must be revalidated on each new lock.
 
1688
        So for now we just don't memoise it.
 
1689
        # RBC 20060304 review this decision.
 
1690
        """
 
1691
        bound_loc = self.get_bound_location()
 
1692
        if not bound_loc:
 
1693
            return None
 
1694
        try:
 
1695
            return Branch.open(bound_loc)
 
1696
        except (errors.NotBranchError, errors.ConnectionError), e:
 
1697
            raise errors.BoundBranchConnectionFailure(
 
1698
                    self, bound_loc, e)
 
1699
 
 
1700
    @needs_write_lock
 
1701
    def set_bound_location(self, location):
 
1702
        """Set the target where this branch is bound to.
 
1703
 
 
1704
        :param location: URL to the target branch
 
1705
        """
 
1706
        if location:
 
1707
            self.control_files.put_utf8('bound', location+'\n')
 
1708
        else:
 
1709
            try:
 
1710
                self.control_files._transport.delete('bound')
 
1711
            except NoSuchFile:
 
1712
                return False
 
1713
            return True
 
1714
 
 
1715
    @needs_write_lock
 
1716
    def bind(self, other):
 
1717
        """Bind this branch to the branch other.
 
1718
 
 
1719
        This does not push or pull data between the branches, though it does
 
1720
        check for divergence to raise an error when the branches are not
 
1721
        either the same, or one a prefix of the other. That behaviour may not
 
1722
        be useful, so that check may be removed in future.
 
1723
        
 
1724
        :param other: The branch to bind to
 
1725
        :type other: Branch
 
1726
        """
 
1727
        # TODO: jam 20051230 Consider checking if the target is bound
 
1728
        #       It is debatable whether you should be able to bind to
 
1729
        #       a branch which is itself bound.
 
1730
        #       Committing is obviously forbidden,
 
1731
        #       but binding itself may not be.
 
1732
        #       Since we *have* to check at commit time, we don't
 
1733
        #       *need* to check here
 
1734
 
 
1735
        # we want to raise diverged if:
 
1736
        # last_rev is not in the other_last_rev history, AND
 
1737
        # other_last_rev is not in our history, and do it without pulling
 
1738
        # history around
 
1739
        last_rev = self.last_revision()
 
1740
        if last_rev is not None:
 
1741
            other.lock_read()
 
1742
            try:
 
1743
                other_last_rev = other.last_revision()
 
1744
                if other_last_rev is not None:
 
1745
                    # neither branch is new, we have to do some work to
 
1746
                    # ascertain diversion.
 
1747
                    remote_graph = other.repository.get_revision_graph(
 
1748
                        other_last_rev)
 
1749
                    local_graph = self.repository.get_revision_graph(last_rev)
 
1750
                    if (last_rev not in remote_graph and
 
1751
                        other_last_rev not in local_graph):
 
1752
                        raise errors.DivergedBranches(self, other)
 
1753
            finally:
 
1754
                other.unlock()
 
1755
        self.set_bound_location(other.base)
 
1756
 
 
1757
    @needs_write_lock
 
1758
    def unbind(self):
 
1759
        """If bound, unbind"""
 
1760
        return self.set_bound_location(None)
 
1761
 
 
1762
    @needs_write_lock
 
1763
    def update(self):
 
1764
        """Synchronise this branch with the master branch if any. 
 
1765
 
 
1766
        :return: None or the last_revision that was pivoted out during the
 
1767
                 update.
 
1768
        """
 
1769
        master = self.get_master_branch()
 
1770
        if master is not None:
 
1771
            old_tip = self.last_revision()
 
1772
            self.pull(master, overwrite=True)
 
1773
            if old_tip in self.repository.get_ancestry(self.last_revision()):
 
1774
                return None
 
1775
            return old_tip
 
1776
        return None
 
1777
 
 
1778
 
 
1779
class BzrBranchExperimental(BzrBranch5):
 
1780
    """Bzr experimental branch format
 
1781
 
 
1782
    This format has:
 
1783
     - a revision-history file.
 
1784
     - a format string
 
1785
     - a lock dir guarding the branch itself
 
1786
     - all of this stored in a branch/ subdirectory
 
1787
     - works with shared repositories.
 
1788
     - a tag dictionary in the branch
 
1789
 
 
1790
    This format is new in bzr 0.15, but shouldn't be used for real data, 
 
1791
    only for testing.
 
1792
 
 
1793
    This class acts as it's own BranchFormat.
 
1794
    """
 
1795
 
 
1796
    _matchingbzrdir = bzrdir.BzrDirMetaFormat1()
 
1797
 
 
1798
    @classmethod
 
1799
    def get_format_string(cls):
 
1800
        """See BranchFormat.get_format_string()."""
 
1801
        return "Bazaar-NG branch format experimental\n"
 
1802
 
 
1803
    @classmethod
 
1804
    def get_format_description(cls):
 
1805
        """See BranchFormat.get_format_description()."""
 
1806
        return "Experimental branch format"
 
1807
 
 
1808
    @classmethod
 
1809
    def _initialize_control_files(cls, a_bzrdir, utf8_files, lock_filename,
 
1810
            lock_class):
 
1811
        branch_transport = a_bzrdir.get_branch_transport(cls)
 
1812
        control_files = lockable_files.LockableFiles(branch_transport,
 
1813
            lock_filename, lock_class)
 
1814
        control_files.create_lock()
 
1815
        control_files.lock_write()
 
1816
        try:
 
1817
            for filename, content in utf8_files:
 
1818
                control_files.put_utf8(filename, content)
 
1819
        finally:
 
1820
            control_files.unlock()
 
1821
        
 
1822
    @classmethod
 
1823
    def initialize(cls, a_bzrdir):
 
1824
        """Create a branch of this format in a_bzrdir."""
 
1825
        utf8_files = [('format', cls.get_format_string()),
 
1826
                      ('revision-history', ''),
 
1827
                      ('branch-name', ''),
 
1828
                      ('tags', ''),
 
1829
                      ]
 
1830
        cls._initialize_control_files(a_bzrdir, utf8_files,
 
1831
            'lock', lockdir.LockDir)
 
1832
        return cls.open(a_bzrdir, _found=True)
 
1833
 
 
1834
    @classmethod
 
1835
    def open(cls, a_bzrdir, _found=False):
 
1836
        """Return the branch object for a_bzrdir
 
1837
 
 
1838
        _found is a private parameter, do not use it. It is used to indicate
 
1839
               if format probing has already be done.
 
1840
        """
 
1841
        if not _found:
 
1842
            format = BranchFormat.find_format(a_bzrdir)
 
1843
            assert format.__class__ == cls
 
1844
        transport = a_bzrdir.get_branch_transport(None)
 
1845
        control_files = lockable_files.LockableFiles(transport, 'lock',
 
1846
                                                     lockdir.LockDir)
 
1847
        return cls(_format=cls,
 
1848
            _control_files=control_files,
 
1849
            a_bzrdir=a_bzrdir,
 
1850
            _repository=a_bzrdir.find_repository())
 
1851
 
 
1852
    @classmethod
 
1853
    def is_supported(cls):
 
1854
        return True
 
1855
 
 
1856
    def _make_tags(self):
 
1857
        return BasicTags(self)
 
1858
 
 
1859
    @classmethod
 
1860
    def supports_tags(cls):
 
1861
        return True
 
1862
 
 
1863
 
 
1864
BranchFormat.register_format(BzrBranchExperimental)
 
1865
 
 
1866
 
 
1867
class BzrBranch6(BzrBranch5):
 
1868
 
 
1869
    @needs_read_lock
 
1870
    def last_revision_info(self):
 
1871
        revision_string = self.control_files.get('last-revision').read()
 
1872
        revno, revision_id = revision_string.rstrip('\n').split(' ', 1)
 
1873
        revision_id = cache_utf8.get_cached_utf8(revision_id)
 
1874
        revno = int(revno)
 
1875
        return revno, revision_id
 
1876
 
 
1877
    def last_revision(self):
 
1878
        """Return last revision id, or None"""
 
1879
        revision_id = self.last_revision_info()[1]
 
1880
        if revision_id == _mod_revision.NULL_REVISION:
 
1881
            revision_id = None
 
1882
        return revision_id
 
1883
 
 
1884
    def _write_last_revision_info(self, revno, revision_id):
 
1885
        """Simply write out the revision id, with no checks.
 
1886
 
 
1887
        Use set_last_revision_info to perform this safely.
 
1888
 
 
1889
        Does not update the revision_history cache.
 
1890
        Intended to be called by set_last_revision_info and
 
1891
        _write_revision_history.
 
1892
        """
 
1893
        if revision_id is None:
 
1894
            revision_id = 'null:'
 
1895
        out_string = '%d %s\n' % (revno, revision_id)
 
1896
        self.control_files.put_bytes('last-revision', out_string)
 
1897
 
 
1898
    @needs_write_lock
 
1899
    def set_last_revision_info(self, revno, revision_id):
 
1900
        revision_id = osutils.safe_revision_id(revision_id)
 
1901
        if self._get_append_revisions_only():
 
1902
            self._check_history_violation(revision_id)
 
1903
        self._write_last_revision_info(revno, revision_id)
 
1904
        self._clear_cached_state()
 
1905
 
 
1906
    def _check_history_violation(self, revision_id):
 
1907
        last_revision = self.last_revision()
 
1908
        if last_revision is None:
 
1909
            return
 
1910
        if last_revision not in self._lefthand_history(revision_id):
 
1911
            raise errors.AppendRevisionsOnlyViolation(self.base)
 
1912
 
 
1913
    def _gen_revision_history(self):
 
1914
        """Generate the revision history from last revision
 
1915
        """
 
1916
        history = list(self.repository.iter_reverse_revision_history(
 
1917
            self.last_revision()))
 
1918
        history.reverse()
 
1919
        return history
 
1920
 
 
1921
    def _write_revision_history(self, history):
 
1922
        """Factored out of set_revision_history.
 
1923
 
 
1924
        This performs the actual writing to disk, with format-specific checks.
 
1925
        It is intended to be called by BzrBranch5.set_revision_history.
 
1926
        """
 
1927
        if len(history) == 0:
 
1928
            last_revision = 'null:'
 
1929
        else:
 
1930
            if history != self._lefthand_history(history[-1]):
 
1931
                raise errors.NotLefthandHistory(history)
 
1932
            last_revision = history[-1]
 
1933
        if self._get_append_revisions_only():
 
1934
            self._check_history_violation(last_revision)
 
1935
        self._write_last_revision_info(len(history), last_revision)
 
1936
 
 
1937
    @needs_write_lock
 
1938
    def append_revision(self, *revision_ids):
 
1939
        revision_ids = [osutils.safe_revision_id(r) for r in revision_ids]
 
1940
        if len(revision_ids) == 0:
 
1941
            return
 
1942
        prev_revno, prev_revision = self.last_revision_info()
 
1943
        for revision in self.repository.get_revisions(revision_ids):
 
1944
            if prev_revision == _mod_revision.NULL_REVISION:
 
1945
                if revision.parent_ids != []:
 
1946
                    raise errors.NotLeftParentDescendant(self, prev_revision,
 
1947
                                                         revision.revision_id)
 
1948
            else:
 
1949
                if revision.parent_ids[0] != prev_revision:
 
1950
                    raise errors.NotLeftParentDescendant(self, prev_revision,
 
1951
                                                         revision.revision_id)
 
1952
            prev_revision = revision.revision_id
 
1953
        self.set_last_revision_info(prev_revno + len(revision_ids),
 
1954
                                    revision_ids[-1])
 
1955
 
 
1956
    @needs_write_lock
 
1957
    def _set_parent_location(self, url):
 
1958
        """Set the parent branch"""
 
1959
        self._set_config_location('parent_location', url, make_relative=True)
 
1960
 
 
1961
    @needs_read_lock
 
1962
    def _get_parent_location(self):
 
1963
        """Set the parent branch"""
 
1964
        return self._get_config_location('parent_location')
 
1965
 
 
1966
    def set_push_location(self, location):
 
1967
        """See Branch.set_push_location."""
 
1968
        self._set_config_location('push_location', location)
 
1969
 
 
1970
    def set_bound_location(self, location):
 
1971
        """See Branch.set_push_location."""
 
1972
        result = None
 
1973
        config = self.get_config()
 
1974
        if location is None:
 
1975
            if config.get_user_option('bound') != 'True':
 
1976
                return False
 
1977
            else:
 
1978
                config.set_user_option('bound', 'False')
 
1979
                return True
 
1980
        else:
 
1981
            self._set_config_location('bound_location', location,
 
1982
                                      config=config)
 
1983
            config.set_user_option('bound', 'True')
 
1984
        return True
 
1985
 
 
1986
    def _get_bound_location(self, bound):
 
1987
        """Return the bound location in the config file.
 
1988
 
 
1989
        Return None if the bound parameter does not match"""
 
1990
        config = self.get_config()
 
1991
        config_bound = (config.get_user_option('bound') == 'True')
 
1992
        if config_bound != bound:
 
1993
            return None
 
1994
        return self._get_config_location('bound_location', config=config)
 
1995
 
 
1996
    def get_bound_location(self):
 
1997
        """See Branch.set_push_location."""
 
1998
        return self._get_bound_location(True)
 
1999
 
 
2000
    def get_old_bound_location(self):
 
2001
        """See Branch.get_old_bound_location"""
 
2002
        return self._get_bound_location(False)
 
2003
 
 
2004
    def set_append_revisions_only(self, enabled):
 
2005
        if enabled:
 
2006
            value = 'True'
 
2007
        else:
 
2008
            value = 'False'
 
2009
        self.get_config().set_user_option('append_revisions_only', value)
 
2010
 
 
2011
    def _get_append_revisions_only(self):
 
2012
        value = self.get_config().get_user_option('append_revisions_only')
 
2013
        return value == 'True'
 
2014
 
 
2015
    def _synchronize_history(self, destination, revision_id):
 
2016
        """Synchronize last revision and revision history between branches.
 
2017
 
 
2018
        This version is most efficient when the destination is also a
 
2019
        BzrBranch6, but works for BzrBranch5, as long as the destination's
 
2020
        repository contains all the lefthand ancestors of the intended
 
2021
        last_revision.  If not, set_last_revision_info will fail.
 
2022
 
 
2023
        :param destination: The branch to copy the history into
 
2024
        :param revision_id: The revision-id to truncate history at.  May
 
2025
          be None to copy complete history.
 
2026
        """
 
2027
        if revision_id is None:
 
2028
            revno, revision_id = self.last_revision_info()
 
2029
        else:
 
2030
            revno = self.revision_id_to_revno(revision_id)
 
2031
        destination.set_last_revision_info(revno, revision_id)
 
2032
 
 
2033
    def _make_tags(self):
 
2034
        return BasicTags(self)
 
2035
 
 
2036
 
 
2037
class BranchTestProviderAdapter(object):
 
2038
    """A tool to generate a suite testing multiple branch formats at once.
 
2039
 
 
2040
    This is done by copying the test once for each transport and injecting
 
2041
    the transport_server, transport_readonly_server, and branch_format
 
2042
    classes into each copy. Each copy is also given a new id() to make it
 
2043
    easy to identify.
 
2044
    """
 
2045
 
 
2046
    def __init__(self, transport_server, transport_readonly_server, formats):
 
2047
        self._transport_server = transport_server
 
2048
        self._transport_readonly_server = transport_readonly_server
 
2049
        self._formats = formats
 
2050
    
 
2051
    def adapt(self, test):
 
2052
        result = TestSuite()
 
2053
        for branch_format, bzrdir_format in self._formats:
 
2054
            new_test = deepcopy(test)
 
2055
            new_test.transport_server = self._transport_server
 
2056
            new_test.transport_readonly_server = self._transport_readonly_server
 
2057
            new_test.bzrdir_format = bzrdir_format
 
2058
            new_test.branch_format = branch_format
 
2059
            def make_new_test_id():
 
2060
                # the format can be either a class or an instance
 
2061
                name = getattr(branch_format, '__name__',
 
2062
                        branch_format.__class__.__name__)
 
2063
                new_id = "%s(%s)" % (new_test.id(), name)
 
2064
                return lambda: new_id
 
2065
            new_test.id = make_new_test_id()
 
2066
            result.addTest(new_test)
 
2067
        return result
 
2068
 
 
2069
 
 
2070
######################################################################
 
2071
# results of operations
 
2072
 
 
2073
 
 
2074
class _Result(object):
 
2075
 
 
2076
    def _show_tag_conficts(self, to_file):
 
2077
        if not getattr(self, 'tag_conflicts', None):
 
2078
            return
 
2079
        to_file.write('Conflicting tags:\n')
 
2080
        for name, value1, value2 in self.tag_conflicts:
 
2081
            to_file.write('    %s\n' % (name, ))
 
2082
 
 
2083
 
 
2084
class PullResult(_Result):
 
2085
    """Result of a Branch.pull operation.
 
2086
 
 
2087
    :ivar old_revno: Revision number before pull.
 
2088
    :ivar new_revno: Revision number after pull.
 
2089
    :ivar old_revid: Tip revision id before pull.
 
2090
    :ivar new_revid: Tip revision id after pull.
 
2091
    :ivar source_branch: Source (local) branch object.
 
2092
    :ivar master_branch: Master branch of the target, or None.
 
2093
    :ivar target_branch: Target/destination branch object.
 
2094
    """
 
2095
 
 
2096
    def __int__(self):
 
2097
        # DEPRECATED: pull used to return the change in revno
 
2098
        return self.new_revno - self.old_revno
 
2099
 
 
2100
    def report(self, to_file):
 
2101
        if self.old_revid == self.new_revid:
 
2102
            to_file.write('No revisions to pull.\n')
 
2103
        else:
 
2104
            to_file.write('Now on revision %d.\n' % self.new_revno)
 
2105
        self._show_tag_conficts(to_file)
 
2106
 
 
2107
 
 
2108
class PushResult(_Result):
 
2109
    """Result of a Branch.push operation.
 
2110
 
 
2111
    :ivar old_revno: Revision number before push.
 
2112
    :ivar new_revno: Revision number after push.
 
2113
    :ivar old_revid: Tip revision id before push.
 
2114
    :ivar new_revid: Tip revision id after push.
 
2115
    :ivar source_branch: Source branch object.
 
2116
    :ivar master_branch: Master branch of the target, or None.
 
2117
    :ivar target_branch: Target/destination branch object.
 
2118
    """
 
2119
 
 
2120
    def __int__(self):
 
2121
        # DEPRECATED: push used to return the change in revno
 
2122
        return self.new_revno - self.old_revno
 
2123
 
 
2124
    def report(self, to_file):
 
2125
        """Write a human-readable description of the result."""
 
2126
        if self.old_revid == self.new_revid:
 
2127
            to_file.write('No new revisions to push.\n')
 
2128
        else:
 
2129
            to_file.write('Pushed up to revision %d.\n' % self.new_revno)
 
2130
        self._show_tag_conficts(to_file)
 
2131
 
 
2132
 
 
2133
class BranchCheckResult(object):
 
2134
    """Results of checking branch consistency.
 
2135
 
 
2136
    :see: Branch.check
 
2137
    """
 
2138
 
 
2139
    def __init__(self, branch):
 
2140
        self.branch = branch
 
2141
 
 
2142
    def report_results(self, verbose):
 
2143
        """Report the check results via trace.note.
 
2144
        
 
2145
        :param verbose: Requests more detailed display of what was checked,
 
2146
            if any.
 
2147
        """
 
2148
        note('checked branch %s format %s',
 
2149
             self.branch.base,
 
2150
             self.branch._format)
 
2151
 
 
2152
 
 
2153
class Converter5to6(object):
 
2154
    """Perform an in-place upgrade of format 5 to format 6"""
 
2155
 
 
2156
    def convert(self, branch):
 
2157
        # Data for 5 and 6 can peacefully coexist.
 
2158
        format = BzrBranchFormat6()
 
2159
        new_branch = format.open(branch.bzrdir, _found=True)
 
2160
 
 
2161
        # Copy source data into target
 
2162
        new_branch.set_last_revision_info(*branch.last_revision_info())
 
2163
        new_branch.set_parent(branch.get_parent())
 
2164
        new_branch.set_bound_location(branch.get_bound_location())
 
2165
        new_branch.set_push_location(branch.get_push_location())
 
2166
 
 
2167
        # New branch has no tags by default
 
2168
        new_branch.tags._set_tag_dict({})
 
2169
 
 
2170
        # Copying done; now update target format
 
2171
        new_branch.control_files.put_utf8('format',
 
2172
            format.get_format_string())
 
2173
 
 
2174
        # Clean up old files
 
2175
        new_branch.control_files._transport.delete('revision-history')
 
2176
        try:
 
2177
            branch.set_parent(None)
 
2178
        except NoSuchFile:
 
2179
            pass
 
2180
        branch.set_bound_location(None)