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
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
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_file, sha_string, file_kind, local_time_offset, appendpath
30
from store import ImmutableStore
31
from revision import Revision
32
from errors import BzrError
33
from textui import show_status
26
35
BZR_BRANCH_FORMAT = "Bazaar-NG branch, format 0.0.4\n"
27
36
## TODO: Maybe include checks for common corruption of newlines, etc?
333
315
['use a different bzr version',
334
316
'or remove the .bzr directory and "bzr init" again'])
336
def get_root_id(self):
337
"""Return the id of this branches root"""
338
inv = self.read_working_inventory()
339
return inv.root.file_id
341
def set_root_id(self, file_id):
342
inv = self.read_working_inventory()
343
orig_root_id = inv.root.file_id
344
del inv._byid[inv.root.file_id]
345
inv.root.file_id = file_id
346
inv._byid[inv.root.file_id] = inv.root
349
if entry.parent_id in (None, orig_root_id):
350
entry.parent_id = inv.root.file_id
351
self._write_inventory(inv)
353
320
def read_working_inventory(self):
354
321
"""Read the working inventory."""
355
from bzrlib.inventory import Inventory
356
from bzrlib.xml import unpack_xml
357
from time import time
323
# ElementTree does its own conversion from UTF-8, so open in
361
# ElementTree does its own conversion from UTF-8, so open in
363
inv = unpack_xml(Inventory,
364
self.controlfile('inventory', 'rb'))
327
inv = Inventory.read_xml(self.controlfile('inventory', 'rb'))
365
328
mutter("loaded inventory of %d items in %f"
366
% (len(inv), time() - before))
329
% (len(inv), time.time() - before))
564
520
return self.working_tree().unknowns()
567
def append_revision(self, *revision_ids):
568
from bzrlib.atomicfile import AtomicFile
570
for revision_id in revision_ids:
571
mutter("add {%s} to revision-history" % revision_id)
523
def append_revision(self, revision_id):
524
mutter("add {%s} to revision-history" % revision_id)
573
525
rev_history = self.revision_history()
574
rev_history.extend(revision_ids)
576
f = AtomicFile(self.controlfilename('revision-history'))
578
for rev_id in rev_history:
527
tmprhname = self.controlfilename('revision-history.tmp')
528
rhname = self.controlfilename('revision-history')
530
f = file(tmprhname, 'wt')
531
rev_history.append(revision_id)
532
f.write('\n'.join(rev_history))
536
if sys.platform == 'win32':
538
os.rename(tmprhname, rhname)
585
542
def get_revision(self, revision_id):
586
543
"""Return the Revision object for a named revision"""
587
from bzrlib.revision import Revision
588
from bzrlib.xml import unpack_xml
592
if not revision_id or not isinstance(revision_id, basestring):
593
raise ValueError('invalid revision-id: %r' % revision_id)
594
r = unpack_xml(Revision, self.revision_store[revision_id])
544
if not revision_id or not isinstance(revision_id, basestring):
545
raise ValueError('invalid revision-id: %r' % revision_id)
546
r = Revision.read_xml(self.revision_store[revision_id])
598
547
assert r.revision_id == revision_id
602
550
def get_revision_sha1(self, revision_id):
603
551
"""Hash the stored value of a revision, and return it."""
853
787
def commit(self, *args, **kw):
854
789
from bzrlib.commit import commit
855
790
commit(self, *args, **kw)
858
def lookup_revision(self, revision):
859
"""Return the revision identifier for a given revision information."""
860
revno, info = self.get_revision_info(revision)
863
def get_revision_info(self, revision):
864
"""Return (revno, revision id) for revision identifier.
866
revision can be an integer, in which case it is assumed to be revno (though
867
this will translate negative values into positive ones)
868
revision can also be a string, in which case it is parsed for something like
869
'date:' or 'revid:' etc.
874
try:# Convert to int if possible
875
revision = int(revision)
878
revs = self.revision_history()
879
if isinstance(revision, int):
882
# Mabye we should do this first, but we don't need it if revision == 0
884
revno = len(revs) + revision + 1
887
elif isinstance(revision, basestring):
888
for prefix, func in Branch.REVISION_NAMESPACES.iteritems():
889
if revision.startswith(prefix):
890
revno = func(self, revs, revision)
893
raise BzrError('No namespace registered for string: %r' % revision)
895
if revno is None or revno <= 0 or revno > len(revs):
896
raise BzrError("no such revision %s" % revision)
897
return revno, revs[revno-1]
899
def _namespace_revno(self, revs, revision):
900
"""Lookup a revision by revision number"""
901
assert revision.startswith('revno:')
903
return int(revision[6:])
906
REVISION_NAMESPACES['revno:'] = _namespace_revno
908
def _namespace_revid(self, revs, revision):
909
assert revision.startswith('revid:')
911
return revs.index(revision[6:]) + 1
914
REVISION_NAMESPACES['revid:'] = _namespace_revid
916
def _namespace_last(self, revs, revision):
917
assert revision.startswith('last:')
919
offset = int(revision[5:])
924
raise BzrError('You must supply a positive value for --revision last:XXX')
925
return len(revs) - offset + 1
926
REVISION_NAMESPACES['last:'] = _namespace_last
928
def _namespace_tag(self, revs, revision):
929
assert revision.startswith('tag:')
930
raise BzrError('tag: namespace registered, but not implemented.')
931
REVISION_NAMESPACES['tag:'] = _namespace_tag
933
def _namespace_date(self, revs, revision):
934
assert revision.startswith('date:')
936
# Spec for date revisions:
938
# value can be 'yesterday', 'today', 'tomorrow' or a YYYY-MM-DD string.
939
# it can also start with a '+/-/='. '+' says match the first
940
# entry after the given date. '-' is match the first entry before the date
941
# '=' is match the first entry after, but still on the given date.
943
# +2005-05-12 says find the first matching entry after May 12th, 2005 at 0:00
944
# -2005-05-12 says find the first matching entry before May 12th, 2005 at 0:00
945
# =2005-05-12 says find the first match after May 12th, 2005 at 0:00 but before
946
# May 13th, 2005 at 0:00
948
# So the proper way of saying 'give me all entries for today' is:
949
# -r {date:+today}:{date:-tomorrow}
950
# The default is '=' when not supplied
953
if val[:1] in ('+', '-', '='):
954
match_style = val[:1]
957
today = datetime.datetime.today().replace(hour=0,minute=0,second=0,microsecond=0)
958
if val.lower() == 'yesterday':
959
dt = today - datetime.timedelta(days=1)
960
elif val.lower() == 'today':
962
elif val.lower() == 'tomorrow':
963
dt = today + datetime.timedelta(days=1)
966
# This should be done outside the function to avoid recompiling it.
967
_date_re = re.compile(
968
r'(?P<date>(?P<year>\d\d\d\d)-(?P<month>\d\d)-(?P<day>\d\d))?'
970
r'(?P<time>(?P<hour>\d\d):(?P<minute>\d\d)(:(?P<second>\d\d))?)?'
972
m = _date_re.match(val)
973
if not m or (not m.group('date') and not m.group('time')):
974
raise BzrError('Invalid revision date %r' % revision)
977
year, month, day = int(m.group('year')), int(m.group('month')), int(m.group('day'))
979
year, month, day = today.year, today.month, today.day
981
hour = int(m.group('hour'))
982
minute = int(m.group('minute'))
983
if m.group('second'):
984
second = int(m.group('second'))
988
hour, minute, second = 0,0,0
990
dt = datetime.datetime(year=year, month=month, day=day,
991
hour=hour, minute=minute, second=second)
995
if match_style == '-':
997
elif match_style == '=':
998
last = dt + datetime.timedelta(days=1)
1001
for i in range(len(revs)-1, -1, -1):
1002
r = self.get_revision(revs[i])
1003
# TODO: Handle timezone.
1004
dt = datetime.datetime.fromtimestamp(r.timestamp)
1005
if first >= dt and (last is None or dt >= last):
1008
for i in range(len(revs)):
1009
r = self.get_revision(revs[i])
1010
# TODO: Handle timezone.
1011
dt = datetime.datetime.fromtimestamp(r.timestamp)
1012
if first <= dt and (last is None or dt <= last):
1014
REVISION_NAMESPACES['date:'] = _namespace_date
793
def lookup_revision(self, revno):
794
"""Return revision hash for revision number."""
799
# list is 0-based; revisions are 1-based
800
return self.revision_history()[revno-1]
802
raise BzrError("no such revision %s" % revno)
1016
805
def revision_tree(self, revision_id):
1017
806
"""Return Tree for a revision on this branch.
1019
808
`revision_id` may be None for the null revision, in which case
1020
809
an `EmptyTree` is returned."""
1021
from bzrlib.tree import EmptyTree, RevisionTree
1022
810
# TODO: refactor this to use an existing revision object
1023
811
# so we don't need to read it in twice.
1024
812
if revision_id == None:
1025
return EmptyTree(self.get_root_id())
1027
815
inv = self.get_revision_inventory(revision_id)
1028
816
return RevisionTree(self.text_store, inv)
1166
def revert(self, filenames, old_tree=None, backups=True):
1167
"""Restore selected files to the versions from a previous tree.
1170
If true (default) backups are made of files before
1173
from bzrlib.errors import NotVersionedError, BzrError
1174
from bzrlib.atomicfile import AtomicFile
1175
from bzrlib.osutils import backup_file
1177
inv = self.read_working_inventory()
1178
if old_tree is None:
1179
old_tree = self.basis_tree()
1180
old_inv = old_tree.inventory
1183
for fn in filenames:
1184
file_id = inv.path2id(fn)
1186
raise NotVersionedError("not a versioned file", fn)
1187
if not old_inv.has_id(file_id):
1188
raise BzrError("file not present in old tree", fn, file_id)
1189
nids.append((fn, file_id))
1191
# TODO: Rename back if it was previously at a different location
1193
# TODO: If given a directory, restore the entire contents from
1194
# the previous version.
1196
# TODO: Make a backup to a temporary file.
1198
# TODO: If the file previously didn't exist, delete it?
1199
for fn, file_id in nids:
1202
f = AtomicFile(fn, 'wb')
1204
f.write(old_tree.get_file(file_id).read())
1210
def pending_merges(self):
1211
"""Return a list of pending merges.
1213
These are revisions that have been merged into the working
1214
directory but not yet committed.
1216
cfn = self.controlfilename('pending-merges')
1217
if not os.path.exists(cfn):
1220
for l in self.controlfile('pending-merges', 'r').readlines():
1221
p.append(l.rstrip('\n'))
1225
def add_pending_merge(self, revision_id):
1226
from bzrlib.revision import validate_revision_id
1228
validate_revision_id(revision_id)
1230
p = self.pending_merges()
1231
if revision_id in p:
1233
p.append(revision_id)
1234
self.set_pending_merges(p)
1237
def set_pending_merges(self, rev_list):
1238
from bzrlib.atomicfile import AtomicFile
1241
f = AtomicFile(self.controlfilename('pending-merges'))
1253
954
class ScratchBranch(Branch):
1254
955
"""Special test class: a branch that cleans up after itself.