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.
47
def find_branch(base, init=False, find_root=True):
49
return Branch.initialize(base)
51
return Branch.open_containing(base)
52
return Branch.open(base)
55
def find_cached_branch(f, cache_root, **args):
56
from bzrlib.remotebranch import RemoteBranch
57
br = find_branch(f, **args)
58
def cacheify(br, store_name):
59
from bzrlib.meta_store import CachedStore
60
cache_path = os.path.join(cache_root, store_name)
62
new_store = CachedStore(getattr(br, store_name), cache_path)
63
setattr(br, store_name, new_store)
65
if isinstance(br, RemoteBranch):
66
cacheify(br, 'inventory_store')
67
cacheify(br, 'text_store')
68
cacheify(br, 'revision_store')
72
def _relpath(base, path):
73
"""Return path relative to base, or raise exception.
75
The path may be either an absolute path or a path relative to the
76
current working directory.
78
Lifted out of Branch.relpath for ease of testing.
80
os.path.commonprefix (python2.4) has a bad bug that it works just
81
on string prefixes, assuming that '/u' is a prefix of '/u2'. This
82
avoids that problem."""
83
rp = os.path.abspath(path)
87
while len(head) >= len(base):
90
head, tail = os.path.split(head)
94
raise NotBranchError("path %r is not within branch %r" % (rp, base))
99
def find_branch_root(f=None):
100
"""Find the branch root enclosing f, or pwd.
102
f may be a filename or a URL.
104
It is not necessary that f exists.
106
Basically we keep looking up until we find the control directory or
107
run into the root. If there isn't one, raises NotBranchError.
111
elif hasattr(os.path, 'realpath'):
112
f = os.path.realpath(f)
114
f = os.path.abspath(f)
115
if not os.path.exists(f):
116
raise BzrError('%r does not exist' % f)
122
if os.path.exists(os.path.join(f, bzrlib.BZRDIR)):
124
head, tail = os.path.split(f)
126
# reached the root, whatever that may be
127
raise NotBranchError('%s is not in a branch' % orig_f)
133
######################################################################
136
class Branch(object):
137
"""Branch holding a history of revisions.
140
Base directory/url of the branch.
144
def __new__(cls, *a, **kw):
145
"""this is temporary, till we get rid of all code that does
148
# XXX: AAARGH! MY EYES! UUUUGLY!!!
151
b = object.__new__(cls)
156
"""Open an existing branch, rooted at 'base' (url)"""
157
if base and (base.startswith('http://') or base.startswith('https://')):
158
from bzrlib.remotebranch import RemoteBranch
159
return RemoteBranch(base, find_root=False)
161
return LocalBranch(base, find_root=False)
164
def open_containing(url):
165
"""Open an existing branch, containing url (search upwards for the root)
167
if url and (url.startswith('http://') or url.startswith('https://')):
168
from bzrlib.remotebranch import RemoteBranch
169
return RemoteBranch(url)
171
return LocalBranch(url)
174
def initialize(base):
175
"""Create a new branch, rooted at 'base' (url)"""
176
if base and (base.startswith('http://') or base.startswith('https://')):
177
from bzrlib.remotebranch import RemoteBranch
178
return RemoteBranch(base, init=True)
180
return LocalBranch(base, init=True)
183
class LocalBranch(Branch):
184
"""A branch stored in the actual filesystem.
186
Note that it's "local" in the context of the filesystem; it doesn't
187
really matter if it's on an nfs/smb/afs/coda/... share, as long as
188
it's writable, and can be accessed via the normal filesystem API.
194
If _lock_mode is true, a positive count of the number of times the
198
Lock object from bzrlib.lock.
200
# We actually expect this class to be somewhat short-lived; part of its
201
# purpose is to try to isolate what bits of the branch logic are tied to
202
# filesystem access, so that in a later step, we can extricate them to
203
# a separarte ("storage") class.
208
def __init__(self, base, init=False, find_root=True):
209
"""Create new branch object at a particular location.
211
base -- Base directory for the branch.
213
init -- If True, create new control files in a previously
214
unversioned directory. If False, the branch must already
217
find_root -- If true and init is false, find the root of the
218
existing branch containing base.
220
In the test suite, creation of new trees is tested using the
221
`ScratchBranch` class.
223
from bzrlib.store import ImmutableStore
225
self.base = os.path.realpath(base)
228
self.base = find_branch_root(base)
230
self.base = os.path.realpath(base)
231
if not isdir(self.controlfilename('.')):
232
raise NotBranchError("not a bzr branch: %s" % quotefn(base),
233
['use "bzr init" to initialize a new working tree',
234
'current bzr can only operate from top-of-tree'])
237
self.text_store = ImmutableStore(self.controlfilename('text-store'))
238
self.revision_store = ImmutableStore(self.controlfilename('revision-store'))
239
self.inventory_store = ImmutableStore(self.controlfilename('inventory-store'))
243
return '%s(%r)' % (self.__class__.__name__, self.base)
250
if self._lock_mode or self._lock:
251
from bzrlib.warnings import warn
252
warn("branch %r was not explicitly unlocked" % self)
256
def lock_write(self):
258
if self._lock_mode != 'w':
259
from bzrlib.errors import LockError
260
raise LockError("can't upgrade to a write lock from %r" %
262
self._lock_count += 1
264
from bzrlib.lock import WriteLock
266
self._lock = WriteLock(self.controlfilename('branch-lock'))
267
self._lock_mode = 'w'
273
assert self._lock_mode in ('r', 'w'), \
274
"invalid lock mode %r" % self._lock_mode
275
self._lock_count += 1
277
from bzrlib.lock import ReadLock
279
self._lock = ReadLock(self.controlfilename('branch-lock'))
280
self._lock_mode = 'r'
284
if not self._lock_mode:
285
from bzrlib.errors import LockError
286
raise LockError('branch %r is not locked' % (self))
288
if self._lock_count > 1:
289
self._lock_count -= 1
293
self._lock_mode = self._lock_count = None
295
def abspath(self, name):
296
"""Return absolute filename for something in the branch"""
297
return os.path.join(self.base, name)
299
def relpath(self, path):
300
"""Return path relative to this branch of something inside it.
302
Raises an error if path is not in this branch."""
303
return _relpath(self.base, path)
305
def controlfilename(self, file_or_path):
306
"""Return location relative to branch."""
307
if isinstance(file_or_path, basestring):
308
file_or_path = [file_or_path]
309
return os.path.join(self.base, bzrlib.BZRDIR, *file_or_path)
312
def controlfile(self, file_or_path, mode='r'):
313
"""Open a control file for this branch.
315
There are two classes of file in the control directory: text
316
and binary. binary files are untranslated byte streams. Text
317
control files are stored with Unix newlines and in UTF-8, even
318
if the platform or locale defaults are different.
320
Controlfiles should almost never be opened in write mode but
321
rather should be atomically copied and replaced using atomicfile.
324
fn = self.controlfilename(file_or_path)
326
if mode == 'rb' or mode == 'wb':
327
return file(fn, mode)
328
elif mode == 'r' or mode == 'w':
329
# open in binary mode anyhow so there's no newline translation;
330
# codecs uses line buffering by default; don't want that.
332
return codecs.open(fn, mode + 'b', 'utf-8',
335
raise BzrError("invalid controlfile mode %r" % mode)
337
def _make_control(self):
338
from bzrlib.inventory import Inventory
340
os.mkdir(self.controlfilename([]))
341
self.controlfile('README', 'w').write(
342
"This is a Bazaar-NG control directory.\n"
343
"Do not change any files in this directory.\n")
344
self.controlfile('branch-format', 'w').write(BZR_BRANCH_FORMAT)
345
for d in ('text-store', 'inventory-store', 'revision-store'):
346
os.mkdir(self.controlfilename(d))
347
for f in ('revision-history', 'merged-patches',
348
'pending-merged-patches', 'branch-name',
351
self.controlfile(f, 'w').write('')
352
mutter('created control directory in ' + self.base)
354
# if we want per-tree root ids then this is the place to set
355
# them; they're not needed for now and so ommitted for
357
f = self.controlfile('inventory','w')
358
bzrlib.xml.serializer_v4.write_inventory(Inventory(), f)
361
def _check_format(self):
362
"""Check this branch format is supported.
364
The current tool only supports the current unstable format.
366
In the future, we might need different in-memory Branch
367
classes to support downlevel branches. But not yet.
369
# This ignores newlines so that we can open branches created
370
# on Windows from Linux and so on. I think it might be better
371
# to always make all internal files in unix format.
372
fmt = self.controlfile('branch-format', 'r').read()
373
fmt = fmt.replace('\r\n', '\n')
374
if fmt != BZR_BRANCH_FORMAT:
375
raise BzrError('sorry, branch format %r not supported' % fmt,
376
['use a different bzr version',
377
'or remove the .bzr directory and "bzr init" again'])
379
def get_root_id(self):
380
"""Return the id of this branches root"""
381
inv = self.read_working_inventory()
382
return inv.root.file_id
384
def set_root_id(self, file_id):
385
inv = self.read_working_inventory()
386
orig_root_id = inv.root.file_id
387
del inv._byid[inv.root.file_id]
388
inv.root.file_id = file_id
389
inv._byid[inv.root.file_id] = inv.root
392
if entry.parent_id in (None, orig_root_id):
393
entry.parent_id = inv.root.file_id
394
self._write_inventory(inv)
396
def read_working_inventory(self):
397
"""Read the working inventory."""
398
from bzrlib.inventory import Inventory
401
# ElementTree does its own conversion from UTF-8, so open in
403
f = self.controlfile('inventory', 'rb')
404
return bzrlib.xml.serializer_v4.read_inventory(f)
409
def _write_inventory(self, inv):
410
"""Update the working inventory.
412
That is to say, the inventory describing changes underway, that
413
will be committed to the next revision.
415
from bzrlib.atomicfile import AtomicFile
419
f = AtomicFile(self.controlfilename('inventory'), 'wb')
421
bzrlib.xml.serializer_v4.write_inventory(inv, f)
428
mutter('wrote working inventory')
431
inventory = property(read_working_inventory, _write_inventory, None,
432
"""Inventory for the working copy.""")
435
def add(self, files, ids=None):
436
"""Make files versioned.
438
Note that the command line normally calls smart_add instead,
439
which can automatically recurse.
441
This puts the files in the Added state, so that they will be
442
recorded by the next commit.
445
List of paths to add, relative to the base of the tree.
448
If set, use these instead of automatically generated ids.
449
Must be the same length as the list of files, but may
450
contain None for ids that are to be autogenerated.
452
TODO: Perhaps have an option to add the ids even if the files do
455
TODO: Perhaps yield the ids and paths as they're added.
457
# TODO: Re-adding a file that is removed in the working copy
458
# should probably put it back with the previous ID.
459
if isinstance(files, basestring):
460
assert(ids is None or isinstance(ids, basestring))
466
ids = [None] * len(files)
468
assert(len(ids) == len(files))
472
inv = self.read_working_inventory()
473
for f,file_id in zip(files, ids):
474
if is_control_file(f):
475
raise BzrError("cannot add control file %s" % quotefn(f))
480
raise BzrError("cannot add top-level %r" % f)
482
fullpath = os.path.normpath(self.abspath(f))
485
kind = file_kind(fullpath)
487
# maybe something better?
488
raise BzrError('cannot add: not a regular file or directory: %s' % quotefn(f))
490
if kind != 'file' and kind != 'directory':
491
raise BzrError('cannot add: not a regular file or directory: %s' % quotefn(f))
494
file_id = gen_file_id(f)
495
inv.add_path(f, kind=kind, file_id=file_id)
497
mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
499
self._write_inventory(inv)
504
def print_file(self, file, revno):
505
"""Print `file` to stdout."""
508
tree = self.revision_tree(self.get_rev_id(revno))
509
# use inventory as it was in that revision
510
file_id = tree.inventory.path2id(file)
512
raise BzrError("%r is not present in revision %s" % (file, revno))
513
tree.print_file(file_id)
518
def remove(self, files, verbose=False):
519
"""Mark nominated files for removal from the inventory.
521
This does not remove their text. This does not run on
523
TODO: Refuse to remove modified files unless --force is given?
525
TODO: Do something useful with directories.
527
TODO: Should this remove the text or not? Tough call; not
528
removing may be useful and the user can just use use rm, and
529
is the opposite of add. Removing it is consistent with most
530
other tools. Maybe an option.
532
## TODO: Normalize names
533
## TODO: Remove nested loops; better scalability
534
if isinstance(files, basestring):
540
tree = self.working_tree()
543
# do this before any modifications
547
raise BzrError("cannot remove unversioned file %s" % quotefn(f))
548
mutter("remove inventory entry %s {%s}" % (quotefn(f), fid))
550
# having remove it, it must be either ignored or unknown
551
if tree.is_ignored(f):
555
show_status(new_status, inv[fid].kind, quotefn(f))
558
self._write_inventory(inv)
563
# FIXME: this doesn't need to be a branch method
564
def set_inventory(self, new_inventory_list):
565
from bzrlib.inventory import Inventory, InventoryEntry
566
inv = Inventory(self.get_root_id())
567
for path, file_id, parent, kind in new_inventory_list:
568
name = os.path.basename(path)
571
inv.add(InventoryEntry(file_id, name, kind, parent))
572
self._write_inventory(inv)
576
"""Return all unknown files.
578
These are files in the working directory that are not versioned or
579
control files or ignored.
581
>>> b = ScratchBranch(files=['foo', 'foo~'])
582
>>> list(b.unknowns())
585
>>> list(b.unknowns())
588
>>> list(b.unknowns())
591
return self.working_tree().unknowns()
594
def append_revision(self, *revision_ids):
595
from bzrlib.atomicfile import AtomicFile
597
for revision_id in revision_ids:
598
mutter("add {%s} to revision-history" % revision_id)
600
rev_history = self.revision_history()
601
rev_history.extend(revision_ids)
603
f = AtomicFile(self.controlfilename('revision-history'))
605
for rev_id in rev_history:
612
def get_revision_xml_file(self, revision_id):
613
"""Return XML file object for revision object."""
614
if not revision_id or not isinstance(revision_id, basestring):
615
raise InvalidRevisionId(revision_id)
620
return self.revision_store[revision_id]
622
raise bzrlib.errors.NoSuchRevision(self, revision_id)
628
get_revision_xml = get_revision_xml_file
631
def get_revision(self, revision_id):
632
"""Return the Revision object for a named revision"""
633
xml_file = self.get_revision_xml_file(revision_id)
636
r = bzrlib.xml.serializer_v4.read_revision(xml_file)
637
except SyntaxError, e:
638
raise bzrlib.errors.BzrError('failed to unpack revision_xml',
642
assert r.revision_id == revision_id
646
def get_revision_delta(self, revno):
647
"""Return the delta for one revision.
649
The delta is relative to its mainline predecessor, or the
650
empty tree for revision 1.
652
assert isinstance(revno, int)
653
rh = self.revision_history()
654
if not (1 <= revno <= len(rh)):
655
raise InvalidRevisionNumber(revno)
657
# revno is 1-based; list is 0-based
659
new_tree = self.revision_tree(rh[revno-1])
661
old_tree = EmptyTree()
663
old_tree = self.revision_tree(rh[revno-2])
665
return compare_trees(old_tree, new_tree)
669
def get_revision_sha1(self, revision_id):
670
"""Hash the stored value of a revision, and return it."""
671
# In the future, revision entries will be signed. At that
672
# point, it is probably best *not* to include the signature
673
# in the revision hash. Because that lets you re-sign
674
# the revision, (add signatures/remove signatures) and still
675
# have all hash pointers stay consistent.
676
# But for now, just hash the contents.
677
return bzrlib.osutils.sha_file(self.get_revision_xml(revision_id))
680
def get_inventory(self, inventory_id):
681
"""Get Inventory object by hash.
683
TODO: Perhaps for this and similar methods, take a revision
684
parameter which can be either an integer revno or a
686
from bzrlib.inventory import Inventory
688
f = self.get_inventory_xml_file(inventory_id)
689
return bzrlib.xml.serializer_v4.read_inventory(f)
692
def get_inventory_xml(self, inventory_id):
693
"""Get inventory XML as a file object."""
694
return self.inventory_store[inventory_id]
696
get_inventory_xml_file = get_inventory_xml
699
def get_inventory_sha1(self, inventory_id):
700
"""Return the sha1 hash of the inventory entry
702
return sha_file(self.get_inventory_xml(inventory_id))
705
def get_revision_inventory(self, revision_id):
706
"""Return inventory of a past revision."""
707
# bzr 0.0.6 imposes the constraint that the inventory_id
708
# must be the same as its revision, so this is trivial.
709
if revision_id == None:
710
from bzrlib.inventory import Inventory
711
return Inventory(self.get_root_id())
713
return self.get_inventory(revision_id)
716
def revision_history(self):
717
"""Return sequence of revision hashes on to this branch.
719
>>> ScratchBranch().revision_history()
724
return [l.rstrip('\r\n') for l in
725
self.controlfile('revision-history', 'r').readlines()]
730
def common_ancestor(self, other, self_revno=None, other_revno=None):
732
>>> from bzrlib.commit import commit
733
>>> sb = ScratchBranch(files=['foo', 'foo~'])
734
>>> sb.common_ancestor(sb) == (None, None)
736
>>> commit(sb, "Committing first revision", verbose=False)
737
>>> sb.common_ancestor(sb)[0]
739
>>> clone = sb.clone()
740
>>> commit(sb, "Committing second revision", verbose=False)
741
>>> sb.common_ancestor(sb)[0]
743
>>> sb.common_ancestor(clone)[0]
745
>>> commit(clone, "Committing divergent second revision",
747
>>> sb.common_ancestor(clone)[0]
749
>>> sb.common_ancestor(clone) == clone.common_ancestor(sb)
751
>>> sb.common_ancestor(sb) != clone.common_ancestor(clone)
753
>>> clone2 = sb.clone()
754
>>> sb.common_ancestor(clone2)[0]
756
>>> sb.common_ancestor(clone2, self_revno=1)[0]
758
>>> sb.common_ancestor(clone2, other_revno=1)[0]
761
my_history = self.revision_history()
762
other_history = other.revision_history()
763
if self_revno is None:
764
self_revno = len(my_history)
765
if other_revno is None:
766
other_revno = len(other_history)
767
indices = range(min((self_revno, other_revno)))
770
if my_history[r] == other_history[r]:
771
return r+1, my_history[r]
776
"""Return current revision number for this branch.
778
That is equivalent to the number of revisions committed to
781
return len(self.revision_history())
784
def last_patch(self):
785
"""Return last patch hash, or None if no history.
787
ph = self.revision_history()
794
def missing_revisions(self, other, stop_revision=None, diverged_ok=False):
796
If self and other have not diverged, return a list of the revisions
797
present in other, but missing from self.
799
>>> from bzrlib.commit import commit
800
>>> bzrlib.trace.silent = True
801
>>> br1 = ScratchBranch()
802
>>> br2 = ScratchBranch()
803
>>> br1.missing_revisions(br2)
805
>>> commit(br2, "lala!", rev_id="REVISION-ID-1")
806
>>> br1.missing_revisions(br2)
808
>>> br2.missing_revisions(br1)
810
>>> commit(br1, "lala!", rev_id="REVISION-ID-1")
811
>>> br1.missing_revisions(br2)
813
>>> commit(br2, "lala!", rev_id="REVISION-ID-2A")
814
>>> br1.missing_revisions(br2)
816
>>> commit(br1, "lala!", rev_id="REVISION-ID-2B")
817
>>> br1.missing_revisions(br2)
818
Traceback (most recent call last):
819
DivergedBranches: These branches have diverged.
821
self_history = self.revision_history()
822
self_len = len(self_history)
823
other_history = other.revision_history()
824
other_len = len(other_history)
825
common_index = min(self_len, other_len) -1
826
if common_index >= 0 and \
827
self_history[common_index] != other_history[common_index]:
828
raise DivergedBranches(self, other)
830
if stop_revision is None:
831
stop_revision = other_len
832
elif stop_revision > other_len:
833
raise bzrlib.errors.NoSuchRevision(self, stop_revision)
835
return other_history[self_len:stop_revision]
838
def update_revisions(self, other, stop_revision=None):
839
"""Pull in all new revisions from other branch.
841
from bzrlib.fetch import greedy_fetch
843
pb = bzrlib.ui.ui_factory.progress_bar()
844
pb.update('comparing histories')
846
revision_ids = self.missing_revisions(other, stop_revision)
848
if len(revision_ids) > 0:
849
count = greedy_fetch(self, other, revision_ids[-1], pb)[0]
852
self.append_revision(*revision_ids)
853
## note("Added %d revisions." % count)
856
def install_revisions(self, other, revision_ids, pb):
857
if hasattr(other.revision_store, "prefetch"):
858
other.revision_store.prefetch(revision_ids)
859
if hasattr(other.inventory_store, "prefetch"):
860
inventory_ids = [other.get_revision(r).inventory_id
861
for r in revision_ids]
862
other.inventory_store.prefetch(inventory_ids)
865
pb = bzrlib.ui.ui_factory.progress_bar()
872
for i, rev_id in enumerate(revision_ids):
873
pb.update('fetching revision', i+1, len(revision_ids))
875
rev = other.get_revision(rev_id)
876
except bzrlib.errors.NoSuchRevision:
880
revisions.append(rev)
881
inv = other.get_inventory(str(rev.inventory_id))
882
for key, entry in inv.iter_entries():
883
if entry.text_id is None:
885
if entry.text_id not in self.text_store:
886
needed_texts.add(entry.text_id)
890
count, cp_fail = self.text_store.copy_multi(other.text_store,
892
#print "Added %d texts." % count
893
inventory_ids = [ f.inventory_id for f in revisions ]
894
count, cp_fail = self.inventory_store.copy_multi(other.inventory_store,
896
#print "Added %d inventories." % count
897
revision_ids = [ f.revision_id for f in revisions]
899
count, cp_fail = self.revision_store.copy_multi(other.revision_store,
902
assert len(cp_fail) == 0
903
return count, failures
906
def commit(self, *args, **kw):
907
from bzrlib.commit import commit
908
commit(self, *args, **kw)
911
def revision_id_to_revno(self, revision_id):
912
"""Given a revision id, return its revno"""
913
history = self.revision_history()
915
return history.index(revision_id) + 1
917
raise bzrlib.errors.NoSuchRevision(self, revision_id)
920
def get_rev_id(self, revno, history=None):
921
"""Find the revision id of the specified revno."""
925
history = self.revision_history()
926
elif revno <= 0 or revno > len(history):
927
raise bzrlib.errors.NoSuchRevision(self, revno)
928
return history[revno - 1]
930
def revision_tree(self, revision_id):
931
"""Return Tree for a revision on this branch.
933
`revision_id` may be None for the null revision, in which case
934
an `EmptyTree` is returned."""
935
# TODO: refactor this to use an existing revision object
936
# so we don't need to read it in twice.
937
if revision_id == None:
940
inv = self.get_revision_inventory(revision_id)
941
return RevisionTree(self.text_store, inv)
944
def working_tree(self):
945
"""Return a `Tree` for the working copy."""
946
from bzrlib.workingtree import WorkingTree
947
return WorkingTree(self.base, self.read_working_inventory())
950
def basis_tree(self):
951
"""Return `Tree` object for last revision.
953
If there are no revisions yet, return an `EmptyTree`.
955
r = self.last_patch()
959
return RevisionTree(self.text_store, self.get_revision_inventory(r))
963
def rename_one(self, from_rel, to_rel):
966
This can change the directory or the filename or both.
970
tree = self.working_tree()
972
if not tree.has_filename(from_rel):
973
raise BzrError("can't rename: old working file %r does not exist" % from_rel)
974
if tree.has_filename(to_rel):
975
raise BzrError("can't rename: new working file %r already exists" % to_rel)
977
file_id = inv.path2id(from_rel)
979
raise BzrError("can't rename: old name %r is not versioned" % from_rel)
981
if inv.path2id(to_rel):
982
raise BzrError("can't rename: new name %r is already versioned" % to_rel)
984
to_dir, to_tail = os.path.split(to_rel)
985
to_dir_id = inv.path2id(to_dir)
986
if to_dir_id == None and to_dir != '':
987
raise BzrError("can't determine destination directory id for %r" % to_dir)
989
mutter("rename_one:")
990
mutter(" file_id {%s}" % file_id)
991
mutter(" from_rel %r" % from_rel)
992
mutter(" to_rel %r" % to_rel)
993
mutter(" to_dir %r" % to_dir)
994
mutter(" to_dir_id {%s}" % to_dir_id)
996
inv.rename(file_id, to_dir_id, to_tail)
998
from_abs = self.abspath(from_rel)
999
to_abs = self.abspath(to_rel)
1001
os.rename(from_abs, to_abs)
1003
raise BzrError("failed to rename %r to %r: %s"
1004
% (from_abs, to_abs, e[1]),
1005
["rename rolled back"])
1007
self._write_inventory(inv)
1012
def move(self, from_paths, to_name):
1015
to_name must exist as a versioned directory.
1017
If to_name exists and is a directory, the files are moved into
1018
it, keeping their old names. If it is a directory,
1020
Note that to_name is only the last component of the new name;
1021
this doesn't change the directory.
1023
This returns a list of (from_path, to_path) pairs for each
1024
entry that is moved.
1029
## TODO: Option to move IDs only
1030
assert not isinstance(from_paths, basestring)
1031
tree = self.working_tree()
1032
inv = tree.inventory
1033
to_abs = self.abspath(to_name)
1034
if not isdir(to_abs):
1035
raise BzrError("destination %r is not a directory" % to_abs)
1036
if not tree.has_filename(to_name):
1037
raise BzrError("destination %r not in working directory" % to_abs)
1038
to_dir_id = inv.path2id(to_name)
1039
if to_dir_id == None and to_name != '':
1040
raise BzrError("destination %r is not a versioned directory" % to_name)
1041
to_dir_ie = inv[to_dir_id]
1042
if to_dir_ie.kind not in ('directory', 'root_directory'):
1043
raise BzrError("destination %r is not a directory" % to_abs)
1045
to_idpath = inv.get_idpath(to_dir_id)
1047
for f in from_paths:
1048
if not tree.has_filename(f):
1049
raise BzrError("%r does not exist in working tree" % f)
1050
f_id = inv.path2id(f)
1052
raise BzrError("%r is not versioned" % f)
1053
name_tail = splitpath(f)[-1]
1054
dest_path = appendpath(to_name, name_tail)
1055
if tree.has_filename(dest_path):
1056
raise BzrError("destination %r already exists" % dest_path)
1057
if f_id in to_idpath:
1058
raise BzrError("can't move %r to a subdirectory of itself" % f)
1060
# OK, so there's a race here, it's possible that someone will
1061
# create a file in this interval and then the rename might be
1062
# left half-done. But we should have caught most problems.
1064
for f in from_paths:
1065
name_tail = splitpath(f)[-1]
1066
dest_path = appendpath(to_name, name_tail)
1067
result.append((f, dest_path))
1068
inv.rename(inv.path2id(f), to_dir_id, name_tail)
1070
os.rename(self.abspath(f), self.abspath(dest_path))
1072
raise BzrError("failed to rename %r to %r: %s" % (f, dest_path, e[1]),
1073
["rename rolled back"])
1075
self._write_inventory(inv)
1082
def revert(self, filenames, old_tree=None, backups=True):
1083
"""Restore selected files to the versions from a previous tree.
1086
If true (default) backups are made of files before
1089
from bzrlib.errors import NotVersionedError, BzrError
1090
from bzrlib.atomicfile import AtomicFile
1091
from bzrlib.osutils import backup_file
1093
inv = self.read_working_inventory()
1094
if old_tree is None:
1095
old_tree = self.basis_tree()
1096
old_inv = old_tree.inventory
1099
for fn in filenames:
1100
file_id = inv.path2id(fn)
1102
raise NotVersionedError("not a versioned file", fn)
1103
if not old_inv.has_id(file_id):
1104
raise BzrError("file not present in old tree", fn, file_id)
1105
nids.append((fn, file_id))
1107
# TODO: Rename back if it was previously at a different location
1109
# TODO: If given a directory, restore the entire contents from
1110
# the previous version.
1112
# TODO: Make a backup to a temporary file.
1114
# TODO: If the file previously didn't exist, delete it?
1115
for fn, file_id in nids:
1118
f = AtomicFile(fn, 'wb')
1120
f.write(old_tree.get_file(file_id).read())
1126
def pending_merges(self):
1127
"""Return a list of pending merges.
1129
These are revisions that have been merged into the working
1130
directory but not yet committed.
1132
cfn = self.controlfilename('pending-merges')
1133
if not os.path.exists(cfn):
1136
for l in self.controlfile('pending-merges', 'r').readlines():
1137
p.append(l.rstrip('\n'))
1141
def add_pending_merge(self, revision_id):
1142
from bzrlib.revision import validate_revision_id
1144
validate_revision_id(revision_id)
1146
p = self.pending_merges()
1147
if revision_id in p:
1149
p.append(revision_id)
1150
self.set_pending_merges(p)
1153
def set_pending_merges(self, rev_list):
1154
from bzrlib.atomicfile import AtomicFile
1157
f = AtomicFile(self.controlfilename('pending-merges'))
1168
def get_parent(self):
1169
"""Return the parent location of the branch.
1171
This is the default location for push/pull/missing. The usual
1172
pattern is that the user can override it by specifying a
1176
_locs = ['parent', 'pull', 'x-pull']
1179
return self.controlfile(l, 'r').read().strip('\n')
1181
if e.errno != errno.ENOENT:
1186
def set_parent(self, url):
1187
# TODO: Maybe delete old location files?
1188
from bzrlib.atomicfile import AtomicFile
1191
f = AtomicFile(self.controlfilename('parent'))
1200
def check_revno(self, revno):
1202
Check whether a revno corresponds to any revision.
1203
Zero (the NULL revision) is considered valid.
1206
self.check_real_revno(revno)
1208
def check_real_revno(self, revno):
1210
Check whether a revno corresponds to a real revision.
1211
Zero (the NULL revision) is considered invalid
1213
if revno < 1 or revno > self.revno():
1214
raise InvalidRevisionNumber(revno)
1219
class ScratchBranch(LocalBranch):
1220
"""Special test class: a branch that cleans up after itself.
1222
>>> b = ScratchBranch()
1230
def __init__(self, files=[], dirs=[], base=None):
1231
"""Make a test branch.
1233
This creates a temporary directory and runs init-tree in it.
1235
If any files are listed, they are created in the working copy.
1237
from tempfile import mkdtemp
1242
LocalBranch.__init__(self, base, init=init)
1244
os.mkdir(self.abspath(d))
1247
file(os.path.join(self.base, f), 'w').write('content of %s' % f)
1252
>>> orig = ScratchBranch(files=["file1", "file2"])
1253
>>> clone = orig.clone()
1254
>>> os.path.samefile(orig.base, clone.base)
1256
>>> os.path.isfile(os.path.join(clone.base, "file1"))
1259
from shutil import copytree
1260
from tempfile import mkdtemp
1263
copytree(self.base, base, symlinks=True)
1264
return ScratchBranch(base=base)
1272
"""Destroy the test branch, removing the scratch directory."""
1273
from shutil import rmtree
1276
mutter("delete ScratchBranch %s" % self.base)
1279
# Work around for shutil.rmtree failing on Windows when
1280
# readonly files are encountered
1281
mutter("hit exception in destroying ScratchBranch: %s" % e)
1282
for root, dirs, files in os.walk(self.base, topdown=False):
1284
os.chmod(os.path.join(root, name), 0700)
1290
######################################################################
1294
def is_control_file(filename):
1295
## FIXME: better check
1296
filename = os.path.normpath(filename)
1297
while filename != '':
1298
head, tail = os.path.split(filename)
1299
## mutter('check %r for control file' % ((head, tail), ))
1300
if tail == bzrlib.BZRDIR:
1302
if filename == head:
1309
def gen_file_id(name):
1310
"""Return new file id.
1312
This should probably generate proper UUIDs, but for the moment we
1313
cope with just randomness because running uuidgen every time is
1316
from binascii import hexlify
1317
from time import time
1319
# get last component
1320
idx = name.rfind('/')
1322
name = name[idx+1 : ]
1323
idx = name.rfind('\\')
1325
name = name[idx+1 : ]
1327
# make it not a hidden file
1328
name = name.lstrip('.')
1330
# remove any wierd characters; we don't escape them but rather
1331
# just pull them out
1332
name = re.sub(r'[^\w.]', '', name)
1334
s = hexlify(rand_bytes(8))
1335
return '-'.join((name, compact_date(time()), s))
1339
"""Return a new tree-root file id."""
1340
return gen_file_id('TREE_ROOT')
1343
def copy_branch(branch_from, to_location, revision=None):
1344
"""Copy branch_from into the existing directory to_location.
1347
If not None, only revisions up to this point will be copied.
1348
The head of the new branch will be that revision.
1351
The name of a local directory that exists but is empty.
1353
from bzrlib.merge import merge
1354
from bzrlib.revisionspec import RevisionSpec
1356
assert isinstance(branch_from, Branch)
1357
assert isinstance(to_location, basestring)
1359
br_to = Branch.initialize(to_location)
1360
br_to.set_root_id(branch_from.get_root_id())
1361
if revision is None:
1362
revno = branch_from.revno()
1364
revno, rev_id = RevisionSpec(branch_from, revision)
1365
br_to.update_revisions(branch_from, stop_revision=revno)
1366
merge((to_location, -1), (to_location, 0), this_dir=to_location,
1367
check_clean=False, ignore_zero=True)
1369
from_location = branch_from.base
1370
br_to.set_parent(branch_from.base)