15
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
22
28
from bzrlib.trace import mutter, note
23
from bzrlib.osutils import isdir, quotefn, compact_date, rand_bytes, \
25
sha_file, appendpath, file_kind
27
from bzrlib.errors import BzrError, InvalidRevisionNumber, InvalidRevisionId, \
28
DivergedBranches, NotBranchError
29
from bzrlib.osutils import (isdir, quotefn,
30
rename, splitpath, sha_file,
31
file_kind, abspath, normpath, pathjoin)
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,
29
38
from bzrlib.textui import show_status
30
from bzrlib.revision import Revision
39
from bzrlib.revision import (Revision, is_ancestor, get_intervening_revisions,
31
42
from bzrlib.delta import compare_trees
32
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
38
BZR_BRANCH_FORMAT = "Bazaar-NG branch, format 0.0.4\n"
53
from config import TreeConfig
56
BZR_BRANCH_FORMAT_4 = "Bazaar-NG branch, format 0.0.4\n"
57
BZR_BRANCH_FORMAT_5 = "Bazaar-NG branch, format 5\n"
58
BZR_BRANCH_FORMAT_6 = "Bazaar-NG branch, format 6\n"
39
59
## TODO: Maybe include checks for common corruption of newlines, etc?
42
62
# TODO: Some operations like log might retrieve the same revisions
43
63
# repeatedly to calculate deltas. We could perhaps have a weakref
44
# cache in memory to make this faster.
46
# TODO: please move the revision-string syntax stuff out of the branch
47
# object; it's clutter
50
def find_branch(f, **args):
51
if f and (f.startswith('http://') or f.startswith('https://')):
52
from bzrlib.remotebranch import RemoteBranch
53
return RemoteBranch(f, **args)
55
return LocalBranch(f, **args)
58
def find_cached_branch(f, cache_root, **args):
59
from bzrlib.remotebranch import RemoteBranch
60
br = find_branch(f, **args)
61
def cacheify(br, store_name):
62
from bzrlib.meta_store import CachedStore
63
cache_path = os.path.join(cache_root, store_name)
65
new_store = CachedStore(getattr(br, store_name), cache_path)
66
setattr(br, store_name, new_store)
68
if isinstance(br, RemoteBranch):
69
cacheify(br, 'inventory_store')
70
cacheify(br, 'text_store')
71
cacheify(br, 'revision_store')
75
def _relpath(base, path):
76
"""Return path relative to base, or raise exception.
78
The path may be either an absolute path or a path relative to the
79
current working directory.
81
Lifted out of Branch.relpath for ease of testing.
83
os.path.commonprefix (python2.4) has a bad bug that it works just
84
on string prefixes, assuming that '/u' is a prefix of '/u2'. This
85
avoids that problem."""
86
rp = os.path.abspath(path)
90
while len(head) >= len(base):
93
head, tail = os.path.split(head)
97
raise NotBranchError("path %r is not within branch %r" % (rp, base))
102
def find_branch_root(f=None):
103
"""Find the branch root enclosing f, or pwd.
105
f may be a filename or a URL.
107
It is not necessary that f exists.
109
Basically we keep looking up until we find the control directory or
110
run into the root. If there isn't one, raises NotBranchError.
114
elif hasattr(os.path, 'realpath'):
115
f = os.path.realpath(f)
117
f = os.path.abspath(f)
118
if not os.path.exists(f):
119
raise BzrError('%r does not exist' % f)
125
if os.path.exists(os.path.join(f, bzrlib.BZRDIR)):
127
head, tail = os.path.split(f)
129
# reached the root, whatever that may be
130
raise NotBranchError('%s is not in a branch' % orig_f)
64
# cache in memory to make this faster. In general anything can be
65
# cached in memory between lock and unlock operations.
67
def find_branch(*ignored, **ignored_too):
68
# XXX: leave this here for about one release, then remove it
69
raise NotImplementedError('find_branch() is not supported anymore, '
70
'please use one of the new branch constructors')
73
def needs_read_lock(unbound):
74
"""Decorate unbound to take out and release a read lock."""
75
def decorated(self, *args, **kwargs):
78
return unbound(self, *args, **kwargs)
84
def needs_write_lock(unbound):
85
"""Decorate unbound to take out and release a write lock."""
86
def decorated(self, *args, **kwargs):
89
return unbound(self, *args, **kwargs)
136
94
######################################################################
147
def __new__(cls, *a, **kw):
148
"""this is temporary, till we get rid of all code that does
151
# XXX: AAARGH! MY EYES! UUUUGLY!!!
154
b = object.__new__(cls)
158
class LocalBranch(Branch):
159
"""A branch stored in the actual filesystem.
161
Note that it's "local" in the context of the filesystem; it doesn't
162
really matter if it's on an nfs/smb/afs/coda/... share, as long as
163
it's writable, and can be accessed via the normal filesystem API.
169
If _lock_mode is true, a positive count of the number of times the
173
Lock object from bzrlib.lock.
175
# We actually expect this class to be somewhat short-lived; part of its
176
# purpose is to try to isolate what bits of the branch logic are tied to
177
# filesystem access, so that in a later step, we can extricate them to
178
# a separarte ("storage") class.
183
def __init__(self, base, init=False, find_root=True):
184
"""Create new branch object at a particular location.
186
base -- Base directory for the branch.
188
init -- If True, create new control files in a previously
189
unversioned directory. If False, the branch must already
192
find_root -- If true and init is false, find the root of the
193
existing branch containing base.
195
In the test suite, creation of new trees is tested using the
196
`ScratchBranch` class.
198
from bzrlib.store import ImmutableStore
200
self.base = os.path.realpath(base)
203
self.base = find_branch_root(base)
205
self.base = os.path.realpath(base)
206
if not isdir(self.controlfilename('.')):
207
raise NotBranchError("not a bzr branch: %s" % quotefn(base),
208
['use "bzr init" to initialize a new working tree',
209
'current bzr can only operate from top-of-tree'])
212
self.text_store = ImmutableStore(self.controlfilename('text-store'))
213
self.revision_store = ImmutableStore(self.controlfilename('revision-store'))
214
self.inventory_store = ImmutableStore(self.controlfilename('inventory-store'))
218
return '%s(%r)' % (self.__class__.__name__, self.base)
225
if self._lock_mode or self._lock:
226
from bzrlib.warnings import warn
227
warn("branch %r was not explicitly unlocked" % self)
105
def __init__(self, *ignored, **ignored_too):
106
raise NotImplementedError('The Branch class is abstract')
109
def open_downlevel(base):
110
"""Open a branch which may be of an old format.
112
Only local branches are supported."""
113
return BzrBranch(get_transport(base), relax_version_check=True)
117
"""Open an existing branch, rooted at 'base' (url)"""
118
t = get_transport(base)
119
mutter("trying to open %r with transport %r", base, t)
123
def open_containing(url):
124
"""Open an existing branch which contains url.
126
This probes for a branch at url, and searches upwards from there.
128
Basically we keep looking up until we find the control directory or
129
run into the root. If there isn't one, raises NotBranchError.
130
If there is one, it is returned, along with the unused portion of url.
132
t = get_transport(url)
135
return BzrBranch(t), t.relpath(url)
136
except NotBranchError, e:
137
mutter('not a branch in: %r %s', t.base, e)
138
new_t = t.clone('..')
139
if new_t.base == t.base:
140
# reached the root, whatever that may be
141
raise NotBranchError(path=url)
145
def initialize(base):
146
"""Create a new branch, rooted at 'base' (url)"""
147
t = get_transport(base)
148
return BzrBranch(t, init=True)
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.
154
self.cache_root = cache_root
157
cfg = self.tree_config()
158
return cfg.get_option(u"nickname", default=self.base.split('/')[-1])
160
def _set_nick(self, nick):
161
cfg = self.tree_config()
162
cfg.set_option(nick, "nickname")
163
assert cfg.get_option("nickname") == nick
165
nick = property(_get_nick, _set_nick)
167
def push_stores(self, branch_to):
168
"""Copy the content of this branches store to branch_to."""
169
raise NotImplementedError('push_stores is abstract')
171
def get_transaction(self):
172
"""Return the current active transaction.
174
If no transaction is active, this returns a passthrough object
175
for which all data is immediately flushed and no caching happens.
177
raise NotImplementedError('get_transaction is abstract')
231
179
def lock_write(self):
233
if self._lock_mode != 'w':
234
from bzrlib.errors import LockError
235
raise LockError("can't upgrade to a write lock from %r" %
237
self._lock_count += 1
239
from bzrlib.lock import WriteLock
241
self._lock = WriteLock(self.controlfilename('branch-lock'))
242
self._lock_mode = 'w'
180
raise NotImplementedError('lock_write is abstract')
246
182
def lock_read(self):
248
assert self._lock_mode in ('r', 'w'), \
249
"invalid lock mode %r" % self._lock_mode
250
self._lock_count += 1
252
from bzrlib.lock import ReadLock
183
raise NotImplementedError('lock_read is abstract')
254
self._lock = ReadLock(self.controlfilename('branch-lock'))
255
self._lock_mode = 'r'
258
185
def unlock(self):
259
if not self._lock_mode:
260
from bzrlib.errors import LockError
261
raise LockError('branch %r is not locked' % (self))
263
if self._lock_count > 1:
264
self._lock_count -= 1
268
self._lock_mode = self._lock_count = None
186
raise NotImplementedError('unlock is abstract')
270
188
def abspath(self, name):
271
"""Return absolute filename for something in the branch"""
272
return os.path.join(self.base, name)
274
def relpath(self, path):
275
"""Return path relative to this branch of something inside it.
277
Raises an error if path is not in this branch."""
278
return _relpath(self.base, path)
189
"""Return absolute filename for something in the branch
191
XXX: Robert Collins 20051017 what is this used for? why is it a branch
192
method and not a tree method.
194
raise NotImplementedError('abspath is abstract')
280
196
def controlfilename(self, file_or_path):
281
197
"""Return location relative to branch."""
282
if isinstance(file_or_path, basestring):
283
file_or_path = [file_or_path]
284
return os.path.join(self.base, bzrlib.BZRDIR, *file_or_path)
198
raise NotImplementedError('controlfilename is abstract')
287
200
def controlfile(self, file_or_path, mode='r'):
288
201
"""Open a control file for this branch.
295
208
Controlfiles should almost never be opened in write mode but
296
209
rather should be atomically copied and replaced using atomicfile.
299
fn = self.controlfilename(file_or_path)
301
if mode == 'rb' or mode == 'wb':
302
return file(fn, mode)
303
elif mode == 'r' or mode == 'w':
304
# open in binary mode anyhow so there's no newline translation;
305
# codecs uses line buffering by default; don't want that.
307
return codecs.open(fn, mode + 'b', 'utf-8',
310
raise BzrError("invalid controlfile mode %r" % mode)
312
def _make_control(self):
313
from bzrlib.inventory import Inventory
315
os.mkdir(self.controlfilename([]))
316
self.controlfile('README', 'w').write(
317
"This is a Bazaar-NG control directory.\n"
318
"Do not change any files in this directory.\n")
319
self.controlfile('branch-format', 'w').write(BZR_BRANCH_FORMAT)
320
for d in ('text-store', 'inventory-store', 'revision-store'):
321
os.mkdir(self.controlfilename(d))
322
for f in ('revision-history', 'merged-patches',
323
'pending-merged-patches', 'branch-name',
326
self.controlfile(f, 'w').write('')
327
mutter('created control directory in ' + self.base)
329
# if we want per-tree root ids then this is the place to set
330
# them; they're not needed for now and so ommitted for
332
f = self.controlfile('inventory','w')
333
bzrlib.xml.serializer_v4.write_inventory(Inventory(), f)
336
def _check_format(self):
337
"""Check this branch format is supported.
339
The current tool only supports the current unstable format.
341
In the future, we might need different in-memory Branch
342
classes to support downlevel branches. But not yet.
344
# This ignores newlines so that we can open branches created
345
# on Windows from Linux and so on. I think it might be better
346
# to always make all internal files in unix format.
347
fmt = self.controlfile('branch-format', 'r').read()
348
fmt = fmt.replace('\r\n', '\n')
349
if fmt != BZR_BRANCH_FORMAT:
350
raise BzrError('sorry, branch format %r not supported' % fmt,
351
['use a different bzr version',
352
'or remove the .bzr directory and "bzr init" again'])
211
raise NotImplementedError('controlfile is abstract')
213
def put_controlfile(self, path, f, encode=True):
214
"""Write an entry as a controlfile.
216
:param path: The path to put the file, relative to the .bzr control
218
:param f: A file-like or string object whose contents should be copied.
219
:param encode: If true, encode the contents as utf-8
221
raise NotImplementedError('put_controlfile is abstract')
223
def put_controlfiles(self, files, encode=True):
224
"""Write several entries as controlfiles.
226
:param files: A list of [(path, file)] pairs, where the path is the directory
227
underneath the bzr control directory
228
:param encode: If true, encode the contents as utf-8
230
raise NotImplementedError('put_controlfiles is abstract')
354
232
def get_root_id(self):
355
233
"""Return the id of this branches root"""
356
inv = self.read_working_inventory()
357
return inv.root.file_id
234
raise NotImplementedError('get_root_id is abstract')
359
236
def set_root_id(self, file_id):
360
inv = self.read_working_inventory()
361
orig_root_id = inv.root.file_id
362
del inv._byid[inv.root.file_id]
363
inv.root.file_id = file_id
364
inv._byid[inv.root.file_id] = inv.root
367
if entry.parent_id in (None, orig_root_id):
368
entry.parent_id = inv.root.file_id
369
self._write_inventory(inv)
371
def read_working_inventory(self):
372
"""Read the working inventory."""
373
from bzrlib.inventory import Inventory
376
# ElementTree does its own conversion from UTF-8, so open in
378
f = self.controlfile('inventory', 'rb')
379
return bzrlib.xml.serializer_v4.read_inventory(f)
384
def _write_inventory(self, inv):
385
"""Update the working inventory.
387
That is to say, the inventory describing changes underway, that
388
will be committed to the next revision.
390
from bzrlib.atomicfile import AtomicFile
394
f = AtomicFile(self.controlfilename('inventory'), 'wb')
396
bzrlib.xml.serializer_v4.write_inventory(inv, f)
403
mutter('wrote working inventory')
406
inventory = property(read_working_inventory, _write_inventory, None,
407
"""Inventory for the working copy.""")
410
def add(self, files, ids=None):
411
"""Make files versioned.
413
Note that the command line normally calls smart_add instead,
414
which can automatically recurse.
416
This puts the files in the Added state, so that they will be
417
recorded by the next commit.
420
List of paths to add, relative to the base of the tree.
423
If set, use these instead of automatically generated ids.
424
Must be the same length as the list of files, but may
425
contain None for ids that are to be autogenerated.
427
TODO: Perhaps have an option to add the ids even if the files do
430
TODO: Perhaps yield the ids and paths as they're added.
432
# TODO: Re-adding a file that is removed in the working copy
433
# should probably put it back with the previous ID.
434
if isinstance(files, basestring):
435
assert(ids is None or isinstance(ids, basestring))
441
ids = [None] * len(files)
443
assert(len(ids) == len(files))
447
inv = self.read_working_inventory()
448
for f,file_id in zip(files, ids):
449
if is_control_file(f):
450
raise BzrError("cannot add control file %s" % quotefn(f))
455
raise BzrError("cannot add top-level %r" % f)
457
fullpath = os.path.normpath(self.abspath(f))
460
kind = file_kind(fullpath)
462
# maybe something better?
463
raise BzrError('cannot add: not a regular file or directory: %s' % quotefn(f))
465
if kind != 'file' and kind != 'directory':
466
raise BzrError('cannot add: not a regular file or directory: %s' % quotefn(f))
469
file_id = gen_file_id(f)
470
inv.add_path(f, kind=kind, file_id=file_id)
472
mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
474
self._write_inventory(inv)
479
def print_file(self, file, revno):
237
raise NotImplementedError('set_root_id is abstract')
239
def print_file(self, file, revision_id):
480
240
"""Print `file` to stdout."""
483
tree = self.revision_tree(self.get_rev_id(revno))
484
# use inventory as it was in that revision
485
file_id = tree.inventory.path2id(file)
487
raise BzrError("%r is not present in revision %s" % (file, revno))
488
tree.print_file(file_id)
493
def remove(self, files, verbose=False):
494
"""Mark nominated files for removal from the inventory.
496
This does not remove their text. This does not run on
498
TODO: Refuse to remove modified files unless --force is given?
500
TODO: Do something useful with directories.
502
TODO: Should this remove the text or not? Tough call; not
503
removing may be useful and the user can just use use rm, and
504
is the opposite of add. Removing it is consistent with most
505
other tools. Maybe an option.
507
## TODO: Normalize names
508
## TODO: Remove nested loops; better scalability
509
if isinstance(files, basestring):
515
tree = self.working_tree()
518
# do this before any modifications
522
raise BzrError("cannot remove unversioned file %s" % quotefn(f))
523
mutter("remove inventory entry %s {%s}" % (quotefn(f), fid))
525
# having remove it, it must be either ignored or unknown
526
if tree.is_ignored(f):
530
show_status(new_status, inv[fid].kind, quotefn(f))
533
self._write_inventory(inv)
538
# FIXME: this doesn't need to be a branch method
539
def set_inventory(self, new_inventory_list):
540
from bzrlib.inventory import Inventory, InventoryEntry
541
inv = Inventory(self.get_root_id())
542
for path, file_id, parent, kind in new_inventory_list:
543
name = os.path.basename(path)
546
inv.add(InventoryEntry(file_id, name, kind, parent))
547
self._write_inventory(inv)
551
"""Return all unknown files.
553
These are files in the working directory that are not versioned or
554
control files or ignored.
556
>>> b = ScratchBranch(files=['foo', 'foo~'])
557
>>> list(b.unknowns())
560
>>> list(b.unknowns())
563
>>> list(b.unknowns())
566
return self.working_tree().unknowns()
241
raise NotImplementedError('print_file is abstract')
569
243
def append_revision(self, *revision_ids):
570
from bzrlib.atomicfile import AtomicFile
572
for revision_id in revision_ids:
573
mutter("add {%s} to revision-history" % revision_id)
575
rev_history = self.revision_history()
576
rev_history.extend(revision_ids)
578
f = AtomicFile(self.controlfilename('revision-history'))
580
for rev_id in rev_history:
587
def get_revision_xml_file(self, revision_id):
588
"""Return XML file object for revision object."""
589
if not revision_id or not isinstance(revision_id, basestring):
590
raise InvalidRevisionId(revision_id)
595
return self.revision_store[revision_id]
597
raise bzrlib.errors.NoSuchRevision(self, revision_id)
603
get_revision_xml = get_revision_xml_file
244
raise NotImplementedError('append_revision is abstract')
246
def set_revision_history(self, rev_history):
247
raise NotImplementedError('set_revision_history is abstract')
249
def has_revision(self, revision_id):
250
"""True if this branch has a copy of the revision.
252
This does not necessarily imply the revision is merge
253
or on the mainline."""
254
raise NotImplementedError('has_revision is abstract')
256
def get_revision_xml(self, revision_id):
257
raise NotImplementedError('get_revision_xml is abstract')
606
259
def get_revision(self, revision_id):
607
260
"""Return the Revision object for a named revision"""
608
xml_file = self.get_revision_xml_file(revision_id)
611
r = bzrlib.xml.serializer_v4.read_revision(xml_file)
612
except SyntaxError, e:
613
raise bzrlib.errors.BzrError('failed to unpack revision_xml',
617
assert r.revision_id == revision_id
261
raise NotImplementedError('get_revision is abstract')
621
263
def get_revision_delta(self, revno):
622
264
"""Return the delta for one revision.
1210
486
if revno < 1 or revno > self.revno():
1211
487
raise InvalidRevisionNumber(revno)
1216
class ScratchBranch(LocalBranch):
489
def sign_revision(self, revision_id, gpg_strategy):
490
raise NotImplementedError('sign_revision is abstract')
492
def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
493
raise NotImplementedError('store_revision_signature is abstract')
495
class BzrBranch(Branch):
496
"""A branch stored in the actual filesystem.
498
Note that it's "local" in the context of the filesystem; it doesn't
499
really matter if it's on an nfs/smb/afs/coda/... share, as long as
500
it's writable, and can be accessed via the normal filesystem API.
506
If _lock_mode is true, a positive count of the number of times the
510
Lock object from bzrlib.lock.
512
# We actually expect this class to be somewhat short-lived; part of its
513
# purpose is to try to isolate what bits of the branch logic are tied to
514
# filesystem access, so that in a later step, we can extricate them to
515
# a separarte ("storage") class.
519
_inventory_weave = None
520
_master_branch = None
521
# If set to False (by a plugin, etc) BzrBranch will not set the
522
# mode on created files or directories
523
_set_file_mode = True
526
# Map some sort of prefix into a namespace
527
# stuff like "revno:10", "revid:", etc.
528
# This should match a prefix with a function which accepts
529
REVISION_NAMESPACES = {}
531
def push_stores(self, branch_to):
532
"""See Branch.push_stores."""
533
if (self._branch_format != branch_to._branch_format
534
or self._branch_format != 4):
535
from bzrlib.fetch import greedy_fetch
536
mutter("falling back to fetch logic to push between %s(%s) and %s(%s)",
537
self, self._branch_format, branch_to, branch_to._branch_format)
538
greedy_fetch(to_branch=branch_to, from_branch=self,
539
revision=self.last_revision())
542
store_pairs = ((self.text_store, branch_to.text_store),
543
(self.inventory_store, branch_to.inventory_store),
544
(self.revision_store, branch_to.revision_store))
546
for from_store, to_store in store_pairs:
547
copy_all(from_store, to_store)
548
except UnlistableStore:
549
raise UnlistableBranch(from_store)
551
def __init__(self, transport, init=False,
552
relax_version_check=False):
553
"""Create new branch object at a particular location.
555
transport -- A Transport object, defining how to access files.
557
init -- If True, create new control files in a previously
558
unversioned directory. If False, the branch must already
561
relax_version_check -- If true, the usual check for the branch
562
version is not applied. This is intended only for
563
upgrade/recovery type use; it's not guaranteed that
564
all operations will work on old format branches.
566
In the test suite, creation of new trees is tested using the
567
`ScratchBranch` class.
569
assert isinstance(transport, Transport), \
570
"%r is not a Transport" % transport
571
self._transport = transport
574
self._check_format(relax_version_check)
577
def get_store(name, compressed=True, prefixed=False):
578
relpath = self._rel_controlfilename(unicode(name))
579
store = TextStore(self._transport.clone(relpath),
580
dir_mode=self._dir_mode,
581
file_mode=self._file_mode,
583
compressed=compressed)
586
def get_weave(name, prefixed=False):
587
relpath = self._rel_controlfilename(unicode(name))
588
ws = WeaveStore(self._transport.clone(relpath),
590
dir_mode=self._dir_mode,
591
file_mode=self._file_mode)
592
if self._transport.should_cache():
593
ws.enable_cache = True
596
if self._branch_format == 4:
597
self.inventory_store = get_store('inventory-store')
598
self.text_store = get_store('text-store')
599
self.revision_store = get_store('revision-store')
600
elif self._branch_format == 5:
601
self.control_weaves = get_weave(u'')
602
self.weave_store = get_weave(u'weaves')
603
self.revision_store = get_store(u'revision-store', compressed=False)
604
elif self._branch_format == 6:
605
self.control_weaves = get_weave(u'')
606
self.weave_store = get_weave(u'weaves', prefixed=True)
607
self.revision_store = get_store(u'revision-store', compressed=False,
609
self.revision_store.register_suffix('sig')
610
self._transaction = None
613
return '%s(%r)' % (self.__class__.__name__, self._transport.base)
618
if self._lock_mode or self._lock:
619
# XXX: This should show something every time, and be suitable for
620
# headless operation and embedding
621
warn("branch %r was not explicitly unlocked" % self)
624
# TODO: It might be best to do this somewhere else,
625
# but it is nice for a Branch object to automatically
626
# cache it's information.
627
# Alternatively, we could have the Transport objects cache requests
628
# See the earlier discussion about how major objects (like Branch)
629
# should never expect their __del__ function to run.
630
if hasattr(self, 'cache_root') and self.cache_root is not None:
632
shutil.rmtree(self.cache_root)
635
self.cache_root = None
639
return self._transport.base
642
base = property(_get_base, doc="The URL for the root of this branch.")
644
def _finish_transaction(self):
645
"""Exit the current transaction."""
646
if self._transaction is None:
647
raise errors.LockError('Branch %s is not in a transaction' %
649
transaction = self._transaction
650
self._transaction = None
653
def get_transaction(self):
654
"""See Branch.get_transaction."""
655
if self._transaction is None:
656
return transactions.PassThroughTransaction()
658
return self._transaction
660
def _set_transaction(self, new_transaction):
661
"""Set a new active transaction."""
662
if self._transaction is not None:
663
raise errors.LockError('Branch %s is in a transaction already.' %
665
self._transaction = new_transaction
667
def lock_write(self):
668
#mutter("lock write: %s (%s)", self, self._lock_count)
669
# TODO: Upgrade locking to support using a Transport,
670
# and potentially a remote locking protocol
672
if self._lock_mode != 'w':
673
raise LockError("can't upgrade to a write lock from %r" %
675
self._lock_count += 1
677
self._lock = self._transport.lock_write(
678
self._rel_controlfilename('branch-lock'))
679
self._lock_mode = 'w'
681
self._set_transaction(transactions.PassThroughTransaction())
684
#mutter("lock read: %s (%s)", self, self._lock_count)
686
assert self._lock_mode in ('r', 'w'), \
687
"invalid lock mode %r" % self._lock_mode
688
self._lock_count += 1
690
self._lock = self._transport.lock_read(
691
self._rel_controlfilename('branch-lock'))
692
self._lock_mode = 'r'
694
self._set_transaction(transactions.ReadOnlyTransaction())
695
# 5K may be excessive, but hey, its a knob.
696
self.get_transaction().set_cache_size(5000)
699
#mutter("unlock: %s (%s)", self, self._lock_count)
700
if not self._lock_mode:
701
raise LockError('branch %r is not locked' % (self))
703
if self._lock_count > 1:
704
self._lock_count -= 1
706
self._finish_transaction()
709
self._lock_mode = self._lock_count = None
710
# TODO: jam 20051230 Consider letting go of the master_branch
712
def abspath(self, name):
713
"""See Branch.abspath."""
714
return self._transport.abspath(name)
716
def _rel_controlfilename(self, file_or_path):
717
if not isinstance(file_or_path, basestring):
718
file_or_path = u'/'.join(file_or_path)
719
if file_or_path == '':
721
return bzrlib.transport.urlescape(bzrlib.BZRDIR + u'/' + file_or_path)
723
def controlfilename(self, file_or_path):
724
"""See Branch.controlfilename."""
725
return self._transport.abspath(self._rel_controlfilename(file_or_path))
727
def controlfile(self, file_or_path, mode='r'):
728
"""See Branch.controlfile."""
731
relpath = self._rel_controlfilename(file_or_path)
732
#TODO: codecs.open() buffers linewise, so it was overloaded with
733
# a much larger buffer, do we need to do the same for getreader/getwriter?
735
return self._transport.get(relpath)
737
raise BzrError("Branch.controlfile(mode='wb') is not supported, use put_controlfiles")
739
# XXX: Do we really want errors='replace'? Perhaps it should be
740
# an error, or at least reported, if there's incorrectly-encoded
741
# data inside a file.
742
# <https://launchpad.net/products/bzr/+bug/3823>
743
return codecs.getreader('utf-8')(self._transport.get(relpath), errors='replace')
745
raise BzrError("Branch.controlfile(mode='w') is not supported, use put_controlfiles")
747
raise BzrError("invalid controlfile mode %r" % mode)
749
def put_controlfile(self, path, f, encode=True):
750
"""See Branch.put_controlfile."""
751
self.put_controlfiles([(path, f)], encode=encode)
753
def put_controlfiles(self, files, encode=True):
754
"""See Branch.put_controlfiles."""
757
for path, f in files:
759
if isinstance(f, basestring):
760
f = f.encode('utf-8', 'replace')
762
f = codecs.getwriter('utf-8')(f, errors='replace')
763
path = self._rel_controlfilename(path)
764
ctrl_files.append((path, f))
765
self._transport.put_multi(ctrl_files, mode=self._file_mode)
767
def _find_modes(self, path=None):
768
"""Determine the appropriate modes for files and directories."""
771
path = self._rel_controlfilename('')
772
st = self._transport.stat(path)
773
except errors.TransportNotPossible:
774
self._dir_mode = 0755
775
self._file_mode = 0644
777
self._dir_mode = st.st_mode & 07777
778
# Remove the sticky and execute bits for files
779
self._file_mode = self._dir_mode & ~07111
780
if not self._set_dir_mode:
781
self._dir_mode = None
782
if not self._set_file_mode:
783
self._file_mode = None
785
def _make_control(self):
786
from bzrlib.inventory import Inventory
787
from bzrlib.weavefile import write_weave_v5
788
from bzrlib.weave import Weave
790
# Create an empty inventory
792
# if we want per-tree root ids then this is the place to set
793
# them; they're not needed for now and so ommitted for
795
bzrlib.xml5.serializer_v5.write_inventory(Inventory(), sio)
796
empty_inv = sio.getvalue()
798
bzrlib.weavefile.write_weave_v5(Weave(), sio)
799
empty_weave = sio.getvalue()
801
cfn = self._rel_controlfilename
802
# Since we don't have a .bzr directory, inherit the
803
# mode from the root directory
804
self._find_modes(u'.')
806
dirs = ['', 'revision-store', 'weaves']
808
"This is a Bazaar-NG control directory.\n"
809
"Do not change any files in this directory.\n"),
810
('branch-format', BZR_BRANCH_FORMAT_6),
811
('revision-history', ''),
814
('pending-merges', ''),
815
('inventory', empty_inv),
816
('inventory.weave', empty_weave),
817
('ancestry.weave', empty_weave)
819
self._transport.mkdir_multi([cfn(d) for d in dirs], mode=self._dir_mode)
820
self.put_controlfiles(files)
821
mutter('created control directory in ' + self._transport.base)
823
def _check_format(self, relax_version_check):
824
"""Check this branch format is supported.
826
The format level is stored, as an integer, in
827
self._branch_format for code that needs to check it later.
829
In the future, we might need different in-memory Branch
830
classes to support downlevel branches. But not yet.
833
fmt = self.controlfile('branch-format', 'r').read()
835
raise NotBranchError(path=self.base)
836
mutter("got branch format %r", fmt)
837
if fmt == BZR_BRANCH_FORMAT_6:
838
self._branch_format = 6
839
elif fmt == BZR_BRANCH_FORMAT_5:
840
self._branch_format = 5
841
elif fmt == BZR_BRANCH_FORMAT_4:
842
self._branch_format = 4
844
if (not relax_version_check
845
and self._branch_format not in (5, 6)):
846
raise errors.UnsupportedFormatError(
847
'sorry, branch format %r not supported' % fmt,
848
['use a different bzr version',
849
'or remove the .bzr directory'
850
' and "bzr init" again'])
853
def get_root_id(self):
854
"""See Branch.get_root_id."""
855
inv = self.get_inventory(self.last_revision())
856
return inv.root.file_id
859
def print_file(self, file, revision_id):
860
"""See Branch.print_file."""
861
tree = self.revision_tree(revision_id)
862
# use inventory as it was in that revision
863
file_id = tree.inventory.path2id(file)
866
revno = self.revision_id_to_revno(revision_id)
867
except errors.NoSuchRevision:
868
# TODO: This should not be BzrError,
869
# but NoSuchFile doesn't fit either
870
raise BzrError('%r is not present in revision %s'
871
% (file, revision_id))
873
raise BzrError('%r is not present in revision %s'
875
tree.print_file(file_id)
878
def append_revision(self, *revision_ids):
879
"""See Branch.append_revision."""
880
for revision_id in revision_ids:
881
mutter("add {%s} to revision-history" % revision_id)
882
rev_history = self.revision_history()
883
rev_history.extend(revision_ids)
884
self.set_revision_history(rev_history)
887
def set_revision_history(self, rev_history):
888
"""See Branch.set_revision_history."""
889
old_revision = self.last_revision()
890
new_revision = rev_history[-1]
892
# TODO: jam 20051230 This is actually just an integrity check
893
# This shouldn't be necessary, as other code should
894
# handle making sure this is correct
895
master_branch = self.get_master_branch()
897
master_history = master_branch.revision_history()
898
if rev_history != master_history[:len(rev_history)]:
899
mutter('Invalid revision history, bound branches should always be a subset of their master history')
900
mutter('Local: %s', rev_history)
901
mutter('Master: %s', master_history)
902
assert False, 'Invalid revision history'
904
self.put_controlfile('revision-history', '\n'.join(rev_history))
906
self.working_tree().set_last_revision(new_revision, old_revision)
907
except NoWorkingTree:
908
mutter('Unable to set_last_revision without a working tree.')
910
def has_revision(self, revision_id):
911
"""See Branch.has_revision."""
912
return (revision_id is None
913
or self.revision_store.has_id(revision_id))
916
def _get_revision_xml_file(self, revision_id):
917
if not revision_id or not isinstance(revision_id, basestring):
918
raise InvalidRevisionId(revision_id=revision_id, branch=self)
920
return self.revision_store.get(revision_id)
921
except (IndexError, KeyError):
922
raise bzrlib.errors.NoSuchRevision(self, revision_id)
924
def get_revision_xml(self, revision_id):
925
"""See Branch.get_revision_xml."""
926
return self._get_revision_xml_file(revision_id).read()
928
def get_revision(self, revision_id):
929
"""See Branch.get_revision."""
930
xml_file = self._get_revision_xml_file(revision_id)
933
r = bzrlib.xml5.serializer_v5.read_revision(xml_file)
934
except SyntaxError, e:
935
raise bzrlib.errors.BzrError('failed to unpack revision_xml',
939
assert r.revision_id == revision_id
942
def get_revision_sha1(self, revision_id):
943
"""See Branch.get_revision_sha1."""
944
# In the future, revision entries will be signed. At that
945
# point, it is probably best *not* to include the signature
946
# in the revision hash. Because that lets you re-sign
947
# the revision, (add signatures/remove signatures) and still
948
# have all hash pointers stay consistent.
949
# But for now, just hash the contents.
950
return bzrlib.osutils.sha_file(self.get_revision_xml_file(revision_id))
952
def get_ancestry(self, revision_id):
953
"""See Branch.get_ancestry."""
954
if revision_id is None:
956
w = self._get_inventory_weave()
957
return [None] + map(w.idx_to_name,
958
w.inclusions([w.lookup(revision_id)]))
960
def _get_inventory_weave(self):
961
return self.control_weaves.get_weave('inventory',
962
self.get_transaction())
964
def get_inventory(self, revision_id):
965
"""See Branch.get_inventory."""
966
xml = self.get_inventory_xml(revision_id)
967
return bzrlib.xml5.serializer_v5.read_inventory_from_string(xml)
969
def get_inventory_xml(self, revision_id):
970
"""See Branch.get_inventory_xml."""
972
assert isinstance(revision_id, basestring), type(revision_id)
973
iw = self._get_inventory_weave()
974
return iw.get_text(iw.lookup(revision_id))
976
raise bzrlib.errors.HistoryMissing(self, 'inventory', revision_id)
978
def get_inventory_sha1(self, revision_id):
979
"""See Branch.get_inventory_sha1."""
980
return self.get_revision(revision_id).inventory_sha1
982
def get_revision_inventory(self, revision_id):
983
"""See Branch.get_revision_inventory."""
984
# TODO: Unify this with get_inventory()
985
# bzr 0.0.6 and later imposes the constraint that the inventory_id
986
# must be the same as its revision, so this is trivial.
987
if revision_id == None:
988
# This does not make sense: if there is no revision,
989
# then it is the current tree inventory surely ?!
990
# and thus get_root_id() is something that looks at the last
991
# commit on the branch, and the get_root_id is an inventory check.
992
raise NotImplementedError
993
# return Inventory(self.get_root_id())
995
return self.get_inventory(revision_id)
998
def revision_history(self):
999
"""See Branch.revision_history."""
1000
transaction = self.get_transaction()
1001
history = transaction.map.find_revision_history()
1002
if history is not None:
1003
mutter("cache hit for revision-history in %s", self)
1004
return list(history)
1005
history = [l.rstrip('\r\n') for l in
1006
self.controlfile('revision-history', 'r').readlines()]
1007
transaction.map.add_revision_history(history)
1008
# this call is disabled because revision_history is
1009
# not really an object yet, and the transaction is for objects.
1010
# transaction.register_clean(history, precious=True)
1011
return list(history)
1013
def update_revisions(self, other, stop_revision=None):
1014
"""See Branch.update_revisions."""
1015
from bzrlib.fetch import greedy_fetch
1016
if stop_revision is None:
1017
stop_revision = other.last_revision()
1018
### Should this be checking is_ancestor instead of revision_history?
1019
if (stop_revision is not None and
1020
stop_revision in self.revision_history()):
1022
greedy_fetch(to_branch=self, from_branch=other,
1023
revision=stop_revision)
1024
pullable_revs = self.pullable_revisions(other, stop_revision)
1025
if len(pullable_revs) > 0:
1026
self.append_revision(*pullable_revs)
1028
def pullable_revisions(self, other, stop_revision):
1029
other_revno = other.revision_id_to_revno(stop_revision)
1031
return self.missing_revisions(other, other_revno)
1032
except DivergedBranches, e:
1034
pullable_revs = get_intervening_revisions(self.last_revision(),
1035
stop_revision, self)
1036
assert self.last_revision() not in pullable_revs
1037
return pullable_revs
1038
except bzrlib.errors.NotAncestor:
1039
if is_ancestor(self.last_revision(), stop_revision, self):
1044
def revision_tree(self, revision_id):
1045
"""See Branch.revision_tree."""
1046
# TODO: refactor this to use an existing revision object
1047
# so we don't need to read it in twice.
1048
if revision_id == None or revision_id == NULL_REVISION:
1051
inv = self.get_revision_inventory(revision_id)
1052
return RevisionTree(self, inv, revision_id)
1054
def basis_tree(self):
1055
"""See Branch.basis_tree."""
1057
revision_id = self.revision_history()[-1]
1058
xml = self.working_tree().read_basis_inventory(revision_id)
1059
inv = bzrlib.xml5.serializer_v5.read_inventory_from_string(xml)
1060
return RevisionTree(self, inv, revision_id)
1061
except (IndexError, NoSuchFile, NoWorkingTree), e:
1062
return self.revision_tree(self.last_revision())
1064
def working_tree(self):
1065
"""See Branch.working_tree."""
1066
from bzrlib.workingtree import WorkingTree
1067
if self._transport.base.find('://') != -1:
1068
raise NoWorkingTree(self.base)
1069
return WorkingTree(self.base, branch=self)
1072
def pull(self, source, overwrite=False):
1073
"""See Branch.pull."""
1074
# TODO: jam 20051230 This does work, in that 'bzr pull'
1075
# will update the master branch before updating the
1076
# local branch. However, 'source' can also already
1077
# be the master branch. Which means that we are
1078
# asking it to update from itself, before we continue.
1079
# This probably causes double downloads, etc.
1080
# So we probably want to put in an explicit check
1081
# of whether source is already the master branch.
1082
master_branch = self.get_master_branch()
1084
# TODO: jam 20051230 It would certainly be possible
1085
# to overwrite the master branch, I just feel
1086
# a little funny about doing it. This should be
1089
raise errors.OverwriteBoundBranch(self)
1090
# TODO: jam 20051230 Consider updating the working tree
1091
master_branch.pull(source)
1092
source = master_branch
1096
old_count = len(self.revision_history())
1098
self.update_revisions(source)
1099
except DivergedBranches:
1103
self.set_revision_history(source.revision_history())
1104
new_count = len(self.revision_history())
1105
return new_count - old_count
1109
def get_parent(self):
1110
"""See Branch.get_parent."""
1112
_locs = ['parent', 'pull', 'x-pull']
1115
return self.controlfile(l, 'r').read().strip('\n')
1120
def get_push_location(self):
1121
"""See Branch.get_push_location."""
1122
config = bzrlib.config.BranchConfig(self)
1123
push_loc = config.get_user_option('push_location')
1126
def set_push_location(self, location):
1127
"""See Branch.set_push_location."""
1128
config = bzrlib.config.LocationConfig(self.base)
1129
config.set_user_option('push_location', location)
1132
def set_parent(self, url):
1133
"""See Branch.set_parent."""
1134
# TODO: Maybe delete old location files?
1135
from bzrlib.atomicfile import AtomicFile
1136
f = AtomicFile(self.controlfilename('parent'))
1143
def tree_config(self):
1144
return TreeConfig(self)
1146
def sign_revision(self, revision_id, gpg_strategy):
1147
"""See Branch.sign_revision."""
1148
plaintext = Testament.from_revision(self, revision_id).as_short_text()
1149
self.store_revision_signature(gpg_strategy, plaintext, revision_id)
1152
def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
1153
"""See Branch.store_revision_signature."""
1154
self.revision_store.add(StringIO(gpg_strategy.sign(plaintext)),
1158
def get_bound_location(self):
1159
bound_path = self._rel_controlfilename('bound')
1161
f = self._transport.get(bound_path)
1165
return f.read().strip()
1168
def get_master_branch(self):
1169
"""Return the branch we are bound to.
1171
:return: Either a Branch, or None
1173
bound_loc = self.get_bound_location()
1175
self._master_branch = None
1177
if self._master_branch is None:
1179
self._master_branch = Branch.open(bound_loc)
1180
except (errors.NotBranchError, errors.ConnectionError), e:
1181
raise errors.BoundBranchConnectionFailure(
1183
return self._master_branch
1186
def set_bound_location(self, location):
1187
"""Set the target where this branch is bound to.
1189
:param location: URL to the target branch
1191
self._master_branch = None
1193
self.put_controlfile('bound', location+'\n')
1195
bound_path = self._rel_controlfilename('bound')
1197
self._transport.delete(bound_path)
1203
def bind(self, other):
1204
"""Bind the local branch the other branch.
1206
:param other: The branch to bind to
1209
# TODO: jam 20051230 According to the API tests, Branch should
1210
# avoid knowing about the working tree. However, since on
1211
# binding A pulls B and B pulls A even if we moved this
1212
# code into Working Tree, you get much more complicated
1213
# logic to handle where one of them has a working tree,
1214
# but the other one doesn't
1215
# And all we really end up doing is moving the try/except
1216
# into builtins.bind()
1217
# The other issue is that Working Tree should not have
1218
# a bind() member. Because working trees are not bound.
1219
# at some point in the future they may be checkouts,
1220
# which means they reference some other branch. But
1221
# only the branch itself is bound.
1222
# I started creating a Working Tree.bind() but realized
1223
# that was worse than having Branch.bind() try to
1224
# update its working tree.
1226
# TODO: jam 20051230 Consider checking if the target is bound
1227
# It is debatable whether you should be able to bind to
1228
# a branch which is itself bound.
1229
# Committing is obviously forbidden,
1230
# but binding itself may not be.
1231
# Since we *have* to check at commit time, we don't
1232
# *need* to check here
1235
self.working_tree().pull(other)
1236
except NoWorkingTree:
1239
# Since we have 'pulled' from the remote location,
1240
# now we should try to pull in the opposite direction
1241
# in case the local tree has more revisions than the
1243
# There may be a different check you could do here
1244
# rather than actually trying to install revisions remotely.
1245
# TODO: capture an exception which indicates the remote branch
1247
# If it is up-to-date, this probably should not be a failure
1249
# We used to update the working tree here.
1250
# However, it was the only place. 'bzr pull', and 'bzr commit'
1251
# Would not update the remote working tree.
1252
# So for consistency, we are only updating the branch information
1255
# Make sure the revision histories are now identical
1256
other_rh = other.revision_history()
1257
self.set_revision_history(other_rh)
1259
# Both branches should now be at the same revision
1260
self.set_bound_location(other.base)
1264
"""If bound, unbind"""
1265
return self.set_bound_location(None)
1268
class ScratchBranch(BzrBranch):
1217
1269
"""Special test class: a branch that cleans up after itself.
1219
1271
>>> b = ScratchBranch()
1220
1272
>>> isdir(b.base)
1222
1274
>>> bd = b.base
1275
>>> b._transport.__del__()
1227
def __init__(self, files=[], dirs=[], base=None):
1280
def __init__(self, files=[], dirs=[], transport=None):
1228
1281
"""Make a test branch.
1230
1283
This creates a temporary directory and runs init-tree in it.
1232
1285
If any files are listed, they are created in the working copy.
1234
from tempfile import mkdtemp
1239
LocalBranch.__init__(self, base, init=init)
1287
if transport is None:
1288
transport = bzrlib.transport.local.ScratchTransport()
1289
super(ScratchBranch, self).__init__(transport, init=True)
1291
super(ScratchBranch, self).__init__(transport)
1241
os.mkdir(self.abspath(d))
1294
self._transport.mkdir(d)
1243
1296
for f in files:
1244
file(os.path.join(self.base, f), 'w').write('content of %s' % f)
1297
self._transport.put(f, 'content of %s' % f)
1247
1300
def clone(self):
1249
1302
>>> orig = ScratchBranch(files=["file1", "file2"])
1250
1303
>>> clone = orig.clone()
1251
>>> os.path.samefile(orig.base, clone.base)
1304
>>> if os.name != 'nt':
1305
... os.path.samefile(orig.base, clone.base)
1307
... orig.base == clone.base
1253
>>> os.path.isfile(os.path.join(clone.base, "file1"))
1310
>>> os.path.isfile(pathjoin(clone.base, "file1"))
1256
1313
from shutil import copytree
1257
from tempfile import mkdtemp
1314
from bzrlib.osutils import mkdtemp
1258
1315
base = mkdtemp()
1260
1317
copytree(self.base, base, symlinks=True)
1261
return ScratchBranch(base=base)
1269
"""Destroy the test branch, removing the scratch directory."""
1270
from shutil import rmtree
1273
mutter("delete ScratchBranch %s" % self.base)
1276
# Work around for shutil.rmtree failing on Windows when
1277
# readonly files are encountered
1278
mutter("hit exception in destroying ScratchBranch: %s" % e)
1279
for root, dirs, files in os.walk(self.base, topdown=False):
1281
os.chmod(os.path.join(root, name), 0700)
1318
return ScratchBranch(
1319
transport=bzrlib.transport.local.ScratchTransport(base))
1287
1322
######################################################################