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, \
25
sha_file, appendpath, file_kind
27
from bzrlib.errors import BzrError, InvalidRevisionNumber, InvalidRevisionId, \
28
DivergedBranches, NotBranchError
29
from bzrlib.textui import show_status
30
from bzrlib.revision import Revision
31
from bzrlib.delta import compare_trees
32
from bzrlib.tree import EmptyTree, RevisionTree
38
BZR_BRANCH_FORMAT = "Bazaar-NG branch, format 0.0.4\n"
39
## TODO: Maybe include checks for common corruption of newlines, etc?
42
# TODO: Some operations like log might retrieve the same revisions
43
# 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)
136
######################################################################
139
class Branch(object):
140
"""Branch holding a history of revisions.
143
Base directory/url of the branch.
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)
231
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'
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
254
self._lock = ReadLock(self.controlfilename('branch-lock'))
255
self._lock_mode = 'r'
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
270
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)
280
def controlfilename(self, file_or_path):
281
"""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)
287
def controlfile(self, file_or_path, mode='r'):
288
"""Open a control file for this branch.
290
There are two classes of file in the control directory: text
291
and binary. binary files are untranslated byte streams. Text
292
control files are stored with Unix newlines and in UTF-8, even
293
if the platform or locale defaults are different.
295
Controlfiles should almost never be opened in write mode but
296
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'])
354
def get_root_id(self):
355
"""Return the id of this branches root"""
356
inv = self.read_working_inventory()
357
return inv.root.file_id
359
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):
480
"""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()
569
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
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
621
def get_revision_delta(self, revno):
622
"""Return the delta for one revision.
624
The delta is relative to its mainline predecessor, or the
625
empty tree for revision 1.
627
assert isinstance(revno, int)
628
rh = self.revision_history()
629
if not (1 <= revno <= len(rh)):
630
raise InvalidRevisionNumber(revno)
632
# revno is 1-based; list is 0-based
634
new_tree = self.revision_tree(rh[revno-1])
636
old_tree = EmptyTree()
638
old_tree = self.revision_tree(rh[revno-2])
640
return compare_trees(old_tree, new_tree)
644
def get_revision_sha1(self, revision_id):
645
"""Hash the stored value of a revision, and return it."""
646
# In the future, revision entries will be signed. At that
647
# point, it is probably best *not* to include the signature
648
# in the revision hash. Because that lets you re-sign
649
# the revision, (add signatures/remove signatures) and still
650
# have all hash pointers stay consistent.
651
# But for now, just hash the contents.
652
return bzrlib.osutils.sha_file(self.get_revision_xml(revision_id))
655
def get_inventory(self, inventory_id):
656
"""Get Inventory object by hash.
658
TODO: Perhaps for this and similar methods, take a revision
659
parameter which can be either an integer revno or a
661
from bzrlib.inventory import Inventory
663
f = self.get_inventory_xml_file(inventory_id)
664
return bzrlib.xml.serializer_v4.read_inventory(f)
667
def get_inventory_xml(self, inventory_id):
668
"""Get inventory XML as a file object."""
669
return self.inventory_store[inventory_id]
671
get_inventory_xml_file = get_inventory_xml
674
def get_inventory_sha1(self, inventory_id):
675
"""Return the sha1 hash of the inventory entry
677
return sha_file(self.get_inventory_xml(inventory_id))
680
def get_revision_inventory(self, revision_id):
681
"""Return inventory of a past revision."""
682
# bzr 0.0.6 imposes the constraint that the inventory_id
683
# must be the same as its revision, so this is trivial.
684
if revision_id == None:
685
from bzrlib.inventory import Inventory
686
return Inventory(self.get_root_id())
688
return self.get_inventory(revision_id)
691
def revision_history(self):
692
"""Return sequence of revision hashes on to this branch.
694
>>> ScratchBranch().revision_history()
699
return [l.rstrip('\r\n') for l in
700
self.controlfile('revision-history', 'r').readlines()]
705
def common_ancestor(self, other, self_revno=None, other_revno=None):
707
>>> from bzrlib.commit import commit
708
>>> sb = ScratchBranch(files=['foo', 'foo~'])
709
>>> sb.common_ancestor(sb) == (None, None)
711
>>> commit(sb, "Committing first revision", verbose=False)
712
>>> sb.common_ancestor(sb)[0]
714
>>> clone = sb.clone()
715
>>> commit(sb, "Committing second revision", verbose=False)
716
>>> sb.common_ancestor(sb)[0]
718
>>> sb.common_ancestor(clone)[0]
720
>>> commit(clone, "Committing divergent second revision",
722
>>> sb.common_ancestor(clone)[0]
724
>>> sb.common_ancestor(clone) == clone.common_ancestor(sb)
726
>>> sb.common_ancestor(sb) != clone.common_ancestor(clone)
728
>>> clone2 = sb.clone()
729
>>> sb.common_ancestor(clone2)[0]
731
>>> sb.common_ancestor(clone2, self_revno=1)[0]
733
>>> sb.common_ancestor(clone2, other_revno=1)[0]
736
my_history = self.revision_history()
737
other_history = other.revision_history()
738
if self_revno is None:
739
self_revno = len(my_history)
740
if other_revno is None:
741
other_revno = len(other_history)
742
indices = range(min((self_revno, other_revno)))
745
if my_history[r] == other_history[r]:
746
return r+1, my_history[r]
751
"""Return current revision number for this branch.
753
That is equivalent to the number of revisions committed to
756
return len(self.revision_history())
759
def last_patch(self):
760
"""Return last patch hash, or None if no history.
762
ph = self.revision_history()
769
def missing_revisions(self, other, stop_revision=None, diverged_ok=False):
771
If self and other have not diverged, return a list of the revisions
772
present in other, but missing from self.
774
>>> from bzrlib.commit import commit
775
>>> bzrlib.trace.silent = True
776
>>> br1 = ScratchBranch()
777
>>> br2 = ScratchBranch()
778
>>> br1.missing_revisions(br2)
780
>>> commit(br2, "lala!", rev_id="REVISION-ID-1")
781
>>> br1.missing_revisions(br2)
783
>>> br2.missing_revisions(br1)
785
>>> commit(br1, "lala!", rev_id="REVISION-ID-1")
786
>>> br1.missing_revisions(br2)
788
>>> commit(br2, "lala!", rev_id="REVISION-ID-2A")
789
>>> br1.missing_revisions(br2)
791
>>> commit(br1, "lala!", rev_id="REVISION-ID-2B")
792
>>> br1.missing_revisions(br2)
793
Traceback (most recent call last):
794
DivergedBranches: These branches have diverged.
796
self_history = self.revision_history()
797
self_len = len(self_history)
798
other_history = other.revision_history()
799
other_len = len(other_history)
800
common_index = min(self_len, other_len) -1
801
if common_index >= 0 and \
802
self_history[common_index] != other_history[common_index]:
803
raise DivergedBranches(self, other)
805
if stop_revision is None:
806
stop_revision = other_len
807
elif stop_revision > other_len:
808
raise bzrlib.errors.NoSuchRevision(self, stop_revision)
810
return other_history[self_len:stop_revision]
813
def update_revisions(self, other, stop_revision=None):
814
"""Pull in all new revisions from other branch.
816
from bzrlib.fetch import greedy_fetch
818
pb = bzrlib.ui.ui_factory.progress_bar()
819
pb.update('comparing histories')
821
revision_ids = self.missing_revisions(other, stop_revision)
823
if len(revision_ids) > 0:
824
count = greedy_fetch(self, other, revision_ids[-1], pb)[0]
827
self.append_revision(*revision_ids)
828
## note("Added %d revisions." % count)
831
def install_revisions(self, other, revision_ids, pb):
832
if hasattr(other.revision_store, "prefetch"):
833
other.revision_store.prefetch(revision_ids)
834
if hasattr(other.inventory_store, "prefetch"):
835
inventory_ids = [other.get_revision(r).inventory_id
836
for r in revision_ids]
837
other.inventory_store.prefetch(inventory_ids)
840
pb = bzrlib.ui.ui_factory.progress_bar()
847
for i, rev_id in enumerate(revision_ids):
848
pb.update('fetching revision', i+1, len(revision_ids))
850
rev = other.get_revision(rev_id)
851
except bzrlib.errors.NoSuchRevision:
855
revisions.append(rev)
856
inv = other.get_inventory(str(rev.inventory_id))
857
for key, entry in inv.iter_entries():
858
if entry.text_id is None:
860
if entry.text_id not in self.text_store:
861
needed_texts.add(entry.text_id)
865
count, cp_fail = self.text_store.copy_multi(other.text_store,
867
#print "Added %d texts." % count
868
inventory_ids = [ f.inventory_id for f in revisions ]
869
count, cp_fail = self.inventory_store.copy_multi(other.inventory_store,
871
#print "Added %d inventories." % count
872
revision_ids = [ f.revision_id for f in revisions]
874
count, cp_fail = self.revision_store.copy_multi(other.revision_store,
877
assert len(cp_fail) == 0
878
return count, failures
881
def commit(self, *args, **kw):
882
from bzrlib.commit import commit
883
commit(self, *args, **kw)
886
def lookup_revision(self, revision):
887
"""Return the revision identifier for a given revision specifier."""
888
# XXX: I'm not sure this method belongs here; I'd rather have the
889
# revision spec stuff be an UI thing, and branch blissfully unaware
891
# Also, I'm not entirely happy with this method returning None
892
# when the revision doesn't exist.
893
# But I'm keeping the contract I found, because this seems to be
894
# used in a lot of places - and when I do change these, I'd rather
895
# figure out case-by-case which ones actually want to care about
896
# revision specs (eg, they are UI-level) and which ones should trust
897
# that they have a revno/revid.
898
# -- lalo@exoweb.net, 2005-09-07
899
from bzrlib.errors import NoSuchRevision
900
from bzrlib.revisionspec import RevisionSpec
902
spec = RevisionSpec(self, revision)
903
except NoSuchRevision:
908
def revision_id_to_revno(self, revision_id):
909
"""Given a revision id, return its revno"""
910
history = self.revision_history()
912
return history.index(revision_id) + 1
914
raise bzrlib.errors.NoSuchRevision(self, revision_id)
917
def get_rev_id(self, revno, history=None):
918
"""Find the revision id of the specified revno."""
922
history = self.revision_history()
923
elif revno <= 0 or revno > len(history):
924
raise bzrlib.errors.NoSuchRevision(self, revno)
925
return history[revno - 1]
927
def revision_tree(self, revision_id):
928
"""Return Tree for a revision on this branch.
930
`revision_id` may be None for the null revision, in which case
931
an `EmptyTree` is returned."""
932
# TODO: refactor this to use an existing revision object
933
# so we don't need to read it in twice.
934
if revision_id == None:
937
inv = self.get_revision_inventory(revision_id)
938
return RevisionTree(self.text_store, inv)
941
def working_tree(self):
942
"""Return a `Tree` for the working copy."""
943
from bzrlib.workingtree import WorkingTree
944
return WorkingTree(self.base, self.read_working_inventory())
947
def basis_tree(self):
948
"""Return `Tree` object for last revision.
950
If there are no revisions yet, return an `EmptyTree`.
952
r = self.last_patch()
956
return RevisionTree(self.text_store, self.get_revision_inventory(r))
960
def rename_one(self, from_rel, to_rel):
963
This can change the directory or the filename or both.
967
tree = self.working_tree()
969
if not tree.has_filename(from_rel):
970
raise BzrError("can't rename: old working file %r does not exist" % from_rel)
971
if tree.has_filename(to_rel):
972
raise BzrError("can't rename: new working file %r already exists" % to_rel)
974
file_id = inv.path2id(from_rel)
976
raise BzrError("can't rename: old name %r is not versioned" % from_rel)
978
if inv.path2id(to_rel):
979
raise BzrError("can't rename: new name %r is already versioned" % to_rel)
981
to_dir, to_tail = os.path.split(to_rel)
982
to_dir_id = inv.path2id(to_dir)
983
if to_dir_id == None and to_dir != '':
984
raise BzrError("can't determine destination directory id for %r" % to_dir)
986
mutter("rename_one:")
987
mutter(" file_id {%s}" % file_id)
988
mutter(" from_rel %r" % from_rel)
989
mutter(" to_rel %r" % to_rel)
990
mutter(" to_dir %r" % to_dir)
991
mutter(" to_dir_id {%s}" % to_dir_id)
993
inv.rename(file_id, to_dir_id, to_tail)
995
from_abs = self.abspath(from_rel)
996
to_abs = self.abspath(to_rel)
998
os.rename(from_abs, to_abs)
1000
raise BzrError("failed to rename %r to %r: %s"
1001
% (from_abs, to_abs, e[1]),
1002
["rename rolled back"])
1004
self._write_inventory(inv)
1009
def move(self, from_paths, to_name):
1012
to_name must exist as a versioned directory.
1014
If to_name exists and is a directory, the files are moved into
1015
it, keeping their old names. If it is a directory,
1017
Note that to_name is only the last component of the new name;
1018
this doesn't change the directory.
1020
This returns a list of (from_path, to_path) pairs for each
1021
entry that is moved.
1026
## TODO: Option to move IDs only
1027
assert not isinstance(from_paths, basestring)
1028
tree = self.working_tree()
1029
inv = tree.inventory
1030
to_abs = self.abspath(to_name)
1031
if not isdir(to_abs):
1032
raise BzrError("destination %r is not a directory" % to_abs)
1033
if not tree.has_filename(to_name):
1034
raise BzrError("destination %r not in working directory" % to_abs)
1035
to_dir_id = inv.path2id(to_name)
1036
if to_dir_id == None and to_name != '':
1037
raise BzrError("destination %r is not a versioned directory" % to_name)
1038
to_dir_ie = inv[to_dir_id]
1039
if to_dir_ie.kind not in ('directory', 'root_directory'):
1040
raise BzrError("destination %r is not a directory" % to_abs)
1042
to_idpath = inv.get_idpath(to_dir_id)
1044
for f in from_paths:
1045
if not tree.has_filename(f):
1046
raise BzrError("%r does not exist in working tree" % f)
1047
f_id = inv.path2id(f)
1049
raise BzrError("%r is not versioned" % f)
1050
name_tail = splitpath(f)[-1]
1051
dest_path = appendpath(to_name, name_tail)
1052
if tree.has_filename(dest_path):
1053
raise BzrError("destination %r already exists" % dest_path)
1054
if f_id in to_idpath:
1055
raise BzrError("can't move %r to a subdirectory of itself" % f)
1057
# OK, so there's a race here, it's possible that someone will
1058
# create a file in this interval and then the rename might be
1059
# left half-done. But we should have caught most problems.
1061
for f in from_paths:
1062
name_tail = splitpath(f)[-1]
1063
dest_path = appendpath(to_name, name_tail)
1064
result.append((f, dest_path))
1065
inv.rename(inv.path2id(f), to_dir_id, name_tail)
1067
os.rename(self.abspath(f), self.abspath(dest_path))
1069
raise BzrError("failed to rename %r to %r: %s" % (f, dest_path, e[1]),
1070
["rename rolled back"])
1072
self._write_inventory(inv)
1079
def revert(self, filenames, old_tree=None, backups=True):
1080
"""Restore selected files to the versions from a previous tree.
1083
If true (default) backups are made of files before
1086
from bzrlib.errors import NotVersionedError, BzrError
1087
from bzrlib.atomicfile import AtomicFile
1088
from bzrlib.osutils import backup_file
1090
inv = self.read_working_inventory()
1091
if old_tree is None:
1092
old_tree = self.basis_tree()
1093
old_inv = old_tree.inventory
1096
for fn in filenames:
1097
file_id = inv.path2id(fn)
1099
raise NotVersionedError("not a versioned file", fn)
1100
if not old_inv.has_id(file_id):
1101
raise BzrError("file not present in old tree", fn, file_id)
1102
nids.append((fn, file_id))
1104
# TODO: Rename back if it was previously at a different location
1106
# TODO: If given a directory, restore the entire contents from
1107
# the previous version.
1109
# TODO: Make a backup to a temporary file.
1111
# TODO: If the file previously didn't exist, delete it?
1112
for fn, file_id in nids:
1115
f = AtomicFile(fn, 'wb')
1117
f.write(old_tree.get_file(file_id).read())
1123
def pending_merges(self):
1124
"""Return a list of pending merges.
1126
These are revisions that have been merged into the working
1127
directory but not yet committed.
1129
cfn = self.controlfilename('pending-merges')
1130
if not os.path.exists(cfn):
1133
for l in self.controlfile('pending-merges', 'r').readlines():
1134
p.append(l.rstrip('\n'))
1138
def add_pending_merge(self, revision_id):
1139
from bzrlib.revision import validate_revision_id
1141
validate_revision_id(revision_id)
1143
p = self.pending_merges()
1144
if revision_id in p:
1146
p.append(revision_id)
1147
self.set_pending_merges(p)
1150
def set_pending_merges(self, rev_list):
1151
from bzrlib.atomicfile import AtomicFile
1154
f = AtomicFile(self.controlfilename('pending-merges'))
1165
def get_parent(self):
1166
"""Return the parent location of the branch.
1168
This is the default location for push/pull/missing. The usual
1169
pattern is that the user can override it by specifying a
1173
_locs = ['parent', 'pull', 'x-pull']
1176
return self.controlfile(l, 'r').read().strip('\n')
1178
if e.errno != errno.ENOENT:
1183
def set_parent(self, url):
1184
# TODO: Maybe delete old location files?
1185
from bzrlib.atomicfile import AtomicFile
1188
f = AtomicFile(self.controlfilename('parent'))
1197
def check_revno(self, revno):
1199
Check whether a revno corresponds to any revision.
1200
Zero (the NULL revision) is considered valid.
1203
self.check_real_revno(revno)
1205
def check_real_revno(self, revno):
1207
Check whether a revno corresponds to a real revision.
1208
Zero (the NULL revision) is considered invalid
1210
if revno < 1 or revno > self.revno():
1211
raise InvalidRevisionNumber(revno)
1216
class ScratchBranch(LocalBranch):
1217
"""Special test class: a branch that cleans up after itself.
1219
>>> b = ScratchBranch()
1227
def __init__(self, files=[], dirs=[], base=None):
1228
"""Make a test branch.
1230
This creates a temporary directory and runs init-tree in it.
1232
If any files are listed, they are created in the working copy.
1234
from tempfile import mkdtemp
1239
LocalBranch.__init__(self, base, init=init)
1241
os.mkdir(self.abspath(d))
1244
file(os.path.join(self.base, f), 'w').write('content of %s' % f)
1249
>>> orig = ScratchBranch(files=["file1", "file2"])
1250
>>> clone = orig.clone()
1251
>>> os.path.samefile(orig.base, clone.base)
1253
>>> os.path.isfile(os.path.join(clone.base, "file1"))
1256
from shutil import copytree
1257
from tempfile import mkdtemp
1260
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)
1287
######################################################################
1291
def is_control_file(filename):
1292
## FIXME: better check
1293
filename = os.path.normpath(filename)
1294
while filename != '':
1295
head, tail = os.path.split(filename)
1296
## mutter('check %r for control file' % ((head, tail), ))
1297
if tail == bzrlib.BZRDIR:
1299
if filename == head:
1306
def gen_file_id(name):
1307
"""Return new file id.
1309
This should probably generate proper UUIDs, but for the moment we
1310
cope with just randomness because running uuidgen every time is
1313
from binascii import hexlify
1314
from time import time
1316
# get last component
1317
idx = name.rfind('/')
1319
name = name[idx+1 : ]
1320
idx = name.rfind('\\')
1322
name = name[idx+1 : ]
1324
# make it not a hidden file
1325
name = name.lstrip('.')
1327
# remove any wierd characters; we don't escape them but rather
1328
# just pull them out
1329
name = re.sub(r'[^\w.]', '', name)
1331
s = hexlify(rand_bytes(8))
1332
return '-'.join((name, compact_date(time()), s))
1336
"""Return a new tree-root file id."""
1337
return gen_file_id('TREE_ROOT')
1340
def copy_branch(branch_from, to_location, revision=None):
1341
"""Copy branch_from into the existing directory to_location.
1344
If not None, only revisions up to this point will be copied.
1345
The head of the new branch will be that revision.
1348
The name of a local directory that exists but is empty.
1350
from bzrlib.merge import merge
1351
from bzrlib.revisionspec import RevisionSpec
1353
assert isinstance(branch_from, Branch)
1354
assert isinstance(to_location, basestring)
1356
br_to = Branch(to_location, init=True)
1357
br_to.set_root_id(branch_from.get_root_id())
1358
if revision is None:
1359
revno = branch_from.revno()
1361
revno, rev_id = RevisionSpec(branch_from, revision)
1362
br_to.update_revisions(branch_from, stop_revision=revno)
1363
merge((to_location, -1), (to_location, 0), this_dir=to_location,
1364
check_clean=False, ignore_zero=True)
1366
from_location = branch_from.base
1367
br_to.set_parent(branch_from.base)