/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: Martin Pool
  • Date: 2007-08-14 11:53:00 UTC
  • mto: This revision was merged to the branch mainline in revision 2722.
  • Revision ID: mbp@sourcefrog.net-20070814115300-ck5miivuv97mj8gp
doc

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