15
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
import sys, os, os.path, random, time, sha, sets, types, re, shutil, tempfile
19
import traceback, socket, fnmatch, difflib, time
20
from binascii import hexlify
23
from inventory import Inventory
24
from trace import mutter, note
25
from tree import Tree, EmptyTree, RevisionTree
26
from inventory import InventoryEntry, Inventory
27
from osutils import isdir, quotefn, isfile, uuid, sha_file, username, \
28
format_date, compact_date, pumpfile, user_email, rand_bytes, splitpath, \
29
joinpath, sha_string, file_kind, local_time_offset, appendpath
30
from store import ImmutableStore
31
from revision import Revision
32
from errors import bailout, BzrError
33
from textui import show_status
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
29
from bzrlib.textui import show_status
30
from bzrlib.revision import Revision
31
from bzrlib.xml import unpack_xml
32
from bzrlib.delta import compare_trees
33
from bzrlib.tree import EmptyTree, RevisionTree
35
38
BZR_BRANCH_FORMAT = "Bazaar-NG branch, format 0.0.4\n"
36
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
40
50
def find_branch(f, **args):
41
51
if f and (f.startswith('http://') or f.startswith('https://')):
129
212
__repr__ = __str__
133
def lock(self, mode='w'):
134
"""Lock the on-disk branch, excluding other processes."""
140
om = os.O_WRONLY | os.O_CREAT
145
raise BzrError("invalid locking mode %r" % mode)
148
lockfile = os.open(self.controlfilename('branch-lock'), om)
150
if e.errno == errno.ENOENT:
151
# might not exist on branches from <0.0.4
152
self.controlfile('branch-lock', 'w').close()
153
lockfile = os.open(self.controlfilename('branch-lock'), om)
157
fcntl.lockf(lockfile, lm)
159
fcntl.lockf(lockfile, fcntl.LOCK_UN)
161
self._lockmode = None
163
self._lockmode = mode
165
warning("please write a locking method for platform %r" % sys.platform)
167
self._lockmode = None
169
self._lockmode = mode
172
def _need_readlock(self):
173
if self._lockmode not in ['r', 'w']:
174
raise BzrError('need read lock on branch, only have %r' % self._lockmode)
176
def _need_writelock(self):
177
if self._lockmode not in ['w']:
178
raise BzrError('need write lock on branch, only have %r' % self._lockmode)
216
if self._lock_mode or self._lock:
217
from warnings import warn
218
warn("branch %r was not explicitly unlocked" % self)
222
def lock_write(self):
224
if self._lock_mode != 'w':
225
from errors import LockError
226
raise LockError("can't upgrade to a write lock from %r" %
228
self._lock_count += 1
230
from bzrlib.lock import WriteLock
232
self._lock = WriteLock(self.controlfilename('branch-lock'))
233
self._lock_mode = 'w'
239
assert self._lock_mode in ('r', 'w'), \
240
"invalid lock mode %r" % self._lock_mode
241
self._lock_count += 1
243
from bzrlib.lock import ReadLock
245
self._lock = ReadLock(self.controlfilename('branch-lock'))
246
self._lock_mode = 'r'
250
if not self._lock_mode:
251
from errors import LockError
252
raise LockError('branch %r is not locked' % (self))
254
if self._lock_count > 1:
255
self._lock_count -= 1
259
self._lock_mode = self._lock_count = None
181
261
def abspath(self, name):
182
262
"""Return absolute filename for something in the branch"""
183
263
return os.path.join(self.base, name)
186
265
def relpath(self, path):
187
266
"""Return path relative to this branch of something inside it.
189
268
Raises an error if path is not in this branch."""
190
rp = os.path.realpath(path)
192
if not rp.startswith(self.base):
193
bailout("path %r is not within branch %r" % (rp, self.base))
194
rp = rp[len(self.base):]
195
rp = rp.lstrip(os.sep)
269
return _relpath(self.base, path)
199
271
def controlfilename(self, file_or_path):
200
272
"""Return location relative to branch."""
201
if isinstance(file_or_path, types.StringTypes):
273
if isinstance(file_or_path, basestring):
202
274
file_or_path = [file_or_path]
203
275
return os.path.join(self.base, bzrlib.BZRDIR, *file_or_path)
283
383
That is to say, the inventory describing changes underway, that
284
384
will be committed to the next revision.
286
self._need_writelock()
287
## TODO: factor out to atomicfile? is rename safe on windows?
288
## TODO: Maybe some kind of clean/dirty marker on inventory?
289
tmpfname = self.controlfilename('inventory.tmp')
290
tmpf = file(tmpfname, 'wb')
293
inv_fname = self.controlfilename('inventory')
294
if sys.platform == 'win32':
296
os.rename(tmpfname, inv_fname)
386
from bzrlib.atomicfile import AtomicFile
387
from bzrlib.xml import pack_xml
391
f = AtomicFile(self.controlfilename('inventory'), 'wb')
297
400
mutter('wrote working inventory')
300
403
inventory = property(read_working_inventory, _write_inventory, None,
301
404
"""Inventory for the working copy.""")
304
def add(self, files, verbose=False, ids=None):
407
def add(self, files, ids=None):
305
408
"""Make files versioned.
307
Note that the command line normally calls smart_add instead.
410
Note that the command line normally calls smart_add instead,
411
which can automatically recurse.
309
413
This puts the files in the Added state, so that they will be
310
414
recorded by the next commit.
417
List of paths to add, relative to the base of the tree.
420
If set, use these instead of automatically generated ids.
421
Must be the same length as the list of files, but may
422
contain None for ids that are to be autogenerated.
312
424
TODO: Perhaps have an option to add the ids even if the files do
315
TODO: Perhaps return the ids of the files? But then again it
316
is easy to retrieve them if they're needed.
318
TODO: Option to specify file id.
320
TODO: Adding a directory should optionally recurse down and
321
add all non-ignored children. Perhaps do that in a
427
TODO: Perhaps yield the ids and paths as they're added.
324
self._need_writelock()
326
429
# TODO: Re-adding a file that is removed in the working copy
327
430
# should probably put it back with the previous ID.
328
if isinstance(files, types.StringTypes):
329
assert(ids is None or isinstance(ids, types.StringTypes))
431
if isinstance(files, basestring):
432
assert(ids is None or isinstance(ids, basestring))
331
434
if ids is not None:
335
438
ids = [None] * len(files)
337
440
assert(len(ids) == len(files))
339
inv = self.read_working_inventory()
340
for f,file_id in zip(files, ids):
341
if is_control_file(f):
342
bailout("cannot add control file %s" % quotefn(f))
347
bailout("cannot add top-level %r" % f)
349
fullpath = os.path.normpath(self.abspath(f))
352
kind = file_kind(fullpath)
354
# maybe something better?
355
bailout('cannot add: not a regular file or directory: %s' % quotefn(f))
357
if kind != 'file' and kind != 'directory':
358
bailout('cannot add: not a regular file or directory: %s' % quotefn(f))
361
file_id = gen_file_id(f)
362
inv.add_path(f, kind=kind, file_id=file_id)
365
show_status('A', kind, quotefn(f))
367
mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
369
self._write_inventory(inv)
444
inv = self.read_working_inventory()
445
for f,file_id in zip(files, ids):
446
if is_control_file(f):
447
raise BzrError("cannot add control file %s" % quotefn(f))
452
raise BzrError("cannot add top-level %r" % f)
454
fullpath = os.path.normpath(self.abspath(f))
457
kind = file_kind(fullpath)
459
# maybe something better?
460
raise BzrError('cannot add: not a regular file or directory: %s' % quotefn(f))
462
if kind != 'file' and kind != 'directory':
463
raise BzrError('cannot add: not a regular file or directory: %s' % quotefn(f))
466
file_id = gen_file_id(f)
467
inv.add_path(f, kind=kind, file_id=file_id)
469
mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
471
self._write_inventory(inv)
372
476
def print_file(self, file, revno):
373
477
"""Print `file` to stdout."""
374
self._need_readlock()
375
tree = self.revision_tree(self.lookup_revision(revno))
376
# use inventory as it was in that revision
377
file_id = tree.inventory.path2id(file)
379
bailout("%r is not present in revision %d" % (file, revno))
380
tree.print_file(file_id)
480
tree = self.revision_tree(self.lookup_revision(revno))
481
# use inventory as it was in that revision
482
file_id = tree.inventory.path2id(file)
484
raise BzrError("%r is not present in revision %s" % (file, revno))
485
tree.print_file(file_id)
383
490
def remove(self, files, verbose=False):
384
491
"""Mark nominated files for removal from the inventory.
450
563
return self.working_tree().unknowns()
453
def append_revision(self, revision_id):
454
mutter("add {%s} to revision-history" % revision_id)
566
def append_revision(self, *revision_ids):
567
from bzrlib.atomicfile import AtomicFile
569
for revision_id in revision_ids:
570
mutter("add {%s} to revision-history" % revision_id)
455
572
rev_history = self.revision_history()
457
tmprhname = self.controlfilename('revision-history.tmp')
458
rhname = self.controlfilename('revision-history')
460
f = file(tmprhname, 'wt')
461
rev_history.append(revision_id)
462
f.write('\n'.join(rev_history))
466
if sys.platform == 'win32':
468
os.rename(tmprhname, rhname)
573
rev_history.extend(revision_ids)
575
f = AtomicFile(self.controlfilename('revision-history'))
577
for rev_id in rev_history:
584
def get_revision_xml(self, revision_id):
585
"""Return XML file object for revision object."""
586
if not revision_id or not isinstance(revision_id, basestring):
587
raise InvalidRevisionId(revision_id)
592
return self.revision_store[revision_id]
594
raise bzrlib.errors.NoSuchRevision(self, revision_id)
472
599
def get_revision(self, revision_id):
473
600
"""Return the Revision object for a named revision"""
474
self._need_readlock()
475
r = Revision.read_xml(self.revision_store[revision_id])
601
xml_file = self.get_revision_xml(revision_id)
604
r = unpack_xml(Revision, xml_file)
605
except SyntaxError, e:
606
raise bzrlib.errors.BzrError('failed to unpack revision_xml',
476
610
assert r.revision_id == revision_id
614
def get_revision_delta(self, revno):
615
"""Return the delta for one revision.
617
The delta is relative to its mainline predecessor, or the
618
empty tree for revision 1.
620
assert isinstance(revno, int)
621
rh = self.revision_history()
622
if not (1 <= revno <= len(rh)):
623
raise InvalidRevisionNumber(revno)
625
# revno is 1-based; list is 0-based
627
new_tree = self.revision_tree(rh[revno-1])
629
old_tree = EmptyTree()
631
old_tree = self.revision_tree(rh[revno-2])
633
return compare_trees(old_tree, new_tree)
637
def get_revision_sha1(self, revision_id):
638
"""Hash the stored value of a revision, and return it."""
639
# In the future, revision entries will be signed. At that
640
# point, it is probably best *not* to include the signature
641
# in the revision hash. Because that lets you re-sign
642
# the revision, (add signatures/remove signatures) and still
643
# have all hash pointers stay consistent.
644
# But for now, just hash the contents.
645
return bzrlib.osutils.sha_file(self.get_revision_xml(revision_id))
480
648
def get_inventory(self, inventory_id):
481
649
"""Get Inventory object by hash.
483
651
TODO: Perhaps for this and similar methods, take a revision
484
652
parameter which can be either an integer revno or a
486
self._need_readlock()
487
i = Inventory.read_xml(self.inventory_store[inventory_id])
654
from bzrlib.inventory import Inventory
655
from bzrlib.xml import unpack_xml
657
return unpack_xml(Inventory, self.get_inventory_xml(inventory_id))
660
def get_inventory_xml(self, inventory_id):
661
"""Get inventory XML as a file object."""
662
return self.inventory_store[inventory_id]
665
def get_inventory_sha1(self, inventory_id):
666
"""Return the sha1 hash of the inventory entry
668
return sha_file(self.get_inventory_xml(inventory_id))
491
671
def get_revision_inventory(self, revision_id):
492
672
"""Return inventory of a past revision."""
493
self._need_readlock()
673
# bzr 0.0.6 imposes the constraint that the inventory_id
674
# must be the same as its revision, so this is trivial.
494
675
if revision_id == None:
676
from bzrlib.inventory import Inventory
677
return Inventory(self.get_root_id())
497
return self.get_inventory(self.get_revision(revision_id).inventory_id)
679
return self.get_inventory(revision_id)
500
682
def revision_history(self):
760
def missing_revisions(self, other, stop_revision=None, diverged_ok=False):
762
If self and other have not diverged, return a list of the revisions
763
present in other, but missing from self.
765
>>> from bzrlib.commit import commit
766
>>> bzrlib.trace.silent = True
767
>>> br1 = ScratchBranch()
768
>>> br2 = ScratchBranch()
769
>>> br1.missing_revisions(br2)
771
>>> commit(br2, "lala!", rev_id="REVISION-ID-1")
772
>>> br1.missing_revisions(br2)
774
>>> br2.missing_revisions(br1)
776
>>> commit(br1, "lala!", rev_id="REVISION-ID-1")
777
>>> br1.missing_revisions(br2)
779
>>> commit(br2, "lala!", rev_id="REVISION-ID-2A")
780
>>> br1.missing_revisions(br2)
782
>>> commit(br1, "lala!", rev_id="REVISION-ID-2B")
783
>>> br1.missing_revisions(br2)
784
Traceback (most recent call last):
785
DivergedBranches: These branches have diverged.
787
self_history = self.revision_history()
788
self_len = len(self_history)
789
other_history = other.revision_history()
790
other_len = len(other_history)
791
common_index = min(self_len, other_len) -1
792
if common_index >= 0 and \
793
self_history[common_index] != other_history[common_index]:
794
raise DivergedBranches(self, other)
796
if stop_revision is None:
797
stop_revision = other_len
798
elif stop_revision > other_len:
799
raise bzrlib.errors.NoSuchRevision(self, stop_revision)
801
return other_history[self_len:stop_revision]
804
def update_revisions(self, other, stop_revision=None):
805
"""Pull in all new revisions from other branch.
807
from bzrlib.fetch import greedy_fetch
809
pb = bzrlib.ui.ui_factory.progress_bar()
810
pb.update('comparing histories')
812
revision_ids = self.missing_revisions(other, stop_revision)
814
if len(revision_ids) > 0:
815
count = greedy_fetch(self, other, revision_ids[-1], pb)[0]
818
self.append_revision(*revision_ids)
819
## note("Added %d revisions." % count)
822
def install_revisions(self, other, revision_ids, pb):
823
if hasattr(other.revision_store, "prefetch"):
824
other.revision_store.prefetch(revision_ids)
825
if hasattr(other.inventory_store, "prefetch"):
826
inventory_ids = [other.get_revision(r).inventory_id
827
for r in revision_ids]
828
other.inventory_store.prefetch(inventory_ids)
831
pb = bzrlib.ui.ui_factory.progress_bar()
838
for i, rev_id in enumerate(revision_ids):
839
pb.update('fetching revision', i+1, len(revision_ids))
841
rev = other.get_revision(rev_id)
842
except bzrlib.errors.NoSuchRevision:
846
revisions.append(rev)
847
inv = other.get_inventory(str(rev.inventory_id))
848
for key, entry in inv.iter_entries():
849
if entry.text_id is None:
851
if entry.text_id not in self.text_store:
852
needed_texts.add(entry.text_id)
856
count, cp_fail = self.text_store.copy_multi(other.text_store,
858
#print "Added %d texts." % count
859
inventory_ids = [ f.inventory_id for f in revisions ]
860
count, cp_fail = self.inventory_store.copy_multi(other.inventory_store,
862
#print "Added %d inventories." % count
863
revision_ids = [ f.revision_id for f in revisions]
865
count, cp_fail = self.revision_store.copy_multi(other.revision_store,
868
assert len(cp_fail) == 0
869
return count, failures
551
872
def commit(self, *args, **kw):
553
873
from bzrlib.commit import commit
554
874
commit(self, *args, **kw)
557
def lookup_revision(self, revno):
558
"""Return revision hash for revision number."""
877
def lookup_revision(self, revision):
878
"""Return the revision identifier for a given revision information."""
879
revno, info = self._get_revision_info(revision)
883
def revision_id_to_revno(self, revision_id):
884
"""Given a revision id, return its revno"""
885
history = self.revision_history()
887
return history.index(revision_id) + 1
889
raise bzrlib.errors.NoSuchRevision(self, revision_id)
892
def get_revision_info(self, revision):
893
"""Return (revno, revision id) for revision identifier.
895
revision can be an integer, in which case it is assumed to be revno (though
896
this will translate negative values into positive ones)
897
revision can also be a string, in which case it is parsed for something like
898
'date:' or 'revid:' etc.
900
revno, rev_id = self._get_revision_info(revision)
902
raise bzrlib.errors.NoSuchRevision(self, revision)
905
def get_rev_id(self, revno, history=None):
906
"""Find the revision id of the specified revno."""
563
# list is 0-based; revisions are 1-based
564
return self.revision_history()[revno-1]
566
raise BzrError("no such revision %s" % revno)
910
history = self.revision_history()
911
elif revno <= 0 or revno > len(history):
912
raise bzrlib.errors.NoSuchRevision(self, revno)
913
return history[revno - 1]
915
def _get_revision_info(self, revision):
916
"""Return (revno, revision id) for revision specifier.
918
revision can be an integer, in which case it is assumed to be revno
919
(though this will translate negative values into positive ones)
920
revision can also be a string, in which case it is parsed for something
921
like 'date:' or 'revid:' etc.
923
A revid is always returned. If it is None, the specifier referred to
924
the null revision. If the revid does not occur in the revision
925
history, revno will be None.
931
try:# Convert to int if possible
932
revision = int(revision)
935
revs = self.revision_history()
936
if isinstance(revision, int):
938
revno = len(revs) + revision + 1
941
rev_id = self.get_rev_id(revno, revs)
942
elif isinstance(revision, basestring):
943
for prefix, func in Branch.REVISION_NAMESPACES.iteritems():
944
if revision.startswith(prefix):
945
result = func(self, revs, revision)
947
revno, rev_id = result
950
rev_id = self.get_rev_id(revno, revs)
953
raise BzrError('No namespace registered for string: %r' %
956
raise TypeError('Unhandled revision type %s' % revision)
960
raise bzrlib.errors.NoSuchRevision(self, revision)
963
def _namespace_revno(self, revs, revision):
964
"""Lookup a revision by revision number"""
965
assert revision.startswith('revno:')
967
return (int(revision[6:]),)
970
REVISION_NAMESPACES['revno:'] = _namespace_revno
972
def _namespace_revid(self, revs, revision):
973
assert revision.startswith('revid:')
974
rev_id = revision[len('revid:'):]
976
return revs.index(rev_id) + 1, rev_id
979
REVISION_NAMESPACES['revid:'] = _namespace_revid
981
def _namespace_last(self, revs, revision):
982
assert revision.startswith('last:')
984
offset = int(revision[5:])
989
raise BzrError('You must supply a positive value for --revision last:XXX')
990
return (len(revs) - offset + 1,)
991
REVISION_NAMESPACES['last:'] = _namespace_last
993
def _namespace_tag(self, revs, revision):
994
assert revision.startswith('tag:')
995
raise BzrError('tag: namespace registered, but not implemented.')
996
REVISION_NAMESPACES['tag:'] = _namespace_tag
998
def _namespace_date(self, revs, revision):
999
assert revision.startswith('date:')
1001
# Spec for date revisions:
1003
# value can be 'yesterday', 'today', 'tomorrow' or a YYYY-MM-DD string.
1004
# it can also start with a '+/-/='. '+' says match the first
1005
# entry after the given date. '-' is match the first entry before the date
1006
# '=' is match the first entry after, but still on the given date.
1008
# +2005-05-12 says find the first matching entry after May 12th, 2005 at 0:00
1009
# -2005-05-12 says find the first matching entry before May 12th, 2005 at 0:00
1010
# =2005-05-12 says find the first match after May 12th, 2005 at 0:00 but before
1011
# May 13th, 2005 at 0:00
1013
# So the proper way of saying 'give me all entries for today' is:
1014
# -r {date:+today}:{date:-tomorrow}
1015
# The default is '=' when not supplied
1018
if val[:1] in ('+', '-', '='):
1019
match_style = val[:1]
1022
today = datetime.datetime.today().replace(hour=0,minute=0,second=0,microsecond=0)
1023
if val.lower() == 'yesterday':
1024
dt = today - datetime.timedelta(days=1)
1025
elif val.lower() == 'today':
1027
elif val.lower() == 'tomorrow':
1028
dt = today + datetime.timedelta(days=1)
1031
# This should be done outside the function to avoid recompiling it.
1032
_date_re = re.compile(
1033
r'(?P<date>(?P<year>\d\d\d\d)-(?P<month>\d\d)-(?P<day>\d\d))?'
1035
r'(?P<time>(?P<hour>\d\d):(?P<minute>\d\d)(:(?P<second>\d\d))?)?'
1037
m = _date_re.match(val)
1038
if not m or (not m.group('date') and not m.group('time')):
1039
raise BzrError('Invalid revision date %r' % revision)
1042
year, month, day = int(m.group('year')), int(m.group('month')), int(m.group('day'))
1044
year, month, day = today.year, today.month, today.day
1046
hour = int(m.group('hour'))
1047
minute = int(m.group('minute'))
1048
if m.group('second'):
1049
second = int(m.group('second'))
1053
hour, minute, second = 0,0,0
1055
dt = datetime.datetime(year=year, month=month, day=day,
1056
hour=hour, minute=minute, second=second)
1060
if match_style == '-':
1062
elif match_style == '=':
1063
last = dt + datetime.timedelta(days=1)
1066
for i in range(len(revs)-1, -1, -1):
1067
r = self.get_revision(revs[i])
1068
# TODO: Handle timezone.
1069
dt = datetime.datetime.fromtimestamp(r.timestamp)
1070
if first >= dt and (last is None or dt >= last):
1073
for i in range(len(revs)):
1074
r = self.get_revision(revs[i])
1075
# TODO: Handle timezone.
1076
dt = datetime.datetime.fromtimestamp(r.timestamp)
1077
if first <= dt and (last is None or dt <= last):
1079
REVISION_NAMESPACES['date:'] = _namespace_date
569
1081
def revision_tree(self, revision_id):
570
1082
"""Return Tree for a revision on this branch.
606
1117
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)
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)
1121
tree = self.working_tree()
1122
inv = tree.inventory
1123
if not tree.has_filename(from_rel):
1124
raise BzrError("can't rename: old working file %r does not exist" % from_rel)
1125
if tree.has_filename(to_rel):
1126
raise BzrError("can't rename: new working file %r already exists" % to_rel)
1128
file_id = inv.path2id(from_rel)
1130
raise BzrError("can't rename: old name %r is not versioned" % from_rel)
1132
if inv.path2id(to_rel):
1133
raise BzrError("can't rename: new name %r is already versioned" % to_rel)
1135
to_dir, to_tail = os.path.split(to_rel)
1136
to_dir_id = inv.path2id(to_dir)
1137
if to_dir_id == None and to_dir != '':
1138
raise BzrError("can't determine destination directory id for %r" % to_dir)
1140
mutter("rename_one:")
1141
mutter(" file_id {%s}" % file_id)
1142
mutter(" from_rel %r" % from_rel)
1143
mutter(" to_rel %r" % to_rel)
1144
mutter(" to_dir %r" % to_dir)
1145
mutter(" to_dir_id {%s}" % to_dir_id)
1147
inv.rename(file_id, to_dir_id, to_tail)
1149
from_abs = self.abspath(from_rel)
1150
to_abs = self.abspath(to_rel)
1152
os.rename(from_abs, to_abs)
1154
raise BzrError("failed to rename %r to %r: %s"
1155
% (from_abs, to_abs, e[1]),
1156
["rename rolled back"])
1158
self._write_inventory(inv)
652
1163
def move(self, from_paths, to_name):
660
1171
Note that to_name is only the last component of the new name;
661
1172
this doesn't change the directory.
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 = 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)
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)
1174
This returns a list of (from_path, to_path) pairs for each
1175
entry that is moved.
1180
## TODO: Option to move IDs only
1181
assert not isinstance(from_paths, basestring)
1182
tree = self.working_tree()
1183
inv = tree.inventory
1184
to_abs = self.abspath(to_name)
1185
if not isdir(to_abs):
1186
raise BzrError("destination %r is not a directory" % to_abs)
1187
if not tree.has_filename(to_name):
1188
raise BzrError("destination %r not in working directory" % to_abs)
1189
to_dir_id = inv.path2id(to_name)
1190
if to_dir_id == None and to_name != '':
1191
raise BzrError("destination %r is not a versioned directory" % to_name)
1192
to_dir_ie = inv[to_dir_id]
1193
if to_dir_ie.kind not in ('directory', 'root_directory'):
1194
raise BzrError("destination %r is not a directory" % to_abs)
1196
to_idpath = inv.get_idpath(to_dir_id)
1198
for f in from_paths:
1199
if not tree.has_filename(f):
1200
raise BzrError("%r does not exist in working tree" % f)
1201
f_id = inv.path2id(f)
1203
raise BzrError("%r is not versioned" % f)
1204
name_tail = splitpath(f)[-1]
1205
dest_path = appendpath(to_name, name_tail)
1206
if tree.has_filename(dest_path):
1207
raise BzrError("destination %r already exists" % dest_path)
1208
if f_id in to_idpath:
1209
raise BzrError("can't move %r to a subdirectory of itself" % f)
1211
# OK, so there's a race here, it's possible that someone will
1212
# create a file in this interval and then the rename might be
1213
# left half-done. But we should have caught most problems.
1215
for f in from_paths:
1216
name_tail = splitpath(f)[-1]
1217
dest_path = appendpath(to_name, name_tail)
1218
result.append((f, dest_path))
1219
inv.rename(inv.path2id(f), to_dir_id, name_tail)
1221
os.rename(self.abspath(f), self.abspath(dest_path))
1223
raise BzrError("failed to rename %r to %r: %s" % (f, dest_path, e[1]),
1224
["rename rolled back"])
1226
self._write_inventory(inv)
1233
def revert(self, filenames, old_tree=None, backups=True):
1234
"""Restore selected files to the versions from a previous tree.
1237
If true (default) backups are made of files before
1240
from bzrlib.errors import NotVersionedError, BzrError
1241
from bzrlib.atomicfile import AtomicFile
1242
from bzrlib.osutils import backup_file
1244
inv = self.read_working_inventory()
1245
if old_tree is None:
1246
old_tree = self.basis_tree()
1247
old_inv = old_tree.inventory
1250
for fn in filenames:
1251
file_id = inv.path2id(fn)
1253
raise NotVersionedError("not a versioned file", fn)
1254
if not old_inv.has_id(file_id):
1255
raise BzrError("file not present in old tree", fn, file_id)
1256
nids.append((fn, file_id))
1258
# TODO: Rename back if it was previously at a different location
1260
# TODO: If given a directory, restore the entire contents from
1261
# the previous version.
1263
# TODO: Make a backup to a temporary file.
1265
# TODO: If the file previously didn't exist, delete it?
1266
for fn, file_id in nids:
1269
f = AtomicFile(fn, 'wb')
1271
f.write(old_tree.get_file(file_id).read())
1277
def pending_merges(self):
1278
"""Return a list of pending merges.
1280
These are revisions that have been merged into the working
1281
directory but not yet committed.
1283
cfn = self.controlfilename('pending-merges')
1284
if not os.path.exists(cfn):
1287
for l in self.controlfile('pending-merges', 'r').readlines():
1288
p.append(l.rstrip('\n'))
1292
def add_pending_merge(self, revision_id):
1293
from bzrlib.revision import validate_revision_id
1295
validate_revision_id(revision_id)
1297
p = self.pending_merges()
1298
if revision_id in p:
1300
p.append(revision_id)
1301
self.set_pending_merges(p)
1304
def set_pending_merges(self, rev_list):
1305
from bzrlib.atomicfile import AtomicFile
1308
f = AtomicFile(self.controlfilename('pending-merges'))
1319
def get_parent(self):
1320
"""Return the parent location of the branch.
1322
This is the default location for push/pull/missing. The usual
1323
pattern is that the user can override it by specifying a
1327
_locs = ['parent', 'pull', 'x-pull']
1330
return self.controlfile(l, 'r').read().strip('\n')
1332
if e.errno != errno.ENOENT:
1337
def set_parent(self, url):
1338
# TODO: Maybe delete old location files?
1339
from bzrlib.atomicfile import AtomicFile
1342
f = AtomicFile(self.controlfilename('parent'))
1351
def check_revno(self, revno):
1353
Check whether a revno corresponds to any revision.
1354
Zero (the NULL revision) is considered valid.
1357
self.check_real_revno(revno)
1359
def check_real_revno(self, revno):
1361
Check whether a revno corresponds to a real revision.
1362
Zero (the NULL revision) is considered invalid
1364
if revno < 1 or revno > self.revno():
1365
raise InvalidRevisionNumber(revno)
715
1370
class ScratchBranch(Branch):