~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Aaron Bentley
  • Date: 2007-02-06 14:52:16 UTC
  • mfrom: (2266 +trunk)
  • mto: This revision was merged to the branch mainline in revision 2268.
  • Revision ID: abentley@panoramicfeedback.com-20070206145216-fcpi8o3ufvuzwbp9
Merge bzr.dev

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007, 2008 Canonical Ltd
 
1
# Copyright (C) 2005, 2006 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
15
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
17
 
18
 
import sys
 
18
from cStringIO import StringIO
19
19
 
20
20
from bzrlib.lazy_import import lazy_import
21
21
lazy_import(globals(), """
22
 
from itertools import chain
 
22
from copy import deepcopy
 
23
from unittest import TestSuite
 
24
from warnings import warn
 
25
 
 
26
import bzrlib
23
27
from bzrlib import (
24
28
        bzrdir,
25
29
        cache_utf8,
26
30
        config as _mod_config,
27
 
        debug,
28
31
        errors,
29
32
        lockdir,
30
33
        lockable_files,
31
 
        repository,
 
34
        osutils,
32
35
        revision as _mod_revision,
33
36
        transport,
34
 
        tsort,
 
37
        tree,
35
38
        ui,
36
39
        urlutils,
37
40
        )
38
 
from bzrlib.config import BranchConfig
39
 
from bzrlib.repofmt.pack_repo import RepositoryFormatPackDevelopment1Subtree
40
 
from bzrlib.tag import (
41
 
    BasicTags,
42
 
    DisabledTags,
43
 
    )
 
41
from bzrlib.config import BranchConfig, TreeConfig
 
42
from bzrlib.lockable_files import LockableFiles, TransportLock
44
43
""")
45
44
 
46
45
from bzrlib.decorators import needs_read_lock, needs_write_lock
47
 
from bzrlib.hooks import Hooks
48
 
from bzrlib.symbol_versioning import (
49
 
    deprecated_in,
50
 
    deprecated_method,
51
 
    )
52
 
from bzrlib.trace import mutter, mutter_callsite, note, is_quiet
 
46
from bzrlib.errors import (BzrError, BzrCheckError, DivergedBranches,
 
47
                           HistoryMissing, InvalidRevisionId,
 
48
                           InvalidRevisionNumber, LockError, NoSuchFile,
 
49
                           NoSuchRevision, NoWorkingTree, NotVersionedError,
 
50
                           NotBranchError, UninitializableFormat,
 
51
                           UnlistableStore, UnlistableBranch,
 
52
                           )
 
53
from bzrlib.symbol_versioning import (deprecated_function,
 
54
                                      deprecated_method,
 
55
                                      DEPRECATED_PARAMETER,
 
56
                                      deprecated_passed,
 
57
                                      zero_eight, zero_nine,
 
58
                                      )
 
59
from bzrlib.trace import mutter, note
53
60
 
54
61
 
55
62
BZR_BRANCH_FORMAT_4 = "Bazaar-NG branch, format 0.0.4\n"
56
63
BZR_BRANCH_FORMAT_5 = "Bazaar-NG branch, format 5\n"
57
 
BZR_BRANCH_FORMAT_6 = "Bazaar Branch Format 6 (bzr 0.15)\n"
 
64
BZR_BRANCH_FORMAT_6 = "Bazaar-NG branch, format 6\n"
58
65
 
59
66
 
60
67
# TODO: Maybe include checks for common corruption of newlines, etc?
81
88
    # - RBC 20060112
82
89
    base = None
83
90
 
84
 
    # override this to set the strategy for storing tags
85
 
    def _make_tags(self):
86
 
        return DisabledTags(self)
87
 
 
88
91
    def __init__(self, *ignored, **ignored_too):
89
 
        self.tags = self._make_tags()
90
 
        self._revision_history_cache = None
91
 
        self._revision_id_to_revno_cache = None
92
 
        self._last_revision_info_cache = None
93
 
        self._open_hook()
94
 
 
95
 
    def _open_hook(self):
96
 
        """Called by init to allow simpler extension of the base class."""
 
92
        raise NotImplementedError('The Branch class is abstract')
97
93
 
98
94
    def break_lock(self):
99
95
        """Break a lock if one is present from another instance.
110
106
            master.break_lock()
111
107
 
112
108
    @staticmethod
113
 
    def open(base, _unsupported=False, possible_transports=None):
 
109
    @deprecated_method(zero_eight)
 
110
    def open_downlevel(base):
 
111
        """Open a branch which may be of an old format."""
 
112
        return Branch.open(base, _unsupported=True)
 
113
        
 
114
    @staticmethod
 
115
    def open(base, _unsupported=False):
114
116
        """Open the branch rooted at base.
115
117
 
116
118
        For instance, if the branch is at URL/.bzr/branch,
117
119
        Branch.open(URL) -> a Branch instance.
118
120
        """
119
 
        control = bzrdir.BzrDir.open(base, _unsupported,
120
 
                                     possible_transports=possible_transports)
121
 
        return control.open_branch(_unsupported)
122
 
 
123
 
    @staticmethod
124
 
    def open_from_transport(transport, _unsupported=False):
125
 
        """Open the branch rooted at transport"""
126
 
        control = bzrdir.BzrDir.open_from_transport(transport, _unsupported)
127
 
        return control.open_branch(_unsupported)
128
 
 
129
 
    @staticmethod
130
 
    def open_containing(url, possible_transports=None):
 
121
        control = bzrdir.BzrDir.open(base, _unsupported)
 
122
        return control.open_branch(_unsupported)
 
123
 
 
124
    @staticmethod
 
125
    def open_containing(url):
131
126
        """Open an existing branch which contains url.
132
127
        
133
128
        This probes for a branch at url, and searches upwards from there.
138
133
        format, UnknownFormatError or UnsupportedFormatError are raised.
139
134
        If there is one, it is returned, along with the unused portion of url.
140
135
        """
141
 
        control, relpath = bzrdir.BzrDir.open_containing(url,
142
 
                                                         possible_transports)
 
136
        control, relpath = bzrdir.BzrDir.open_containing(url)
143
137
        return control.open_branch(), relpath
144
138
 
 
139
    @staticmethod
 
140
    @deprecated_function(zero_eight)
 
141
    def initialize(base):
 
142
        """Create a new working tree and branch, rooted at 'base' (url)
 
143
 
 
144
        NOTE: This will soon be deprecated in favour of creation
 
145
        through a BzrDir.
 
146
        """
 
147
        return bzrdir.BzrDir.create_standalone_workingtree(base).branch
 
148
 
 
149
    @deprecated_function(zero_eight)
 
150
    def setup_caching(self, cache_root):
 
151
        """Subclasses that care about caching should override this, and set
 
152
        up cached stores located under cache_root.
 
153
        
 
154
        NOTE: This is unused.
 
155
        """
 
156
        pass
 
157
 
145
158
    def get_config(self):
146
159
        return BranchConfig(self)
147
160
 
149
162
        return self.get_config().get_nickname()
150
163
 
151
164
    def _set_nick(self, nick):
152
 
        self.get_config().set_user_option('nickname', nick, warn_masked=True)
 
165
        self.get_config().set_user_option('nickname', nick)
153
166
 
154
167
    nick = property(_get_nick, _set_nick)
155
168
 
172
185
    def get_physical_lock_status(self):
173
186
        raise NotImplementedError(self.get_physical_lock_status)
174
187
 
175
 
    @needs_read_lock
176
 
    def get_revision_id_to_revno_map(self):
177
 
        """Return the revision_id => dotted revno map.
178
 
 
179
 
        This will be regenerated on demand, but will be cached.
180
 
 
181
 
        :return: A dictionary mapping revision_id => dotted revno.
182
 
            This dictionary should not be modified by the caller.
183
 
        """
184
 
        if self._revision_id_to_revno_cache is not None:
185
 
            mapping = self._revision_id_to_revno_cache
186
 
        else:
187
 
            mapping = self._gen_revno_map()
188
 
            self._cache_revision_id_to_revno(mapping)
189
 
        # TODO: jam 20070417 Since this is being cached, should we be returning
190
 
        #       a copy?
191
 
        # I would rather not, and instead just declare that users should not
192
 
        # modify the return value.
193
 
        return mapping
194
 
 
195
 
    def _gen_revno_map(self):
196
 
        """Create a new mapping from revision ids to dotted revnos.
197
 
 
198
 
        Dotted revnos are generated based on the current tip in the revision
199
 
        history.
200
 
        This is the worker function for get_revision_id_to_revno_map, which
201
 
        just caches the return value.
202
 
 
203
 
        :return: A dictionary mapping revision_id => dotted revno.
204
 
        """
205
 
        last_revision = self.last_revision()
206
 
        revision_graph = repository._old_get_graph(self.repository,
207
 
            last_revision)
208
 
        merge_sorted_revisions = tsort.merge_sort(
209
 
            revision_graph,
210
 
            last_revision,
211
 
            None,
212
 
            generate_revno=True)
213
 
        revision_id_to_revno = dict((rev_id, revno)
214
 
                                    for seq_num, rev_id, depth, revno, end_of_merge
215
 
                                     in merge_sorted_revisions)
216
 
        return revision_id_to_revno
217
 
 
218
 
    def leave_lock_in_place(self):
219
 
        """Tell this branch object not to release the physical lock when this
220
 
        object is unlocked.
221
 
        
222
 
        If lock_write doesn't return a token, then this method is not supported.
223
 
        """
224
 
        self.control_files.leave_in_place()
225
 
 
226
 
    def dont_leave_lock_in_place(self):
227
 
        """Tell this branch object to release the physical lock when this
228
 
        object is unlocked, even if it didn't originally acquire it.
229
 
 
230
 
        If lock_write doesn't return a token, then this method is not supported.
231
 
        """
232
 
        self.control_files.dont_leave_in_place()
233
 
 
234
 
    @deprecated_method(deprecated_in((0, 16, 0)))
235
188
    def abspath(self, name):
236
189
        """Return absolute filename for something in the branch
237
190
        
272
225
        try:
273
226
            if last_revision is None:
274
227
                pb.update('get source history')
275
 
                last_revision = from_branch.last_revision()
276
 
                last_revision = _mod_revision.ensure_null(last_revision)
 
228
                last_revision = from_branch.last_revision_info()[1]
277
229
            return self.repository.fetch(from_branch.repository,
278
230
                                         revision_id=last_revision,
279
231
                                         pb=nested_pb)
290
242
        """
291
243
        return None
292
244
    
293
 
    def get_old_bound_location(self):
294
 
        """Return the URL of the branch we used to be bound to
295
 
        """
296
 
        raise errors.UpgradeRequired(self.base)
297
 
 
298
245
    def get_commit_builder(self, parents, config=None, timestamp=None, 
299
246
                           timezone=None, committer=None, revprops=None, 
300
247
                           revision_id=None):
312
259
        if config is None:
313
260
            config = self.get_config()
314
261
        
315
 
        return self.repository.get_commit_builder(self, parents, config,
 
262
        return self.repository.get_commit_builder(self, parents, config, 
316
263
            timestamp, timezone, committer, revprops, revision_id)
317
264
 
318
 
    def get_master_branch(self, possible_transports=None):
 
265
    def get_master_branch(self):
319
266
        """Return the branch we are bound to.
320
267
        
321
268
        :return: Either a Branch, or None
328
275
        The delta is relative to its mainline predecessor, or the
329
276
        empty tree for revision 1.
330
277
        """
 
278
        assert isinstance(revno, int)
331
279
        rh = self.revision_history()
332
280
        if not (1 <= revno <= len(rh)):
333
 
            raise errors.InvalidRevisionNumber(revno)
 
281
            raise InvalidRevisionNumber(revno)
334
282
        return self.repository.get_revision_delta(rh[revno-1])
335
283
 
336
 
    def get_stacked_on_url(self):
337
 
        """Get the URL this branch is stacked against.
338
 
 
339
 
        :raises NotStacked: If the branch is not stacked.
340
 
        :raises UnstackableBranchFormat: If the branch does not support
341
 
            stacking.
342
 
        """
343
 
        raise NotImplementedError(self.get_stacked_on_url)
 
284
    def get_root_id(self):
 
285
        """Return the id of this branches root"""
 
286
        raise NotImplementedError(self.get_root_id)
344
287
 
345
288
    def print_file(self, file, revision_id):
346
289
        """Print `file` to stdout."""
347
290
        raise NotImplementedError(self.print_file)
348
291
 
 
292
    def append_revision(self, *revision_ids):
 
293
        raise NotImplementedError(self.append_revision)
 
294
 
349
295
    def set_revision_history(self, rev_history):
350
296
        raise NotImplementedError(self.set_revision_history)
351
297
 
352
 
    def set_stacked_on_url(self, url):
353
 
        """Set the URL this branch is stacked against.
354
 
 
355
 
        :raises UnstackableBranchFormat: If the branch does not support
356
 
            stacking.
357
 
        :raises UnstackableRepositoryFormat: If the repository does not support
358
 
            stacking.
359
 
        """
360
 
        raise NotImplementedError(self.set_stacked_on_url)
361
 
 
362
 
    def _cache_revision_history(self, rev_history):
363
 
        """Set the cached revision history to rev_history.
364
 
 
365
 
        The revision_history method will use this cache to avoid regenerating
366
 
        the revision history.
367
 
 
368
 
        This API is semi-public; it only for use by subclasses, all other code
369
 
        should consider it to be private.
370
 
        """
371
 
        self._revision_history_cache = rev_history
372
 
 
373
 
    def _cache_revision_id_to_revno(self, revision_id_to_revno):
374
 
        """Set the cached revision_id => revno map to revision_id_to_revno.
375
 
 
376
 
        This API is semi-public; it only for use by subclasses, all other code
377
 
        should consider it to be private.
378
 
        """
379
 
        self._revision_id_to_revno_cache = revision_id_to_revno
380
 
 
381
 
    def _clear_cached_state(self):
382
 
        """Clear any cached data on this branch, e.g. cached revision history.
383
 
 
384
 
        This means the next call to revision_history will need to call
385
 
        _gen_revision_history.
386
 
 
387
 
        This API is semi-public; it only for use by subclasses, all other code
388
 
        should consider it to be private.
389
 
        """
390
 
        self._revision_history_cache = None
391
 
        self._revision_id_to_revno_cache = None
392
 
        self._last_revision_info_cache = None
393
 
 
394
 
    def _gen_revision_history(self):
395
 
        """Return sequence of revision hashes on to this branch.
396
 
        
397
 
        Unlike revision_history, this method always regenerates or rereads the
398
 
        revision history, i.e. it does not cache the result, so repeated calls
399
 
        may be expensive.
400
 
 
401
 
        Concrete subclasses should override this instead of revision_history so
402
 
        that subclasses do not need to deal with caching logic.
403
 
        
404
 
        This API is semi-public; it only for use by subclasses, all other code
405
 
        should consider it to be private.
406
 
        """
407
 
        raise NotImplementedError(self._gen_revision_history)
408
 
 
409
 
    @needs_read_lock
410
298
    def revision_history(self):
411
 
        """Return sequence of revision ids on this branch.
412
 
        
413
 
        This method will cache the revision history for as long as it is safe to
414
 
        do so.
415
 
        """
416
 
        if 'evil' in debug.debug_flags:
417
 
            mutter_callsite(3, "revision_history scales with history.")
418
 
        if self._revision_history_cache is not None:
419
 
            history = self._revision_history_cache
420
 
        else:
421
 
            history = self._gen_revision_history()
422
 
            self._cache_revision_history(history)
423
 
        return list(history)
 
299
        """Return sequence of revision hashes on to this branch."""
 
300
        raise NotImplementedError(self.revision_history)
424
301
 
425
302
    def revno(self):
426
303
        """Return current revision number for this branch.
428
305
        That is equivalent to the number of revisions committed to
429
306
        this branch.
430
307
        """
431
 
        return self.last_revision_info()[0]
 
308
        return len(self.revision_history())
432
309
 
433
310
    def unbind(self):
434
311
        """Older format branches cannot bind or unbind."""
435
312
        raise errors.UpgradeRequired(self.base)
436
313
 
437
 
    def set_append_revisions_only(self, enabled):
438
 
        """Older format branches are never restricted to append-only"""
439
 
        raise errors.UpgradeRequired(self.base)
440
 
 
441
314
    def last_revision(self):
442
 
        """Return last revision id, or NULL_REVISION."""
443
 
        return self.last_revision_info()[1]
 
315
        """Return last revision id, or None"""
 
316
        ph = self.revision_history()
 
317
        if ph:
 
318
            return ph[-1]
 
319
        else:
 
320
            return None
444
321
 
445
 
    @needs_read_lock
446
322
    def last_revision_info(self):
447
323
        """Return information about the last revision.
448
324
 
449
 
        :return: A tuple (revno, revision_id).
 
325
        :return: A tuple (revno, last_revision_id).
450
326
        """
451
 
        if self._last_revision_info_cache is None:
452
 
            self._last_revision_info_cache = self._last_revision_info()
453
 
        return self._last_revision_info_cache
454
 
 
455
 
    def _last_revision_info(self):
456
327
        rh = self.revision_history()
457
328
        revno = len(rh)
458
329
        if revno:
460
331
        else:
461
332
            return (0, _mod_revision.NULL_REVISION)
462
333
 
463
 
    @deprecated_method(deprecated_in((1, 6, 0)))
464
334
    def missing_revisions(self, other, stop_revision=None):
465
335
        """Return a list of new revisions that would perfectly fit.
466
336
        
474
344
        common_index = min(self_len, other_len) -1
475
345
        if common_index >= 0 and \
476
346
            self_history[common_index] != other_history[common_index]:
477
 
            raise errors.DivergedBranches(self, other)
 
347
            raise DivergedBranches(self, other)
478
348
 
479
349
        if stop_revision is None:
480
350
            stop_revision = other_len
481
351
        else:
 
352
            assert isinstance(stop_revision, int)
482
353
            if stop_revision > other_len:
483
354
                raise errors.NoSuchRevision(self, stop_revision)
484
355
        return other_history[self_len:stop_revision]
485
356
 
486
 
    @needs_write_lock
487
 
    def update_revisions(self, other, stop_revision=None, overwrite=False,
488
 
                         graph=None):
 
357
    def update_revisions(self, other, stop_revision=None):
489
358
        """Pull in new perfect-fit revisions.
490
359
 
491
360
        :param other: Another Branch to pull from
492
361
        :param stop_revision: Updated until the given revision
493
 
        :param overwrite: Always set the branch pointer, rather than checking
494
 
            to see if it is a proper descendant.
495
 
        :param graph: A Graph object that can be used to query history
496
 
            information. This can be None.
497
362
        :return: None
498
363
        """
499
 
        other.lock_read()
500
 
        try:
501
 
            other_revno, other_last_revision = other.last_revision_info()
502
 
            stop_revno = None # unknown
503
 
            if stop_revision is None:
504
 
                stop_revision = other_last_revision
505
 
                if _mod_revision.is_null(stop_revision):
506
 
                    # if there are no commits, we're done.
507
 
                    return
508
 
                stop_revno = other_revno
509
 
 
510
 
            # what's the current last revision, before we fetch [and change it
511
 
            # possibly]
512
 
            last_rev = _mod_revision.ensure_null(self.last_revision())
513
 
            # we fetch here so that we don't process data twice in the common
514
 
            # case of having something to pull, and so that the check for 
515
 
            # already merged can operate on the just fetched graph, which will
516
 
            # be cached in memory.
517
 
            self.fetch(other, stop_revision)
518
 
            # Check to see if one is an ancestor of the other
519
 
            if not overwrite:
520
 
                if graph is None:
521
 
                    graph = self.repository.get_graph()
522
 
                if self._check_if_descendant_or_diverged(
523
 
                        stop_revision, last_rev, graph, other):
524
 
                    # stop_revision is a descendant of last_rev, but we aren't
525
 
                    # overwriting, so we're done.
526
 
                    return
527
 
            if stop_revno is None:
528
 
                if graph is None:
529
 
                    graph = self.repository.get_graph()
530
 
                this_revno, this_last_revision = self.last_revision_info()
531
 
                stop_revno = graph.find_distance_to_null(stop_revision,
532
 
                                [(other_last_revision, other_revno),
533
 
                                 (this_last_revision, this_revno)])
534
 
            self.set_last_revision_info(stop_revno, stop_revision)
535
 
        finally:
536
 
            other.unlock()
 
364
        raise NotImplementedError(self.update_revisions)
537
365
 
538
366
    def revision_id_to_revno(self, revision_id):
539
367
        """Given a revision id, return its revno"""
540
 
        if _mod_revision.is_null(revision_id):
 
368
        if revision_id is None:
541
369
            return 0
542
370
        history = self.revision_history()
543
371
        try:
544
372
            return history.index(revision_id) + 1
545
373
        except ValueError:
546
 
            raise errors.NoSuchRevision(self, revision_id)
 
374
            raise bzrlib.errors.NoSuchRevision(self, revision_id)
547
375
 
548
376
    def get_rev_id(self, revno, history=None):
549
377
        """Find the revision id of the specified revno."""
550
378
        if revno == 0:
551
 
            return _mod_revision.NULL_REVISION
 
379
            return None
552
380
        if history is None:
553
381
            history = self.revision_history()
554
382
        if revno <= 0 or revno > len(history):
555
 
            raise errors.NoSuchRevision(self, revno)
 
383
            raise bzrlib.errors.NoSuchRevision(self, revno)
556
384
        return history[revno - 1]
557
385
 
558
 
    def pull(self, source, overwrite=False, stop_revision=None,
559
 
             possible_transports=None, _override_hook_target=None):
 
386
    def pull(self, source, overwrite=False, stop_revision=None):
560
387
        """Mirror source into this branch.
561
388
 
562
389
        This branch is considered to be 'local', having low latency.
563
 
 
564
 
        :returns: PullResult instance
565
390
        """
566
391
        raise NotImplementedError(self.pull)
567
392
 
608
433
        """
609
434
        raise NotImplementedError(self.get_parent)
610
435
 
611
 
    def _set_config_location(self, name, url, config=None,
612
 
                             make_relative=False):
613
 
        if config is None:
614
 
            config = self.get_config()
615
 
        if url is None:
616
 
            url = ''
617
 
        elif make_relative:
618
 
            url = urlutils.relative_url(self.base, url)
619
 
        config.set_user_option(name, url, warn_masked=True)
620
 
 
621
 
    def _get_config_location(self, name, config=None):
622
 
        if config is None:
623
 
            config = self.get_config()
624
 
        location = config.get_user_option(name)
625
 
        if location == '':
626
 
            location = None
627
 
        return location
628
 
 
629
436
    def get_submit_branch(self):
630
437
        """Return the submit location of the branch.
631
438
 
642
449
        pattern is that the user can override it by specifying a
643
450
        location.
644
451
        """
645
 
        self.get_config().set_user_option('submit_branch', location,
646
 
            warn_masked=True)
647
 
 
648
 
    def get_public_branch(self):
649
 
        """Return the public location of the branch.
650
 
 
651
 
        This is is used by merge directives.
652
 
        """
653
 
        return self._get_config_location('public_branch')
654
 
 
655
 
    def set_public_branch(self, location):
656
 
        """Return the submit location of the branch.
657
 
 
658
 
        This is the default location for bundle.  The usual
659
 
        pattern is that the user can override it by specifying a
660
 
        location.
661
 
        """
662
 
        self._set_config_location('public_branch', location)
 
452
        self.get_config().set_user_option('submit_branch', location)
663
453
 
664
454
    def get_push_location(self):
665
455
        """Return the None or the location to push this branch to."""
666
 
        push_loc = self.get_config().get_user_option('push_location')
667
 
        return push_loc
 
456
        raise NotImplementedError(self.get_push_location)
668
457
 
669
458
    def set_push_location(self, location):
670
459
        """Set a new push location for this branch."""
695
484
        Zero (the NULL revision) is considered invalid
696
485
        """
697
486
        if revno < 1 or revno > self.revno():
698
 
            raise errors.InvalidRevisionNumber(revno)
 
487
            raise InvalidRevisionNumber(revno)
699
488
 
700
489
    @needs_read_lock
701
 
    def clone(self, to_bzrdir, revision_id=None):
 
490
    def clone(self, *args, **kwargs):
702
491
        """Clone this branch into to_bzrdir preserving all semantic values.
703
492
        
704
493
        revision_id: if not None, the revision history in the new branch will
705
494
                     be truncated to end with revision_id.
706
495
        """
 
496
        # for API compatibility, until 0.8 releases we provide the old api:
 
497
        # def clone(self, to_location, revision=None, basis_branch=None, to_branch_format=None):
 
498
        # after 0.8 releases, the *args and **kwargs should be changed:
 
499
        # def clone(self, to_bzrdir, revision_id=None):
 
500
        if (kwargs.get('to_location', None) or
 
501
            kwargs.get('revision', None) or
 
502
            kwargs.get('basis_branch', None) or
 
503
            (len(args) and isinstance(args[0], basestring))):
 
504
            # backwards compatibility api:
 
505
            warn("Branch.clone() has been deprecated for BzrDir.clone() from"
 
506
                 " bzrlib 0.8.", DeprecationWarning, stacklevel=3)
 
507
            # get basis_branch
 
508
            if len(args) > 2:
 
509
                basis_branch = args[2]
 
510
            else:
 
511
                basis_branch = kwargs.get('basis_branch', None)
 
512
            if basis_branch:
 
513
                basis = basis_branch.bzrdir
 
514
            else:
 
515
                basis = None
 
516
            # get revision
 
517
            if len(args) > 1:
 
518
                revision_id = args[1]
 
519
            else:
 
520
                revision_id = kwargs.get('revision', None)
 
521
            # get location
 
522
            if len(args):
 
523
                url = args[0]
 
524
            else:
 
525
                # no default to raise if not provided.
 
526
                url = kwargs.get('to_location')
 
527
            return self.bzrdir.clone(url,
 
528
                                     revision_id=revision_id,
 
529
                                     basis=basis).open_branch()
 
530
        # new cleaner api.
 
531
        # generate args by hand 
 
532
        if len(args) > 1:
 
533
            revision_id = args[1]
 
534
        else:
 
535
            revision_id = kwargs.get('revision_id', None)
 
536
        if len(args):
 
537
            to_bzrdir = args[0]
 
538
        else:
 
539
            # no default to raise if not provided.
 
540
            to_bzrdir = kwargs.get('to_bzrdir')
707
541
        result = self._format.initialize(to_bzrdir)
708
542
        self.copy_content_into(result, revision_id=revision_id)
709
543
        return  result
720
554
        result.set_parent(self.bzrdir.root_transport.base)
721
555
        return result
722
556
 
723
 
    def _synchronize_history(self, destination, revision_id):
724
 
        """Synchronize last revision and revision history between branches.
725
 
 
726
 
        This version is most efficient when the destination is also a
727
 
        BzrBranch5, but works for BzrBranch6 as long as the revision
728
 
        history is the true lefthand parent history, and all of the revisions
729
 
        are in the destination's repository.  If not, set_revision_history
730
 
        will fail.
731
 
 
732
 
        :param destination: The branch to copy the history into
733
 
        :param revision_id: The revision-id to truncate history at.  May
734
 
          be None to copy complete history.
 
557
    @needs_read_lock
 
558
    def copy_content_into(self, destination, revision_id=None):
 
559
        """Copy the content of self into destination.
 
560
 
 
561
        revision_id: if not None, the revision history in the new branch will
 
562
                     be truncated to end with revision_id.
735
563
        """
736
 
        if revision_id == _mod_revision.NULL_REVISION:
737
 
            new_history = []
738
564
        new_history = self.revision_history()
739
 
        if revision_id is not None and new_history != []:
 
565
        if revision_id is not None:
740
566
            try:
741
567
                new_history = new_history[:new_history.index(revision_id) + 1]
742
568
            except ValueError:
743
569
                rev = self.repository.get_revision(revision_id)
744
570
                new_history = rev.get_history(self.repository)[1:]
745
571
        destination.set_revision_history(new_history)
746
 
 
747
 
    @needs_read_lock
748
 
    def copy_content_into(self, destination, revision_id=None):
749
 
        """Copy the content of self into destination.
750
 
 
751
 
        revision_id: if not None, the revision history in the new branch will
752
 
                     be truncated to end with revision_id.
753
 
        """
754
 
        self._synchronize_history(destination, revision_id)
755
572
        try:
756
573
            parent = self.get_parent()
757
574
        except errors.InaccessibleParent, e:
759
576
        else:
760
577
            if parent:
761
578
                destination.set_parent(parent)
762
 
        self.tags.merge_to(destination.tags)
763
579
 
764
580
    @needs_read_lock
765
581
    def check(self):
774
590
        :return: A BranchCheckResult.
775
591
        """
776
592
        mainline_parent_id = None
777
 
        last_revno, last_revision_id = self.last_revision_info()
778
 
        real_rev_history = list(self.repository.iter_reverse_revision_history(
779
 
                                last_revision_id))
780
 
        real_rev_history.reverse()
781
 
        if len(real_rev_history) != last_revno:
782
 
            raise errors.BzrCheckError('revno does not match len(mainline)'
783
 
                ' %s != %s' % (last_revno, len(real_rev_history)))
784
 
        # TODO: We should probably also check that real_rev_history actually
785
 
        #       matches self.revision_history()
786
 
        for revision_id in real_rev_history:
 
593
        for revision_id in self.revision_history():
787
594
            try:
788
595
                revision = self.repository.get_revision(revision_id)
789
596
            except errors.NoSuchRevision, e:
802
609
 
803
610
    def _get_checkout_format(self):
804
611
        """Return the most suitable metadir for a checkout of this branch.
805
 
        Weaves are used if this branch's repository uses weaves.
 
612
        Weaves are used if this branch's repostory uses weaves.
806
613
        """
807
614
        if isinstance(self.bzrdir, bzrdir.BzrDirPreSplitOut):
808
 
            from bzrlib.repofmt import weaverepo
 
615
            from bzrlib import repository
809
616
            format = bzrdir.BzrDirMetaFormat1()
810
 
            format.repository_format = weaverepo.RepositoryFormat7()
 
617
            format.repository_format = repository.RepositoryFormat7()
811
618
        else:
812
 
            format = self.repository.bzrdir.checkout_metadir()
813
 
            format.set_branch_format(self._format)
 
619
            format = self.repository.bzrdir.cloning_metadir()
814
620
        return format
815
621
 
816
622
    def create_checkout(self, to_location, revision_id=None,
817
 
                        lightweight=False, accelerator_tree=None,
818
 
                        hardlink=False):
 
623
                        lightweight=False):
819
624
        """Create a checkout of a branch.
820
625
        
821
626
        :param to_location: The url to produce the checkout at
822
627
        :param revision_id: The revision to check out
823
628
        :param lightweight: If True, produce a lightweight checkout, otherwise,
824
629
        produce a bound branch (heavyweight checkout)
825
 
        :param accelerator_tree: A tree which can be used for retrieving file
826
 
            contents more quickly than the revision tree, i.e. a workingtree.
827
 
            The revision tree will be used for cases where accelerator_tree's
828
 
            content is different.
829
 
        :param hardlink: If true, hard-link files from accelerator_tree,
830
 
            where possible.
831
630
        :return: The tree of the created checkout
832
631
        """
833
632
        t = transport.get_transport(to_location)
834
 
        t.ensure_base()
 
633
        try:
 
634
            t.mkdir('.')
 
635
        except errors.FileExists:
 
636
            pass
835
637
        if lightweight:
836
 
            format = self._get_checkout_format()
837
 
            checkout = format.initialize_on_transport(t)
838
 
            from_branch = BranchReferenceFormat().initialize(checkout, self)
 
638
            checkout = bzrdir.BzrDirMetaFormat1().initialize_on_transport(t)
 
639
            BranchReferenceFormat().initialize(checkout, self)
839
640
        else:
840
641
            format = self._get_checkout_format()
841
642
            checkout_branch = bzrdir.BzrDir.create_branch_convenience(
845
646
            # pull up to the specified revision_id to set the initial 
846
647
            # branch tip correctly, and seed it with history.
847
648
            checkout_branch.pull(self, stop_revision=revision_id)
848
 
            from_branch=None
849
 
        tree = checkout.create_workingtree(revision_id,
850
 
                                           from_branch=from_branch,
851
 
                                           accelerator_tree=accelerator_tree,
852
 
                                           hardlink=hardlink)
853
 
        basis_tree = tree.basis_tree()
854
 
        basis_tree.lock_read()
855
 
        try:
856
 
            for path, file_id in basis_tree.iter_references():
857
 
                reference_parent = self.reference_parent(file_id, path)
858
 
                reference_parent.create_checkout(tree.abspath(path),
859
 
                    basis_tree.get_reference_revision(file_id, path),
860
 
                    lightweight)
861
 
        finally:
862
 
            basis_tree.unlock()
863
 
        return tree
864
 
 
865
 
    @needs_write_lock
866
 
    def reconcile(self, thorough=True):
867
 
        """Make sure the data stored in this branch is consistent."""
868
 
        from bzrlib.reconcile import BranchReconciler
869
 
        reconciler = BranchReconciler(self, thorough=thorough)
870
 
        reconciler.reconcile()
871
 
        return reconciler
872
 
 
873
 
    def reference_parent(self, file_id, path):
874
 
        """Return the parent branch for a tree-reference file_id
875
 
        :param file_id: The file_id of the tree reference
876
 
        :param path: The path of the file_id in the tree
877
 
        :return: A branch associated with the file_id
878
 
        """
879
 
        # FIXME should provide multiple branches, based on config
880
 
        return Branch.open(self.bzrdir.root_transport.clone(path).base)
881
 
 
882
 
    def supports_tags(self):
883
 
        return self._format.supports_tags()
884
 
 
885
 
    def _check_if_descendant_or_diverged(self, revision_a, revision_b, graph,
886
 
                                         other_branch):
887
 
        """Ensure that revision_b is a descendant of revision_a.
888
 
 
889
 
        This is a helper function for update_revisions.
890
 
        
891
 
        :raises: DivergedBranches if revision_b has diverged from revision_a.
892
 
        :returns: True if revision_b is a descendant of revision_a.
893
 
        """
894
 
        relation = self._revision_relations(revision_a, revision_b, graph)
895
 
        if relation == 'b_descends_from_a':
896
 
            return True
897
 
        elif relation == 'diverged':
898
 
            raise errors.DivergedBranches(self, other_branch)
899
 
        elif relation == 'a_descends_from_b':
900
 
            return False
901
 
        else:
902
 
            raise AssertionError("invalid relation: %r" % (relation,))
903
 
 
904
 
    def _revision_relations(self, revision_a, revision_b, graph):
905
 
        """Determine the relationship between two revisions.
906
 
        
907
 
        :returns: One of: 'a_descends_from_b', 'b_descends_from_a', 'diverged'
908
 
        """
909
 
        heads = graph.heads([revision_a, revision_b])
910
 
        if heads == set([revision_b]):
911
 
            return 'b_descends_from_a'
912
 
        elif heads == set([revision_a, revision_b]):
913
 
            # These branches have diverged
914
 
            return 'diverged'
915
 
        elif heads == set([revision_a]):
916
 
            return 'a_descends_from_b'
917
 
        else:
918
 
            raise AssertionError("invalid heads: %r" % (heads,))
 
649
        return checkout.create_workingtree(revision_id)
919
650
 
920
651
 
921
652
class BranchFormat(object):
942
673
    _formats = {}
943
674
    """The known formats."""
944
675
 
945
 
    def __eq__(self, other):
946
 
        return self.__class__ is other.__class__
947
 
 
948
 
    def __ne__(self, other):
949
 
        return not (self == other)
950
 
 
951
676
    @classmethod
952
677
    def find_format(klass, a_bzrdir):
953
678
        """Return the format for the branch object in a_bzrdir."""
955
680
            transport = a_bzrdir.get_branch_transport(None)
956
681
            format_string = transport.get("format").read()
957
682
            return klass._formats[format_string]
958
 
        except errors.NoSuchFile:
959
 
            raise errors.NotBranchError(path=transport.base)
 
683
        except NoSuchFile:
 
684
            raise NotBranchError(path=transport.base)
960
685
        except KeyError:
961
 
            raise errors.UnknownFormatError(format=format_string, kind='branch')
 
686
            raise errors.UnknownFormatError(format=format_string)
962
687
 
963
688
    @classmethod
964
689
    def get_default_format(klass):
965
690
        """Return the current default format."""
966
691
        return klass._default_format
967
692
 
968
 
    def get_reference(self, a_bzrdir):
969
 
        """Get the target reference of the branch in a_bzrdir.
970
 
 
971
 
        format probing must have been completed before calling
972
 
        this method - it is assumed that the format of the branch
973
 
        in a_bzrdir is correct.
974
 
 
975
 
        :param a_bzrdir: The bzrdir to get the branch data from.
976
 
        :return: None if the branch is not a reference branch.
977
 
        """
978
 
        return None
979
 
 
980
 
    @classmethod
981
 
    def set_reference(self, a_bzrdir, to_branch):
982
 
        """Set the target reference of the branch in a_bzrdir.
983
 
 
984
 
        format probing must have been completed before calling
985
 
        this method - it is assumed that the format of the branch
986
 
        in a_bzrdir is correct.
987
 
 
988
 
        :param a_bzrdir: The bzrdir to set the branch reference for.
989
 
        :param to_branch: branch that the checkout is to reference
990
 
        """
991
 
        raise NotImplementedError(self.set_reference)
992
 
 
993
693
    def get_format_string(self):
994
694
        """Return the ASCII format string that identifies this format."""
995
695
        raise NotImplementedError(self.get_format_string)
998
698
        """Return the short format description for this format."""
999
699
        raise NotImplementedError(self.get_format_description)
1000
700
 
1001
 
    def _initialize_helper(self, a_bzrdir, utf8_files, lock_type='metadir',
1002
 
                           set_format=True):
1003
 
        """Initialize a branch in a bzrdir, with specified files
1004
 
 
1005
 
        :param a_bzrdir: The bzrdir to initialize the branch in
1006
 
        :param utf8_files: The files to create as a list of
1007
 
            (filename, content) tuples
1008
 
        :param set_format: If True, set the format with
1009
 
            self.get_format_string.  (BzrBranch4 has its format set
1010
 
            elsewhere)
1011
 
        :return: a branch in this format
1012
 
        """
1013
 
        mutter('creating branch %r in %s', self, a_bzrdir.transport.base)
1014
 
        branch_transport = a_bzrdir.get_branch_transport(self)
1015
 
        lock_map = {
1016
 
            'metadir': ('lock', lockdir.LockDir),
1017
 
            'branch4': ('branch-lock', lockable_files.TransportLock),
1018
 
        }
1019
 
        lock_name, lock_class = lock_map[lock_type]
1020
 
        control_files = lockable_files.LockableFiles(branch_transport,
1021
 
            lock_name, lock_class)
1022
 
        control_files.create_lock()
1023
 
        control_files.lock_write()
1024
 
        if set_format:
1025
 
            utf8_files += [('format', self.get_format_string())]
1026
 
        try:
1027
 
            for (filename, content) in utf8_files:
1028
 
                branch_transport.put_bytes(
1029
 
                    filename, content,
1030
 
                    mode=a_bzrdir._get_file_mode())
1031
 
        finally:
1032
 
            control_files.unlock()
1033
 
        return self.open(a_bzrdir, _found=True)
1034
 
 
1035
701
    def initialize(self, a_bzrdir):
1036
702
        """Create a branch of this format in a_bzrdir."""
1037
703
        raise NotImplementedError(self.initialize)
1061
727
    def set_default_format(klass, format):
1062
728
        klass._default_format = format
1063
729
 
1064
 
    def supports_stacking(self):
1065
 
        """True if this format records a stacked-on branch."""
1066
 
        return False
1067
 
 
1068
730
    @classmethod
1069
731
    def unregister_format(klass, format):
 
732
        assert klass._formats[format.get_format_string()] is format
1070
733
        del klass._formats[format.get_format_string()]
1071
734
 
1072
735
    def __str__(self):
1073
736
        return self.get_format_string().rstrip()
1074
737
 
1075
 
    def supports_tags(self):
1076
 
        """True if this format supports tags stored in the branch"""
1077
 
        return False  # by default
1078
 
 
1079
 
 
1080
 
class BranchHooks(Hooks):
 
738
 
 
739
class BranchHooks(dict):
1081
740
    """A dictionary mapping hook name to a list of callables for branch hooks.
1082
741
    
1083
742
    e.g. ['set_rh'] Is the list of items to be called when the
1090
749
        These are all empty initially, because by default nothing should get
1091
750
        notified.
1092
751
        """
1093
 
        Hooks.__init__(self)
1094
 
        # Introduced in 0.15:
 
752
        dict.__init__(self)
1095
753
        # invoked whenever the revision history has been set
1096
754
        # with set_revision_history. The api signature is
1097
755
        # (branch, revision_history), and the branch will
1098
 
        # be write-locked.
 
756
        # be write-locked. Introduced in 0.15.
1099
757
        self['set_rh'] = []
1100
 
        # invoked after a push operation completes.
1101
 
        # the api signature is
1102
 
        # (push_result)
1103
 
        # containing the members
1104
 
        # (source, local, master, old_revno, old_revid, new_revno, new_revid)
1105
 
        # where local is the local target branch or None, master is the target 
1106
 
        # master branch, and the rest should be self explanatory. The source
1107
 
        # is read locked and the target branches write locked. Source will
1108
 
        # be the local low-latency branch.
1109
 
        self['post_push'] = []
1110
 
        # invoked after a pull operation completes.
1111
 
        # the api signature is
1112
 
        # (pull_result)
1113
 
        # containing the members
1114
 
        # (source, local, master, old_revno, old_revid, new_revno, new_revid)
1115
 
        # where local is the local branch or None, master is the target 
1116
 
        # master branch, and the rest should be self explanatory. The source
1117
 
        # is read locked and the target branches write locked. The local
1118
 
        # branch is the low-latency branch.
1119
 
        self['post_pull'] = []
1120
 
        # invoked before a commit operation takes place.
1121
 
        # the api signature is
1122
 
        # (local, master, old_revno, old_revid, future_revno, future_revid,
1123
 
        #  tree_delta, future_tree).
1124
 
        # old_revid is NULL_REVISION for the first commit to a branch
1125
 
        # tree_delta is a TreeDelta object describing changes from the basis
1126
 
        # revision, hooks MUST NOT modify this delta
1127
 
        # future_tree is an in-memory tree obtained from
1128
 
        # CommitBuilder.revision_tree() and hooks MUST NOT modify this tree
1129
 
        self['pre_commit'] = []
1130
 
        # invoked after a commit operation completes.
1131
 
        # the api signature is 
1132
 
        # (local, master, old_revno, old_revid, new_revno, new_revid)
1133
 
        # old_revid is NULL_REVISION for the first commit to a branch.
1134
 
        self['post_commit'] = []
1135
 
        # invoked after a uncommit operation completes.
1136
 
        # the api signature is
1137
 
        # (local, master, old_revno, old_revid, new_revno, new_revid) where
1138
 
        # local is the local branch or None, master is the target branch,
1139
 
        # and an empty branch recieves new_revno of 0, new_revid of None.
1140
 
        self['post_uncommit'] = []
1141
 
        # Introduced in 1.6
1142
 
        # Invoked before the tip of a branch changes.
1143
 
        # the api signature is
1144
 
        # (params) where params is a ChangeBranchTipParams with the members
1145
 
        # (branch, old_revno, new_revno, old_revid, new_revid)
1146
 
        self['pre_change_branch_tip'] = []
1147
 
        # Introduced in 1.4
1148
 
        # Invoked after the tip of a branch changes.
1149
 
        # the api signature is
1150
 
        # (params) where params is a ChangeBranchTipParams with the members
1151
 
        # (branch, old_revno, new_revno, old_revid, new_revid)
1152
 
        self['post_change_branch_tip'] = []
 
758
 
 
759
    def install_hook(self, hook_name, a_callable):
 
760
        """Install a_callable in to the hook hook_name.
 
761
 
 
762
        :param hook_name: A hook name. See the __init__ method of BranchHooks
 
763
            for the complete list of hooks.
 
764
        :param a_callable: The callable to be invoked when the hook triggers.
 
765
            The exact signature will depend on the hook - see the __init__ 
 
766
            method of BranchHooks for details on each hook.
 
767
        """
 
768
        try:
 
769
            self[hook_name].append(a_callable)
 
770
        except KeyError:
 
771
            raise errors.UnknownHook('branch', hook_name)
1153
772
 
1154
773
 
1155
774
# install the default hooks into the Branch class.
1156
775
Branch.hooks = BranchHooks()
1157
776
 
1158
777
 
1159
 
class ChangeBranchTipParams(object):
1160
 
    """Object holding parameters passed to *_change_branch_tip hooks.
1161
 
 
1162
 
    There are 5 fields that hooks may wish to access:
1163
 
 
1164
 
    :ivar branch: the branch being changed
1165
 
    :ivar old_revno: revision number before the change
1166
 
    :ivar new_revno: revision number after the change
1167
 
    :ivar old_revid: revision id before the change
1168
 
    :ivar new_revid: revision id after the change
1169
 
 
1170
 
    The revid fields are strings. The revno fields are integers.
1171
 
    """
1172
 
 
1173
 
    def __init__(self, branch, old_revno, new_revno, old_revid, new_revid):
1174
 
        """Create a group of ChangeBranchTip parameters.
1175
 
 
1176
 
        :param branch: The branch being changed.
1177
 
        :param old_revno: Revision number before the change.
1178
 
        :param new_revno: Revision number after the change.
1179
 
        :param old_revid: Tip revision id before the change.
1180
 
        :param new_revid: Tip revision id after the change.
1181
 
        """
1182
 
        self.branch = branch
1183
 
        self.old_revno = old_revno
1184
 
        self.new_revno = new_revno
1185
 
        self.old_revid = old_revid
1186
 
        self.new_revid = new_revid
1187
 
 
1188
 
    def __eq__(self, other):
1189
 
        return self.__dict__ == other.__dict__
1190
 
    
1191
 
    def __repr__(self):
1192
 
        return "<%s of %s from (%s, %s) to (%s, %s)>" % (
1193
 
            self.__class__.__name__, self.branch, 
1194
 
            self.old_revno, self.old_revid, self.new_revno, self.new_revid)
1195
 
 
1196
 
 
1197
778
class BzrBranchFormat4(BranchFormat):
1198
779
    """Bzr branch format 4.
1199
780
 
1208
789
 
1209
790
    def initialize(self, a_bzrdir):
1210
791
        """Create a branch of this format in a_bzrdir."""
 
792
        mutter('creating branch in %s', a_bzrdir.transport.base)
 
793
        branch_transport = a_bzrdir.get_branch_transport(self)
1211
794
        utf8_files = [('revision-history', ''),
1212
795
                      ('branch-name', ''),
1213
796
                      ]
1214
 
        return self._initialize_helper(a_bzrdir, utf8_files,
1215
 
                                       lock_type='branch4', set_format=False)
 
797
        control_files = lockable_files.LockableFiles(branch_transport,
 
798
                             'branch-lock', lockable_files.TransportLock)
 
799
        control_files.create_lock()
 
800
        control_files.lock_write()
 
801
        try:
 
802
            for file, content in utf8_files:
 
803
                control_files.put_utf8(file, content)
 
804
        finally:
 
805
            control_files.unlock()
 
806
        return self.open(a_bzrdir, _found=True)
1216
807
 
1217
808
    def __init__(self):
1218
809
        super(BzrBranchFormat4, self).__init__()
1236
827
        return "Bazaar-NG branch format 4"
1237
828
 
1238
829
 
1239
 
class BranchFormatMetadir(BranchFormat):
1240
 
    """Common logic for meta-dir based branch formats."""
1241
 
 
1242
 
    def _branch_class(self):
1243
 
        """What class to instantiate on open calls."""
1244
 
        raise NotImplementedError(self._branch_class)
1245
 
 
1246
 
    def open(self, a_bzrdir, _found=False):
1247
 
        """Return the branch object for a_bzrdir.
1248
 
 
1249
 
        _found is a private parameter, do not use it. It is used to indicate
1250
 
               if format probing has already be done.
1251
 
        """
1252
 
        if not _found:
1253
 
            format = BranchFormat.find_format(a_bzrdir)
1254
 
            if format.__class__ != self.__class__:
1255
 
                raise AssertionError("wrong format %r found for %r" %
1256
 
                    (format, self))
1257
 
        try:
1258
 
            transport = a_bzrdir.get_branch_transport(None)
1259
 
            control_files = lockable_files.LockableFiles(transport, 'lock',
1260
 
                                                         lockdir.LockDir)
1261
 
            return self._branch_class()(_format=self,
1262
 
                              _control_files=control_files,
1263
 
                              a_bzrdir=a_bzrdir,
1264
 
                              _repository=a_bzrdir.find_repository())
1265
 
        except errors.NoSuchFile:
1266
 
            raise errors.NotBranchError(path=transport.base)
1267
 
 
1268
 
    def __init__(self):
1269
 
        super(BranchFormatMetadir, self).__init__()
1270
 
        self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
1271
 
 
1272
 
    def supports_tags(self):
1273
 
        return True
1274
 
 
1275
 
 
1276
 
class BzrBranchFormat5(BranchFormatMetadir):
 
830
class BzrBranchFormat5(BranchFormat):
1277
831
    """Bzr branch format 5.
1278
832
 
1279
833
    This format has:
1286
840
    This format is new in bzr 0.8.
1287
841
    """
1288
842
 
1289
 
    def _branch_class(self):
1290
 
        return BzrBranch5
1291
 
 
1292
843
    def get_format_string(self):
1293
844
        """See BranchFormat.get_format_string()."""
1294
845
        return "Bazaar-NG branch format 5\n"
1299
850
        
1300
851
    def initialize(self, a_bzrdir):
1301
852
        """Create a branch of this format in a_bzrdir."""
 
853
        mutter('creating branch %r in %s', self, a_bzrdir.transport.base)
 
854
        branch_transport = a_bzrdir.get_branch_transport(self)
1302
855
        utf8_files = [('revision-history', ''),
1303
856
                      ('branch-name', ''),
1304
857
                      ]
1305
 
        return self._initialize_helper(a_bzrdir, utf8_files)
1306
 
 
1307
 
    def supports_tags(self):
1308
 
        return False
1309
 
 
1310
 
 
1311
 
class BzrBranchFormat6(BranchFormatMetadir):
1312
 
    """Branch format with last-revision and tags.
1313
 
 
1314
 
    Unlike previous formats, this has no explicit revision history. Instead,
1315
 
    this just stores the last-revision, and the left-hand history leading
1316
 
    up to there is the history.
1317
 
 
1318
 
    This format was introduced in bzr 0.15
1319
 
    and became the default in 0.91.
1320
 
    """
1321
 
 
1322
 
    def _branch_class(self):
1323
 
        return BzrBranch6
1324
 
 
1325
 
    def get_format_string(self):
1326
 
        """See BranchFormat.get_format_string()."""
1327
 
        return "Bazaar Branch Format 6 (bzr 0.15)\n"
1328
 
 
1329
 
    def get_format_description(self):
1330
 
        """See BranchFormat.get_format_description()."""
1331
 
        return "Branch format 6"
1332
 
 
1333
 
    def initialize(self, a_bzrdir):
1334
 
        """Create a branch of this format in a_bzrdir."""
1335
 
        utf8_files = [('last-revision', '0 null:\n'),
1336
 
                      ('branch.conf', ''),
1337
 
                      ('tags', ''),
1338
 
                      ]
1339
 
        return self._initialize_helper(a_bzrdir, utf8_files)
1340
 
 
1341
 
 
1342
 
class BzrBranchFormat7(BranchFormatMetadir):
1343
 
    """Branch format with last-revision, tags, and a stacked location pointer.
1344
 
 
1345
 
    The stacked location pointer is passed down to the repository and requires
1346
 
    a repository format with supports_external_lookups = True.
1347
 
 
1348
 
    This format was introduced in bzr 1.6.
1349
 
    """
1350
 
 
1351
 
    def _branch_class(self):
1352
 
        return BzrBranch7
1353
 
 
1354
 
    def get_format_string(self):
1355
 
        """See BranchFormat.get_format_string()."""
1356
 
        return "Bazaar Branch Format 7 (needs bzr 1.6)\n"
1357
 
 
1358
 
    def get_format_description(self):
1359
 
        """See BranchFormat.get_format_description()."""
1360
 
        return "Branch format 7"
1361
 
 
1362
 
    def initialize(self, a_bzrdir):
1363
 
        """Create a branch of this format in a_bzrdir."""
1364
 
        utf8_files = [('last-revision', '0 null:\n'),
1365
 
                      ('branch.conf', ''),
1366
 
                      ('tags', ''),
1367
 
                      ]
1368
 
        return self._initialize_helper(a_bzrdir, utf8_files)
 
858
        control_files = lockable_files.LockableFiles(branch_transport, 'lock',
 
859
                                                     lockdir.LockDir)
 
860
        control_files.create_lock()
 
861
        control_files.lock_write()
 
862
        control_files.put_utf8('format', self.get_format_string())
 
863
        try:
 
864
            for file, content in utf8_files:
 
865
                control_files.put_utf8(file, content)
 
866
        finally:
 
867
            control_files.unlock()
 
868
        return self.open(a_bzrdir, _found=True, )
1369
869
 
1370
870
    def __init__(self):
1371
 
        super(BzrBranchFormat7, self).__init__()
1372
 
        self._matchingbzrdir.repository_format = \
1373
 
            RepositoryFormatPackDevelopment1Subtree()
1374
 
 
1375
 
    def supports_stacking(self):
1376
 
        return True
 
871
        super(BzrBranchFormat5, self).__init__()
 
872
        self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
 
873
 
 
874
    def open(self, a_bzrdir, _found=False):
 
875
        """Return the branch object for a_bzrdir
 
876
 
 
877
        _found is a private parameter, do not use it. It is used to indicate
 
878
               if format probing has already be done.
 
879
        """
 
880
        if not _found:
 
881
            format = BranchFormat.find_format(a_bzrdir)
 
882
            assert format.__class__ == self.__class__
 
883
        transport = a_bzrdir.get_branch_transport(None)
 
884
        control_files = lockable_files.LockableFiles(transport, 'lock',
 
885
                                                     lockdir.LockDir)
 
886
        return BzrBranch5(_format=self,
 
887
                          _control_files=control_files,
 
888
                          a_bzrdir=a_bzrdir,
 
889
                          _repository=a_bzrdir.find_repository())
 
890
 
 
891
    def __str__(self):
 
892
        return "Bazaar-NG Metadir branch format 5"
1377
893
 
1378
894
 
1379
895
class BranchReferenceFormat(BranchFormat):
1394
910
    def get_format_description(self):
1395
911
        """See BranchFormat.get_format_description()."""
1396
912
        return "Checkout reference format 1"
1397
 
 
1398
 
    def get_reference(self, a_bzrdir):
1399
 
        """See BranchFormat.get_reference()."""
1400
 
        transport = a_bzrdir.get_branch_transport(None)
1401
 
        return transport.get('location').read()
1402
 
 
1403
 
    def set_reference(self, a_bzrdir, to_branch):
1404
 
        """See BranchFormat.set_reference()."""
1405
 
        transport = a_bzrdir.get_branch_transport(None)
1406
 
        location = transport.put_bytes('location', to_branch.base)
1407
 
 
 
913
        
1408
914
    def initialize(self, a_bzrdir, target_branch=None):
1409
915
        """Create a branch of this format in a_bzrdir."""
1410
916
        if target_branch is None:
1416
922
        branch_transport.put_bytes('location',
1417
923
            target_branch.bzrdir.root_transport.base)
1418
924
        branch_transport.put_bytes('format', self.get_format_string())
1419
 
        return self.open(
1420
 
            a_bzrdir, _found=True,
1421
 
            possible_transports=[target_branch.bzrdir.root_transport])
 
925
        return self.open(a_bzrdir, _found=True)
1422
926
 
1423
927
    def __init__(self):
1424
928
        super(BranchReferenceFormat, self).__init__()
1434
938
            # emit some sort of warning/error to the caller ?!
1435
939
        return clone
1436
940
 
1437
 
    def open(self, a_bzrdir, _found=False, location=None,
1438
 
             possible_transports=None):
 
941
    def open(self, a_bzrdir, _found=False):
1439
942
        """Return the branch that the branch reference in a_bzrdir points at.
1440
943
 
1441
944
        _found is a private parameter, do not use it. It is used to indicate
1443
946
        """
1444
947
        if not _found:
1445
948
            format = BranchFormat.find_format(a_bzrdir)
1446
 
            if format.__class__ != self.__class__:
1447
 
                raise AssertionError("wrong format %r found for %r" %
1448
 
                    (format, self))
1449
 
        if location is None:
1450
 
            location = self.get_reference(a_bzrdir)
1451
 
        real_bzrdir = bzrdir.BzrDir.open(
1452
 
            location, possible_transports=possible_transports)
 
949
            assert format.__class__ == self.__class__
 
950
        transport = a_bzrdir.get_branch_transport(None)
 
951
        real_bzrdir = bzrdir.BzrDir.open(transport.get('location').read())
1453
952
        result = real_bzrdir.open_branch()
1454
953
        # this changes the behaviour of result.clone to create a new reference
1455
954
        # rather than a copy of the content of the branch.
1465
964
 
1466
965
# formats which have no format string are not discoverable
1467
966
# and not independently creatable, so are not registered.
1468
 
__format5 = BzrBranchFormat5()
1469
 
__format6 = BzrBranchFormat6()
1470
 
__format7 = BzrBranchFormat7()
1471
 
BranchFormat.register_format(__format5)
 
967
__default_format = BzrBranchFormat5()
 
968
BranchFormat.register_format(__default_format)
1472
969
BranchFormat.register_format(BranchReferenceFormat())
1473
 
BranchFormat.register_format(__format6)
1474
 
BranchFormat.register_format(__format7)
1475
 
BranchFormat.set_default_format(__format6)
 
970
BranchFormat.set_default_format(__default_format)
1476
971
_legacy_formats = [BzrBranchFormat4(),
1477
972
                   ]
1478
973
 
1482
977
    Note that it's "local" in the context of the filesystem; it doesn't
1483
978
    really matter if it's on an nfs/smb/afs/coda/... share, as long as
1484
979
    it's writable, and can be accessed via the normal filesystem API.
1485
 
 
1486
 
    :ivar _transport: Transport for file operations on this branch's 
1487
 
        control files, typically pointing to the .bzr/branch directory.
1488
 
    :ivar repository: Repository for this branch.
1489
 
    :ivar base: The url of the base directory for this branch; the one 
1490
 
        containing the .bzr directory.
1491
980
    """
1492
981
    
1493
 
    def __init__(self, _format=None,
 
982
    def __init__(self, transport=DEPRECATED_PARAMETER, init=DEPRECATED_PARAMETER,
 
983
                 relax_version_check=DEPRECATED_PARAMETER, _format=None,
1494
984
                 _control_files=None, a_bzrdir=None, _repository=None):
1495
 
        """Create new branch object at a particular location."""
 
985
        """Create new branch object at a particular location.
 
986
 
 
987
        transport -- A Transport object, defining how to access files.
 
988
        
 
989
        init -- If True, create new control files in a previously
 
990
             unversioned directory.  If False, the branch must already
 
991
             be versioned.
 
992
 
 
993
        relax_version_check -- If true, the usual check for the branch
 
994
            version is not applied.  This is intended only for
 
995
            upgrade/recovery type use; it's not guaranteed that
 
996
            all operations will work on old format branches.
 
997
        """
1496
998
        if a_bzrdir is None:
1497
 
            raise ValueError('a_bzrdir must be supplied')
 
999
            self.bzrdir = bzrdir.BzrDir.open(transport.base)
1498
1000
        else:
1499
1001
            self.bzrdir = a_bzrdir
1500
 
        self._base = self.bzrdir.transport.clone('..').base
1501
 
        # XXX: We should be able to just do
1502
 
        #   self.base = self.bzrdir.root_transport.base
1503
 
        # but this does not quite work yet -- mbp 20080522
 
1002
        self._transport = self.bzrdir.transport.clone('..')
 
1003
        self._base = self._transport.base
1504
1004
        self._format = _format
1505
1005
        if _control_files is None:
1506
1006
            raise ValueError('BzrBranch _control_files is None')
1507
1007
        self.control_files = _control_files
1508
 
        self._transport = _control_files._transport
 
1008
        if deprecated_passed(init):
 
1009
            warn("BzrBranch.__init__(..., init=XXX): The init parameter is "
 
1010
                 "deprecated as of bzr 0.8. Please use Branch.create().",
 
1011
                 DeprecationWarning,
 
1012
                 stacklevel=2)
 
1013
            if init:
 
1014
                # this is slower than before deprecation, oh well never mind.
 
1015
                # -> its deprecated.
 
1016
                self._initialize(transport.base)
 
1017
        self._check_format(_format)
 
1018
        if deprecated_passed(relax_version_check):
 
1019
            warn("BzrBranch.__init__(..., relax_version_check=XXX_: The "
 
1020
                 "relax_version_check parameter is deprecated as of bzr 0.8. "
 
1021
                 "Please use BzrDir.open_downlevel, or a BzrBranchFormat's "
 
1022
                 "open() method.",
 
1023
                 DeprecationWarning,
 
1024
                 stacklevel=2)
 
1025
            if (not relax_version_check
 
1026
                and not self._format.is_supported()):
 
1027
                raise errors.UnsupportedFormatError(format=fmt)
 
1028
        if deprecated_passed(transport):
 
1029
            warn("BzrBranch.__init__(transport=XXX...): The transport "
 
1030
                 "parameter is deprecated as of bzr 0.8. "
 
1031
                 "Please use Branch.open, or bzrdir.open_branch().",
 
1032
                 DeprecationWarning,
 
1033
                 stacklevel=2)
1509
1034
        self.repository = _repository
1510
 
        Branch.__init__(self)
1511
1035
 
1512
1036
    def __str__(self):
1513
1037
        return '%s(%r)' % (self.__class__.__name__, self.base)
1515
1039
    __repr__ = __str__
1516
1040
 
1517
1041
    def _get_base(self):
1518
 
        """Returns the directory containing the control directory."""
1519
1042
        return self._base
1520
1043
 
1521
1044
    base = property(_get_base, doc="The URL for the root of this branch.")
1522
1045
 
1523
 
    @deprecated_method(deprecated_in((0, 16, 0)))
 
1046
    def _finish_transaction(self):
 
1047
        """Exit the current transaction."""
 
1048
        return self.control_files._finish_transaction()
 
1049
 
 
1050
    def get_transaction(self):
 
1051
        """Return the current active transaction.
 
1052
 
 
1053
        If no transaction is active, this returns a passthrough object
 
1054
        for which all data is immediately flushed and no caching happens.
 
1055
        """
 
1056
        # this is an explicit function so that we can do tricky stuff
 
1057
        # when the storage in rev_storage is elsewhere.
 
1058
        # we probably need to hook the two 'lock a location' and 
 
1059
        # 'have a transaction' together more delicately, so that
 
1060
        # we can have two locks (branch and storage) and one transaction
 
1061
        # ... and finishing the transaction unlocks both, but unlocking
 
1062
        # does not. - RBC 20051121
 
1063
        return self.control_files.get_transaction()
 
1064
 
 
1065
    def _set_transaction(self, transaction):
 
1066
        """Set a new active transaction."""
 
1067
        return self.control_files._set_transaction(transaction)
 
1068
 
1524
1069
    def abspath(self, name):
1525
1070
        """See Branch.abspath."""
1526
 
        return self._transport.abspath(name)
 
1071
        return self.control_files._transport.abspath(name)
 
1072
 
 
1073
    def _check_format(self, format):
 
1074
        """Identify the branch format if needed.
 
1075
 
 
1076
        The format is stored as a reference to the format object in
 
1077
        self._format for code that needs to check it later.
 
1078
 
 
1079
        The format parameter is either None or the branch format class
 
1080
        used to open this branch.
 
1081
 
 
1082
        FIXME: DELETE THIS METHOD when pre 0.8 support is removed.
 
1083
        """
 
1084
        if format is None:
 
1085
            format = BranchFormat.find_format(self.bzrdir)
 
1086
        self._format = format
 
1087
        mutter("got branch format %s", self._format)
 
1088
 
 
1089
    @needs_read_lock
 
1090
    def get_root_id(self):
 
1091
        """See Branch.get_root_id."""
 
1092
        tree = self.repository.revision_tree(self.last_revision())
 
1093
        return tree.inventory.root.file_id
1527
1094
 
1528
1095
    def is_locked(self):
1529
1096
        return self.control_files.is_locked()
1530
1097
 
1531
 
    def lock_write(self, token=None):
1532
 
        repo_token = self.repository.lock_write()
 
1098
    def lock_write(self):
 
1099
        self.repository.lock_write()
1533
1100
        try:
1534
 
            token = self.control_files.lock_write(token=token)
 
1101
            self.control_files.lock_write()
1535
1102
        except:
1536
1103
            self.repository.unlock()
1537
1104
            raise
1538
 
        return token
1539
1105
 
1540
1106
    def lock_read(self):
1541
1107
        self.repository.lock_read()
1551
1117
            self.control_files.unlock()
1552
1118
        finally:
1553
1119
            self.repository.unlock()
1554
 
        if not self.control_files.is_locked():
1555
 
            # we just released the lock
1556
 
            self._clear_cached_state()
1557
1120
        
1558
1121
    def peek_lock_mode(self):
1559
1122
        if self.control_files._lock_count == 0:
1569
1132
        """See Branch.print_file."""
1570
1133
        return self.repository.print_file(file, revision_id)
1571
1134
 
1572
 
    def _write_revision_history(self, history):
1573
 
        """Factored out of set_revision_history.
1574
 
 
1575
 
        This performs the actual writing to disk.
1576
 
        It is intended to be called by BzrBranch5.set_revision_history."""
1577
 
        self._transport.put_bytes(
1578
 
            'revision-history', '\n'.join(history),
1579
 
            mode=self.bzrdir._get_file_mode())
 
1135
    @needs_write_lock
 
1136
    def append_revision(self, *revision_ids):
 
1137
        """See Branch.append_revision."""
 
1138
        for revision_id in revision_ids:
 
1139
            _mod_revision.check_not_reserved_id(revision_id)
 
1140
            mutter("add {%s} to revision-history" % revision_id)
 
1141
        rev_history = self.revision_history()
 
1142
        rev_history.extend(revision_ids)
 
1143
        self.set_revision_history(rev_history)
1580
1144
 
1581
1145
    @needs_write_lock
1582
1146
    def set_revision_history(self, rev_history):
1583
1147
        """See Branch.set_revision_history."""
1584
 
        if 'evil' in debug.debug_flags:
1585
 
            mutter_callsite(3, "set_revision_history scales with history.")
1586
 
        check_not_reserved_id = _mod_revision.check_not_reserved_id
1587
 
        for rev_id in rev_history:
1588
 
            check_not_reserved_id(rev_id)
1589
 
        if Branch.hooks['post_change_branch_tip']:
1590
 
            # Don't calculate the last_revision_info() if there are no hooks
1591
 
            # that will use it.
1592
 
            old_revno, old_revid = self.last_revision_info()
1593
 
        if len(rev_history) == 0:
1594
 
            revid = _mod_revision.NULL_REVISION
 
1148
        self.control_files.put_utf8(
 
1149
            'revision-history', '\n'.join(rev_history))
 
1150
        transaction = self.get_transaction()
 
1151
        history = transaction.map.find_revision_history()
 
1152
        if history is not None:
 
1153
            # update the revision history in the identity map.
 
1154
            history[:] = list(rev_history)
 
1155
            # this call is disabled because revision_history is 
 
1156
            # not really an object yet, and the transaction is for objects.
 
1157
            # transaction.register_dirty(history)
1595
1158
        else:
1596
 
            revid = rev_history[-1]
1597
 
        self._run_pre_change_branch_tip_hooks(len(rev_history), revid)
1598
 
        self._write_revision_history(rev_history)
1599
 
        self._clear_cached_state()
1600
 
        self._cache_revision_history(rev_history)
 
1159
            transaction.map.add_revision_history(rev_history)
 
1160
            # this call is disabled because revision_history is 
 
1161
            # not really an object yet, and the transaction is for objects.
 
1162
            # transaction.register_clean(history)
1601
1163
        for hook in Branch.hooks['set_rh']:
1602
1164
            hook(self, rev_history)
1603
 
        if Branch.hooks['post_change_branch_tip']:
1604
 
            self._run_post_change_branch_tip_hooks(old_revno, old_revid)
1605
 
 
1606
 
    def _run_pre_change_branch_tip_hooks(self, new_revno, new_revid):
1607
 
        """Run the pre_change_branch_tip hooks."""
1608
 
        hooks = Branch.hooks['pre_change_branch_tip']
1609
 
        if not hooks:
1610
 
            return
1611
 
        old_revno, old_revid = self.last_revision_info()
1612
 
        params = ChangeBranchTipParams(
1613
 
            self, old_revno, new_revno, old_revid, new_revid)
1614
 
        for hook in hooks:
1615
 
            try:
1616
 
                hook(params)
1617
 
            except errors.TipChangeRejected:
1618
 
                raise
1619
 
            except Exception:
1620
 
                exc_info = sys.exc_info()
1621
 
                hook_name = Branch.hooks.get_hook_name(hook)
1622
 
                raise errors.HookFailed(
1623
 
                    'pre_change_branch_tip', hook_name, exc_info)
1624
 
 
1625
 
    def _run_post_change_branch_tip_hooks(self, old_revno, old_revid):
1626
 
        """Run the post_change_branch_tip hooks."""
1627
 
        hooks = Branch.hooks['post_change_branch_tip']
1628
 
        if not hooks:
1629
 
            return
1630
 
        new_revno, new_revid = self.last_revision_info()
1631
 
        params = ChangeBranchTipParams(
1632
 
            self, old_revno, new_revno, old_revid, new_revid)
1633
 
        for hook in hooks:
1634
 
            hook(params)
1635
 
 
1636
 
    @needs_write_lock
1637
 
    def set_last_revision_info(self, revno, revision_id):
1638
 
        """Set the last revision of this branch.
1639
 
 
1640
 
        The caller is responsible for checking that the revno is correct
1641
 
        for this revision id.
1642
 
 
1643
 
        It may be possible to set the branch last revision to an id not
1644
 
        present in the repository.  However, branches can also be 
1645
 
        configured to check constraints on history, in which case this may not
1646
 
        be permitted.
1647
 
        """
1648
 
        revision_id = _mod_revision.ensure_null(revision_id)
1649
 
        # this old format stores the full history, but this api doesn't
1650
 
        # provide it, so we must generate, and might as well check it's
1651
 
        # correct
1652
 
        history = self._lefthand_history(revision_id)
1653
 
        if len(history) != revno:
1654
 
            raise AssertionError('%d != %d' % (len(history), revno))
1655
 
        self.set_revision_history(history)
1656
 
 
1657
 
    def _gen_revision_history(self):
1658
 
        history = self._transport.get_bytes('revision-history').split('\n')
1659
 
        if history[-1:] == ['']:
1660
 
            # There shouldn't be a trailing newline, but just in case.
1661
 
            history.pop()
1662
 
        return history
1663
 
 
1664
 
    def _lefthand_history(self, revision_id, last_rev=None,
1665
 
                          other_branch=None):
1666
 
        if 'evil' in debug.debug_flags:
1667
 
            mutter_callsite(4, "_lefthand_history scales with history.")
1668
 
        # stop_revision must be a descendant of last_revision
1669
 
        graph = self.repository.get_graph()
1670
 
        if last_rev is not None:
1671
 
            if not graph.is_ancestor(last_rev, revision_id):
1672
 
                # our previous tip is not merged into stop_revision
1673
 
                raise errors.DivergedBranches(self, other_branch)
1674
 
        # make a new revision history from the graph
1675
 
        parents_map = graph.get_parent_map([revision_id])
1676
 
        if revision_id not in parents_map:
1677
 
            raise errors.NoSuchRevision(self, revision_id)
1678
 
        current_rev_id = revision_id
1679
 
        new_history = []
1680
 
        check_not_reserved_id = _mod_revision.check_not_reserved_id
1681
 
        # Do not include ghosts or graph origin in revision_history
1682
 
        while (current_rev_id in parents_map and
1683
 
               len(parents_map[current_rev_id]) > 0):
1684
 
            check_not_reserved_id(current_rev_id)
1685
 
            new_history.append(current_rev_id)
1686
 
            current_rev_id = parents_map[current_rev_id][0]
1687
 
            parents_map = graph.get_parent_map([current_rev_id])
1688
 
        new_history.reverse()
1689
 
        return new_history
1690
 
 
1691
 
    @needs_write_lock
1692
 
    def generate_revision_history(self, revision_id, last_rev=None,
 
1165
 
 
1166
    @needs_read_lock
 
1167
    def revision_history(self):
 
1168
        """See Branch.revision_history."""
 
1169
        transaction = self.get_transaction()
 
1170
        history = transaction.map.find_revision_history()
 
1171
        if history is not None:
 
1172
            # mutter("cache hit for revision-history in %s", self)
 
1173
            return list(history)
 
1174
        decode_utf8 = cache_utf8.decode
 
1175
        history = [decode_utf8(l.rstrip('\r\n')) for l in
 
1176
                self.control_files.get('revision-history').readlines()]
 
1177
        transaction.map.add_revision_history(history)
 
1178
        # this call is disabled because revision_history is 
 
1179
        # not really an object yet, and the transaction is for objects.
 
1180
        # transaction.register_clean(history, precious=True)
 
1181
        return list(history)
 
1182
 
 
1183
    @needs_write_lock
 
1184
    def generate_revision_history(self, revision_id, last_rev=None, 
1693
1185
        other_branch=None):
1694
1186
        """Create a new revision history that will finish with revision_id.
1695
 
 
 
1187
        
1696
1188
        :param revision_id: the new tip to use.
1697
1189
        :param last_rev: The previous last_revision. If not None, then this
1698
1190
            must be a ancestory of revision_id, or DivergedBranches is raised.
1699
1191
        :param other_branch: The other branch that DivergedBranches should
1700
1192
            raise with respect to.
1701
1193
        """
1702
 
        self.set_revision_history(self._lefthand_history(revision_id,
1703
 
            last_rev, other_branch))
 
1194
        # stop_revision must be a descendant of last_revision
 
1195
        stop_graph = self.repository.get_revision_graph(revision_id)
 
1196
        if last_rev is not None and last_rev not in stop_graph:
 
1197
            # our previous tip is not merged into stop_revision
 
1198
            raise errors.DivergedBranches(self, other_branch)
 
1199
        # make a new revision history from the graph
 
1200
        current_rev_id = revision_id
 
1201
        new_history = []
 
1202
        while current_rev_id not in (None, _mod_revision.NULL_REVISION):
 
1203
            new_history.append(current_rev_id)
 
1204
            current_rev_id_parents = stop_graph[current_rev_id]
 
1205
            try:
 
1206
                current_rev_id = current_rev_id_parents[0]
 
1207
            except IndexError:
 
1208
                current_rev_id = None
 
1209
        new_history.reverse()
 
1210
        self.set_revision_history(new_history)
 
1211
 
 
1212
    @needs_write_lock
 
1213
    def update_revisions(self, other, stop_revision=None):
 
1214
        """See Branch.update_revisions."""
 
1215
        other.lock_read()
 
1216
        try:
 
1217
            if stop_revision is None:
 
1218
                stop_revision = other.last_revision()
 
1219
                if stop_revision is None:
 
1220
                    # if there are no commits, we're done.
 
1221
                    return
 
1222
            # whats the current last revision, before we fetch [and change it
 
1223
            # possibly]
 
1224
            last_rev = self.last_revision()
 
1225
            # we fetch here regardless of whether we need to so that we pickup
 
1226
            # filled in ghosts.
 
1227
            self.fetch(other, stop_revision)
 
1228
            my_ancestry = self.repository.get_ancestry(last_rev)
 
1229
            if stop_revision in my_ancestry:
 
1230
                # last_revision is a descendant of stop_revision
 
1231
                return
 
1232
            self.generate_revision_history(stop_revision, last_rev=last_rev,
 
1233
                other_branch=other)
 
1234
        finally:
 
1235
            other.unlock()
1704
1236
 
1705
1237
    def basis_tree(self):
1706
1238
        """See Branch.basis_tree."""
1707
1239
        return self.repository.revision_tree(self.last_revision())
1708
1240
 
 
1241
    @deprecated_method(zero_eight)
 
1242
    def working_tree(self):
 
1243
        """Create a Working tree object for this branch."""
 
1244
 
 
1245
        from bzrlib.transport.local import LocalTransport
 
1246
        if (self.base.find('://') != -1 or 
 
1247
            not isinstance(self._transport, LocalTransport)):
 
1248
            raise NoWorkingTree(self.base)
 
1249
        return self.bzrdir.open_workingtree()
 
1250
 
1709
1251
    @needs_write_lock
1710
 
    def pull(self, source, overwrite=False, stop_revision=None,
1711
 
             _hook_master=None, run_hooks=True, possible_transports=None,
1712
 
             _override_hook_target=None):
1713
 
        """See Branch.pull.
1714
 
 
1715
 
        :param _hook_master: Private parameter - set the branch to 
1716
 
            be supplied as the master to pull hooks.
1717
 
        :param run_hooks: Private parameter - if false, this branch
1718
 
            is being called because it's the master of the primary branch,
1719
 
            so it should not run its hooks.
1720
 
        :param _override_hook_target: Private parameter - set the branch to be
1721
 
            supplied as the target_branch to pull hooks.
1722
 
        """
1723
 
        result = PullResult()
1724
 
        result.source_branch = source
1725
 
        if _override_hook_target is None:
1726
 
            result.target_branch = self
1727
 
        else:
1728
 
            result.target_branch = _override_hook_target
 
1252
    def pull(self, source, overwrite=False, stop_revision=None):
 
1253
        """See Branch.pull."""
1729
1254
        source.lock_read()
1730
1255
        try:
1731
 
            # We assume that during 'pull' the local repository is closer than
1732
 
            # the remote one.
1733
 
            graph = self.repository.get_graph(source.repository)
1734
 
            result.old_revno, result.old_revid = self.last_revision_info()
1735
 
            self.update_revisions(source, stop_revision, overwrite=overwrite,
1736
 
                                  graph=graph)
1737
 
            result.tag_conflicts = source.tags.merge_to(self.tags, overwrite)
1738
 
            result.new_revno, result.new_revid = self.last_revision_info()
1739
 
            if _hook_master:
1740
 
                result.master_branch = _hook_master
1741
 
                result.local_branch = result.target_branch
1742
 
            else:
1743
 
                result.master_branch = result.target_branch
1744
 
                result.local_branch = None
1745
 
            if run_hooks:
1746
 
                for hook in Branch.hooks['post_pull']:
1747
 
                    hook(result)
 
1256
            old_count = self.last_revision_info()[0]
 
1257
            try:
 
1258
                self.update_revisions(source, stop_revision)
 
1259
            except DivergedBranches:
 
1260
                if not overwrite:
 
1261
                    raise
 
1262
            if overwrite:
 
1263
                self.set_revision_history(source.revision_history())
 
1264
            new_count = self.last_revision_info()[0]
 
1265
            return new_count - old_count
1748
1266
        finally:
1749
1267
            source.unlock()
1750
 
        return result
1751
 
 
1752
 
    def _get_parent_location(self):
1753
 
        _locs = ['parent', 'pull', 'x-pull']
1754
 
        for l in _locs:
1755
 
            try:
1756
 
                return self._transport.get_bytes(l).strip('\n')
1757
 
            except errors.NoSuchFile:
1758
 
                pass
1759
 
        return None
1760
1268
 
1761
1269
    @needs_read_lock
1762
 
    def push(self, target, overwrite=False, stop_revision=None,
1763
 
             _override_hook_source_branch=None):
1764
 
        """See Branch.push.
1765
 
 
1766
 
        This is the basic concrete implementation of push()
1767
 
 
1768
 
        :param _override_hook_source_branch: If specified, run
1769
 
        the hooks passing this Branch as the source, rather than self.  
1770
 
        This is for use of RemoteBranch, where push is delegated to the
1771
 
        underlying vfs-based Branch. 
1772
 
        """
1773
 
        # TODO: Public option to disable running hooks - should be trivial but
1774
 
        # needs tests.
 
1270
    def push(self, target, overwrite=False, stop_revision=None):
 
1271
        """See Branch.push."""
1775
1272
        target.lock_write()
1776
1273
        try:
1777
 
            result = self._push_with_bound_branches(target, overwrite,
1778
 
                    stop_revision,
1779
 
                    _override_hook_source_branch=_override_hook_source_branch)
1780
 
            return result
 
1274
            old_count = len(target.revision_history())
 
1275
            try:
 
1276
                target.update_revisions(self, stop_revision)
 
1277
            except DivergedBranches:
 
1278
                if not overwrite:
 
1279
                    raise
 
1280
            if overwrite:
 
1281
                target.set_revision_history(self.revision_history())
 
1282
            new_count = len(target.revision_history())
 
1283
            return new_count - old_count
1781
1284
        finally:
1782
1285
            target.unlock()
1783
1286
 
1784
 
    def _push_with_bound_branches(self, target, overwrite,
1785
 
            stop_revision,
1786
 
            _override_hook_source_branch=None):
1787
 
        """Push from self into target, and into target's master if any.
1788
 
        
1789
 
        This is on the base BzrBranch class even though it doesn't support 
1790
 
        bound branches because the *target* might be bound.
1791
 
        """
1792
 
        def _run_hooks():
1793
 
            if _override_hook_source_branch:
1794
 
                result.source_branch = _override_hook_source_branch
1795
 
            for hook in Branch.hooks['post_push']:
1796
 
                hook(result)
1797
 
 
1798
 
        bound_location = target.get_bound_location()
1799
 
        if bound_location and target.base != bound_location:
1800
 
            # there is a master branch.
1801
 
            #
1802
 
            # XXX: Why the second check?  Is it even supported for a branch to
1803
 
            # be bound to itself? -- mbp 20070507
1804
 
            master_branch = target.get_master_branch()
1805
 
            master_branch.lock_write()
1806
 
            try:
1807
 
                # push into the master from this branch.
1808
 
                self._basic_push(master_branch, overwrite, stop_revision)
1809
 
                # and push into the target branch from this. Note that we push from
1810
 
                # this branch again, because its considered the highest bandwidth
1811
 
                # repository.
1812
 
                result = self._basic_push(target, overwrite, stop_revision)
1813
 
                result.master_branch = master_branch
1814
 
                result.local_branch = target
1815
 
                _run_hooks()
1816
 
                return result
1817
 
            finally:
1818
 
                master_branch.unlock()
1819
 
        else:
1820
 
            # no master branch
1821
 
            result = self._basic_push(target, overwrite, stop_revision)
1822
 
            # TODO: Why set master_branch and local_branch if there's no
1823
 
            # binding?  Maybe cleaner to just leave them unset? -- mbp
1824
 
            # 20070504
1825
 
            result.master_branch = target
1826
 
            result.local_branch = None
1827
 
            _run_hooks()
1828
 
            return result
1829
 
 
1830
 
    def _basic_push(self, target, overwrite, stop_revision):
1831
 
        """Basic implementation of push without bound branches or hooks.
1832
 
 
1833
 
        Must be called with self read locked and target write locked.
1834
 
        """
1835
 
        result = PushResult()
1836
 
        result.source_branch = self
1837
 
        result.target_branch = target
1838
 
        result.old_revno, result.old_revid = target.last_revision_info()
1839
 
 
1840
 
        # We assume that during 'push' this repository is closer than
1841
 
        # the target.
1842
 
        graph = self.repository.get_graph(target.repository)
1843
 
        target.update_revisions(self, stop_revision, overwrite=overwrite,
1844
 
                                graph=graph)
1845
 
        result.tag_conflicts = self.tags.merge_to(target.tags, overwrite)
1846
 
        result.new_revno, result.new_revid = target.last_revision_info()
1847
 
        return result
1848
 
 
1849
1287
    def get_parent(self):
1850
1288
        """See Branch.get_parent."""
1851
 
        parent = self._get_parent_location()
1852
 
        if parent is None:
1853
 
            return parent
1854
 
        # This is an old-format absolute path to a local branch
1855
 
        # turn it into a url
1856
 
        if parent.startswith('/'):
1857
 
            parent = urlutils.local_path_to_url(parent.decode('utf8'))
1858
 
        try:
1859
 
            return urlutils.join(self.base[:-1], parent)
1860
 
        except errors.InvalidURLJoin, e:
1861
 
            raise errors.InaccessibleParent(parent, self.base)
1862
 
 
1863
 
    def get_stacked_on_url(self):
1864
 
        raise errors.UnstackableBranchFormat(self._format, self.base)
 
1289
 
 
1290
        _locs = ['parent', 'pull', 'x-pull']
 
1291
        assert self.base[-1] == '/'
 
1292
        for l in _locs:
 
1293
            try:
 
1294
                parent = self.control_files.get(l).read().strip('\n')
 
1295
            except NoSuchFile:
 
1296
                continue
 
1297
            # This is an old-format absolute path to a local branch
 
1298
            # turn it into a url
 
1299
            if parent.startswith('/'):
 
1300
                parent = urlutils.local_path_to_url(parent.decode('utf8'))
 
1301
            try:
 
1302
                return urlutils.join(self.base[:-1], parent)
 
1303
            except errors.InvalidURLJoin, e:
 
1304
                raise errors.InaccessibleParent(parent, self.base)
 
1305
        return None
 
1306
 
 
1307
    def get_push_location(self):
 
1308
        """See Branch.get_push_location."""
 
1309
        push_loc = self.get_config().get_user_option('push_location')
 
1310
        return push_loc
1865
1311
 
1866
1312
    def set_push_location(self, location):
1867
1313
        """See Branch.set_push_location."""
1875
1321
        # TODO: Maybe delete old location files?
1876
1322
        # URLs should never be unicode, even on the local fs,
1877
1323
        # FIXUP this and get_parent in a future branch format bump:
1878
 
        # read and rewrite the file. RBC 20060125
1879
 
        if url is not None:
 
1324
        # read and rewrite the file, and have the new format code read
 
1325
        # using .get not .get_utf8. RBC 20060125
 
1326
        if url is None:
 
1327
            self.control_files._transport.delete('parent')
 
1328
        else:
1880
1329
            if isinstance(url, unicode):
1881
 
                try:
 
1330
                try: 
1882
1331
                    url = url.encode('ascii')
1883
1332
                except UnicodeEncodeError:
1884
 
                    raise errors.InvalidURL(url,
 
1333
                    raise bzrlib.errors.InvalidURL(url,
1885
1334
                        "Urls must be 7-bit ascii, "
1886
1335
                        "use bzrlib.urlutils.escape")
 
1336
                    
1887
1337
            url = urlutils.relative_url(self.base, url)
1888
 
        self._set_parent_location(url)
1889
 
 
1890
 
    def _set_parent_location(self, url):
1891
 
        if url is None:
1892
 
            self._transport.delete('parent')
1893
 
        else:
1894
 
            self._transport.put_bytes('parent', url + '\n',
1895
 
                mode=self.bzrdir._get_file_mode())
1896
 
 
1897
 
    def set_stacked_on_url(self, url):
1898
 
        raise errors.UnstackableBranchFormat(self._format, self.base)
 
1338
            self.control_files.put('parent', StringIO(url + '\n'))
 
1339
 
 
1340
    @deprecated_function(zero_nine)
 
1341
    def tree_config(self):
 
1342
        """DEPRECATED; call get_config instead.  
 
1343
        TreeConfig has become part of BranchConfig."""
 
1344
        return TreeConfig(self)
1899
1345
 
1900
1346
 
1901
1347
class BzrBranch5(BzrBranch):
1902
 
    """A format 5 branch. This supports new features over plain branches.
 
1348
    """A format 5 branch. This supports new features over plan branches.
1903
1349
 
1904
1350
    It has support for a master_branch which is the data for bound branches.
1905
1351
    """
1906
1352
 
 
1353
    def __init__(self,
 
1354
                 _format,
 
1355
                 _control_files,
 
1356
                 a_bzrdir,
 
1357
                 _repository):
 
1358
        super(BzrBranch5, self).__init__(_format=_format,
 
1359
                                         _control_files=_control_files,
 
1360
                                         a_bzrdir=a_bzrdir,
 
1361
                                         _repository=_repository)
 
1362
        
1907
1363
    @needs_write_lock
1908
 
    def pull(self, source, overwrite=False, stop_revision=None,
1909
 
             run_hooks=True, possible_transports=None,
1910
 
             _override_hook_target=None):
1911
 
        """Pull from source into self, updating my master if any.
1912
 
        
1913
 
        :param run_hooks: Private parameter - if false, this branch
1914
 
            is being called because it's the master of the primary branch,
1915
 
            so it should not run its hooks.
1916
 
        """
 
1364
    def pull(self, source, overwrite=False, stop_revision=None):
 
1365
        """Extends branch.pull to be bound branch aware."""
1917
1366
        bound_location = self.get_bound_location()
1918
 
        master_branch = None
1919
 
        if bound_location and source.base != bound_location:
 
1367
        if source.base != bound_location:
1920
1368
            # not pulling from master, so we need to update master.
1921
 
            master_branch = self.get_master_branch(possible_transports)
1922
 
            master_branch.lock_write()
1923
 
        try:
1924
 
            if master_branch:
1925
 
                # pull from source into master.
1926
 
                master_branch.pull(source, overwrite, stop_revision,
1927
 
                    run_hooks=False)
1928
 
            return super(BzrBranch5, self).pull(source, overwrite,
1929
 
                stop_revision, _hook_master=master_branch,
1930
 
                run_hooks=run_hooks,
1931
 
                _override_hook_target=_override_hook_target)
1932
 
        finally:
1933
 
            if master_branch:
1934
 
                master_branch.unlock()
 
1369
            master_branch = self.get_master_branch()
 
1370
            if master_branch:
 
1371
                master_branch.pull(source)
 
1372
                source = master_branch
 
1373
        return super(BzrBranch5, self).pull(source, overwrite, stop_revision)
 
1374
 
 
1375
    @needs_write_lock
 
1376
    def push(self, target, overwrite=False, stop_revision=None):
 
1377
        """Updates branch.push to be bound branch aware."""
 
1378
        bound_location = target.get_bound_location()
 
1379
        if target.base != bound_location:
 
1380
            # not pushing to master, so we need to update master.
 
1381
            master_branch = target.get_master_branch()
 
1382
            if master_branch:
 
1383
                # push into the master from this branch.
 
1384
                super(BzrBranch5, self).push(master_branch, overwrite,
 
1385
                    stop_revision)
 
1386
        # and push into the target branch from this. Note that we push from
 
1387
        # this branch again, because its considered the highest bandwidth
 
1388
        # repository.
 
1389
        return super(BzrBranch5, self).push(target, overwrite, stop_revision)
1935
1390
 
1936
1391
    def get_bound_location(self):
1937
1392
        try:
1938
 
            return self._transport.get_bytes('bound')[:-1]
 
1393
            return self.control_files.get_utf8('bound').read()[:-1]
1939
1394
        except errors.NoSuchFile:
1940
1395
            return None
1941
1396
 
1942
1397
    @needs_read_lock
1943
 
    def get_master_branch(self, possible_transports=None):
 
1398
    def get_master_branch(self):
1944
1399
        """Return the branch we are bound to.
1945
1400
        
1946
1401
        :return: Either a Branch, or None
1954
1409
        if not bound_loc:
1955
1410
            return None
1956
1411
        try:
1957
 
            return Branch.open(bound_loc,
1958
 
                               possible_transports=possible_transports)
 
1412
            return Branch.open(bound_loc)
1959
1413
        except (errors.NotBranchError, errors.ConnectionError), e:
1960
1414
            raise errors.BoundBranchConnectionFailure(
1961
1415
                    self, bound_loc, e)
1967
1421
        :param location: URL to the target branch
1968
1422
        """
1969
1423
        if location:
1970
 
            self._transport.put_bytes('bound', location+'\n',
1971
 
                mode=self.bzrdir._get_file_mode())
 
1424
            self.control_files.put_utf8('bound', location+'\n')
1972
1425
        else:
1973
1426
            try:
1974
 
                self._transport.delete('bound')
1975
 
            except errors.NoSuchFile:
 
1427
                self.control_files._transport.delete('bound')
 
1428
            except NoSuchFile:
1976
1429
                return False
1977
1430
            return True
1978
1431
 
2000
1453
        # last_rev is not in the other_last_rev history, AND
2001
1454
        # other_last_rev is not in our history, and do it without pulling
2002
1455
        # history around
 
1456
        last_rev = self.last_revision()
 
1457
        if last_rev is not None:
 
1458
            other.lock_read()
 
1459
            try:
 
1460
                other_last_rev = other.last_revision()
 
1461
                if other_last_rev is not None:
 
1462
                    # neither branch is new, we have to do some work to
 
1463
                    # ascertain diversion.
 
1464
                    remote_graph = other.repository.get_revision_graph(
 
1465
                        other_last_rev)
 
1466
                    local_graph = self.repository.get_revision_graph(last_rev)
 
1467
                    if (last_rev not in remote_graph and
 
1468
                        other_last_rev not in local_graph):
 
1469
                        raise errors.DivergedBranches(self, other)
 
1470
            finally:
 
1471
                other.unlock()
2003
1472
        self.set_bound_location(other.base)
2004
1473
 
2005
1474
    @needs_write_lock
2008
1477
        return self.set_bound_location(None)
2009
1478
 
2010
1479
    @needs_write_lock
2011
 
    def update(self, possible_transports=None):
 
1480
    def update(self):
2012
1481
        """Synchronise this branch with the master branch if any. 
2013
1482
 
2014
1483
        :return: None or the last_revision that was pivoted out during the
2015
1484
                 update.
2016
1485
        """
2017
 
        master = self.get_master_branch(possible_transports)
 
1486
        master = self.get_master_branch()
2018
1487
        if master is not None:
2019
 
            old_tip = _mod_revision.ensure_null(self.last_revision())
 
1488
            old_tip = self.last_revision()
2020
1489
            self.pull(master, overwrite=True)
2021
 
            if self.repository.get_graph().is_ancestor(old_tip,
2022
 
                _mod_revision.ensure_null(self.last_revision())):
 
1490
            if old_tip in self.repository.get_ancestry(self.last_revision()):
2023
1491
                return None
2024
1492
            return old_tip
2025
1493
        return None
2026
1494
 
2027
1495
 
2028
 
class BzrBranch7(BzrBranch5):
2029
 
    """A branch with support for a fallback repository."""
2030
 
 
2031
 
    def _get_fallback_repository(self, url):
2032
 
        """Get the repository we fallback to at url."""
2033
 
        url = urlutils.join(self.base, url)
2034
 
        return bzrdir.BzrDir.open(url).open_branch().repository
2035
 
 
2036
 
    def _activate_fallback_location(self, url):
2037
 
        """Activate the branch/repository from url as a fallback repository."""
2038
 
        self.repository.add_fallback_repository(
2039
 
            self._get_fallback_repository(url))
2040
 
 
2041
 
    def _open_hook(self):
2042
 
        try:
2043
 
            url = self.get_stacked_on_url()
2044
 
        except (errors.UnstackableRepositoryFormat, errors.NotStacked,
2045
 
            errors.UnstackableBranchFormat):
2046
 
            pass
2047
 
        else:
2048
 
            self._activate_fallback_location(url)
2049
 
 
2050
 
    def _check_stackable_repo(self):
2051
 
        if not self.repository._format.supports_external_lookups:
2052
 
            raise errors.UnstackableRepositoryFormat(self.repository._format,
2053
 
                self.repository.base)
2054
 
 
2055
 
    def __init__(self, *args, **kwargs):
2056
 
        super(BzrBranch7, self).__init__(*args, **kwargs)
2057
 
        self._last_revision_info_cache = None
2058
 
        self._partial_revision_history_cache = []
2059
 
 
2060
 
    def _clear_cached_state(self):
2061
 
        super(BzrBranch7, self)._clear_cached_state()
2062
 
        self._last_revision_info_cache = None
2063
 
        self._partial_revision_history_cache = []
2064
 
 
2065
 
    def _last_revision_info(self):
2066
 
        revision_string = self._transport.get_bytes('last-revision')
2067
 
        revno, revision_id = revision_string.rstrip('\n').split(' ', 1)
2068
 
        revision_id = cache_utf8.get_cached_utf8(revision_id)
2069
 
        revno = int(revno)
2070
 
        return revno, revision_id
2071
 
 
2072
 
    def _write_last_revision_info(self, revno, revision_id):
2073
 
        """Simply write out the revision id, with no checks.
2074
 
 
2075
 
        Use set_last_revision_info to perform this safely.
2076
 
 
2077
 
        Does not update the revision_history cache.
2078
 
        Intended to be called by set_last_revision_info and
2079
 
        _write_revision_history.
2080
 
        """
2081
 
        revision_id = _mod_revision.ensure_null(revision_id)
2082
 
        out_string = '%d %s\n' % (revno, revision_id)
2083
 
        self._transport.put_bytes('last-revision', out_string,
2084
 
            mode=self.bzrdir._get_file_mode())
2085
 
 
2086
 
    @needs_write_lock
2087
 
    def set_last_revision_info(self, revno, revision_id):
2088
 
        revision_id = _mod_revision.ensure_null(revision_id)
2089
 
        old_revno, old_revid = self.last_revision_info()
2090
 
        if self._get_append_revisions_only():
2091
 
            self._check_history_violation(revision_id)
2092
 
        self._run_pre_change_branch_tip_hooks(revno, revision_id)
2093
 
        self._write_last_revision_info(revno, revision_id)
2094
 
        self._clear_cached_state()
2095
 
        self._last_revision_info_cache = revno, revision_id
2096
 
        self._run_post_change_branch_tip_hooks(old_revno, old_revid)
2097
 
 
2098
 
    def _check_history_violation(self, revision_id):
2099
 
        last_revision = _mod_revision.ensure_null(self.last_revision())
2100
 
        if _mod_revision.is_null(last_revision):
2101
 
            return
2102
 
        if last_revision not in self._lefthand_history(revision_id):
2103
 
            raise errors.AppendRevisionsOnlyViolation(self.base)
2104
 
 
2105
 
    def _gen_revision_history(self):
2106
 
        """Generate the revision history from last revision
2107
 
        """
2108
 
        last_revno, last_revision = self.last_revision_info()
2109
 
        self._extend_partial_history(stop_index=last_revno-1)
2110
 
        return list(reversed(self._partial_revision_history_cache))
2111
 
 
2112
 
    def _extend_partial_history(self, stop_index=None, stop_revision=None):
2113
 
        """Extend the partial history to include a given index
2114
 
 
2115
 
        If a stop_index is supplied, stop when that index has been reached.
2116
 
        If a stop_revision is supplied, stop when that revision is
2117
 
        encountered.  Otherwise, stop when the beginning of history is
2118
 
        reached.
2119
 
 
2120
 
        :param stop_index: The index which should be present.  When it is
2121
 
            present, history extension will stop.
2122
 
        :param revision_id: The revision id which should be present.  When
2123
 
            it is encountered, history extension will stop.
2124
 
        """
2125
 
        repo = self.repository
2126
 
        if len(self._partial_revision_history_cache) == 0:
2127
 
            iterator = repo.iter_reverse_revision_history(self.last_revision())
2128
 
        else:
2129
 
            start_revision = self._partial_revision_history_cache[-1]
2130
 
            iterator = repo.iter_reverse_revision_history(start_revision)
2131
 
            #skip the last revision in the list
2132
 
            next_revision = iterator.next()
2133
 
        for revision_id in iterator:
2134
 
            self._partial_revision_history_cache.append(revision_id)
2135
 
            if (stop_index is not None and
2136
 
                len(self._partial_revision_history_cache) > stop_index):
2137
 
                break
2138
 
            if revision_id == stop_revision:
2139
 
                break
2140
 
 
2141
 
    def _write_revision_history(self, history):
2142
 
        """Factored out of set_revision_history.
2143
 
 
2144
 
        This performs the actual writing to disk, with format-specific checks.
2145
 
        It is intended to be called by BzrBranch5.set_revision_history.
2146
 
        """
2147
 
        if len(history) == 0:
2148
 
            last_revision = 'null:'
2149
 
        else:
2150
 
            if history != self._lefthand_history(history[-1]):
2151
 
                raise errors.NotLefthandHistory(history)
2152
 
            last_revision = history[-1]
2153
 
        if self._get_append_revisions_only():
2154
 
            self._check_history_violation(last_revision)
2155
 
        self._write_last_revision_info(len(history), last_revision)
2156
 
 
2157
 
    @needs_write_lock
2158
 
    def _set_parent_location(self, url):
2159
 
        """Set the parent branch"""
2160
 
        self._set_config_location('parent_location', url, make_relative=True)
2161
 
 
2162
 
    @needs_read_lock
2163
 
    def _get_parent_location(self):
2164
 
        """Set the parent branch"""
2165
 
        return self._get_config_location('parent_location')
2166
 
 
2167
 
    def set_push_location(self, location):
2168
 
        """See Branch.set_push_location."""
2169
 
        self._set_config_location('push_location', location)
2170
 
 
2171
 
    def set_bound_location(self, location):
2172
 
        """See Branch.set_push_location."""
2173
 
        result = None
2174
 
        config = self.get_config()
2175
 
        if location is None:
2176
 
            if config.get_user_option('bound') != 'True':
2177
 
                return False
2178
 
            else:
2179
 
                config.set_user_option('bound', 'False', warn_masked=True)
2180
 
                return True
2181
 
        else:
2182
 
            self._set_config_location('bound_location', location,
2183
 
                                      config=config)
2184
 
            config.set_user_option('bound', 'True', warn_masked=True)
2185
 
        return True
2186
 
 
2187
 
    def _get_bound_location(self, bound):
2188
 
        """Return the bound location in the config file.
2189
 
 
2190
 
        Return None if the bound parameter does not match"""
2191
 
        config = self.get_config()
2192
 
        config_bound = (config.get_user_option('bound') == 'True')
2193
 
        if config_bound != bound:
2194
 
            return None
2195
 
        return self._get_config_location('bound_location', config=config)
2196
 
 
2197
 
    def get_bound_location(self):
2198
 
        """See Branch.set_push_location."""
2199
 
        return self._get_bound_location(True)
2200
 
 
2201
 
    def get_old_bound_location(self):
2202
 
        """See Branch.get_old_bound_location"""
2203
 
        return self._get_bound_location(False)
2204
 
 
2205
 
    def get_stacked_on_url(self):
2206
 
        self._check_stackable_repo()
2207
 
        stacked_url = self._get_config_location('stacked_on_location')
2208
 
        if stacked_url is None:
2209
 
            raise errors.NotStacked(self)
2210
 
        return stacked_url
2211
 
 
2212
 
    def set_append_revisions_only(self, enabled):
2213
 
        if enabled:
2214
 
            value = 'True'
2215
 
        else:
2216
 
            value = 'False'
2217
 
        self.get_config().set_user_option('append_revisions_only', value,
2218
 
            warn_masked=True)
2219
 
 
2220
 
    def set_stacked_on_url(self, url):
2221
 
        self._check_stackable_repo()
2222
 
        if not url:
2223
 
            try:
2224
 
                old_url = self.get_stacked_on_url()
2225
 
            except (errors.NotStacked, errors.UnstackableBranchFormat,
2226
 
                errors.UnstackableRepositoryFormat):
2227
 
                return
2228
 
            url = ''
2229
 
            # repositories don't offer an interface to remove fallback
2230
 
            # repositories today; take the conceptually simpler option and just
2231
 
            # reopen it.
2232
 
            self.repository = self.bzrdir.find_repository()
2233
 
            # for every revision reference the branch has, ensure it is pulled
2234
 
            # in.
2235
 
            source_repository = self._get_fallback_repository(old_url)
2236
 
            for revision_id in chain([self.last_revision()],
2237
 
                self.tags.get_reverse_tag_dict()):
2238
 
                self.repository.fetch(source_repository, revision_id,
2239
 
                    find_ghosts=True)
2240
 
        else:
2241
 
            self._activate_fallback_location(url)
2242
 
        # write this out after the repository is stacked to avoid setting a
2243
 
        # stacked config that doesn't work.
2244
 
        self._set_config_location('stacked_on_location', url)
2245
 
 
2246
 
    def _get_append_revisions_only(self):
2247
 
        value = self.get_config().get_user_option('append_revisions_only')
2248
 
        return value == 'True'
2249
 
 
2250
 
    def _synchronize_history(self, destination, revision_id):
2251
 
        """Synchronize last revision and revision history between branches.
2252
 
 
2253
 
        This version is most efficient when the destination is also a
2254
 
        BzrBranch6, but works for BzrBranch5, as long as the destination's
2255
 
        repository contains all the lefthand ancestors of the intended
2256
 
        last_revision.  If not, set_last_revision_info will fail.
2257
 
 
2258
 
        :param destination: The branch to copy the history into
2259
 
        :param revision_id: The revision-id to truncate history at.  May
2260
 
          be None to copy complete history.
2261
 
        """
2262
 
        source_revno, source_revision_id = self.last_revision_info()
2263
 
        if revision_id is None:
2264
 
            revno, revision_id = source_revno, source_revision_id
2265
 
        elif source_revision_id == revision_id:
2266
 
            # we know the revno without needing to walk all of history
2267
 
            revno = source_revno
2268
 
        else:
2269
 
            # To figure out the revno for a random revision, we need to build
2270
 
            # the revision history, and count its length.
2271
 
            # We don't care about the order, just how long it is.
2272
 
            # Alternatively, we could start at the current location, and count
2273
 
            # backwards. But there is no guarantee that we will find it since
2274
 
            # it may be a merged revision.
2275
 
            revno = len(list(self.repository.iter_reverse_revision_history(
2276
 
                                                                revision_id)))
2277
 
        destination.set_last_revision_info(revno, revision_id)
2278
 
 
2279
 
    def _make_tags(self):
2280
 
        return BasicTags(self)
2281
 
 
2282
 
    @needs_write_lock
2283
 
    def generate_revision_history(self, revision_id, last_rev=None,
2284
 
                                  other_branch=None):
2285
 
        """See BzrBranch5.generate_revision_history"""
2286
 
        history = self._lefthand_history(revision_id, last_rev, other_branch)
2287
 
        revno = len(history)
2288
 
        self.set_last_revision_info(revno, revision_id)
2289
 
 
2290
 
    @needs_read_lock
2291
 
    def get_rev_id(self, revno, history=None):
2292
 
        """Find the revision id of the specified revno."""
2293
 
        if revno == 0:
2294
 
            return _mod_revision.NULL_REVISION
2295
 
 
2296
 
        last_revno, last_revision_id = self.last_revision_info()
2297
 
        if revno <= 0 or revno > last_revno:
2298
 
            raise errors.NoSuchRevision(self, revno)
2299
 
 
2300
 
        if history is not None:
2301
 
            return history[revno - 1]
2302
 
 
2303
 
        index = last_revno - revno
2304
 
        if len(self._partial_revision_history_cache) <= index:
2305
 
            self._extend_partial_history(stop_index=index)
2306
 
        if len(self._partial_revision_history_cache) > index:
2307
 
            return self._partial_revision_history_cache[index]
2308
 
        else:
2309
 
            raise errors.NoSuchRevision(self, revno)
2310
 
 
2311
 
    @needs_read_lock
2312
 
    def revision_id_to_revno(self, revision_id):
2313
 
        """Given a revision id, return its revno"""
2314
 
        if _mod_revision.is_null(revision_id):
2315
 
            return 0
2316
 
        try:
2317
 
            index = self._partial_revision_history_cache.index(revision_id)
2318
 
        except ValueError:
2319
 
            self._extend_partial_history(stop_revision=revision_id)
2320
 
            index = len(self._partial_revision_history_cache) - 1
2321
 
            if self._partial_revision_history_cache[index] != revision_id:
2322
 
                raise errors.NoSuchRevision(self, revision_id)
2323
 
        return self.revno() - index
2324
 
 
2325
 
 
2326
 
class BzrBranch6(BzrBranch7):
2327
 
    """See BzrBranchFormat6 for the capabilities of this branch.
2328
 
 
2329
 
    This subclass of BzrBranch7 disables the new features BzrBranch7 added,
2330
 
    i.e. stacking.
2331
 
    """
2332
 
 
2333
 
    def get_stacked_on_url(self):
2334
 
        raise errors.UnstackableBranchFormat(self._format, self.base)
2335
 
 
2336
 
    def set_stacked_on_url(self, url):
2337
 
        raise errors.UnstackableBranchFormat(self._format, self.base)
2338
 
 
2339
 
 
2340
 
######################################################################
2341
 
# results of operations
2342
 
 
2343
 
 
2344
 
class _Result(object):
2345
 
 
2346
 
    def _show_tag_conficts(self, to_file):
2347
 
        if not getattr(self, 'tag_conflicts', None):
2348
 
            return
2349
 
        to_file.write('Conflicting tags:\n')
2350
 
        for name, value1, value2 in self.tag_conflicts:
2351
 
            to_file.write('    %s\n' % (name, ))
2352
 
 
2353
 
 
2354
 
class PullResult(_Result):
2355
 
    """Result of a Branch.pull operation.
2356
 
 
2357
 
    :ivar old_revno: Revision number before pull.
2358
 
    :ivar new_revno: Revision number after pull.
2359
 
    :ivar old_revid: Tip revision id before pull.
2360
 
    :ivar new_revid: Tip revision id after pull.
2361
 
    :ivar source_branch: Source (local) branch object.
2362
 
    :ivar master_branch: Master branch of the target, or the target if no
2363
 
        Master
2364
 
    :ivar local_branch: target branch if there is a Master, else None
2365
 
    :ivar target_branch: Target/destination branch object.
2366
 
    :ivar tag_conflicts: A list of tag conflicts, see BasicTags.merge_to
2367
 
    """
2368
 
 
2369
 
    def __int__(self):
2370
 
        # DEPRECATED: pull used to return the change in revno
2371
 
        return self.new_revno - self.old_revno
2372
 
 
2373
 
    def report(self, to_file):
2374
 
        if not is_quiet():
2375
 
            if self.old_revid == self.new_revid:
2376
 
                to_file.write('No revisions to pull.\n')
2377
 
            else:
2378
 
                to_file.write('Now on revision %d.\n' % self.new_revno)
2379
 
        self._show_tag_conficts(to_file)
2380
 
 
2381
 
 
2382
 
class PushResult(_Result):
2383
 
    """Result of a Branch.push operation.
2384
 
 
2385
 
    :ivar old_revno: Revision number before push.
2386
 
    :ivar new_revno: Revision number after push.
2387
 
    :ivar old_revid: Tip revision id before push.
2388
 
    :ivar new_revid: Tip revision id after push.
2389
 
    :ivar source_branch: Source branch object.
2390
 
    :ivar master_branch: Master branch of the target, or None.
2391
 
    :ivar target_branch: Target/destination branch object.
2392
 
    """
2393
 
 
2394
 
    def __int__(self):
2395
 
        # DEPRECATED: push used to return the change in revno
2396
 
        return self.new_revno - self.old_revno
2397
 
 
2398
 
    def report(self, to_file):
2399
 
        """Write a human-readable description of the result."""
2400
 
        if self.old_revid == self.new_revid:
2401
 
            to_file.write('No new revisions to push.\n')
2402
 
        else:
2403
 
            to_file.write('Pushed up to revision %d.\n' % self.new_revno)
2404
 
        self._show_tag_conficts(to_file)
 
1496
class BranchTestProviderAdapter(object):
 
1497
    """A tool to generate a suite testing multiple branch formats at once.
 
1498
 
 
1499
    This is done by copying the test once for each transport and injecting
 
1500
    the transport_server, transport_readonly_server, and branch_format
 
1501
    classes into each copy. Each copy is also given a new id() to make it
 
1502
    easy to identify.
 
1503
    """
 
1504
 
 
1505
    def __init__(self, transport_server, transport_readonly_server, formats):
 
1506
        self._transport_server = transport_server
 
1507
        self._transport_readonly_server = transport_readonly_server
 
1508
        self._formats = formats
 
1509
    
 
1510
    def adapt(self, test):
 
1511
        result = TestSuite()
 
1512
        for branch_format, bzrdir_format in self._formats:
 
1513
            new_test = deepcopy(test)
 
1514
            new_test.transport_server = self._transport_server
 
1515
            new_test.transport_readonly_server = self._transport_readonly_server
 
1516
            new_test.bzrdir_format = bzrdir_format
 
1517
            new_test.branch_format = branch_format
 
1518
            def make_new_test_id():
 
1519
                new_id = "%s(%s)" % (new_test.id(), branch_format.__class__.__name__)
 
1520
                return lambda: new_id
 
1521
            new_test.id = make_new_test_id()
 
1522
            result.addTest(new_test)
 
1523
        return result
2405
1524
 
2406
1525
 
2407
1526
class BranchCheckResult(object):
2424
1543
             self.branch._format)
2425
1544
 
2426
1545
 
2427
 
class Converter5to6(object):
2428
 
    """Perform an in-place upgrade of format 5 to format 6"""
2429
 
 
2430
 
    def convert(self, branch):
2431
 
        # Data for 5 and 6 can peacefully coexist.
2432
 
        format = BzrBranchFormat6()
2433
 
        new_branch = format.open(branch.bzrdir, _found=True)
2434
 
 
2435
 
        # Copy source data into target
2436
 
        new_branch._write_last_revision_info(*branch.last_revision_info())
2437
 
        new_branch.set_parent(branch.get_parent())
2438
 
        new_branch.set_bound_location(branch.get_bound_location())
2439
 
        new_branch.set_push_location(branch.get_push_location())
2440
 
 
2441
 
        # New branch has no tags by default
2442
 
        new_branch.tags._set_tag_dict({})
2443
 
 
2444
 
        # Copying done; now update target format
2445
 
        new_branch._transport.put_bytes('format',
2446
 
            format.get_format_string(),
2447
 
            mode=new_branch.bzrdir._get_file_mode())
2448
 
 
2449
 
        # Clean up old files
2450
 
        new_branch._transport.delete('revision-history')
2451
 
        try:
2452
 
            branch.set_parent(None)
2453
 
        except errors.NoSuchFile:
2454
 
            pass
2455
 
        branch.set_bound_location(None)
2456
 
 
2457
 
 
2458
 
class Converter6to7(object):
2459
 
    """Perform an in-place upgrade of format 6 to format 7"""
2460
 
 
2461
 
    def convert(self, branch):
2462
 
        format = BzrBranchFormat7()
2463
 
        branch._set_config_location('stacked_on_location', '')
2464
 
        # update target format
2465
 
        branch._transport.put_bytes('format', format.get_format_string())
 
1546
######################################################################
 
1547
# predicates
 
1548
 
 
1549
 
 
1550
@deprecated_function(zero_eight)
 
1551
def is_control_file(*args, **kwargs):
 
1552
    """See bzrlib.workingtree.is_control_file."""
 
1553
    from bzrlib import workingtree
 
1554
    return workingtree.is_control_file(*args, **kwargs)