1
# Copyright (C) 2005 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22
from warnings import warn
23
from cStringIO import StringIO
27
import bzrlib.inventory as inventory
28
from bzrlib.trace import mutter, note
29
from bzrlib.osutils import (isdir, quotefn,
30
rename, splitpath, sha_file, appendpath,
32
import bzrlib.errors as errors
33
from bzrlib.errors import (BzrError, InvalidRevisionNumber, InvalidRevisionId,
34
NoSuchRevision, HistoryMissing, NotBranchError,
35
DivergedBranches, LockError, UnlistableStore,
36
UnlistableBranch, NoSuchFile, NotVersionedError,
38
from bzrlib.textui import show_status
39
from bzrlib.revision import (Revision, is_ancestor, get_intervening_revisions,
42
from bzrlib.delta import compare_trees
43
from bzrlib.tree import EmptyTree, RevisionTree
44
from bzrlib.inventory import Inventory
45
from bzrlib.store import copy_all
46
from bzrlib.store.text import TextStore
47
from bzrlib.store.weave import WeaveStore
48
from bzrlib.testament import Testament
49
import bzrlib.transactions as transactions
50
from bzrlib.transport import Transport, get_transport
55
BZR_BRANCH_FORMAT_4 = "Bazaar-NG branch, format 0.0.4\n"
56
BZR_BRANCH_FORMAT_5 = "Bazaar-NG branch, format 5\n"
57
BZR_BRANCH_FORMAT_6 = "Bazaar-NG branch, format 6\n"
58
## TODO: Maybe include checks for common corruption of newlines, etc?
61
# TODO: Some operations like log might retrieve the same revisions
62
# repeatedly to calculate deltas. We could perhaps have a weakref
63
# cache in memory to make this faster. In general anything can be
64
# cached in memory between lock and unlock operations.
66
def find_branch(*ignored, **ignored_too):
67
# XXX: leave this here for about one release, then remove it
68
raise NotImplementedError('find_branch() is not supported anymore, '
69
'please use one of the new branch constructors')
72
def needs_read_lock(unbound):
73
"""Decorate unbound to take out and release a read lock."""
74
def decorated(self, *args, **kwargs):
77
return unbound(self, *args, **kwargs)
83
def needs_write_lock(unbound):
84
"""Decorate unbound to take out and release a write lock."""
85
def decorated(self, *args, **kwargs):
88
return unbound(self, *args, **kwargs)
93
######################################################################
97
"""Branch holding a history of revisions.
100
Base directory/url of the branch.
104
def __init__(self, *ignored, **ignored_too):
105
raise NotImplementedError('The Branch class is abstract')
108
def open_downlevel(base):
109
"""Open a branch which may be of an old format.
111
Only local branches are supported."""
112
return _Branch(get_transport(base), relax_version_check=True)
116
"""Open an existing branch, rooted at 'base' (url)"""
117
t = get_transport(base)
118
mutter("trying to open %r with transport %r", base, t)
122
def open_containing(url):
123
"""Open an existing branch which contains url.
125
This probes for a branch at url, and searches upwards from there.
127
Basically we keep looking up until we find the control directory or
128
run into the root. If there isn't one, raises NotBranchError.
129
If there is one, it is returned, along with the unused portion of url.
131
t = get_transport(url)
134
return _Branch(t), t.relpath(url)
135
except NotBranchError:
137
new_t = t.clone('..')
138
if new_t.base == t.base:
139
# reached the root, whatever that may be
140
raise NotBranchError(path=url)
144
def initialize(base):
145
"""Create a new branch, rooted at 'base' (url)"""
146
t = get_transport(base)
147
return _Branch(t, init=True)
149
def setup_caching(self, cache_root):
150
"""Subclasses that care about caching should override this, and set
151
up cached stores located under cache_root.
153
self.cache_root = cache_root
156
class _Branch(Branch):
157
"""A branch stored in the actual filesystem.
159
Note that it's "local" in the context of the filesystem; it doesn't
160
really matter if it's on an nfs/smb/afs/coda/... share, as long as
161
it's writable, and can be accessed via the normal filesystem API.
167
If _lock_mode is true, a positive count of the number of times the
171
Lock object from bzrlib.lock.
173
# We actually expect this class to be somewhat short-lived; part of its
174
# purpose is to try to isolate what bits of the branch logic are tied to
175
# filesystem access, so that in a later step, we can extricate them to
176
# a separarte ("storage") class.
180
_inventory_weave = None
182
# Map some sort of prefix into a namespace
183
# stuff like "revno:10", "revid:", etc.
184
# This should match a prefix with a function which accepts
185
REVISION_NAMESPACES = {}
187
def push_stores(self, branch_to):
188
"""Copy the content of this branches store to branch_to."""
189
if (self._branch_format != branch_to._branch_format
190
or self._branch_format != 4):
191
from bzrlib.fetch import greedy_fetch
192
mutter("falling back to fetch logic to push between %s(%s) and %s(%s)",
193
self, self._branch_format, branch_to, branch_to._branch_format)
194
greedy_fetch(to_branch=branch_to, from_branch=self,
195
revision=self.last_revision())
198
store_pairs = ((self.text_store, branch_to.text_store),
199
(self.inventory_store, branch_to.inventory_store),
200
(self.revision_store, branch_to.revision_store))
202
for from_store, to_store in store_pairs:
203
copy_all(from_store, to_store)
204
except UnlistableStore:
205
raise UnlistableBranch(from_store)
207
def __init__(self, transport, init=False,
208
relax_version_check=False):
209
"""Create new branch object at a particular location.
211
transport -- A Transport object, defining how to access files.
213
init -- If True, create new control files in a previously
214
unversioned directory. If False, the branch must already
217
relax_version_check -- If true, the usual check for the branch
218
version is not applied. This is intended only for
219
upgrade/recovery type use; it's not guaranteed that
220
all operations will work on old format branches.
222
In the test suite, creation of new trees is tested using the
223
`ScratchBranch` class.
225
assert isinstance(transport, Transport), \
226
"%r is not a Transport" % transport
227
self._transport = transport
230
self._check_format(relax_version_check)
232
def get_store(name, compressed=True, prefixed=False):
233
# FIXME: This approach of assuming stores are all entirely compressed
234
# or entirely uncompressed is tidy, but breaks upgrade from
235
# some existing branches where there's a mixture; we probably
236
# still want the option to look for both.
237
relpath = self._rel_controlfilename(name)
238
store = TextStore(self._transport.clone(relpath),
240
compressed=compressed)
241
#if self._transport.should_cache():
242
# cache_path = os.path.join(self.cache_root, name)
243
# os.mkdir(cache_path)
244
# store = bzrlib.store.CachedStore(store, cache_path)
246
def get_weave(name, prefixed=False):
247
relpath = self._rel_controlfilename(name)
248
ws = WeaveStore(self._transport.clone(relpath), prefixed=prefixed)
249
if self._transport.should_cache():
250
ws.enable_cache = True
253
if self._branch_format == 4:
254
self.inventory_store = get_store('inventory-store')
255
self.text_store = get_store('text-store')
256
self.revision_store = get_store('revision-store')
257
elif self._branch_format == 5:
258
self.control_weaves = get_weave('')
259
self.weave_store = get_weave('weaves')
260
self.revision_store = get_store('revision-store', compressed=False)
261
elif self._branch_format == 6:
262
self.control_weaves = get_weave('')
263
self.weave_store = get_weave('weaves', prefixed=True)
264
self.revision_store = get_store('revision-store', compressed=False,
266
self.revision_store.register_suffix('sig')
267
self._transaction = None
270
return '%s(%r)' % (self.__class__.__name__, self._transport.base)
275
if self._lock_mode or self._lock:
276
# XXX: This should show something every time, and be suitable for
277
# headless operation and embedding
278
warn("branch %r was not explicitly unlocked" % self)
281
# TODO: It might be best to do this somewhere else,
282
# but it is nice for a Branch object to automatically
283
# cache it's information.
284
# Alternatively, we could have the Transport objects cache requests
285
# See the earlier discussion about how major objects (like Branch)
286
# should never expect their __del__ function to run.
287
if hasattr(self, 'cache_root') and self.cache_root is not None:
289
shutil.rmtree(self.cache_root)
292
self.cache_root = None
296
return self._transport.base
299
base = property(_get_base, doc="The URL for the root of this branch.")
301
def _finish_transaction(self):
302
"""Exit the current transaction."""
303
if self._transaction is None:
304
raise errors.LockError('Branch %s is not in a transaction' %
306
transaction = self._transaction
307
self._transaction = None
310
def get_transaction(self):
311
"""Return the current active transaction.
313
If no transaction is active, this returns a passthrough object
314
for which all data is immediately flushed and no caching happens.
316
if self._transaction is None:
317
return transactions.PassThroughTransaction()
319
return self._transaction
321
def _set_transaction(self, new_transaction):
322
"""Set a new active transaction."""
323
if self._transaction is not None:
324
raise errors.LockError('Branch %s is in a transaction already.' %
326
self._transaction = new_transaction
328
def lock_write(self):
329
mutter("lock write: %s (%s)", self, self._lock_count)
330
# TODO: Upgrade locking to support using a Transport,
331
# and potentially a remote locking protocol
333
if self._lock_mode != 'w':
334
raise LockError("can't upgrade to a write lock from %r" %
336
self._lock_count += 1
338
self._lock = self._transport.lock_write(
339
self._rel_controlfilename('branch-lock'))
340
self._lock_mode = 'w'
342
self._set_transaction(transactions.PassThroughTransaction())
345
mutter("lock read: %s (%s)", self, self._lock_count)
347
assert self._lock_mode in ('r', 'w'), \
348
"invalid lock mode %r" % self._lock_mode
349
self._lock_count += 1
351
self._lock = self._transport.lock_read(
352
self._rel_controlfilename('branch-lock'))
353
self._lock_mode = 'r'
355
self._set_transaction(transactions.ReadOnlyTransaction())
356
# 5K may be excessive, but hey, its a knob.
357
self.get_transaction().set_cache_size(5000)
360
mutter("unlock: %s (%s)", self, self._lock_count)
361
if not self._lock_mode:
362
raise LockError('branch %r is not locked' % (self))
364
if self._lock_count > 1:
365
self._lock_count -= 1
367
self._finish_transaction()
370
self._lock_mode = self._lock_count = None
372
def abspath(self, name):
373
"""Return absolute filename for something in the branch
375
XXX: Robert Collins 20051017 what is this used for? why is it a branch
376
method and not a tree method.
378
return self._transport.abspath(name)
380
def _rel_controlfilename(self, file_or_path):
381
if not isinstance(file_or_path, basestring):
382
file_or_path = '/'.join(file_or_path)
383
if file_or_path == '':
385
return bzrlib.transport.urlescape(bzrlib.BZRDIR + '/' + file_or_path)
387
def controlfilename(self, file_or_path):
388
"""Return location relative to branch."""
389
return self._transport.abspath(self._rel_controlfilename(file_or_path))
391
def controlfile(self, file_or_path, mode='r'):
392
"""Open a control file for this branch.
394
There are two classes of file in the control directory: text
395
and binary. binary files are untranslated byte streams. Text
396
control files are stored with Unix newlines and in UTF-8, even
397
if the platform or locale defaults are different.
399
Controlfiles should almost never be opened in write mode but
400
rather should be atomically copied and replaced using atomicfile.
404
relpath = self._rel_controlfilename(file_or_path)
405
#TODO: codecs.open() buffers linewise, so it was overloaded with
406
# a much larger buffer, do we need to do the same for getreader/getwriter?
408
return self._transport.get(relpath)
410
raise BzrError("Branch.controlfile(mode='wb') is not supported, use put_controlfiles")
412
# XXX: Do we really want errors='replace'? Perhaps it should be
413
# an error, or at least reported, if there's incorrectly-encoded
414
# data inside a file.
415
# <https://launchpad.net/products/bzr/+bug/3823>
416
return codecs.getreader('utf-8')(self._transport.get(relpath), errors='replace')
418
raise BzrError("Branch.controlfile(mode='w') is not supported, use put_controlfiles")
420
raise BzrError("invalid controlfile mode %r" % mode)
422
def put_controlfile(self, path, f, encode=True):
423
"""Write an entry as a controlfile.
425
:param path: The path to put the file, relative to the .bzr control
427
:param f: A file-like or string object whose contents should be copied.
428
:param encode: If true, encode the contents as utf-8
430
self.put_controlfiles([(path, f)], encode=encode)
432
def put_controlfiles(self, files, encode=True):
433
"""Write several entries as controlfiles.
435
:param files: A list of [(path, file)] pairs, where the path is the directory
436
underneath the bzr control directory
437
:param encode: If true, encode the contents as utf-8
441
for path, f in files:
443
if isinstance(f, basestring):
444
f = f.encode('utf-8', 'replace')
446
f = codecs.getwriter('utf-8')(f, errors='replace')
447
path = self._rel_controlfilename(path)
448
ctrl_files.append((path, f))
449
self._transport.put_multi(ctrl_files)
451
def _make_control(self):
452
from bzrlib.inventory import Inventory
453
from bzrlib.weavefile import write_weave_v5
454
from bzrlib.weave import Weave
456
# Create an empty inventory
458
# if we want per-tree root ids then this is the place to set
459
# them; they're not needed for now and so ommitted for
461
bzrlib.xml5.serializer_v5.write_inventory(Inventory(), sio)
462
empty_inv = sio.getvalue()
464
bzrlib.weavefile.write_weave_v5(Weave(), sio)
465
empty_weave = sio.getvalue()
467
dirs = [[], 'revision-store', 'weaves']
469
"This is a Bazaar-NG control directory.\n"
470
"Do not change any files in this directory.\n"),
471
('branch-format', BZR_BRANCH_FORMAT_6),
472
('revision-history', ''),
475
('pending-merges', ''),
476
('inventory', empty_inv),
477
('inventory.weave', empty_weave),
478
('ancestry.weave', empty_weave)
480
cfn = self._rel_controlfilename
481
self._transport.mkdir_multi([cfn(d) for d in dirs])
482
self.put_controlfiles(files)
483
mutter('created control directory in ' + self._transport.base)
485
def _check_format(self, relax_version_check):
486
"""Check this branch format is supported.
488
The format level is stored, as an integer, in
489
self._branch_format for code that needs to check it later.
491
In the future, we might need different in-memory Branch
492
classes to support downlevel branches. But not yet.
495
fmt = self.controlfile('branch-format', 'r').read()
497
raise NotBranchError(path=self.base)
498
mutter("got branch format %r", fmt)
499
if fmt == BZR_BRANCH_FORMAT_6:
500
self._branch_format = 6
501
elif fmt == BZR_BRANCH_FORMAT_5:
502
self._branch_format = 5
503
elif fmt == BZR_BRANCH_FORMAT_4:
504
self._branch_format = 4
506
if (not relax_version_check
507
and self._branch_format not in (5, 6)):
508
raise errors.UnsupportedFormatError(
509
'sorry, branch format %r not supported' % fmt,
510
['use a different bzr version',
511
'or remove the .bzr directory'
512
' and "bzr init" again'])
514
def get_root_id(self):
515
"""Return the id of this branches root"""
516
inv = self.get_inventory(self.last_revision())
517
return inv.root.file_id
520
def print_file(self, file, revno):
521
"""Print `file` to stdout."""
522
tree = self.revision_tree(self.get_rev_id(revno))
523
# use inventory as it was in that revision
524
file_id = tree.inventory.path2id(file)
526
raise BzrError("%r is not present in revision %s" % (file, revno))
527
tree.print_file(file_id)
530
def append_revision(self, *revision_ids):
531
for revision_id in revision_ids:
532
mutter("add {%s} to revision-history" % revision_id)
533
rev_history = self.revision_history()
534
rev_history.extend(revision_ids)
535
self.set_revision_history(rev_history)
538
def set_revision_history(self, rev_history):
539
self.put_controlfile('revision-history', '\n'.join(rev_history))
541
def has_revision(self, revision_id):
542
"""True if this branch has a copy of the revision.
544
This does not necessarily imply the revision is merge
545
or on the mainline."""
546
return (revision_id is None
547
or self.revision_store.has_id(revision_id))
550
def get_revision_xml_file(self, revision_id):
551
"""Return XML file object for revision object."""
552
if not revision_id or not isinstance(revision_id, basestring):
553
raise InvalidRevisionId(revision_id=revision_id, branch=self)
555
return self.revision_store.get(revision_id)
556
except (IndexError, KeyError):
557
raise bzrlib.errors.NoSuchRevision(self, revision_id)
560
get_revision_xml = get_revision_xml_file
562
def get_revision_xml(self, revision_id):
563
return self.get_revision_xml_file(revision_id).read()
566
def get_revision(self, revision_id):
567
"""Return the Revision object for a named revision"""
568
xml_file = self.get_revision_xml_file(revision_id)
571
r = bzrlib.xml5.serializer_v5.read_revision(xml_file)
572
except SyntaxError, e:
573
raise bzrlib.errors.BzrError('failed to unpack revision_xml',
577
assert r.revision_id == revision_id
580
def get_revision_delta(self, revno):
581
"""Return the delta for one revision.
583
The delta is relative to its mainline predecessor, or the
584
empty tree for revision 1.
586
assert isinstance(revno, int)
587
rh = self.revision_history()
588
if not (1 <= revno <= len(rh)):
589
raise InvalidRevisionNumber(revno)
591
# revno is 1-based; list is 0-based
593
new_tree = self.revision_tree(rh[revno-1])
595
old_tree = EmptyTree()
597
old_tree = self.revision_tree(rh[revno-2])
599
return compare_trees(old_tree, new_tree)
601
def get_revision_sha1(self, revision_id):
602
"""Hash the stored value of a revision, and return it."""
603
# In the future, revision entries will be signed. At that
604
# point, it is probably best *not* to include the signature
605
# in the revision hash. Because that lets you re-sign
606
# the revision, (add signatures/remove signatures) and still
607
# have all hash pointers stay consistent.
608
# But for now, just hash the contents.
609
return bzrlib.osutils.sha_file(self.get_revision_xml_file(revision_id))
611
def get_ancestry(self, revision_id):
612
"""Return a list of revision-ids integrated by a revision.
614
This currently returns a list, but the ordering is not guaranteed:
617
if revision_id is None:
619
w = self.get_inventory_weave()
620
return [None] + map(w.idx_to_name,
621
w.inclusions([w.lookup(revision_id)]))
623
def get_inventory_weave(self):
624
return self.control_weaves.get_weave('inventory',
625
self.get_transaction())
627
def get_inventory(self, revision_id):
628
"""Get Inventory object by hash."""
629
xml = self.get_inventory_xml(revision_id)
630
return bzrlib.xml5.serializer_v5.read_inventory_from_string(xml)
632
def get_inventory_xml(self, revision_id):
633
"""Get inventory XML as a file object."""
635
assert isinstance(revision_id, basestring), type(revision_id)
636
iw = self.get_inventory_weave()
637
return iw.get_text(iw.lookup(revision_id))
639
raise bzrlib.errors.HistoryMissing(self, 'inventory', revision_id)
641
def get_inventory_sha1(self, revision_id):
642
"""Return the sha1 hash of the inventory entry
644
return self.get_revision(revision_id).inventory_sha1
646
def get_revision_inventory(self, revision_id):
647
"""Return inventory of a past revision."""
648
# TODO: Unify this with get_inventory()
649
# bzr 0.0.6 and later imposes the constraint that the inventory_id
650
# must be the same as its revision, so this is trivial.
651
if revision_id == None:
652
# This does not make sense: if there is no revision,
653
# then it is the current tree inventory surely ?!
654
# and thus get_root_id() is something that looks at the last
655
# commit on the branch, and the get_root_id is an inventory check.
656
raise NotImplementedError
657
# return Inventory(self.get_root_id())
659
return self.get_inventory(revision_id)
662
def revision_history(self):
663
"""Return sequence of revision hashes on to this branch."""
664
transaction = self.get_transaction()
665
history = transaction.map.find_revision_history()
666
if history is not None:
667
mutter("cache hit for revision-history in %s", self)
669
history = [l.rstrip('\r\n') for l in
670
self.controlfile('revision-history', 'r').readlines()]
671
transaction.map.add_revision_history(history)
672
# this call is disabled because revision_history is
673
# not really an object yet, and the transaction is for objects.
674
# transaction.register_clean(history, precious=True)
678
"""Return current revision number for this branch.
680
That is equivalent to the number of revisions committed to
683
return len(self.revision_history())
685
def last_revision(self):
686
"""Return last patch hash, or None if no history.
688
ph = self.revision_history()
694
def missing_revisions(self, other, stop_revision=None, diverged_ok=False):
695
"""Return a list of new revisions that would perfectly fit.
697
If self and other have not diverged, return a list of the revisions
698
present in other, but missing from self.
700
>>> from bzrlib.commit import commit
701
>>> bzrlib.trace.silent = True
702
>>> br1 = ScratchBranch()
703
>>> br2 = ScratchBranch()
704
>>> br1.missing_revisions(br2)
706
>>> commit(br2, "lala!", rev_id="REVISION-ID-1")
707
>>> br1.missing_revisions(br2)
709
>>> br2.missing_revisions(br1)
711
>>> commit(br1, "lala!", rev_id="REVISION-ID-1")
712
>>> br1.missing_revisions(br2)
714
>>> commit(br2, "lala!", rev_id="REVISION-ID-2A")
715
>>> br1.missing_revisions(br2)
717
>>> commit(br1, "lala!", rev_id="REVISION-ID-2B")
718
>>> br1.missing_revisions(br2)
719
Traceback (most recent call last):
720
DivergedBranches: These branches have diverged.
722
self_history = self.revision_history()
723
self_len = len(self_history)
724
other_history = other.revision_history()
725
other_len = len(other_history)
726
common_index = min(self_len, other_len) -1
727
if common_index >= 0 and \
728
self_history[common_index] != other_history[common_index]:
729
raise DivergedBranches(self, other)
731
if stop_revision is None:
732
stop_revision = other_len
734
assert isinstance(stop_revision, int)
735
if stop_revision > other_len:
736
raise bzrlib.errors.NoSuchRevision(self, stop_revision)
737
return other_history[self_len:stop_revision]
739
def update_revisions(self, other, stop_revision=None):
740
"""Pull in new perfect-fit revisions."""
741
from bzrlib.fetch import greedy_fetch
742
if stop_revision is None:
743
stop_revision = other.last_revision()
744
### Should this be checking is_ancestor instead of revision_history?
745
if (stop_revision is not None and
746
stop_revision in self.revision_history()):
748
greedy_fetch(to_branch=self, from_branch=other,
749
revision=stop_revision)
750
pullable_revs = self.pullable_revisions(other, stop_revision)
751
if len(pullable_revs) > 0:
752
self.append_revision(*pullable_revs)
754
def pullable_revisions(self, other, stop_revision):
755
other_revno = other.revision_id_to_revno(stop_revision)
757
return self.missing_revisions(other, other_revno)
758
except DivergedBranches, e:
760
pullable_revs = get_intervening_revisions(self.last_revision(),
762
assert self.last_revision() not in pullable_revs
764
except bzrlib.errors.NotAncestor:
765
if is_ancestor(self.last_revision(), stop_revision, self):
770
def revision_id_to_revno(self, revision_id):
771
"""Given a revision id, return its revno"""
772
if revision_id is None:
774
history = self.revision_history()
776
return history.index(revision_id) + 1
778
raise bzrlib.errors.NoSuchRevision(self, revision_id)
780
def get_rev_id(self, revno, history=None):
781
"""Find the revision id of the specified revno."""
785
history = self.revision_history()
786
elif revno <= 0 or revno > len(history):
787
raise bzrlib.errors.NoSuchRevision(self, revno)
788
return history[revno - 1]
790
def revision_tree(self, revision_id):
791
"""Return Tree for a revision on this branch.
793
`revision_id` may be None for the null revision, in which case
794
an `EmptyTree` is returned."""
795
# TODO: refactor this to use an existing revision object
796
# so we don't need to read it in twice.
797
if revision_id == None or revision_id == NULL_REVISION:
800
inv = self.get_revision_inventory(revision_id)
801
return RevisionTree(self.weave_store, inv, revision_id)
803
def working_tree(self):
804
"""Return a `Tree` for the working copy if this is a local branch."""
805
from bzrlib.workingtree import WorkingTree
806
if self._transport.base.find('://') != -1:
807
raise NoWorkingTree(self.base)
808
return WorkingTree(self.base, branch=self)
811
def pull(self, source, overwrite=False):
815
self.update_revisions(source)
816
except DivergedBranches:
819
self.set_revision_history(source.revision_history())
823
def basis_tree(self):
824
"""Return `Tree` object for last revision.
826
If there are no revisions yet, return an `EmptyTree`.
828
return self.revision_tree(self.last_revision())
830
def get_parent(self):
831
"""Return the parent location of the branch.
833
This is the default location for push/pull/missing. The usual
834
pattern is that the user can override it by specifying a
838
_locs = ['parent', 'pull', 'x-pull']
841
return self.controlfile(l, 'r').read().strip('\n')
843
if e.errno != errno.ENOENT:
847
def get_push_location(self):
848
"""Return the None or the location to push this branch to."""
849
config = bzrlib.config.BranchConfig(self)
850
push_loc = config.get_user_option('push_location')
853
def set_push_location(self, location):
854
"""Set a new push location for this branch."""
855
config = bzrlib.config.LocationConfig(self.base)
856
config.set_user_option('push_location', location)
859
def set_parent(self, url):
860
# TODO: Maybe delete old location files?
861
from bzrlib.atomicfile import AtomicFile
862
f = AtomicFile(self.controlfilename('parent'))
869
def check_revno(self, revno):
871
Check whether a revno corresponds to any revision.
872
Zero (the NULL revision) is considered valid.
875
self.check_real_revno(revno)
877
def check_real_revno(self, revno):
879
Check whether a revno corresponds to a real revision.
880
Zero (the NULL revision) is considered invalid
882
if revno < 1 or revno > self.revno():
883
raise InvalidRevisionNumber(revno)
885
def sign_revision(self, revision_id, gpg_strategy):
886
plaintext = Testament.from_revision(self, revision_id).as_short_text()
887
self.store_revision_signature(gpg_strategy, plaintext, revision_id)
890
def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
891
self.revision_store.add(StringIO(gpg_strategy.sign(plaintext)),
895
class ScratchBranch(_Branch):
896
"""Special test class: a branch that cleans up after itself.
898
>>> b = ScratchBranch()
902
>>> b._transport.__del__()
907
def __init__(self, files=[], dirs=[], transport=None):
908
"""Make a test branch.
910
This creates a temporary directory and runs init-tree in it.
912
If any files are listed, they are created in the working copy.
914
if transport is None:
915
transport = bzrlib.transport.local.ScratchTransport()
916
super(ScratchBranch, self).__init__(transport, init=True)
918
super(ScratchBranch, self).__init__(transport)
921
self._transport.mkdir(d)
924
self._transport.put(f, 'content of %s' % f)
929
>>> orig = ScratchBranch(files=["file1", "file2"])
930
>>> clone = orig.clone()
931
>>> if os.name != 'nt':
932
... os.path.samefile(orig.base, clone.base)
934
... orig.base == clone.base
937
>>> os.path.isfile(os.path.join(clone.base, "file1"))
940
from shutil import copytree
941
from tempfile import mkdtemp
944
copytree(self.base, base, symlinks=True)
945
return ScratchBranch(
946
transport=bzrlib.transport.local.ScratchTransport(base))
949
######################################################################
953
def is_control_file(filename):
954
## FIXME: better check
955
filename = os.path.normpath(filename)
956
while filename != '':
957
head, tail = os.path.split(filename)
958
## mutter('check %r for control file' % ((head, tail), ))
959
if tail == bzrlib.BZRDIR: