15
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20
import sys, os, os.path, random, time, sha, sets, types, re, shutil, tempfile
21
import traceback, socket, fnmatch, difflib, time
22
from binascii import hexlify
21
from bzrlib.trace import mutter, note
22
from bzrlib.osutils import isdir, quotefn, compact_date, rand_bytes, splitpath, \
23
sha_file, appendpath, file_kind
24
from bzrlib.errors import BzrError
25
from inventory import Inventory
26
from trace import mutter, note
27
from tree import Tree, EmptyTree, RevisionTree
28
from inventory import InventoryEntry, Inventory
29
from osutils import isdir, quotefn, isfile, uuid, sha_file, username, \
30
format_date, compact_date, pumpfile, user_email, rand_bytes, splitpath, \
31
joinpath, sha_string, file_kind, local_time_offset, appendpath
32
from store import ImmutableStore
33
from revision import Revision
34
from errors import bailout, BzrError
35
from textui import show_status
26
37
BZR_BRANCH_FORMAT = "Bazaar-NG branch, format 0.0.4\n"
27
38
## TODO: Maybe include checks for common corruption of newlines, etc?
34
45
return remotebranch.RemoteBranch(f, **args)
36
47
return Branch(f, **args)
39
def find_cached_branch(f, cache_root, **args):
40
from remotebranch import RemoteBranch
41
br = find_branch(f, **args)
42
def cacheify(br, store_name):
43
from meta_store import CachedStore
44
cache_path = os.path.join(cache_root, store_name)
46
new_store = CachedStore(getattr(br, store_name), cache_path)
47
setattr(br, store_name, new_store)
49
if isinstance(br, RemoteBranch):
50
cacheify(br, 'inventory_store')
51
cacheify(br, 'text_store')
52
cacheify(br, 'revision_store')
56
def _relpath(base, path):
57
"""Return path relative to base, or raise exception.
59
The path may be either an absolute path or a path relative to the
60
current working directory.
62
Lifted out of Branch.relpath for ease of testing.
64
os.path.commonprefix (python2.4) has a bad bug that it works just
65
on string prefixes, assuming that '/u' is a prefix of '/u2'. This
66
avoids that problem."""
67
rp = os.path.abspath(path)
71
while len(head) >= len(base):
74
head, tail = os.path.split(head)
78
from errors import NotBranchError
79
raise NotBranchError("path %r is not within branch %r" % (rp, base))
84
50
def find_branch_root(f=None):
111
77
raise BzrError('%r is not in a branch' % orig_f)
114
class DivergedBranches(Exception):
115
def __init__(self, branch1, branch2):
116
self.branch1 = branch1
117
self.branch2 = branch2
118
Exception.__init__(self, "These branches have diverged.")
121
class NoSuchRevision(BzrError):
122
def __init__(self, branch, revision):
124
self.revision = revision
125
msg = "Branch %s has no revision %d" % (branch, revision)
126
BzrError.__init__(self, msg)
129
82
######################################################################
132
class Branch(object):
133
86
"""Branch holding a history of revisions.
136
89
Base directory of the branch.
142
If _lock_mode is true, a positive count of the number of times the
146
Lock object from bzrlib.lock.
153
def __init__(self, base, init=False, find_root=True):
93
def __init__(self, base, init=False, find_root=True, lock_mode='w'):
154
94
"""Create new branch object at a particular location.
156
96
base -- Base directory for the branch.
192
131
__repr__ = __str__
196
if self._lock_mode or self._lock:
197
from warnings import warn
198
warn("branch %r was not explicitly unlocked" % self)
203
def lock_write(self):
205
if self._lock_mode != 'w':
206
from errors import LockError
207
raise LockError("can't upgrade to a write lock from %r" %
209
self._lock_count += 1
211
from bzrlib.lock import WriteLock
213
self._lock = WriteLock(self.controlfilename('branch-lock'))
214
self._lock_mode = 'w'
221
assert self._lock_mode in ('r', 'w'), \
222
"invalid lock mode %r" % self._lock_mode
223
self._lock_count += 1
225
from bzrlib.lock import ReadLock
227
self._lock = ReadLock(self.controlfilename('branch-lock'))
228
self._lock_mode = 'r'
135
def lock(self, mode='w'):
136
"""Lock the on-disk branch, excluding other processes."""
142
om = os.O_WRONLY | os.O_CREAT
147
raise BzrError("invalid locking mode %r" % mode)
150
lockfile = os.open(self.controlfilename('branch-lock'), om)
152
if e.errno == errno.ENOENT:
153
# might not exist on branches from <0.0.4
154
self.controlfile('branch-lock', 'w').close()
155
lockfile = os.open(self.controlfilename('branch-lock'), om)
234
if not self._lock_mode:
235
from errors import LockError
236
raise LockError('branch %r is not locked' % (self))
238
if self._lock_count > 1:
239
self._lock_count -= 1
243
self._lock_mode = self._lock_count = None
159
fcntl.lockf(lockfile, lm)
161
fcntl.lockf(lockfile, fcntl.LOCK_UN)
163
self._lockmode = None
165
self._lockmode = mode
167
warning("please write a locking method for platform %r" % sys.platform)
169
self._lockmode = None
171
self._lockmode = mode
174
def _need_readlock(self):
175
if self._lockmode not in ['r', 'w']:
176
raise BzrError('need read lock on branch, only have %r' % self._lockmode)
178
def _need_writelock(self):
179
if self._lockmode not in ['w']:
180
raise BzrError('need write lock on branch, only have %r' % self._lockmode)
246
183
def abspath(self, name):
323
262
fmt = self.controlfile('branch-format', 'r').read()
324
263
fmt.replace('\r\n', '')
325
264
if fmt != BZR_BRANCH_FORMAT:
326
raise BzrError('sorry, branch format %r not supported' % fmt,
327
['use a different bzr version',
328
'or remove the .bzr directory and "bzr init" again'])
265
bailout('sorry, branch format %r not supported' % fmt,
266
['use a different bzr version',
267
'or remove the .bzr directory and "bzr init" again'])
332
270
def read_working_inventory(self):
333
271
"""Read the working inventory."""
334
from bzrlib.inventory import Inventory
335
from bzrlib.xml import unpack_xml
336
from time import time
340
# ElementTree does its own conversion from UTF-8, so open in
342
inv = unpack_xml(Inventory,
343
self.controlfile('inventory', 'rb'))
344
mutter("loaded inventory of %d items in %f"
345
% (len(inv), time() - before))
272
self._need_readlock()
274
# ElementTree does its own conversion from UTF-8, so open in
276
inv = Inventory.read_xml(self.controlfile('inventory', 'rb'))
277
mutter("loaded inventory of %d items in %f"
278
% (len(inv), time.time() - before))
351
282
def _write_inventory(self, inv):
352
283
"""Update the working inventory.
354
285
That is to say, the inventory describing changes underway, that
355
286
will be committed to the next revision.
357
from bzrlib.atomicfile import AtomicFile
358
from bzrlib.xml import pack_xml
362
f = AtomicFile(self.controlfilename('inventory'), 'wb')
288
self._need_writelock()
289
## TODO: factor out to atomicfile? is rename safe on windows?
290
## TODO: Maybe some kind of clean/dirty marker on inventory?
291
tmpfname = self.controlfilename('inventory.tmp')
292
tmpf = file(tmpfname, 'wb')
295
inv_fname = self.controlfilename('inventory')
296
if sys.platform == 'win32':
298
os.rename(tmpfname, inv_fname)
371
299
mutter('wrote working inventory')
374
302
inventory = property(read_working_inventory, _write_inventory, None,
375
303
"""Inventory for the working copy.""")
383
311
This puts the files in the Added state, so that they will be
384
312
recorded by the next commit.
387
List of paths to add, relative to the base of the tree.
390
If set, use these instead of automatically generated ids.
391
Must be the same length as the list of files, but may
392
contain None for ids that are to be autogenerated.
394
314
TODO: Perhaps have an option to add the ids even if the files do
397
317
TODO: Perhaps return the ids of the files? But then again it
398
is easy to retrieve them if they're needed.
318
is easy to retrieve them if they're needed.
320
TODO: Option to specify file id.
400
322
TODO: Adding a directory should optionally recurse down and
401
add all non-ignored children. Perhaps do that in a
323
add all non-ignored children. Perhaps do that in a
404
from bzrlib.textui import show_status
326
self._need_writelock()
405
328
# TODO: Re-adding a file that is removed in the working copy
406
329
# should probably put it back with the previous ID.
407
if isinstance(files, basestring):
408
assert(ids is None or isinstance(ids, basestring))
330
if isinstance(files, types.StringTypes):
331
assert(ids is None or isinstance(ids, types.StringTypes))
410
333
if ids is not None:
414
337
ids = [None] * len(files)
416
339
assert(len(ids) == len(files))
420
inv = self.read_working_inventory()
421
for f,file_id in zip(files, ids):
422
if is_control_file(f):
423
raise BzrError("cannot add control file %s" % quotefn(f))
428
raise BzrError("cannot add top-level %r" % f)
430
fullpath = os.path.normpath(self.abspath(f))
433
kind = file_kind(fullpath)
435
# maybe something better?
436
raise BzrError('cannot add: not a regular file or directory: %s' % quotefn(f))
438
if kind != 'file' and kind != 'directory':
439
raise BzrError('cannot add: not a regular file or directory: %s' % quotefn(f))
442
file_id = gen_file_id(f)
443
inv.add_path(f, kind=kind, file_id=file_id)
446
print 'added', quotefn(f)
448
mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
450
self._write_inventory(inv)
341
inv = self.read_working_inventory()
342
for f,file_id in zip(files, ids):
343
if is_control_file(f):
344
bailout("cannot add control file %s" % quotefn(f))
349
bailout("cannot add top-level %r" % f)
351
fullpath = os.path.normpath(self.abspath(f))
354
kind = file_kind(fullpath)
356
# maybe something better?
357
bailout('cannot add: not a regular file or directory: %s' % quotefn(f))
359
if kind != 'file' and kind != 'directory':
360
bailout('cannot add: not a regular file or directory: %s' % quotefn(f))
363
file_id = gen_file_id(f)
364
inv.add_path(f, kind=kind, file_id=file_id)
367
show_status('A', kind, quotefn(f))
369
mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
371
self._write_inventory(inv)
455
374
def print_file(self, file, revno):
456
375
"""Print `file` to stdout."""
459
tree = self.revision_tree(self.lookup_revision(revno))
460
# use inventory as it was in that revision
461
file_id = tree.inventory.path2id(file)
463
raise BzrError("%r is not present in revision %d" % (file, revno))
464
tree.print_file(file_id)
376
self._need_readlock()
377
tree = self.revision_tree(self.lookup_revision(revno))
378
# use inventory as it was in that revision
379
file_id = tree.inventory.path2id(file)
381
bailout("%r is not present in revision %d" % (file, revno))
382
tree.print_file(file_id)
469
385
def remove(self, files, verbose=False):
470
386
"""Mark nominated files for removal from the inventory.
480
396
is the opposite of add. Removing it is consistent with most
481
397
other tools. Maybe an option.
483
from bzrlib.textui import show_status
484
399
## TODO: Normalize names
485
400
## TODO: Remove nested loops; better scalability
486
if isinstance(files, basestring):
401
self._need_writelock()
403
if isinstance(files, types.StringTypes):
492
tree = self.working_tree()
495
# do this before any modifications
499
raise BzrError("cannot remove unversioned file %s" % quotefn(f))
500
mutter("remove inventory entry %s {%s}" % (quotefn(f), fid))
502
# having remove it, it must be either ignored or unknown
503
if tree.is_ignored(f):
507
show_status(new_status, inv[fid].kind, quotefn(f))
510
self._write_inventory(inv)
515
# FIXME: this doesn't need to be a branch method
406
tree = self.working_tree()
409
# do this before any modifications
413
bailout("cannot remove unversioned file %s" % quotefn(f))
414
mutter("remove inventory entry %s {%s}" % (quotefn(f), fid))
416
# having remove it, it must be either ignored or unknown
417
if tree.is_ignored(f):
421
show_status(new_status, inv[fid].kind, quotefn(f))
424
self._write_inventory(inv)
516
426
def set_inventory(self, new_inventory_list):
517
from bzrlib.inventory import Inventory, InventoryEntry
518
427
inv = Inventory()
519
428
for path, file_id, parent, kind in new_inventory_list:
520
429
name = os.path.basename(path)
546
455
def append_revision(self, revision_id):
547
from bzrlib.atomicfile import AtomicFile
549
456
mutter("add {%s} to revision-history" % revision_id)
550
rev_history = self.revision_history() + [revision_id]
552
f = AtomicFile(self.controlfilename('revision-history'))
554
for rev_id in rev_history:
457
rev_history = self.revision_history()
459
tmprhname = self.controlfilename('revision-history.tmp')
460
rhname = self.controlfilename('revision-history')
462
f = file(tmprhname, 'wt')
463
rev_history.append(revision_id)
464
f.write('\n'.join(rev_history))
468
if sys.platform == 'win32':
470
os.rename(tmprhname, rhname)
561
474
def get_revision(self, revision_id):
562
475
"""Return the Revision object for a named revision"""
563
from bzrlib.revision import Revision
564
from bzrlib.xml import unpack_xml
568
if not revision_id or not isinstance(revision_id, basestring):
569
raise ValueError('invalid revision-id: %r' % revision_id)
570
r = unpack_xml(Revision, self.revision_store[revision_id])
476
self._need_readlock()
477
r = Revision.read_xml(self.revision_store[revision_id])
574
478
assert r.revision_id == revision_id
578
def get_revision_sha1(self, revision_id):
579
"""Hash the stored value of a revision, and return it."""
580
# In the future, revision entries will be signed. At that
581
# point, it is probably best *not* to include the signature
582
# in the revision hash. Because that lets you re-sign
583
# the revision, (add signatures/remove signatures) and still
584
# have all hash pointers stay consistent.
585
# But for now, just hash the contents.
586
return sha_file(self.revision_store[revision_id])
589
482
def get_inventory(self, inventory_id):
619
505
>>> ScratchBranch().revision_history()
624
return [l.rstrip('\r\n') for l in
625
self.controlfile('revision-history', 'r').readlines()]
630
def common_ancestor(self, other, self_revno=None, other_revno=None):
633
>>> sb = ScratchBranch(files=['foo', 'foo~'])
634
>>> sb.common_ancestor(sb) == (None, None)
636
>>> commit.commit(sb, "Committing first revision", verbose=False)
637
>>> sb.common_ancestor(sb)[0]
639
>>> clone = sb.clone()
640
>>> commit.commit(sb, "Committing second revision", verbose=False)
641
>>> sb.common_ancestor(sb)[0]
643
>>> sb.common_ancestor(clone)[0]
645
>>> commit.commit(clone, "Committing divergent second revision",
647
>>> sb.common_ancestor(clone)[0]
649
>>> sb.common_ancestor(clone) == clone.common_ancestor(sb)
651
>>> sb.common_ancestor(sb) != clone.common_ancestor(clone)
653
>>> clone2 = sb.clone()
654
>>> sb.common_ancestor(clone2)[0]
656
>>> sb.common_ancestor(clone2, self_revno=1)[0]
658
>>> sb.common_ancestor(clone2, other_revno=1)[0]
661
my_history = self.revision_history()
662
other_history = other.revision_history()
663
if self_revno is None:
664
self_revno = len(my_history)
665
if other_revno is None:
666
other_revno = len(other_history)
667
indices = range(min((self_revno, other_revno)))
670
if my_history[r] == other_history[r]:
671
return r+1, my_history[r]
508
self._need_readlock()
509
return [l.rstrip('\r\n') for l in self.controlfile('revision-history', 'r').readlines()]
674
512
def enum_history(self, direction):
675
513
"""Return (revno, revision_id) for history of branch.
715
def missing_revisions(self, other, stop_revision=None):
717
If self and other have not diverged, return a list of the revisions
718
present in other, but missing from self.
720
>>> from bzrlib.commit import commit
721
>>> bzrlib.trace.silent = True
722
>>> br1 = ScratchBranch()
723
>>> br2 = ScratchBranch()
724
>>> br1.missing_revisions(br2)
726
>>> commit(br2, "lala!", rev_id="REVISION-ID-1")
727
>>> br1.missing_revisions(br2)
729
>>> br2.missing_revisions(br1)
731
>>> commit(br1, "lala!", rev_id="REVISION-ID-1")
732
>>> br1.missing_revisions(br2)
734
>>> commit(br2, "lala!", rev_id="REVISION-ID-2A")
735
>>> br1.missing_revisions(br2)
737
>>> commit(br1, "lala!", rev_id="REVISION-ID-2B")
738
>>> br1.missing_revisions(br2)
739
Traceback (most recent call last):
740
DivergedBranches: These branches have diverged.
742
self_history = self.revision_history()
743
self_len = len(self_history)
744
other_history = other.revision_history()
745
other_len = len(other_history)
746
common_index = min(self_len, other_len) -1
747
if common_index >= 0 and \
748
self_history[common_index] != other_history[common_index]:
749
raise DivergedBranches(self, other)
751
if stop_revision is None:
752
stop_revision = other_len
753
elif stop_revision > other_len:
754
raise NoSuchRevision(self, stop_revision)
756
return other_history[self_len:stop_revision]
759
def update_revisions(self, other, stop_revision=None):
760
"""Pull in all new revisions from other branch.
762
>>> from bzrlib.commit import commit
763
>>> bzrlib.trace.silent = True
764
>>> br1 = ScratchBranch(files=['foo', 'bar'])
767
>>> commit(br1, "lala!", rev_id="REVISION-ID-1", verbose=False)
768
>>> br2 = ScratchBranch()
769
>>> br2.update_revisions(br1)
773
>>> br2.revision_history()
775
>>> br2.update_revisions(br1)
779
>>> br1.text_store.total_size() == br2.text_store.total_size()
782
from bzrlib.progress import ProgressBar
786
from sets import Set as set
790
pb.update('comparing histories')
791
revision_ids = self.missing_revisions(other, stop_revision)
793
if hasattr(other.revision_store, "prefetch"):
794
other.revision_store.prefetch(revision_ids)
795
if hasattr(other.inventory_store, "prefetch"):
796
inventory_ids = [other.get_revision(r).inventory_id
797
for r in revision_ids]
798
other.inventory_store.prefetch(inventory_ids)
803
for rev_id in revision_ids:
805
pb.update('fetching revision', i, len(revision_ids))
806
rev = other.get_revision(rev_id)
807
revisions.append(rev)
808
inv = other.get_inventory(str(rev.inventory_id))
809
for key, entry in inv.iter_entries():
810
if entry.text_id is None:
812
if entry.text_id not in self.text_store:
813
needed_texts.add(entry.text_id)
817
count = self.text_store.copy_multi(other.text_store, needed_texts)
818
print "Added %d texts." % count
819
inventory_ids = [ f.inventory_id for f in revisions ]
820
count = self.inventory_store.copy_multi(other.inventory_store,
822
print "Added %d inventories." % count
823
revision_ids = [ f.revision_id for f in revisions]
824
count = self.revision_store.copy_multi(other.revision_store,
826
for revision_id in revision_ids:
827
self.append_revision(revision_id)
828
print "Added %d revisions." % count
831
553
def commit(self, *args, **kw):
832
555
from bzrlib.commit import commit
833
556
commit(self, *args, **kw)
886
606
This can change the directory or the filename or both.
608
self._need_writelock()
609
tree = self.working_tree()
611
if not tree.has_filename(from_rel):
612
bailout("can't rename: old working file %r does not exist" % from_rel)
613
if tree.has_filename(to_rel):
614
bailout("can't rename: new working file %r already exists" % to_rel)
616
file_id = inv.path2id(from_rel)
618
bailout("can't rename: old name %r is not versioned" % from_rel)
620
if inv.path2id(to_rel):
621
bailout("can't rename: new name %r is already versioned" % to_rel)
623
to_dir, to_tail = os.path.split(to_rel)
624
to_dir_id = inv.path2id(to_dir)
625
if to_dir_id == None and to_dir != '':
626
bailout("can't determine destination directory id for %r" % to_dir)
628
mutter("rename_one:")
629
mutter(" file_id {%s}" % file_id)
630
mutter(" from_rel %r" % from_rel)
631
mutter(" to_rel %r" % to_rel)
632
mutter(" to_dir %r" % to_dir)
633
mutter(" to_dir_id {%s}" % to_dir_id)
635
inv.rename(file_id, to_dir_id, to_tail)
637
print "%s => %s" % (from_rel, to_rel)
639
from_abs = self.abspath(from_rel)
640
to_abs = self.abspath(to_rel)
890
tree = self.working_tree()
892
if not tree.has_filename(from_rel):
893
raise BzrError("can't rename: old working file %r does not exist" % from_rel)
894
if tree.has_filename(to_rel):
895
raise BzrError("can't rename: new working file %r already exists" % to_rel)
897
file_id = inv.path2id(from_rel)
899
raise BzrError("can't rename: old name %r is not versioned" % from_rel)
901
if inv.path2id(to_rel):
902
raise BzrError("can't rename: new name %r is already versioned" % to_rel)
904
to_dir, to_tail = os.path.split(to_rel)
905
to_dir_id = inv.path2id(to_dir)
906
if to_dir_id == None and to_dir != '':
907
raise BzrError("can't determine destination directory id for %r" % to_dir)
909
mutter("rename_one:")
910
mutter(" file_id {%s}" % file_id)
911
mutter(" from_rel %r" % from_rel)
912
mutter(" to_rel %r" % to_rel)
913
mutter(" to_dir %r" % to_dir)
914
mutter(" to_dir_id {%s}" % to_dir_id)
916
inv.rename(file_id, to_dir_id, to_tail)
918
print "%s => %s" % (from_rel, to_rel)
920
from_abs = self.abspath(from_rel)
921
to_abs = self.abspath(to_rel)
923
os.rename(from_abs, to_abs)
925
raise BzrError("failed to rename %r to %r: %s"
926
% (from_abs, to_abs, e[1]),
927
["rename rolled back"])
929
self._write_inventory(inv)
642
os.rename(from_abs, to_abs)
644
bailout("failed to rename %r to %r: %s"
645
% (from_abs, to_abs, e[1]),
646
["rename rolled back"])
648
self._write_inventory(inv)
934
652
def move(self, from_paths, to_name):
942
660
Note that to_name is only the last component of the new name;
943
661
this doesn't change the directory.
947
## TODO: Option to move IDs only
948
assert not isinstance(from_paths, basestring)
949
tree = self.working_tree()
951
to_abs = self.abspath(to_name)
952
if not isdir(to_abs):
953
raise BzrError("destination %r is not a directory" % to_abs)
954
if not tree.has_filename(to_name):
955
raise BzrError("destination %r not in working directory" % to_abs)
956
to_dir_id = inv.path2id(to_name)
957
if to_dir_id == None and to_name != '':
958
raise BzrError("destination %r is not a versioned directory" % to_name)
959
to_dir_ie = inv[to_dir_id]
960
if to_dir_ie.kind not in ('directory', 'root_directory'):
961
raise BzrError("destination %r is not a directory" % to_abs)
963
to_idpath = inv.get_idpath(to_dir_id)
966
if not tree.has_filename(f):
967
raise BzrError("%r does not exist in working tree" % f)
968
f_id = inv.path2id(f)
970
raise BzrError("%r is not versioned" % f)
971
name_tail = splitpath(f)[-1]
972
dest_path = appendpath(to_name, name_tail)
973
if tree.has_filename(dest_path):
974
raise BzrError("destination %r already exists" % dest_path)
975
if f_id in to_idpath:
976
raise BzrError("can't move %r to a subdirectory of itself" % f)
978
# OK, so there's a race here, it's possible that someone will
979
# create a file in this interval and then the rename might be
980
# left half-done. But we should have caught most problems.
983
name_tail = splitpath(f)[-1]
984
dest_path = appendpath(to_name, name_tail)
985
print "%s => %s" % (f, dest_path)
986
inv.rename(inv.path2id(f), to_dir_id, name_tail)
988
os.rename(self.abspath(f), self.abspath(dest_path))
990
raise BzrError("failed to rename %r to %r: %s" % (f, dest_path, e[1]),
991
["rename rolled back"])
993
self._write_inventory(inv)
998
def revert(self, filenames, old_tree=None, backups=True):
999
"""Restore selected files to the versions from a previous tree.
1002
If true (default) backups are made of files before
1005
from bzrlib.errors import NotVersionedError, BzrError
1006
from bzrlib.atomicfile import AtomicFile
1007
from bzrlib.osutils import backup_file
1009
inv = self.read_working_inventory()
1010
if old_tree is None:
1011
old_tree = self.basis_tree()
1012
old_inv = old_tree.inventory
1015
for fn in filenames:
1016
file_id = inv.path2id(fn)
1018
raise NotVersionedError("not a versioned file", fn)
1019
if not old_inv.has_id(file_id):
1020
raise BzrError("file not present in old tree", fn, file_id)
1021
nids.append((fn, file_id))
1023
# TODO: Rename back if it was previously at a different location
1025
# TODO: If given a directory, restore the entire contents from
1026
# the previous version.
1028
# TODO: Make a backup to a temporary file.
1030
# TODO: If the file previously didn't exist, delete it?
1031
for fn, file_id in nids:
1034
f = AtomicFile(fn, 'wb')
663
self._need_writelock()
664
## TODO: Option to move IDs only
665
assert not isinstance(from_paths, basestring)
666
tree = self.working_tree()
668
to_abs = self.abspath(to_name)
669
if not isdir(to_abs):
670
bailout("destination %r is not a directory" % to_abs)
671
if not tree.has_filename(to_name):
672
bailout("destination %r not in working directory" % to_abs)
673
to_dir_id = inv.path2id(to_name)
674
if to_dir_id == None and to_name != '':
675
bailout("destination %r is not a versioned directory" % to_name)
676
to_dir_ie = inv[to_dir_id]
677
if to_dir_ie.kind not in ('directory', 'root_directory'):
678
bailout("destination %r is not a directory" % to_abs)
680
to_idpath = Set(inv.get_idpath(to_dir_id))
683
if not tree.has_filename(f):
684
bailout("%r does not exist in working tree" % f)
685
f_id = inv.path2id(f)
687
bailout("%r is not versioned" % f)
688
name_tail = splitpath(f)[-1]
689
dest_path = appendpath(to_name, name_tail)
690
if tree.has_filename(dest_path):
691
bailout("destination %r already exists" % dest_path)
692
if f_id in to_idpath:
693
bailout("can't move %r to a subdirectory of itself" % f)
695
# OK, so there's a race here, it's possible that someone will
696
# create a file in this interval and then the rename might be
697
# left half-done. But we should have caught most problems.
700
name_tail = splitpath(f)[-1]
701
dest_path = appendpath(to_name, name_tail)
702
print "%s => %s" % (f, dest_path)
703
inv.rename(inv.path2id(f), to_dir_id, name_tail)
1036
f.write(old_tree.get_file(file_id).read())
705
os.rename(self.abspath(f), self.abspath(dest_path))
707
bailout("failed to rename %r to %r: %s" % (f, dest_path, e[1]),
708
["rename rolled back"])
710
self._write_inventory(inv)
1071
738
file(os.path.join(self.base, f), 'w').write('content of %s' % f)
1076
>>> orig = ScratchBranch(files=["file1", "file2"])
1077
>>> clone = orig.clone()
1078
>>> os.path.samefile(orig.base, clone.base)
1080
>>> os.path.isfile(os.path.join(clone.base, "file1"))
1083
from shutil import copytree
1084
from tempfile import mkdtemp
1087
copytree(self.base, base, symlinks=True)
1088
return ScratchBranch(base=base)
1090
741
def __del__(self):
1093
744
def destroy(self):
1094
745
"""Destroy the test branch, removing the scratch directory."""
1095
from shutil import rmtree
1098
mutter("delete ScratchBranch %s" % self.base)
747
mutter("delete ScratchBranch %s" % self.base)
748
shutil.rmtree(self.base)
1100
749
except OSError, e:
1101
750
# Work around for shutil.rmtree failing on Windows when
1102
751
# readonly files are encountered