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
21
from warnings import warn
22
from cStringIO import StringIO
26
from bzrlib.inventory import InventoryEntry
27
import bzrlib.inventory as inventory
28
from bzrlib.trace import mutter, note
29
from bzrlib.osutils import (isdir, quotefn, compact_date, rand_bytes,
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)
37
from bzrlib.textui import show_status
38
from bzrlib.revision import Revision, is_ancestor, get_intervening_revisions
40
from bzrlib.delta import compare_trees
41
from bzrlib.tree import EmptyTree, RevisionTree
42
from bzrlib.inventory import Inventory
43
from bzrlib.store import copy_all
44
from bzrlib.store.compressed_text import CompressedTextStore
45
from bzrlib.store.text import TextStore
46
from bzrlib.store.weave import WeaveStore
47
from bzrlib.testament import Testament
48
import bzrlib.transactions as transactions
49
from bzrlib.transport import Transport, get_transport
54
BZR_BRANCH_FORMAT_4 = "Bazaar-NG branch, format 0.0.4\n"
55
BZR_BRANCH_FORMAT_5 = "Bazaar-NG branch, format 5\n"
56
BZR_BRANCH_FORMAT_6 = "Bazaar-NG branch, format 6\n"
57
## TODO: Maybe include checks for common corruption of newlines, etc?
60
# TODO: Some operations like log might retrieve the same revisions
61
# repeatedly to calculate deltas. We could perhaps have a weakref
62
# cache in memory to make this faster. In general anything can be
63
# cached in memory between lock and unlock operations.
65
def find_branch(*ignored, **ignored_too):
66
# XXX: leave this here for about one release, then remove it
67
raise NotImplementedError('find_branch() is not supported anymore, '
68
'please use one of the new branch constructors')
70
######################################################################
74
"""Branch holding a history of revisions.
77
Base directory/url of the branch.
81
def __init__(self, *ignored, **ignored_too):
82
raise NotImplementedError('The Branch class is abstract')
85
def open_downlevel(base):
86
"""Open a branch which may be of an old format.
88
Only local branches are supported."""
89
return _Branch(get_transport(base), relax_version_check=True)
93
"""Open an existing branch, rooted at 'base' (url)"""
94
t = get_transport(base)
95
mutter("trying to open %r with transport %r", base, t)
99
def open_containing(url):
100
"""Open an existing branch which contains url.
102
This probes for a branch at url, and searches upwards from there.
104
Basically we keep looking up until we find the control directory or
105
run into the root. If there isn't one, raises NotBranchError.
107
t = get_transport(url)
111
except NotBranchError:
113
new_t = t.clone('..')
114
if new_t.base == t.base:
115
# reached the root, whatever that may be
116
raise NotBranchError('%s is not in a branch' % url)
120
def initialize(base):
121
"""Create a new branch, rooted at 'base' (url)"""
122
t = get_transport(base)
123
return _Branch(t, init=True)
125
def setup_caching(self, cache_root):
126
"""Subclasses that care about caching should override this, and set
127
up cached stores located under cache_root.
129
self.cache_root = cache_root
132
class _Branch(Branch):
133
"""A branch stored in the actual filesystem.
135
Note that it's "local" in the context of the filesystem; it doesn't
136
really matter if it's on an nfs/smb/afs/coda/... share, as long as
137
it's writable, and can be accessed via the normal filesystem API.
143
If _lock_mode is true, a positive count of the number of times the
147
Lock object from bzrlib.lock.
149
# We actually expect this class to be somewhat short-lived; part of its
150
# purpose is to try to isolate what bits of the branch logic are tied to
151
# filesystem access, so that in a later step, we can extricate them to
152
# a separarte ("storage") class.
156
_inventory_weave = None
158
# Map some sort of prefix into a namespace
159
# stuff like "revno:10", "revid:", etc.
160
# This should match a prefix with a function which accepts
161
REVISION_NAMESPACES = {}
163
def push_stores(self, branch_to):
164
"""Copy the content of this branches store to branch_to."""
165
if (self._branch_format != branch_to._branch_format
166
or self._branch_format != 4):
167
from bzrlib.fetch import greedy_fetch
168
mutter("falling back to fetch logic to push between %s(%s) and %s(%s)",
169
self, self._branch_format, branch_to, branch_to._branch_format)
170
greedy_fetch(to_branch=branch_to, from_branch=self,
171
revision=self.last_revision())
174
store_pairs = ((self.text_store, branch_to.text_store),
175
(self.inventory_store, branch_to.inventory_store),
176
(self.revision_store, branch_to.revision_store))
178
for from_store, to_store in store_pairs:
179
copy_all(from_store, to_store)
180
except UnlistableStore:
181
raise UnlistableBranch(from_store)
183
def __init__(self, transport, init=False,
184
relax_version_check=False):
185
"""Create new branch object at a particular location.
187
transport -- A Transport object, defining how to access files.
188
(If a string, transport.transport() will be used to
189
create a Transport object)
191
init -- If True, create new control files in a previously
192
unversioned directory. If False, the branch must already
195
relax_version_check -- If true, the usual check for the branch
196
version is not applied. This is intended only for
197
upgrade/recovery type use; it's not guaranteed that
198
all operations will work on old format branches.
200
In the test suite, creation of new trees is tested using the
201
`ScratchBranch` class.
203
assert isinstance(transport, Transport), \
204
"%r is not a Transport" % transport
205
self._transport = transport
208
self._check_format(relax_version_check)
210
def get_store(name, compressed=True, prefixed=False):
211
# FIXME: This approach of assuming stores are all entirely compressed
212
# or entirely uncompressed is tidy, but breaks upgrade from
213
# some existing branches where there's a mixture; we probably
214
# still want the option to look for both.
215
relpath = self._rel_controlfilename(name)
217
store = CompressedTextStore(self._transport.clone(relpath),
220
store = TextStore(self._transport.clone(relpath),
222
#if self._transport.should_cache():
223
# cache_path = os.path.join(self.cache_root, name)
224
# os.mkdir(cache_path)
225
# store = bzrlib.store.CachedStore(store, cache_path)
227
def get_weave(name, prefixed=False):
228
relpath = self._rel_controlfilename(name)
229
ws = WeaveStore(self._transport.clone(relpath), prefixed=prefixed)
230
if self._transport.should_cache():
231
ws.enable_cache = True
234
if self._branch_format == 4:
235
self.inventory_store = get_store('inventory-store')
236
self.text_store = get_store('text-store')
237
self.revision_store = get_store('revision-store')
238
elif self._branch_format == 5:
239
self.control_weaves = get_weave([])
240
self.weave_store = get_weave('weaves')
241
self.revision_store = get_store('revision-store', compressed=False)
242
elif self._branch_format == 6:
243
self.control_weaves = get_weave([])
244
self.weave_store = get_weave('weaves', prefixed=True)
245
self.revision_store = get_store('revision-store', compressed=False,
247
self.revision_store.register_suffix('sig')
248
self._transaction = None
251
return '%s(%r)' % (self.__class__.__name__, self._transport.base)
258
if self._lock_mode or self._lock:
259
# XXX: This should show something every time, and be suitable for
260
# headless operation and embedding
261
warn("branch %r was not explicitly unlocked" % self)
264
# TODO: It might be best to do this somewhere else,
265
# but it is nice for a Branch object to automatically
266
# cache it's information.
267
# Alternatively, we could have the Transport objects cache requests
268
# See the earlier discussion about how major objects (like Branch)
269
# should never expect their __del__ function to run.
270
if hasattr(self, 'cache_root') and self.cache_root is not None:
273
shutil.rmtree(self.cache_root)
276
self.cache_root = None
280
return self._transport.base
283
base = property(_get_base, doc="The URL for the root of this branch.")
285
def _finish_transaction(self):
286
"""Exit the current transaction."""
287
if self._transaction is None:
288
raise errors.LockError('Branch %s is not in a transaction' %
290
transaction = self._transaction
291
self._transaction = None
294
def get_transaction(self):
295
"""Return the current active transaction.
297
If no transaction is active, this returns a passthrough object
298
for which all data is immedaitely flushed and no caching happens.
300
if self._transaction is None:
301
return transactions.PassThroughTransaction()
303
return self._transaction
305
def _set_transaction(self, new_transaction):
306
"""Set a new active transaction."""
307
if self._transaction is not None:
308
raise errors.LockError('Branch %s is in a transaction already.' %
310
self._transaction = new_transaction
312
def lock_write(self):
313
mutter("lock write: %s (%s)", self, self._lock_count)
314
# TODO: Upgrade locking to support using a Transport,
315
# and potentially a remote locking protocol
317
if self._lock_mode != 'w':
318
raise LockError("can't upgrade to a write lock from %r" %
320
self._lock_count += 1
322
self._lock = self._transport.lock_write(
323
self._rel_controlfilename('branch-lock'))
324
self._lock_mode = 'w'
326
self._set_transaction(transactions.PassThroughTransaction())
329
mutter("lock read: %s (%s)", self, self._lock_count)
331
assert self._lock_mode in ('r', 'w'), \
332
"invalid lock mode %r" % self._lock_mode
333
self._lock_count += 1
335
self._lock = self._transport.lock_read(
336
self._rel_controlfilename('branch-lock'))
337
self._lock_mode = 'r'
339
self._set_transaction(transactions.ReadOnlyTransaction())
340
# 5K may be excessive, but hey, its a knob.
341
self.get_transaction().set_cache_size(5000)
344
mutter("unlock: %s (%s)", self, self._lock_count)
345
if not self._lock_mode:
346
raise LockError('branch %r is not locked' % (self))
348
if self._lock_count > 1:
349
self._lock_count -= 1
351
self._finish_transaction()
354
self._lock_mode = self._lock_count = None
356
def abspath(self, name):
357
"""Return absolute filename for something in the branch
359
XXX: Robert Collins 20051017 what is this used for? why is it a branch
360
method and not a tree method.
362
return self._transport.abspath(name)
364
def _rel_controlfilename(self, file_or_path):
365
if isinstance(file_or_path, basestring):
366
file_or_path = [file_or_path]
367
return [bzrlib.BZRDIR] + file_or_path
369
def controlfilename(self, file_or_path):
370
"""Return location relative to branch."""
371
return self._transport.abspath(self._rel_controlfilename(file_or_path))
374
def controlfile(self, file_or_path, mode='r'):
375
"""Open a control file for this branch.
377
There are two classes of file in the control directory: text
378
and binary. binary files are untranslated byte streams. Text
379
control files are stored with Unix newlines and in UTF-8, even
380
if the platform or locale defaults are different.
382
Controlfiles should almost never be opened in write mode but
383
rather should be atomically copied and replaced using atomicfile.
387
relpath = self._rel_controlfilename(file_or_path)
388
#TODO: codecs.open() buffers linewise, so it was overloaded with
389
# a much larger buffer, do we need to do the same for getreader/getwriter?
391
return self._transport.get(relpath)
393
raise BzrError("Branch.controlfile(mode='wb') is not supported, use put_controlfiles")
395
return codecs.getreader('utf-8')(self._transport.get(relpath), errors='replace')
397
raise BzrError("Branch.controlfile(mode='w') is not supported, use put_controlfiles")
399
raise BzrError("invalid controlfile mode %r" % mode)
401
def put_controlfile(self, path, f, encode=True):
402
"""Write an entry as a controlfile.
404
:param path: The path to put the file, relative to the .bzr control
406
:param f: A file-like or string object whose contents should be copied.
407
:param encode: If true, encode the contents as utf-8
409
self.put_controlfiles([(path, f)], encode=encode)
411
def put_controlfiles(self, files, encode=True):
412
"""Write several entries as controlfiles.
414
:param files: A list of [(path, file)] pairs, where the path is the directory
415
underneath the bzr control directory
416
:param encode: If true, encode the contents as utf-8
420
for path, f in files:
422
if isinstance(f, basestring):
423
f = f.encode('utf-8', 'replace')
425
f = codecs.getwriter('utf-8')(f, errors='replace')
426
path = self._rel_controlfilename(path)
427
ctrl_files.append((path, f))
428
self._transport.put_multi(ctrl_files)
430
def _make_control(self):
431
from bzrlib.inventory import Inventory
432
from bzrlib.weavefile import write_weave_v5
433
from bzrlib.weave import Weave
435
# Create an empty inventory
437
# if we want per-tree root ids then this is the place to set
438
# them; they're not needed for now and so ommitted for
440
bzrlib.xml5.serializer_v5.write_inventory(Inventory(), sio)
441
empty_inv = sio.getvalue()
443
bzrlib.weavefile.write_weave_v5(Weave(), sio)
444
empty_weave = sio.getvalue()
446
dirs = [[], 'revision-store', 'weaves']
448
"This is a Bazaar-NG control directory.\n"
449
"Do not change any files in this directory.\n"),
450
('branch-format', BZR_BRANCH_FORMAT_6),
451
('revision-history', ''),
454
('pending-merges', ''),
455
('inventory', empty_inv),
456
('inventory.weave', empty_weave),
457
('ancestry.weave', empty_weave)
459
cfn = self._rel_controlfilename
460
self._transport.mkdir_multi([cfn(d) for d in dirs])
461
self.put_controlfiles(files)
462
mutter('created control directory in ' + self._transport.base)
464
def _check_format(self, relax_version_check):
465
"""Check this branch format is supported.
467
The format level is stored, as an integer, in
468
self._branch_format for code that needs to check it later.
470
In the future, we might need different in-memory Branch
471
classes to support downlevel branches. But not yet.
474
fmt = self.controlfile('branch-format', 'r').read()
476
raise NotBranchError(self.base)
477
mutter("got branch format %r", fmt)
478
if fmt == BZR_BRANCH_FORMAT_6:
479
self._branch_format = 6
480
elif fmt == BZR_BRANCH_FORMAT_5:
481
self._branch_format = 5
482
elif fmt == BZR_BRANCH_FORMAT_4:
483
self._branch_format = 4
485
if (not relax_version_check
486
and self._branch_format not in (5, 6)):
487
raise errors.UnsupportedFormatError(
488
'sorry, branch format %r not supported' % fmt,
489
['use a different bzr version',
490
'or remove the .bzr directory'
491
' and "bzr init" again'])
493
def get_root_id(self):
494
"""Return the id of this branches root"""
495
inv = self.read_working_inventory()
496
return inv.root.file_id
498
def set_root_id(self, file_id):
499
inv = self.read_working_inventory()
500
orig_root_id = inv.root.file_id
501
del inv._byid[inv.root.file_id]
502
inv.root.file_id = file_id
503
inv._byid[inv.root.file_id] = inv.root
506
if entry.parent_id in (None, orig_root_id):
507
entry.parent_id = inv.root.file_id
508
self._write_inventory(inv)
510
def read_working_inventory(self):
511
"""Read the working inventory."""
514
# ElementTree does its own conversion from UTF-8, so open in
516
f = self.controlfile('inventory', 'rb')
517
return bzrlib.xml5.serializer_v5.read_inventory(f)
522
def _write_inventory(self, inv):
523
"""Update the working inventory.
525
That is to say, the inventory describing changes underway, that
526
will be committed to the next revision.
528
from cStringIO import StringIO
532
bzrlib.xml5.serializer_v5.write_inventory(inv, sio)
534
# Transport handles atomicity
535
self.put_controlfile('inventory', sio)
539
mutter('wrote working inventory')
541
inventory = property(read_working_inventory, _write_inventory, None,
542
"""Inventory for the working copy.""")
544
def add(self, files, ids=None):
545
"""Make files versioned.
547
Note that the command line normally calls smart_add instead,
548
which can automatically recurse.
550
This puts the files in the Added state, so that they will be
551
recorded by the next commit.
554
List of paths to add, relative to the base of the tree.
557
If set, use these instead of automatically generated ids.
558
Must be the same length as the list of files, but may
559
contain None for ids that are to be autogenerated.
561
TODO: Perhaps have an option to add the ids even if the files do
564
TODO: Perhaps yield the ids and paths as they're added.
566
# TODO: Re-adding a file that is removed in the working copy
567
# should probably put it back with the previous ID.
568
if isinstance(files, basestring):
569
assert(ids is None or isinstance(ids, basestring))
575
ids = [None] * len(files)
577
assert(len(ids) == len(files))
581
inv = self.read_working_inventory()
582
for f,file_id in zip(files, ids):
583
if is_control_file(f):
584
raise BzrError("cannot add control file %s" % quotefn(f))
589
raise BzrError("cannot add top-level %r" % f)
591
fullpath = os.path.normpath(self.abspath(f))
594
kind = file_kind(fullpath)
596
# maybe something better?
597
raise BzrError('cannot add: not a regular file, symlink or directory: %s' % quotefn(f))
599
if not InventoryEntry.versionable_kind(kind):
600
raise BzrError('cannot add: not a versionable file ('
601
'i.e. regular file, symlink or directory): %s' % quotefn(f))
604
file_id = gen_file_id(f)
605
inv.add_path(f, kind=kind, file_id=file_id)
607
mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
609
self._write_inventory(inv)
614
def print_file(self, file, revno):
615
"""Print `file` to stdout."""
618
tree = self.revision_tree(self.get_rev_id(revno))
619
# use inventory as it was in that revision
620
file_id = tree.inventory.path2id(file)
622
raise BzrError("%r is not present in revision %s" % (file, revno))
623
tree.print_file(file_id)
628
def remove(self, files, verbose=False):
629
"""Mark nominated files for removal from the inventory.
631
This does not remove their text. This does not run on
633
TODO: Refuse to remove modified files unless --force is given?
635
TODO: Do something useful with directories.
637
TODO: Should this remove the text or not? Tough call; not
638
removing may be useful and the user can just use use rm, and
639
is the opposite of add. Removing it is consistent with most
640
other tools. Maybe an option.
642
## TODO: Normalize names
643
## TODO: Remove nested loops; better scalability
644
if isinstance(files, basestring):
650
tree = self.working_tree()
653
# do this before any modifications
657
raise BzrError("cannot remove unversioned file %s" % quotefn(f))
658
mutter("remove inventory entry %s {%s}" % (quotefn(f), fid))
660
# having remove it, it must be either ignored or unknown
661
if tree.is_ignored(f):
665
show_status(new_status, inv[fid].kind, quotefn(f))
668
self._write_inventory(inv)
672
# FIXME: this doesn't need to be a branch method
673
def set_inventory(self, new_inventory_list):
674
from bzrlib.inventory import Inventory, InventoryEntry
675
inv = Inventory(self.get_root_id())
676
for path, file_id, parent, kind in new_inventory_list:
677
name = os.path.basename(path)
680
# fixme, there should be a factory function inv,add_??
681
if kind == 'directory':
682
inv.add(inventory.InventoryDirectory(file_id, name, parent))
684
inv.add(inventory.InventoryFile(file_id, name, parent))
685
elif kind == 'symlink':
686
inv.add(inventory.InventoryLink(file_id, name, parent))
688
raise BzrError("unknown kind %r" % kind)
689
self._write_inventory(inv)
692
"""Return all unknown files.
694
These are files in the working directory that are not versioned or
695
control files or ignored.
697
>>> b = ScratchBranch(files=['foo', 'foo~'])
698
>>> list(b.unknowns())
701
>>> list(b.unknowns())
704
>>> list(b.unknowns())
707
return self.working_tree().unknowns()
710
def append_revision(self, *revision_ids):
711
for revision_id in revision_ids:
712
mutter("add {%s} to revision-history" % revision_id)
715
rev_history = self.revision_history()
716
rev_history.extend(revision_ids)
717
self.put_controlfile('revision-history', '\n'.join(rev_history))
721
def has_revision(self, revision_id):
722
"""True if this branch has a copy of the revision.
724
This does not necessarily imply the revision is merge
725
or on the mainline."""
726
return (revision_id is None
727
or self.revision_store.has_id(revision_id))
729
def get_revision_xml_file(self, revision_id):
730
"""Return XML file object for revision object."""
731
if not revision_id or not isinstance(revision_id, basestring):
732
raise InvalidRevisionId(revision_id)
737
return self.revision_store.get(revision_id)
738
except (IndexError, KeyError):
739
raise bzrlib.errors.NoSuchRevision(self, revision_id)
744
get_revision_xml = get_revision_xml_file
746
def get_revision_xml(self, revision_id):
747
return self.get_revision_xml_file(revision_id).read()
750
def get_revision(self, revision_id):
751
"""Return the Revision object for a named revision"""
752
xml_file = self.get_revision_xml_file(revision_id)
755
r = bzrlib.xml5.serializer_v5.read_revision(xml_file)
756
except SyntaxError, e:
757
raise bzrlib.errors.BzrError('failed to unpack revision_xml',
761
assert r.revision_id == revision_id
764
def get_revision_delta(self, revno):
765
"""Return the delta for one revision.
767
The delta is relative to its mainline predecessor, or the
768
empty tree for revision 1.
770
assert isinstance(revno, int)
771
rh = self.revision_history()
772
if not (1 <= revno <= len(rh)):
773
raise InvalidRevisionNumber(revno)
775
# revno is 1-based; list is 0-based
777
new_tree = self.revision_tree(rh[revno-1])
779
old_tree = EmptyTree()
781
old_tree = self.revision_tree(rh[revno-2])
783
return compare_trees(old_tree, new_tree)
785
def get_revision_sha1(self, revision_id):
786
"""Hash the stored value of a revision, and return it."""
787
# In the future, revision entries will be signed. At that
788
# point, it is probably best *not* to include the signature
789
# in the revision hash. Because that lets you re-sign
790
# the revision, (add signatures/remove signatures) and still
791
# have all hash pointers stay consistent.
792
# But for now, just hash the contents.
793
return bzrlib.osutils.sha_file(self.get_revision_xml_file(revision_id))
795
def get_ancestry(self, revision_id):
796
"""Return a list of revision-ids integrated by a revision.
798
This currently returns a list, but the ordering is not guaranteed:
801
if revision_id is None:
803
w = self.get_inventory_weave()
804
return [None] + map(w.idx_to_name,
805
w.inclusions([w.lookup(revision_id)]))
807
def get_inventory_weave(self):
808
return self.control_weaves.get_weave('inventory',
809
self.get_transaction())
811
def get_inventory(self, revision_id):
812
"""Get Inventory object by hash."""
813
xml = self.get_inventory_xml(revision_id)
814
return bzrlib.xml5.serializer_v5.read_inventory_from_string(xml)
816
def get_inventory_xml(self, revision_id):
817
"""Get inventory XML as a file object."""
819
assert isinstance(revision_id, basestring), type(revision_id)
820
iw = self.get_inventory_weave()
821
return iw.get_text(iw.lookup(revision_id))
823
raise bzrlib.errors.HistoryMissing(self, 'inventory', revision_id)
825
def get_inventory_sha1(self, revision_id):
826
"""Return the sha1 hash of the inventory entry
828
return self.get_revision(revision_id).inventory_sha1
830
def get_revision_inventory(self, revision_id):
831
"""Return inventory of a past revision."""
832
# TODO: Unify this with get_inventory()
833
# bzr 0.0.6 and later imposes the constraint that the inventory_id
834
# must be the same as its revision, so this is trivial.
835
if revision_id == None:
836
return Inventory(self.get_root_id())
838
return self.get_inventory(revision_id)
840
def revision_history(self):
841
"""Return sequence of revision hashes on to this branch."""
844
transaction = self.get_transaction()
845
history = transaction.map.find_revision_history()
846
if history is not None:
847
mutter("cache hit for revision-history in %s", self)
849
history = [l.rstrip('\r\n') for l in
850
self.controlfile('revision-history', 'r').readlines()]
851
transaction.map.add_revision_history(history)
852
# this call is disabled because revision_history is
853
# not really an object yet, and the transaction is for objects.
854
# transaction.register_clean(history, precious=True)
860
"""Return current revision number for this branch.
862
That is equivalent to the number of revisions committed to
865
return len(self.revision_history())
868
def last_revision(self):
869
"""Return last patch hash, or None if no history.
871
ph = self.revision_history()
878
def missing_revisions(self, other, stop_revision=None, diverged_ok=False):
879
"""Return a list of new revisions that would perfectly fit.
881
If self and other have not diverged, return a list of the revisions
882
present in other, but missing from self.
884
>>> from bzrlib.commit import commit
885
>>> bzrlib.trace.silent = True
886
>>> br1 = ScratchBranch()
887
>>> br2 = ScratchBranch()
888
>>> br1.missing_revisions(br2)
890
>>> commit(br2, "lala!", rev_id="REVISION-ID-1")
891
>>> br1.missing_revisions(br2)
893
>>> br2.missing_revisions(br1)
895
>>> commit(br1, "lala!", rev_id="REVISION-ID-1")
896
>>> br1.missing_revisions(br2)
898
>>> commit(br2, "lala!", rev_id="REVISION-ID-2A")
899
>>> br1.missing_revisions(br2)
901
>>> commit(br1, "lala!", rev_id="REVISION-ID-2B")
902
>>> br1.missing_revisions(br2)
903
Traceback (most recent call last):
904
DivergedBranches: These branches have diverged.
906
self_history = self.revision_history()
907
self_len = len(self_history)
908
other_history = other.revision_history()
909
other_len = len(other_history)
910
common_index = min(self_len, other_len) -1
911
if common_index >= 0 and \
912
self_history[common_index] != other_history[common_index]:
913
raise DivergedBranches(self, other)
915
if stop_revision is None:
916
stop_revision = other_len
918
assert isinstance(stop_revision, int)
919
if stop_revision > other_len:
920
raise bzrlib.errors.NoSuchRevision(self, stop_revision)
921
return other_history[self_len:stop_revision]
923
def update_revisions(self, other, stop_revision=None):
924
"""Pull in new perfect-fit revisions."""
925
# FIXME: If the branches have diverged, but the latest
926
# revision in this branch is completely merged into the other,
927
# then we should still be able to pull.
928
from bzrlib.fetch import greedy_fetch
929
if stop_revision is None:
930
stop_revision = other.last_revision()
931
### Should this be checking is_ancestor instead of revision_history?
932
if (stop_revision is not None and
933
stop_revision in self.revision_history()):
935
greedy_fetch(to_branch=self, from_branch=other,
936
revision=stop_revision)
937
pullable_revs = self.pullable_revisions(other, stop_revision)
938
if len(pullable_revs) > 0:
939
self.append_revision(*pullable_revs)
941
def pullable_revisions(self, other, stop_revision):
942
other_revno = other.revision_id_to_revno(stop_revision)
944
return self.missing_revisions(other, other_revno)
945
except DivergedBranches, e:
947
pullable_revs = get_intervening_revisions(self.last_revision(),
949
assert self.last_revision() not in pullable_revs
951
except bzrlib.errors.NotAncestor:
952
if is_ancestor(self.last_revision(), stop_revision, self):
957
def commit(self, *args, **kw):
958
from bzrlib.commit import Commit
959
Commit().commit(self, *args, **kw)
961
def revision_id_to_revno(self, revision_id):
962
"""Given a revision id, return its revno"""
963
if revision_id is None:
965
history = self.revision_history()
967
return history.index(revision_id) + 1
969
raise bzrlib.errors.NoSuchRevision(self, revision_id)
971
def get_rev_id(self, revno, history=None):
972
"""Find the revision id of the specified revno."""
976
history = self.revision_history()
977
elif revno <= 0 or revno > len(history):
978
raise bzrlib.errors.NoSuchRevision(self, revno)
979
return history[revno - 1]
981
def revision_tree(self, revision_id):
982
"""Return Tree for a revision on this branch.
984
`revision_id` may be None for the null revision, in which case
985
an `EmptyTree` is returned."""
986
# TODO: refactor this to use an existing revision object
987
# so we don't need to read it in twice.
988
if revision_id == None:
991
inv = self.get_revision_inventory(revision_id)
992
return RevisionTree(self.weave_store, inv, revision_id)
994
def working_tree(self):
995
"""Return a `Tree` for the working copy."""
996
from bzrlib.workingtree import WorkingTree
997
# TODO: In the future, WorkingTree should utilize Transport
998
# RobertCollins 20051003 - I don't think it should - working trees are
999
# much more complex to keep consistent than our careful .bzr subset.
1000
# instead, we should say that working trees are local only, and optimise
1002
return WorkingTree(self.base, branch=self)
1005
def basis_tree(self):
1006
"""Return `Tree` object for last revision.
1008
If there are no revisions yet, return an `EmptyTree`.
1010
return self.revision_tree(self.last_revision())
1013
def rename_one(self, from_rel, to_rel):
1016
This can change the directory or the filename or both.
1020
tree = self.working_tree()
1021
inv = tree.inventory
1022
if not tree.has_filename(from_rel):
1023
raise BzrError("can't rename: old working file %r does not exist" % from_rel)
1024
if tree.has_filename(to_rel):
1025
raise BzrError("can't rename: new working file %r already exists" % to_rel)
1027
file_id = inv.path2id(from_rel)
1029
raise BzrError("can't rename: old name %r is not versioned" % from_rel)
1031
if inv.path2id(to_rel):
1032
raise BzrError("can't rename: new name %r is already versioned" % to_rel)
1034
to_dir, to_tail = os.path.split(to_rel)
1035
to_dir_id = inv.path2id(to_dir)
1036
if to_dir_id == None and to_dir != '':
1037
raise BzrError("can't determine destination directory id for %r" % to_dir)
1039
mutter("rename_one:")
1040
mutter(" file_id {%s}" % file_id)
1041
mutter(" from_rel %r" % from_rel)
1042
mutter(" to_rel %r" % to_rel)
1043
mutter(" to_dir %r" % to_dir)
1044
mutter(" to_dir_id {%s}" % to_dir_id)
1046
inv.rename(file_id, to_dir_id, to_tail)
1048
from_abs = self.abspath(from_rel)
1049
to_abs = self.abspath(to_rel)
1051
rename(from_abs, to_abs)
1053
raise BzrError("failed to rename %r to %r: %s"
1054
% (from_abs, to_abs, e[1]),
1055
["rename rolled back"])
1057
self._write_inventory(inv)
1062
def move(self, from_paths, to_name):
1065
to_name must exist as a versioned directory.
1067
If to_name exists and is a directory, the files are moved into
1068
it, keeping their old names. If it is a directory,
1070
Note that to_name is only the last component of the new name;
1071
this doesn't change the directory.
1073
This returns a list of (from_path, to_path) pairs for each
1074
entry that is moved.
1079
## TODO: Option to move IDs only
1080
assert not isinstance(from_paths, basestring)
1081
tree = self.working_tree()
1082
inv = tree.inventory
1083
to_abs = self.abspath(to_name)
1084
if not isdir(to_abs):
1085
raise BzrError("destination %r is not a directory" % to_abs)
1086
if not tree.has_filename(to_name):
1087
raise BzrError("destination %r not in working directory" % to_abs)
1088
to_dir_id = inv.path2id(to_name)
1089
if to_dir_id == None and to_name != '':
1090
raise BzrError("destination %r is not a versioned directory" % to_name)
1091
to_dir_ie = inv[to_dir_id]
1092
if to_dir_ie.kind not in ('directory', 'root_directory'):
1093
raise BzrError("destination %r is not a directory" % to_abs)
1095
to_idpath = inv.get_idpath(to_dir_id)
1097
for f in from_paths:
1098
if not tree.has_filename(f):
1099
raise BzrError("%r does not exist in working tree" % f)
1100
f_id = inv.path2id(f)
1102
raise BzrError("%r is not versioned" % f)
1103
name_tail = splitpath(f)[-1]
1104
dest_path = appendpath(to_name, name_tail)
1105
if tree.has_filename(dest_path):
1106
raise BzrError("destination %r already exists" % dest_path)
1107
if f_id in to_idpath:
1108
raise BzrError("can't move %r to a subdirectory of itself" % f)
1110
# OK, so there's a race here, it's possible that someone will
1111
# create a file in this interval and then the rename might be
1112
# left half-done. But we should have caught most problems.
1114
for f in from_paths:
1115
name_tail = splitpath(f)[-1]
1116
dest_path = appendpath(to_name, name_tail)
1117
result.append((f, dest_path))
1118
inv.rename(inv.path2id(f), to_dir_id, name_tail)
1120
rename(self.abspath(f), self.abspath(dest_path))
1122
raise BzrError("failed to rename %r to %r: %s" % (f, dest_path, e[1]),
1123
["rename rolled back"])
1125
self._write_inventory(inv)
1132
def revert(self, filenames, old_tree=None, backups=True):
1133
"""Restore selected files to the versions from a previous tree.
1136
If true (default) backups are made of files before
1139
from bzrlib.errors import NotVersionedError, BzrError
1140
from bzrlib.atomicfile import AtomicFile
1141
from bzrlib.osutils import backup_file
1143
inv = self.read_working_inventory()
1144
if old_tree is None:
1145
old_tree = self.basis_tree()
1146
old_inv = old_tree.inventory
1149
for fn in filenames:
1150
file_id = inv.path2id(fn)
1152
raise NotVersionedError("not a versioned file", fn)
1153
if not old_inv.has_id(file_id):
1154
raise BzrError("file not present in old tree", fn, file_id)
1155
nids.append((fn, file_id))
1157
# TODO: Rename back if it was previously at a different location
1159
# TODO: If given a directory, restore the entire contents from
1160
# the previous version.
1162
# TODO: Make a backup to a temporary file.
1164
# TODO: If the file previously didn't exist, delete it?
1165
for fn, file_id in nids:
1168
f = AtomicFile(fn, 'wb')
1170
f.write(old_tree.get_file(file_id).read())
1176
def pending_merges(self):
1177
"""Return a list of pending merges.
1179
These are revisions that have been merged into the working
1180
directory but not yet committed.
1182
cfn = self._rel_controlfilename('pending-merges')
1183
if not self._transport.has(cfn):
1186
for l in self.controlfile('pending-merges', 'r').readlines():
1187
p.append(l.rstrip('\n'))
1191
def add_pending_merge(self, *revision_ids):
1192
# TODO: Perhaps should check at this point that the
1193
# history of the revision is actually present?
1194
p = self.pending_merges()
1196
for rev_id in revision_ids:
1202
self.set_pending_merges(p)
1204
def set_pending_merges(self, rev_list):
1207
self.put_controlfile('pending-merges', '\n'.join(rev_list))
1212
def get_parent(self):
1213
"""Return the parent location of the branch.
1215
This is the default location for push/pull/missing. The usual
1216
pattern is that the user can override it by specifying a
1220
_locs = ['parent', 'pull', 'x-pull']
1223
return self.controlfile(l, 'r').read().strip('\n')
1225
if e.errno != errno.ENOENT:
1230
def set_parent(self, url):
1231
# TODO: Maybe delete old location files?
1232
from bzrlib.atomicfile import AtomicFile
1235
f = AtomicFile(self.controlfilename('parent'))
1244
def check_revno(self, revno):
1246
Check whether a revno corresponds to any revision.
1247
Zero (the NULL revision) is considered valid.
1250
self.check_real_revno(revno)
1252
def check_real_revno(self, revno):
1254
Check whether a revno corresponds to a real revision.
1255
Zero (the NULL revision) is considered invalid
1257
if revno < 1 or revno > self.revno():
1258
raise InvalidRevisionNumber(revno)
1260
def sign_revision(self, revision_id, gpg_strategy):
1263
plaintext = Testament.from_revision(self, revision_id).as_short_text()
1264
self.revision_store.add(StringIO(gpg_strategy.sign(plaintext)),
1270
class ScratchBranch(_Branch):
1271
"""Special test class: a branch that cleans up after itself.
1273
>>> b = ScratchBranch()
1277
>>> b._transport.__del__()
1282
def __init__(self, files=[], dirs=[], transport=None):
1283
"""Make a test branch.
1285
This creates a temporary directory and runs init-tree in it.
1287
If any files are listed, they are created in the working copy.
1289
if transport is None:
1290
transport = bzrlib.transport.local.ScratchTransport()
1291
super(ScratchBranch, self).__init__(transport, init=True)
1293
super(ScratchBranch, self).__init__(transport)
1296
self._transport.mkdir(d)
1299
self._transport.put(f, 'content of %s' % f)
1304
>>> orig = ScratchBranch(files=["file1", "file2"])
1305
>>> clone = orig.clone()
1306
>>> if os.name != 'nt':
1307
... os.path.samefile(orig.base, clone.base)
1309
... orig.base == clone.base
1312
>>> os.path.isfile(os.path.join(clone.base, "file1"))
1315
from shutil import copytree
1316
from tempfile import mkdtemp
1319
copytree(self.base, base, symlinks=True)
1320
return ScratchBranch(
1321
transport=bzrlib.transport.local.ScratchTransport(base))
1324
######################################################################
1328
def is_control_file(filename):
1329
## FIXME: better check
1330
filename = os.path.normpath(filename)
1331
while filename != '':
1332
head, tail = os.path.split(filename)
1333
## mutter('check %r for control file' % ((head, tail), ))
1334
if tail == bzrlib.BZRDIR:
1336
if filename == head:
1343
def gen_file_id(name):
1344
"""Return new file id.
1346
This should probably generate proper UUIDs, but for the moment we
1347
cope with just randomness because running uuidgen every time is
1350
from binascii import hexlify
1351
from time import time
1353
# get last component
1354
idx = name.rfind('/')
1356
name = name[idx+1 : ]
1357
idx = name.rfind('\\')
1359
name = name[idx+1 : ]
1361
# make it not a hidden file
1362
name = name.lstrip('.')
1364
# remove any wierd characters; we don't escape them but rather
1365
# just pull them out
1366
name = re.sub(r'[^\w.]', '', name)
1368
s = hexlify(rand_bytes(8))
1369
return '-'.join((name, compact_date(time()), s))
1373
"""Return a new tree-root file id."""
1374
return gen_file_id('TREE_ROOT')