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 bzrlib.trace import mutter, note
23
from bzrlib.osutils import isdir, quotefn, compact_date, rand_bytes, \
24
rename, splitpath, sha_file, appendpath, file_kind
26
from bzrlib.errors import BzrError, InvalidRevisionNumber, InvalidRevisionId, \
27
DivergedBranches, NotBranchError
28
from bzrlib.textui import show_status
29
from bzrlib.revision import Revision
30
from bzrlib.delta import compare_trees
31
from bzrlib.tree import EmptyTree, RevisionTree
37
BZR_BRANCH_FORMAT = "Bazaar-NG branch, format 0.0.4\n"
38
## TODO: Maybe include checks for common corruption of newlines, etc?
41
# TODO: Some operations like log might retrieve the same revisions
42
# repeatedly to calculate deltas. We could perhaps have a weakref
43
# cache in memory to make this faster.
45
def find_branch(*ignored, **ignored_too):
46
# XXX: leave this here for about one release, then remove it
47
raise NotImplementedError('find_branch() is not supported anymore, '
48
'please use one of the new branch constructors')
50
def _relpath(base, path):
51
"""Return path relative to base, or raise exception.
53
The path may be either an absolute path or a path relative to the
54
current working directory.
56
Lifted out of Branch.relpath for ease of testing.
58
os.path.commonprefix (python2.4) has a bad bug that it works just
59
on string prefixes, assuming that '/u' is a prefix of '/u2'. This
60
avoids that problem."""
61
rp = os.path.abspath(path)
65
while len(head) >= len(base):
68
head, tail = os.path.split(head)
72
raise NotBranchError("path %r is not within branch %r" % (rp, base))
77
def find_branch_root(f=None):
78
"""Find the branch root enclosing f, or pwd.
80
f may be a filename or a URL.
82
It is not necessary that f exists.
84
Basically we keep looking up until we find the control directory or
85
run into the root. If there isn't one, raises NotBranchError.
90
f = bzrlib.osutils.normalizepath(f)
91
if not bzrlib.osutils.lexists(f):
92
raise BzrError('%r does not exist' % f)
97
if os.path.exists(os.path.join(f, bzrlib.BZRDIR)):
99
head, tail = os.path.split(f)
101
# reached the root, whatever that may be
102
raise NotBranchError('%s is not in a branch' % orig_f)
108
######################################################################
111
class Branch(object):
112
"""Branch holding a history of revisions.
115
Base directory/url of the branch.
119
def __init__(self, *ignored, **ignored_too):
120
raise NotImplementedError('The Branch class is abstract')
124
"""Open an existing branch, rooted at 'base' (url)"""
125
if base and (base.startswith('http://') or base.startswith('https://')):
126
from bzrlib.remotebranch import RemoteBranch
127
return RemoteBranch(base, find_root=False)
129
return LocalBranch(base, find_root=False)
132
def open_containing(url):
133
"""Open an existing branch which contains url.
135
This probes for a branch at url, and searches upwards from there.
137
if url and (url.startswith('http://') or url.startswith('https://')):
138
from bzrlib.remotebranch import RemoteBranch
139
return RemoteBranch(url)
141
return LocalBranch(url)
144
def initialize(base):
145
"""Create a new branch, rooted at 'base' (url)"""
146
if base and (base.startswith('http://') or base.startswith('https://')):
147
from bzrlib.remotebranch import RemoteBranch
148
return RemoteBranch(base, init=True)
150
return LocalBranch(base, init=True)
152
def setup_caching(self, cache_root):
153
"""Subclasses that care about caching should override this, and set
154
up cached stores located under cache_root.
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. May be a file:// url.
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
if base.startswith("file://"):
207
self.base = os.path.realpath(base)
208
if not isdir(self.controlfilename('.')):
209
raise NotBranchError("not a bzr branch: %s" % quotefn(base),
210
['use "bzr init" to initialize a new working tree',
211
'current bzr can only operate from top-of-tree'])
214
self.text_store = ImmutableStore(self.controlfilename('text-store'))
215
self.revision_store = ImmutableStore(self.controlfilename('revision-store'))
216
self.inventory_store = ImmutableStore(self.controlfilename('inventory-store'))
220
return '%s(%r)' % (self.__class__.__name__, self.base)
227
if self._lock_mode or self._lock:
228
from bzrlib.warnings import warn
229
warn("branch %r was not explicitly unlocked" % self)
232
def lock_write(self):
234
if self._lock_mode != 'w':
235
from bzrlib.errors import LockError
236
raise LockError("can't upgrade to a write lock from %r" %
238
self._lock_count += 1
240
from bzrlib.lock import WriteLock
242
self._lock = WriteLock(self.controlfilename('branch-lock'))
243
self._lock_mode = 'w'
249
assert self._lock_mode in ('r', 'w'), \
250
"invalid lock mode %r" % self._lock_mode
251
self._lock_count += 1
253
from bzrlib.lock import ReadLock
255
self._lock = ReadLock(self.controlfilename('branch-lock'))
256
self._lock_mode = 'r'
260
if not self._lock_mode:
261
from bzrlib.errors import LockError
262
raise LockError('branch %r is not locked' % (self))
264
if self._lock_count > 1:
265
self._lock_count -= 1
269
self._lock_mode = self._lock_count = None
271
def abspath(self, name):
272
"""Return absolute filename for something in the branch"""
273
return os.path.join(self.base, name)
275
def relpath(self, path):
276
"""Return path relative to this branch of something inside it.
278
Raises an error if path is not in this branch."""
279
return _relpath(self.base, path)
281
def controlfilename(self, file_or_path):
282
"""Return location relative to branch."""
283
if isinstance(file_or_path, basestring):
284
file_or_path = [file_or_path]
285
return os.path.join(self.base, bzrlib.BZRDIR, *file_or_path)
288
def controlfile(self, file_or_path, mode='r'):
289
"""Open a control file for this branch.
291
There are two classes of file in the control directory: text
292
and binary. binary files are untranslated byte streams. Text
293
control files are stored with Unix newlines and in UTF-8, even
294
if the platform or locale defaults are different.
296
Controlfiles should almost never be opened in write mode but
297
rather should be atomically copied and replaced using atomicfile.
300
fn = self.controlfilename(file_or_path)
302
if mode == 'rb' or mode == 'wb':
303
return file(fn, mode)
304
elif mode == 'r' or mode == 'w':
305
# open in binary mode anyhow so there's no newline translation;
306
# codecs uses line buffering by default; don't want that.
308
return codecs.open(fn, mode + 'b', 'utf-8',
311
raise BzrError("invalid controlfile mode %r" % mode)
313
def _make_control(self):
314
from bzrlib.inventory import Inventory
316
os.mkdir(self.controlfilename([]))
317
self.controlfile('README', 'w').write(
318
"This is a Bazaar-NG control directory.\n"
319
"Do not change any files in this directory.\n")
320
self.controlfile('branch-format', 'w').write(BZR_BRANCH_FORMAT)
321
for d in ('text-store', 'inventory-store', 'revision-store'):
322
os.mkdir(self.controlfilename(d))
323
for f in ('revision-history', 'merged-patches',
324
'pending-merged-patches', 'branch-name',
327
self.controlfile(f, 'w').write('')
328
mutter('created control directory in ' + self.base)
330
# if we want per-tree root ids then this is the place to set
331
# them; they're not needed for now and so ommitted for
333
f = self.controlfile('inventory','w')
334
bzrlib.xml.serializer_v4.write_inventory(Inventory(), f)
337
def _check_format(self):
338
"""Check this branch format is supported.
340
The current tool only supports the current unstable format.
342
In the future, we might need different in-memory Branch
343
classes to support downlevel branches. But not yet.
345
# This ignores newlines so that we can open branches created
346
# on Windows from Linux and so on. I think it might be better
347
# to always make all internal files in unix format.
348
fmt = self.controlfile('branch-format', 'r').read()
349
fmt = fmt.replace('\r\n', '\n')
350
if fmt != BZR_BRANCH_FORMAT:
351
raise BzrError('sorry, branch format %r not supported' % fmt,
352
['use a different bzr version',
353
'or remove the .bzr directory and "bzr init" again'])
355
def get_root_id(self):
356
"""Return the id of this branches root"""
357
inv = self.read_working_inventory()
358
return inv.root.file_id
360
def set_root_id(self, file_id):
361
inv = self.read_working_inventory()
362
orig_root_id = inv.root.file_id
363
del inv._byid[inv.root.file_id]
364
inv.root.file_id = file_id
365
inv._byid[inv.root.file_id] = inv.root
368
if entry.parent_id in (None, orig_root_id):
369
entry.parent_id = inv.root.file_id
370
self._write_inventory(inv)
372
def read_working_inventory(self):
373
"""Read the working inventory."""
374
from bzrlib.inventory import Inventory
377
# ElementTree does its own conversion from UTF-8, so open in
379
f = self.controlfile('inventory', 'rb')
380
return bzrlib.xml.serializer_v4.read_inventory(f)
385
def _write_inventory(self, inv):
386
"""Update the working inventory.
388
That is to say, the inventory describing changes underway, that
389
will be committed to the next revision.
391
from bzrlib.atomicfile import AtomicFile
395
f = AtomicFile(self.controlfilename('inventory'), 'wb')
397
bzrlib.xml.serializer_v4.write_inventory(inv, f)
404
mutter('wrote working inventory')
407
inventory = property(read_working_inventory, _write_inventory, None,
408
"""Inventory for the working copy.""")
411
def add(self, files, ids=None):
412
"""Make files versioned.
414
Note that the command line normally calls smart_add instead,
415
which can automatically recurse.
417
This puts the files in the Added state, so that they will be
418
recorded by the next commit.
421
List of paths to add, relative to the base of the tree.
424
If set, use these instead of automatically generated ids.
425
Must be the same length as the list of files, but may
426
contain None for ids that are to be autogenerated.
428
TODO: Perhaps have an option to add the ids even if the files do
431
TODO: Perhaps yield the ids and paths as they're added.
433
# TODO: Re-adding a file that is removed in the working copy
434
# should probably put it back with the previous ID.
435
if isinstance(files, basestring):
436
assert(ids is None or isinstance(ids, basestring))
442
ids = [None] * len(files)
444
assert(len(ids) == len(files))
448
inv = self.read_working_inventory()
449
for f,file_id in zip(files, ids):
450
if is_control_file(f):
451
raise BzrError("cannot add control file %s" % quotefn(f))
456
raise BzrError("cannot add top-level %r" % f)
458
fullpath = os.path.normpath(self.abspath(f))
461
kind = file_kind(fullpath)
463
# maybe something better?
464
raise BzrError('cannot add: not a regular file, symlink or directory: %s' % quotefn(f))
466
if kind not in ('file', 'directory', 'symlink'):
467
raise BzrError('cannot add: not a regular file, symlink or directory: %s' % quotefn(f))
470
file_id = gen_file_id(f)
471
inv.add_path(f, kind=kind, file_id=file_id)
473
mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
475
self._write_inventory(inv)
480
def print_file(self, file, revno):
481
"""Print `file` to stdout."""
484
tree = self.revision_tree(self.get_rev_id(revno))
485
# use inventory as it was in that revision
486
file_id = tree.inventory.path2id(file)
488
raise BzrError("%r is not present in revision %s" % (file, revno))
489
tree.print_file(file_id)
494
def remove(self, files, verbose=False):
495
"""Mark nominated files for removal from the inventory.
497
This does not remove their text. This does not run on
499
TODO: Refuse to remove modified files unless --force is given?
501
TODO: Do something useful with directories.
503
TODO: Should this remove the text or not? Tough call; not
504
removing may be useful and the user can just use use rm, and
505
is the opposite of add. Removing it is consistent with most
506
other tools. Maybe an option.
508
## TODO: Normalize names
509
## TODO: Remove nested loops; better scalability
510
if isinstance(files, basestring):
516
tree = self.working_tree()
519
# do this before any modifications
523
raise BzrError("cannot remove unversioned file %s" % quotefn(f))
524
mutter("remove inventory entry %s {%s}" % (quotefn(f), fid))
526
# having remove it, it must be either ignored or unknown
527
if tree.is_ignored(f):
531
show_status(new_status, inv[fid].kind, quotefn(f))
534
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)
550
"""Return all unknown files.
552
These are files in the working directory that are not versioned or
553
control files or ignored.
555
>>> b = ScratchBranch(files=['foo', 'foo~'])
556
>>> list(b.unknowns())
559
>>> list(b.unknowns())
562
>>> list(b.unknowns())
565
return self.working_tree().unknowns()
568
def append_revision(self, *revision_ids):
569
from bzrlib.atomicfile import AtomicFile
571
for revision_id in revision_ids:
572
mutter("add {%s} to revision-history" % revision_id)
574
rev_history = self.revision_history()
575
rev_history.extend(revision_ids)
577
f = AtomicFile(self.controlfilename('revision-history'))
579
for rev_id in rev_history:
585
def get_revision_xml_file(self, revision_id):
586
"""Return XML file object for revision object."""
587
if not revision_id or not isinstance(revision_id, basestring):
588
raise InvalidRevisionId(revision_id)
593
return self.revision_store[revision_id]
594
except (IndexError, KeyError):
595
raise bzrlib.errors.NoSuchRevision(self, revision_id)
600
get_revision_xml = get_revision_xml_file
603
get_revision_xml = get_revision_xml_file
606
def get_revision(self, revision_id):
607
"""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
620
def get_revision_delta(self, revno):
621
"""Return the delta for one revision.
623
The delta is relative to its mainline predecessor, or the
624
empty tree for revision 1.
626
assert isinstance(revno, int)
627
rh = self.revision_history()
628
if not (1 <= revno <= len(rh)):
629
raise InvalidRevisionNumber(revno)
631
# revno is 1-based; list is 0-based
633
new_tree = self.revision_tree(rh[revno-1])
635
old_tree = EmptyTree()
637
old_tree = self.revision_tree(rh[revno-2])
639
return compare_trees(old_tree, new_tree)
641
def get_revision_sha1(self, revision_id):
642
"""Hash the stored value of a revision, and return it."""
643
# In the future, revision entries will be signed. At that
644
# point, it is probably best *not* to include the signature
645
# in the revision hash. Because that lets you re-sign
646
# the revision, (add signatures/remove signatures) and still
647
# have all hash pointers stay consistent.
648
# But for now, just hash the contents.
649
return bzrlib.osutils.sha_file(self.get_revision_xml(revision_id))
651
def get_inventory(self, inventory_id):
652
"""Get Inventory object by hash.
654
TODO: Perhaps for this and similar methods, take a revision
655
parameter which can be either an integer revno or a
657
from bzrlib.inventory import Inventory
658
f = self.get_inventory_xml_file(inventory_id)
659
return bzrlib.xml.serializer_v4.read_inventory(f)
661
def get_inventory_xml(self, inventory_id):
662
"""Get inventory XML as a file object."""
663
return self.inventory_store[inventory_id]
665
get_inventory_xml_file = get_inventory_xml
667
def get_inventory_sha1(self, inventory_id):
668
"""Return the sha1 hash of the inventory entry
670
return sha_file(self.get_inventory_xml(inventory_id))
672
def get_revision_inventory(self, revision_id):
673
"""Return inventory of a past revision."""
674
# bzr 0.0.6 imposes the constraint that the inventory_id
675
# must be the same as its revision, so this is trivial.
676
if revision_id == None:
677
from bzrlib.inventory import Inventory
678
return Inventory(self.get_root_id())
680
return self.get_inventory(revision_id)
682
def revision_history(self):
683
"""Return sequence of revision hashes on to this branch.
685
>>> ScratchBranch().revision_history()
690
return [l.rstrip('\r\n') for l in
691
self.controlfile('revision-history', 'r').readlines()]
695
def common_ancestor(self, other, self_revno=None, other_revno=None):
697
>>> from bzrlib.commit import commit
698
>>> sb = ScratchBranch(files=['foo', 'foo~'])
699
>>> sb.common_ancestor(sb) == (None, None)
701
>>> commit(sb, "Committing first revision", verbose=False)
702
>>> sb.common_ancestor(sb)[0]
704
>>> clone = sb.clone()
705
>>> commit(sb, "Committing second revision", verbose=False)
706
>>> sb.common_ancestor(sb)[0]
708
>>> sb.common_ancestor(clone)[0]
710
>>> commit(clone, "Committing divergent second revision",
712
>>> sb.common_ancestor(clone)[0]
714
>>> sb.common_ancestor(clone) == clone.common_ancestor(sb)
716
>>> sb.common_ancestor(sb) != clone.common_ancestor(clone)
718
>>> clone2 = sb.clone()
719
>>> sb.common_ancestor(clone2)[0]
721
>>> sb.common_ancestor(clone2, self_revno=1)[0]
723
>>> sb.common_ancestor(clone2, other_revno=1)[0]
726
my_history = self.revision_history()
727
other_history = other.revision_history()
728
if self_revno is None:
729
self_revno = len(my_history)
730
if other_revno is None:
731
other_revno = len(other_history)
732
indices = range(min((self_revno, other_revno)))
735
if my_history[r] == other_history[r]:
736
return r+1, my_history[r]
741
"""Return current revision number for this branch.
743
That is equivalent to the number of revisions committed to
746
return len(self.revision_history())
749
def last_patch(self):
750
"""Return last patch hash, or None if no history.
752
ph = self.revision_history()
759
def missing_revisions(self, other, stop_revision=None, diverged_ok=False):
761
If self and other have not diverged, return a list of the revisions
762
present in other, but missing from self.
764
>>> from bzrlib.commit import commit
765
>>> bzrlib.trace.silent = True
766
>>> br1 = ScratchBranch()
767
>>> br2 = ScratchBranch()
768
>>> br1.missing_revisions(br2)
770
>>> commit(br2, "lala!", rev_id="REVISION-ID-1")
771
>>> br1.missing_revisions(br2)
773
>>> br2.missing_revisions(br1)
775
>>> commit(br1, "lala!", rev_id="REVISION-ID-1")
776
>>> br1.missing_revisions(br2)
778
>>> commit(br2, "lala!", rev_id="REVISION-ID-2A")
779
>>> br1.missing_revisions(br2)
781
>>> commit(br1, "lala!", rev_id="REVISION-ID-2B")
782
>>> br1.missing_revisions(br2)
783
Traceback (most recent call last):
784
DivergedBranches: These branches have diverged.
786
self_history = self.revision_history()
787
self_len = len(self_history)
788
other_history = other.revision_history()
789
other_len = len(other_history)
790
common_index = min(self_len, other_len) -1
791
if common_index >= 0 and \
792
self_history[common_index] != other_history[common_index]:
793
raise DivergedBranches(self, other)
795
if stop_revision is None:
796
stop_revision = other_len
797
elif stop_revision > other_len:
798
raise bzrlib.errors.NoSuchRevision(self, stop_revision)
800
return other_history[self_len:stop_revision]
803
def update_revisions(self, other, stop_revision=None):
804
"""Pull in all new revisions from other branch.
806
from bzrlib.fetch import greedy_fetch
807
from bzrlib.revision import get_intervening_revisions
809
pb = bzrlib.ui.ui_factory.progress_bar()
810
pb.update('comparing histories')
811
if stop_revision is None:
812
other_revision = other.last_patch()
814
other_revision = other.get_rev_id(stop_revision)
815
count = greedy_fetch(self, other, other_revision, pb)[0]
817
revision_ids = self.missing_revisions(other, stop_revision)
818
except DivergedBranches, e:
820
revision_ids = get_intervening_revisions(self.last_patch(),
821
other_revision, self)
822
assert self.last_patch() not in revision_ids
823
except bzrlib.errors.NotAncestor:
826
self.append_revision(*revision_ids)
829
def install_revisions(self, other, revision_ids, pb):
830
if hasattr(other.revision_store, "prefetch"):
831
other.revision_store.prefetch(revision_ids)
832
if hasattr(other.inventory_store, "prefetch"):
834
for rev_id in revision_ids:
836
revision = other.get_revision(rev_id).inventory_id
837
inventory_ids.append(revision)
838
except bzrlib.errors.NoSuchRevision:
840
other.inventory_store.prefetch(inventory_ids)
843
pb = bzrlib.ui.ui_factory.progress_bar()
850
for i, rev_id in enumerate(revision_ids):
851
pb.update('fetching revision', i+1, len(revision_ids))
853
rev = other.get_revision(rev_id)
854
except bzrlib.errors.NoSuchRevision:
858
revisions.append(rev)
859
inv = other.get_inventory(str(rev.inventory_id))
860
for key, entry in inv.iter_entries():
861
if entry.text_id is None:
863
if entry.text_id not in self.text_store:
864
needed_texts.add(entry.text_id)
868
count, cp_fail = self.text_store.copy_multi(other.text_store,
870
#print "Added %d texts." % count
871
inventory_ids = [ f.inventory_id for f in revisions ]
872
count, cp_fail = self.inventory_store.copy_multi(other.inventory_store,
874
#print "Added %d inventories." % count
875
revision_ids = [ f.revision_id for f in revisions]
877
count, cp_fail = self.revision_store.copy_multi(other.revision_store,
880
assert len(cp_fail) == 0
881
return count, failures
884
def commit(self, *args, **kw):
885
from bzrlib.commit import commit
886
commit(self, *args, **kw)
888
def revision_id_to_revno(self, revision_id):
889
"""Given a revision id, return its revno"""
890
history = self.revision_history()
892
return history.index(revision_id) + 1
894
raise bzrlib.errors.NoSuchRevision(self, revision_id)
896
def get_rev_id(self, revno, history=None):
897
"""Find the revision id of the specified revno."""
901
history = self.revision_history()
902
elif revno <= 0 or revno > len(history):
903
raise bzrlib.errors.NoSuchRevision(self, revno)
904
return history[revno - 1]
906
def revision_tree(self, revision_id):
907
"""Return Tree for a revision on this branch.
909
`revision_id` may be None for the null revision, in which case
910
an `EmptyTree` is returned."""
911
# TODO: refactor this to use an existing revision object
912
# so we don't need to read it in twice.
913
if revision_id == None:
916
inv = self.get_revision_inventory(revision_id)
917
return RevisionTree(self.text_store, inv)
920
def working_tree(self):
921
"""Return a `Tree` for the working copy."""
922
from bzrlib.workingtree import WorkingTree
923
return WorkingTree(self.base, self.read_working_inventory())
926
def basis_tree(self):
927
"""Return `Tree` object for last revision.
929
If there are no revisions yet, return an `EmptyTree`.
931
r = self.last_patch()
935
return RevisionTree(self.text_store, self.get_revision_inventory(r))
939
def rename_one(self, from_rel, to_rel):
942
This can change the directory or the filename or both.
946
tree = self.working_tree()
948
if not tree.has_filename(from_rel):
949
raise BzrError("can't rename: old working file %r does not exist" % from_rel)
950
if tree.has_filename(to_rel):
951
raise BzrError("can't rename: new working file %r already exists" % to_rel)
953
file_id = inv.path2id(from_rel)
955
raise BzrError("can't rename: old name %r is not versioned" % from_rel)
957
if inv.path2id(to_rel):
958
raise BzrError("can't rename: new name %r is already versioned" % to_rel)
960
to_dir, to_tail = os.path.split(to_rel)
961
to_dir_id = inv.path2id(to_dir)
962
if to_dir_id == None and to_dir != '':
963
raise BzrError("can't determine destination directory id for %r" % to_dir)
965
mutter("rename_one:")
966
mutter(" file_id {%s}" % file_id)
967
mutter(" from_rel %r" % from_rel)
968
mutter(" to_rel %r" % to_rel)
969
mutter(" to_dir %r" % to_dir)
970
mutter(" to_dir_id {%s}" % to_dir_id)
972
inv.rename(file_id, to_dir_id, to_tail)
974
from_abs = self.abspath(from_rel)
975
to_abs = self.abspath(to_rel)
977
rename(from_abs, to_abs)
979
raise BzrError("failed to rename %r to %r: %s"
980
% (from_abs, to_abs, e[1]),
981
["rename rolled back"])
983
self._write_inventory(inv)
988
def move(self, from_paths, to_name):
991
to_name must exist as a versioned directory.
993
If to_name exists and is a directory, the files are moved into
994
it, keeping their old names. If it is a directory,
996
Note that to_name is only the last component of the new name;
997
this doesn't change the directory.
999
This returns a list of (from_path, to_path) pairs for each
1000
entry that is moved.
1005
## TODO: Option to move IDs only
1006
assert not isinstance(from_paths, basestring)
1007
tree = self.working_tree()
1008
inv = tree.inventory
1009
to_abs = self.abspath(to_name)
1010
if not isdir(to_abs):
1011
raise BzrError("destination %r is not a directory" % to_abs)
1012
if not tree.has_filename(to_name):
1013
raise BzrError("destination %r not in working directory" % to_abs)
1014
to_dir_id = inv.path2id(to_name)
1015
if to_dir_id == None and to_name != '':
1016
raise BzrError("destination %r is not a versioned directory" % to_name)
1017
to_dir_ie = inv[to_dir_id]
1018
if to_dir_ie.kind not in ('directory', 'root_directory'):
1019
raise BzrError("destination %r is not a directory" % to_abs)
1021
to_idpath = inv.get_idpath(to_dir_id)
1023
for f in from_paths:
1024
if not tree.has_filename(f):
1025
raise BzrError("%r does not exist in working tree" % f)
1026
f_id = inv.path2id(f)
1028
raise BzrError("%r is not versioned" % f)
1029
name_tail = splitpath(f)[-1]
1030
dest_path = appendpath(to_name, name_tail)
1031
if tree.has_filename(dest_path):
1032
raise BzrError("destination %r already exists" % dest_path)
1033
if f_id in to_idpath:
1034
raise BzrError("can't move %r to a subdirectory of itself" % f)
1036
# OK, so there's a race here, it's possible that someone will
1037
# create a file in this interval and then the rename might be
1038
# left half-done. But we should have caught most problems.
1040
for f in from_paths:
1041
name_tail = splitpath(f)[-1]
1042
dest_path = appendpath(to_name, name_tail)
1043
result.append((f, dest_path))
1044
inv.rename(inv.path2id(f), to_dir_id, name_tail)
1046
rename(self.abspath(f), self.abspath(dest_path))
1048
raise BzrError("failed to rename %r to %r: %s" % (f, dest_path, e[1]),
1049
["rename rolled back"])
1051
self._write_inventory(inv)
1058
def revert(self, filenames, old_tree=None, backups=True):
1059
"""Restore selected files to the versions from a previous tree.
1062
If true (default) backups are made of files before
1065
from bzrlib.errors import NotVersionedError, BzrError
1066
from bzrlib.atomicfile import AtomicFile
1067
from bzrlib.osutils import backup_file
1069
inv = self.read_working_inventory()
1070
if old_tree is None:
1071
old_tree = self.basis_tree()
1072
old_inv = old_tree.inventory
1075
for fn in filenames:
1076
file_id = inv.path2id(fn)
1078
raise NotVersionedError("not a versioned file", fn)
1079
if not old_inv.has_id(file_id):
1080
raise BzrError("file not present in old tree", fn, file_id)
1081
nids.append((fn, file_id))
1083
# TODO: Rename back if it was previously at a different location
1085
# TODO: If given a directory, restore the entire contents from
1086
# the previous version.
1088
# TODO: Make a backup to a temporary file.
1090
# TODO: If the file previously didn't exist, delete it?
1091
for fn, file_id in nids:
1094
f = AtomicFile(fn, 'wb')
1096
f.write(old_tree.get_file(file_id).read())
1102
def pending_merges(self):
1103
"""Return a list of pending merges.
1105
These are revisions that have been merged into the working
1106
directory but not yet committed.
1108
cfn = self.controlfilename('pending-merges')
1109
if not os.path.exists(cfn):
1112
for l in self.controlfile('pending-merges', 'r').readlines():
1113
p.append(l.rstrip('\n'))
1117
def add_pending_merge(self, revision_id):
1118
from bzrlib.revision import validate_revision_id
1120
validate_revision_id(revision_id)
1122
p = self.pending_merges()
1123
if revision_id in p:
1125
p.append(revision_id)
1126
self.set_pending_merges(p)
1129
def set_pending_merges(self, rev_list):
1130
from bzrlib.atomicfile import AtomicFile
1133
f = AtomicFile(self.controlfilename('pending-merges'))
1144
def get_parent(self):
1145
"""Return the parent location of the branch.
1147
This is the default location for push/pull/missing. The usual
1148
pattern is that the user can override it by specifying a
1152
_locs = ['parent', 'pull', 'x-pull']
1155
return self.controlfile(l, 'r').read().strip('\n')
1157
if e.errno != errno.ENOENT:
1162
def set_parent(self, url):
1163
# TODO: Maybe delete old location files?
1164
from bzrlib.atomicfile import AtomicFile
1167
f = AtomicFile(self.controlfilename('parent'))
1176
def check_revno(self, revno):
1178
Check whether a revno corresponds to any revision.
1179
Zero (the NULL revision) is considered valid.
1182
self.check_real_revno(revno)
1184
def check_real_revno(self, revno):
1186
Check whether a revno corresponds to a real revision.
1187
Zero (the NULL revision) is considered invalid
1189
if revno < 1 or revno > self.revno():
1190
raise InvalidRevisionNumber(revno)
1196
class ScratchBranch(LocalBranch):
1197
"""Special test class: a branch that cleans up after itself.
1199
>>> b = ScratchBranch()
1207
def __init__(self, files=[], dirs=[], base=None):
1208
"""Make a test branch.
1210
This creates a temporary directory and runs init-tree in it.
1212
If any files are listed, they are created in the working copy.
1214
from tempfile import mkdtemp
1219
LocalBranch.__init__(self, base, init=init)
1221
os.mkdir(self.abspath(d))
1224
file(os.path.join(self.base, f), 'w').write('content of %s' % f)
1229
>>> orig = ScratchBranch(files=["file1", "file2"])
1230
>>> clone = orig.clone()
1231
>>> if os.name != 'nt':
1232
... os.path.samefile(orig.base, clone.base)
1234
... orig.base == clone.base
1237
>>> os.path.isfile(os.path.join(clone.base, "file1"))
1240
from shutil import copytree
1241
from tempfile import mkdtemp
1244
copytree(self.base, base, symlinks=True)
1245
return ScratchBranch(base=base)
1253
"""Destroy the test branch, removing the scratch directory."""
1254
from shutil import rmtree
1257
mutter("delete ScratchBranch %s" % self.base)
1260
# Work around for shutil.rmtree failing on Windows when
1261
# readonly files are encountered
1262
mutter("hit exception in destroying ScratchBranch: %s" % e)
1263
for root, dirs, files in os.walk(self.base, topdown=False):
1265
os.chmod(os.path.join(root, name), 0700)
1271
######################################################################
1275
def is_control_file(filename):
1276
## FIXME: better check
1277
filename = os.path.normpath(filename)
1278
while filename != '':
1279
head, tail = os.path.split(filename)
1280
## mutter('check %r for control file' % ((head, tail), ))
1281
if tail == bzrlib.BZRDIR:
1283
if filename == head:
1290
def gen_file_id(name):
1291
"""Return new file id.
1293
This should probably generate proper UUIDs, but for the moment we
1294
cope with just randomness because running uuidgen every time is
1297
from binascii import hexlify
1298
from time import time
1300
# get last component
1301
idx = name.rfind('/')
1303
name = name[idx+1 : ]
1304
idx = name.rfind('\\')
1306
name = name[idx+1 : ]
1308
# make it not a hidden file
1309
name = name.lstrip('.')
1311
# remove any wierd characters; we don't escape them but rather
1312
# just pull them out
1313
name = re.sub(r'[^\w.]', '', name)
1315
s = hexlify(rand_bytes(8))
1316
return '-'.join((name, compact_date(time()), s))
1320
"""Return a new tree-root file id."""
1321
return gen_file_id('TREE_ROOT')
1324
def copy_branch(branch_from, to_location, revno=None):
1325
"""Copy branch_from into the existing directory to_location.
1328
If not None, only revisions up to this point will be copied.
1329
The head of the new branch will be that revision.
1332
The name of a local directory that exists but is empty.
1334
from bzrlib.merge import merge
1336
assert isinstance(branch_from, Branch)
1337
assert isinstance(to_location, basestring)
1339
br_to = Branch.initialize(to_location)
1340
br_to.set_root_id(branch_from.get_root_id())
1342
revno = branch_from.revno()
1343
br_to.update_revisions(branch_from, stop_revision=revno)
1344
merge((to_location, -1), (to_location, 0), this_dir=to_location,
1345
check_clean=False, ignore_zero=True)
1346
br_to.set_parent(branch_from.base)