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
20
from cStringIO import StringIO
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
37
BZR_BRANCH_FORMAT = "Bazaar-NG branch, format 0.0.4\n"
23
from bzrlib.trace import mutter, note
24
from bzrlib.osutils import isdir, quotefn, compact_date, rand_bytes, \
26
sha_file, appendpath, file_kind
28
from bzrlib.errors import (BzrError, InvalidRevisionNumber, InvalidRevisionId,
29
NoSuchRevision, HistoryMissing, NotBranchError,
31
from bzrlib.textui import show_status
32
from bzrlib.revision import Revision, validate_revision_id
33
from bzrlib.delta import compare_trees
34
from bzrlib.tree import EmptyTree, RevisionTree
35
from bzrlib.inventory import Inventory
36
from bzrlib.weavestore import WeaveStore
37
from bzrlib.store import ImmutableStore
42
BZR_BRANCH_FORMAT_4 = "Bazaar-NG branch, format 0.0.4\n"
43
BZR_BRANCH_FORMAT_5 = "Bazaar-NG branch, format 5\n"
38
44
## TODO: Maybe include checks for common corruption of newlines, etc?
47
# TODO: Some operations like log might retrieve the same revisions
48
# repeatedly to calculate deltas. We could perhaps have a weakref
49
# cache in memory to make this faster. In general anything can be
50
# cached in memory between lock and unlock operations.
52
# TODO: please move the revision-string syntax stuff out of the branch
53
# object; it's clutter
42
56
def find_branch(f, **args):
43
57
if f and (f.startswith('http://') or f.startswith('https://')):
131
226
__repr__ = __str__
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)
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)
230
if self._lock_mode or self._lock:
231
from warnings import warn
232
warn("branch %r was not explicitly unlocked" % self)
236
def lock_write(self):
238
if self._lock_mode != 'w':
239
raise LockError("can't upgrade to a write lock from %r" %
241
self._lock_count += 1
243
from bzrlib.lock import WriteLock
245
self._lock = WriteLock(self.controlfilename('branch-lock'))
246
self._lock_mode = 'w'
252
assert self._lock_mode in ('r', 'w'), \
253
"invalid lock mode %r" % self._lock_mode
254
self._lock_count += 1
256
from bzrlib.lock import ReadLock
258
self._lock = ReadLock(self.controlfilename('branch-lock'))
259
self._lock_mode = 'r'
263
if not self._lock_mode:
264
raise LockError('branch %r is not locked' % (self))
266
if self._lock_count > 1:
267
self._lock_count -= 1
271
self._lock_mode = self._lock_count = None
183
273
def abspath(self, name):
184
274
"""Return absolute filename for something in the branch"""
185
275
return os.path.join(self.base, name)
188
277
def relpath(self, path):
189
278
"""Return path relative to this branch of something inside it.
191
280
Raises an error if path is not in this branch."""
192
rp = os.path.realpath(path)
194
if not rp.startswith(self.base):
195
bailout("path %r is not within branch %r" % (rp, self.base))
196
rp = rp[len(self.base):]
197
rp = rp.lstrip(os.sep)
281
return _relpath(self.base, path)
201
283
def controlfilename(self, file_or_path):
202
284
"""Return location relative to branch."""
203
if isinstance(file_or_path, types.StringTypes):
285
if isinstance(file_or_path, basestring):
204
286
file_or_path = [file_or_path]
205
287
return os.path.join(self.base, bzrlib.BZRDIR, *file_or_path)
231
313
raise BzrError("invalid controlfile mode %r" % mode)
235
315
def _make_control(self):
236
316
os.mkdir(self.controlfilename([]))
237
317
self.controlfile('README', 'w').write(
238
318
"This is a Bazaar-NG control directory.\n"
239
"Do not change any files in this directory.")
240
self.controlfile('branch-format', 'w').write(BZR_BRANCH_FORMAT)
241
for d in ('text-store', 'inventory-store', 'revision-store'):
319
"Do not change any files in this directory.\n")
320
self.controlfile('branch-format', 'w').write(BZR_BRANCH_FORMAT_5)
321
for d in ('text-store', 'revision-store',
242
323
os.mkdir(self.controlfilename(d))
243
for f in ('revision-history', 'merged-patches',
244
'pending-merged-patches', 'branch-name',
324
for f in ('revision-history',
246
328
self.controlfile(f, 'w').write('')
247
329
mutter('created control directory in ' + self.base)
248
Inventory().write_xml(self.controlfile('inventory','w'))
251
def _check_format(self):
331
# if we want per-tree root ids then this is the place to set
332
# them; they're not needed for now and so ommitted for
334
f = self.controlfile('inventory','w')
335
bzrlib.xml5.serializer_v5.write_inventory(Inventory(), f)
339
def _check_format(self, relax_version_check):
252
340
"""Check this branch format is supported.
254
The current tool only supports the current unstable format.
342
The format level is stored, as an integer, in
343
self._branch_format for code that needs to check it later.
256
345
In the future, we might need different in-memory Branch
257
346
classes to support downlevel branches. But not yet.
259
# This ignores newlines so that we can open branches created
260
# on Windows from Linux and so on. I think it might be better
261
# to always make all internal files in unix format.
262
348
fmt = self.controlfile('branch-format', 'r').read()
263
fmt.replace('\r\n', '')
264
if fmt != BZR_BRANCH_FORMAT:
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'])
349
if fmt == BZR_BRANCH_FORMAT_5:
350
self._branch_format = 5
351
elif fmt == BZR_BRANCH_FORMAT_4:
352
self._branch_format = 4
354
if (not relax_version_check
355
and self._branch_format != 5):
356
raise BzrError('sorry, branch format "%s" not supported; '
357
'use a different bzr version, '
358
'or run "bzr upgrade"'
359
% fmt.rstrip('\n\r'))
362
def get_root_id(self):
363
"""Return the id of this branches root"""
364
inv = self.read_working_inventory()
365
return inv.root.file_id
367
def set_root_id(self, file_id):
368
inv = self.read_working_inventory()
369
orig_root_id = inv.root.file_id
370
del inv._byid[inv.root.file_id]
371
inv.root.file_id = file_id
372
inv._byid[inv.root.file_id] = inv.root
375
if entry.parent_id in (None, orig_root_id):
376
entry.parent_id = inv.root.file_id
377
self._write_inventory(inv)
270
379
def read_working_inventory(self):
271
380
"""Read the working inventory."""
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))
383
# ElementTree does its own conversion from UTF-8, so open in
385
f = self.controlfile('inventory', 'rb')
386
return bzrlib.xml5.serializer_v5.read_inventory(f)
282
391
def _write_inventory(self, inv):
283
392
"""Update the working inventory.
285
394
That is to say, the inventory describing changes underway, that
286
395
will be committed to the next revision.
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)
397
from bzrlib.atomicfile import AtomicFile
401
f = AtomicFile(self.controlfilename('inventory'), 'wb')
403
bzrlib.xml5.serializer_v5.write_inventory(inv, f)
299
410
mutter('wrote working inventory')
302
413
inventory = property(read_working_inventory, _write_inventory, None,
303
414
"""Inventory for the working copy.""")
306
def add(self, files, verbose=False):
417
def add(self, files, ids=None):
307
418
"""Make files versioned.
309
Note that the command line normally calls smart_add instead.
420
Note that the command line normally calls smart_add instead,
421
which can automatically recurse.
311
423
This puts the files in the Added state, so that they will be
312
424
recorded by the next commit.
427
List of paths to add, relative to the base of the tree.
430
If set, use these instead of automatically generated ids.
431
Must be the same length as the list of files, but may
432
contain None for ids that are to be autogenerated.
314
434
TODO: Perhaps have an option to add the ids even if the files do
317
TODO: Perhaps return the ids of the files? But then again it
318
is easy to retrieve them if they're needed.
320
TODO: Option to specify file id.
322
TODO: Adding a directory should optionally recurse down and
323
add all non-ignored children. Perhaps do that in a
437
TODO: Perhaps yield the ids and paths as they're added.
326
self._need_writelock()
328
439
# TODO: Re-adding a file that is removed in the working copy
329
440
# should probably put it back with the previous ID.
330
if isinstance(files, types.StringTypes):
441
if isinstance(files, basestring):
442
assert(ids is None or isinstance(ids, basestring))
333
inv = self.read_working_inventory()
335
if is_control_file(f):
336
bailout("cannot add control file %s" % quotefn(f))
341
bailout("cannot add top-level %r" % f)
343
fullpath = os.path.normpath(self.abspath(f))
346
kind = file_kind(fullpath)
348
# maybe something better?
349
bailout('cannot add: not a regular file or directory: %s' % quotefn(f))
351
if kind != 'file' and kind != 'directory':
352
bailout('cannot add: not a regular file or directory: %s' % quotefn(f))
354
file_id = gen_file_id(f)
355
inv.add_path(f, kind=kind, file_id=file_id)
358
show_status('A', kind, quotefn(f))
360
mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
362
self._write_inventory(inv)
448
ids = [None] * len(files)
450
assert(len(ids) == len(files))
454
inv = self.read_working_inventory()
455
for f,file_id in zip(files, ids):
456
if is_control_file(f):
457
raise BzrError("cannot add control file %s" % quotefn(f))
462
raise BzrError("cannot add top-level %r" % f)
464
fullpath = os.path.normpath(self.abspath(f))
467
kind = file_kind(fullpath)
469
# maybe something better?
470
raise BzrError('cannot add: not a regular file or directory: %s' % quotefn(f))
472
if kind != 'file' and kind != 'directory':
473
raise BzrError('cannot add: not a regular file or directory: %s' % quotefn(f))
476
file_id = gen_file_id(f)
477
inv.add_path(f, kind=kind, file_id=file_id)
479
mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
481
self._write_inventory(inv)
365
486
def print_file(self, file, revno):
366
487
"""Print `file` to stdout."""
367
self._need_readlock()
368
tree = self.revision_tree(self.lookup_revision(revno))
369
# use inventory as it was in that revision
370
file_id = tree.inventory.path2id(file)
372
bailout("%r is not present in revision %d" % (file, revno))
373
tree.print_file(file_id)
490
tree = self.revision_tree(self.lookup_revision(revno))
491
# use inventory as it was in that revision
492
file_id = tree.inventory.path2id(file)
494
raise BzrError("%r is not present in revision %s" % (file, revno))
495
tree.print_file(file_id)
376
500
def remove(self, files, verbose=False):
377
501
"""Mark nominated files for removal from the inventory.
434
573
return self.working_tree().unknowns()
437
def append_revision(self, revision_id):
438
mutter("add {%s} to revision-history" % revision_id)
576
def append_revision(self, *revision_ids):
577
from bzrlib.atomicfile import AtomicFile
579
for revision_id in revision_ids:
580
mutter("add {%s} to revision-history" % revision_id)
439
582
rev_history = self.revision_history()
441
tmprhname = self.controlfilename('revision-history.tmp')
442
rhname = self.controlfilename('revision-history')
444
f = file(tmprhname, 'wt')
445
rev_history.append(revision_id)
446
f.write('\n'.join(rev_history))
450
if sys.platform == 'win32':
452
os.rename(tmprhname, rhname)
583
rev_history.extend(revision_ids)
585
f = AtomicFile(self.controlfilename('revision-history'))
587
for rev_id in rev_history:
594
def has_revision(self, revision_id):
595
"""True if this branch has a copy of the revision.
597
This does not necessarily imply the revision is merge
598
or on the mainline."""
599
return revision_id in self.revision_store
602
def get_revision_xml_file(self, revision_id):
603
"""Return XML file object for revision object."""
604
if not revision_id or not isinstance(revision_id, basestring):
605
raise InvalidRevisionId(revision_id)
610
return self.revision_store[revision_id]
612
raise bzrlib.errors.NoSuchRevision(self, revision_id)
617
def get_revision_xml(self, revision_id):
618
return self.get_revision_xml_file(revision_id).read()
456
621
def get_revision(self, revision_id):
457
622
"""Return the Revision object for a named revision"""
458
self._need_readlock()
459
r = Revision.read_xml(self.revision_store[revision_id])
623
xml_file = self.get_revision_xml_file(revision_id)
626
r = bzrlib.xml5.serializer_v5.read_revision(xml_file)
627
except SyntaxError, e:
628
raise bzrlib.errors.BzrError('failed to unpack revision_xml',
460
632
assert r.revision_id == revision_id
464
def get_inventory(self, inventory_id):
465
"""Get Inventory object by hash.
467
TODO: Perhaps for this and similar methods, take a revision
468
parameter which can be either an integer revno or a
470
self._need_readlock()
471
i = Inventory.read_xml(self.inventory_store[inventory_id])
636
def get_revision_delta(self, revno):
637
"""Return the delta for one revision.
639
The delta is relative to its mainline predecessor, or the
640
empty tree for revision 1.
642
assert isinstance(revno, int)
643
rh = self.revision_history()
644
if not (1 <= revno <= len(rh)):
645
raise InvalidRevisionNumber(revno)
647
# revno is 1-based; list is 0-based
649
new_tree = self.revision_tree(rh[revno-1])
651
old_tree = EmptyTree()
653
old_tree = self.revision_tree(rh[revno-2])
655
return compare_trees(old_tree, new_tree)
659
def get_revision_sha1(self, revision_id):
660
"""Hash the stored value of a revision, and return it."""
661
return bzrlib.osutils.sha_file(self.get_revision_xml_file(revision_id))
664
def _get_ancestry_weave(self):
665
return self.control_weaves.get_weave('ancestry')
668
def get_ancestry(self, revision_id):
669
"""Return a list of revision-ids integrated by a revision.
672
w = self._get_ancestry_weave()
673
return [l[:-1] for l in w.get_iter(w.lookup(revision_id))]
676
def get_inventory_weave(self):
677
return self.control_weaves.get_weave('inventory')
680
def get_inventory(self, revision_id):
681
"""Get Inventory object by hash."""
682
# FIXME: The text gets passed around a lot coming from the weave.
683
f = StringIO(self.get_inventory_xml(revision_id))
684
return bzrlib.xml5.serializer_v5.read_inventory(f)
687
def get_inventory_xml(self, revision_id):
688
"""Get inventory XML as a file object."""
690
assert isinstance(revision_id, basestring), type(revision_id)
691
iw = self.get_inventory_weave()
692
return iw.get_text(iw.lookup(revision_id))
694
raise bzrlib.errors.HistoryMissing(self, 'inventory', revision_id)
697
def get_inventory_sha1(self, revision_id):
698
"""Return the sha1 hash of the inventory entry
700
return self.get_revision(revision_id).inventory_sha1
475
703
def get_revision_inventory(self, revision_id):
476
704
"""Return inventory of a past revision."""
477
self._need_readlock()
705
# bzr 0.0.6 and later imposes the constraint that the inventory_id
706
# must be the same as its revision, so this is trivial.
478
707
if revision_id == None:
708
return Inventory(self.get_root_id())
481
return self.get_inventory(self.get_revision(revision_id).inventory_id)
710
return self.get_inventory(revision_id)
484
713
def revision_history(self):
485
"""Return sequence of revision hashes on to this branch.
487
>>> ScratchBranch().revision_history()
490
self._need_readlock()
491
return [l.rstrip('\r\n') for l in self.controlfile('revision-history', 'r').readlines()]
494
def enum_history(self, direction):
495
"""Return (revno, revision_id) for history of branch.
498
'forward' is from earliest to latest
499
'reverse' is from latest to earliest
501
rh = self.revision_history()
502
if direction == 'forward':
507
elif direction == 'reverse':
513
raise BzrError('invalid history direction %r' % direction)
714
"""Return sequence of revision hashes on to this branch."""
717
return [l.rstrip('\r\n') for l in
718
self.controlfile('revision-history', 'r').readlines()]
723
def common_ancestor(self, other, self_revno=None, other_revno=None):
726
>>> sb = ScratchBranch(files=['foo', 'foo~'])
727
>>> sb.common_ancestor(sb) == (None, None)
729
>>> commit.commit(sb, "Committing first revision")
730
>>> sb.common_ancestor(sb)[0]
732
>>> clone = sb.clone()
733
>>> commit.commit(sb, "Committing second revision")
734
>>> sb.common_ancestor(sb)[0]
736
>>> sb.common_ancestor(clone)[0]
738
>>> commit.commit(clone, "Committing divergent second revision")
739
>>> sb.common_ancestor(clone)[0]
741
>>> sb.common_ancestor(clone) == clone.common_ancestor(sb)
743
>>> sb.common_ancestor(sb) != clone.common_ancestor(clone)
745
>>> clone2 = sb.clone()
746
>>> sb.common_ancestor(clone2)[0]
748
>>> sb.common_ancestor(clone2, self_revno=1)[0]
750
>>> sb.common_ancestor(clone2, other_revno=1)[0]
753
my_history = self.revision_history()
754
other_history = other.revision_history()
755
if self_revno is None:
756
self_revno = len(my_history)
757
if other_revno is None:
758
other_revno = len(other_history)
759
indices = range(min((self_revno, other_revno)))
762
if my_history[r] == other_history[r]:
763
return r+1, my_history[r]
786
def missing_revisions(self, other, stop_revision=None, diverged_ok=False):
787
"""Return a list of new revisions that would perfectly fit.
789
If self and other have not diverged, return a list of the revisions
790
present in other, but missing from self.
792
>>> from bzrlib.commit import commit
793
>>> bzrlib.trace.silent = True
794
>>> br1 = ScratchBranch()
795
>>> br2 = ScratchBranch()
796
>>> br1.missing_revisions(br2)
798
>>> commit(br2, "lala!", rev_id="REVISION-ID-1")
799
>>> br1.missing_revisions(br2)
801
>>> br2.missing_revisions(br1)
803
>>> commit(br1, "lala!", rev_id="REVISION-ID-1")
804
>>> br1.missing_revisions(br2)
806
>>> commit(br2, "lala!", rev_id="REVISION-ID-2A")
807
>>> br1.missing_revisions(br2)
809
>>> commit(br1, "lala!", rev_id="REVISION-ID-2B")
810
>>> br1.missing_revisions(br2)
811
Traceback (most recent call last):
812
DivergedBranches: These branches have diverged.
814
# FIXME: If the branches have diverged, but the latest
815
# revision in this branch is completely merged into the other,
816
# then we should still be able to pull.
817
self_history = self.revision_history()
818
self_len = len(self_history)
819
other_history = other.revision_history()
820
other_len = len(other_history)
821
common_index = min(self_len, other_len) -1
822
if common_index >= 0 and \
823
self_history[common_index] != other_history[common_index]:
824
raise DivergedBranches(self, other)
826
if stop_revision is None:
827
stop_revision = other_len
829
assert isinstance(stop_revision, int)
830
if stop_revision > other_len:
831
raise bzrlib.errors.NoSuchRevision(self, stop_revision)
833
return other_history[self_len:stop_revision]
836
def update_revisions(self, other, stop_revno=None):
837
"""Pull in new perfect-fit revisions.
839
from bzrlib.fetch import greedy_fetch
842
stop_revision = other.lookup_revision(stop_revno)
845
greedy_fetch(to_branch=self, from_branch=other,
846
revision=stop_revision)
848
pullable_revs = self.missing_revisions(other, stop_revision)
851
greedy_fetch(to_branch=self,
853
revision=pullable_revs[-1])
854
self.append_revision(*pullable_revs)
535
857
def commit(self, *args, **kw):
537
from bzrlib.commit import commit
538
commit(self, *args, **kw)
858
from bzrlib.commit import Commit
859
Commit().commit(self, *args, **kw)
541
def lookup_revision(self, revno):
542
"""Return revision hash for revision number."""
862
def lookup_revision(self, revision):
863
"""Return the revision identifier for a given revision information."""
864
revno, info = self._get_revision_info(revision)
868
def revision_id_to_revno(self, revision_id):
869
"""Given a revision id, return its revno"""
870
history = self.revision_history()
872
return history.index(revision_id) + 1
874
raise bzrlib.errors.NoSuchRevision(self, revision_id)
877
def get_revision_info(self, revision):
878
"""Return (revno, revision id) for revision identifier.
880
revision can be an integer, in which case it is assumed to be revno (though
881
this will translate negative values into positive ones)
882
revision can also be a string, in which case it is parsed for something like
883
'date:' or 'revid:' etc.
885
revno, rev_id = self._get_revision_info(revision)
887
raise bzrlib.errors.NoSuchRevision(self, revision)
890
def get_rev_id(self, revno, history=None):
891
"""Find the revision id of the specified revno."""
547
# list is 0-based; revisions are 1-based
548
return self.revision_history()[revno-1]
550
raise BzrError("no such revision %s" % revno)
895
history = self.revision_history()
896
elif revno <= 0 or revno > len(history):
897
raise bzrlib.errors.NoSuchRevision(self, revno)
898
return history[revno - 1]
900
def _get_revision_info(self, revision):
901
"""Return (revno, revision id) for revision specifier.
903
revision can be an integer, in which case it is assumed to be revno
904
(though this will translate negative values into positive ones)
905
revision can also be a string, in which case it is parsed for something
906
like 'date:' or 'revid:' etc.
908
A revid is always returned. If it is None, the specifier referred to
909
the null revision. If the revid does not occur in the revision
910
history, revno will be None.
916
try:# Convert to int if possible
917
revision = int(revision)
920
revs = self.revision_history()
921
if isinstance(revision, int):
923
revno = len(revs) + revision + 1
926
rev_id = self.get_rev_id(revno, revs)
927
elif isinstance(revision, basestring):
928
for prefix, func in Branch.REVISION_NAMESPACES.iteritems():
929
if revision.startswith(prefix):
930
result = func(self, revs, revision)
932
revno, rev_id = result
935
rev_id = self.get_rev_id(revno, revs)
938
raise BzrError('No namespace registered for string: %r' %
941
raise TypeError('Unhandled revision type %s' % revision)
945
raise bzrlib.errors.NoSuchRevision(self, revision)
948
def _namespace_revno(self, revs, revision):
949
"""Lookup a revision by revision number"""
950
assert revision.startswith('revno:')
952
return (int(revision[6:]),)
955
REVISION_NAMESPACES['revno:'] = _namespace_revno
957
def _namespace_revid(self, revs, revision):
958
assert revision.startswith('revid:')
959
rev_id = revision[len('revid:'):]
961
return revs.index(rev_id) + 1, rev_id
964
REVISION_NAMESPACES['revid:'] = _namespace_revid
966
def _namespace_last(self, revs, revision):
967
assert revision.startswith('last:')
969
offset = int(revision[5:])
974
raise BzrError('You must supply a positive value for --revision last:XXX')
975
return (len(revs) - offset + 1,)
976
REVISION_NAMESPACES['last:'] = _namespace_last
978
def _namespace_tag(self, revs, revision):
979
assert revision.startswith('tag:')
980
raise BzrError('tag: namespace registered, but not implemented.')
981
REVISION_NAMESPACES['tag:'] = _namespace_tag
983
def _namespace_date(self, revs, revision):
984
assert revision.startswith('date:')
986
# Spec for date revisions:
988
# value can be 'yesterday', 'today', 'tomorrow' or a YYYY-MM-DD string.
989
# it can also start with a '+/-/='. '+' says match the first
990
# entry after the given date. '-' is match the first entry before the date
991
# '=' is match the first entry after, but still on the given date.
993
# +2005-05-12 says find the first matching entry after May 12th, 2005 at 0:00
994
# -2005-05-12 says find the first matching entry before May 12th, 2005 at 0:00
995
# =2005-05-12 says find the first match after May 12th, 2005 at 0:00 but before
996
# May 13th, 2005 at 0:00
998
# So the proper way of saying 'give me all entries for today' is:
999
# -r {date:+today}:{date:-tomorrow}
1000
# The default is '=' when not supplied
1003
if val[:1] in ('+', '-', '='):
1004
match_style = val[:1]
1007
today = datetime.datetime.today().replace(hour=0,minute=0,second=0,microsecond=0)
1008
if val.lower() == 'yesterday':
1009
dt = today - datetime.timedelta(days=1)
1010
elif val.lower() == 'today':
1012
elif val.lower() == 'tomorrow':
1013
dt = today + datetime.timedelta(days=1)
1016
# This should be done outside the function to avoid recompiling it.
1017
_date_re = re.compile(
1018
r'(?P<date>(?P<year>\d\d\d\d)-(?P<month>\d\d)-(?P<day>\d\d))?'
1020
r'(?P<time>(?P<hour>\d\d):(?P<minute>\d\d)(:(?P<second>\d\d))?)?'
1022
m = _date_re.match(val)
1023
if not m or (not m.group('date') and not m.group('time')):
1024
raise BzrError('Invalid revision date %r' % revision)
1027
year, month, day = int(m.group('year')), int(m.group('month')), int(m.group('day'))
1029
year, month, day = today.year, today.month, today.day
1031
hour = int(m.group('hour'))
1032
minute = int(m.group('minute'))
1033
if m.group('second'):
1034
second = int(m.group('second'))
1038
hour, minute, second = 0,0,0
1040
dt = datetime.datetime(year=year, month=month, day=day,
1041
hour=hour, minute=minute, second=second)
1045
if match_style == '-':
1047
elif match_style == '=':
1048
last = dt + datetime.timedelta(days=1)
1051
for i in range(len(revs)-1, -1, -1):
1052
r = self.get_revision(revs[i])
1053
# TODO: Handle timezone.
1054
dt = datetime.datetime.fromtimestamp(r.timestamp)
1055
if first >= dt and (last is None or dt >= last):
1058
for i in range(len(revs)):
1059
r = self.get_revision(revs[i])
1060
# TODO: Handle timezone.
1061
dt = datetime.datetime.fromtimestamp(r.timestamp)
1062
if first <= dt and (last is None or dt <= last):
1064
REVISION_NAMESPACES['date:'] = _namespace_date
553
1066
def revision_tree(self, revision_id):
554
1067
"""Return Tree for a revision on this branch.
556
1069
`revision_id` may be None for the null revision, in which case
557
1070
an `EmptyTree` is returned."""
558
self._need_readlock()
1071
# TODO: refactor this to use an existing revision object
1072
# so we don't need to read it in twice.
559
1073
if revision_id == None:
560
1074
return EmptyTree()
562
1076
inv = self.get_revision_inventory(revision_id)
563
return RevisionTree(self.text_store, inv)
1077
return RevisionTree(self.weave_store, inv, revision_id)
566
1080
def working_tree(self):
588
1097
This can change the directory or the filename or both.
590
self._need_writelock()
591
tree = self.working_tree()
593
if not tree.has_filename(from_rel):
594
bailout("can't rename: old working file %r does not exist" % from_rel)
595
if tree.has_filename(to_rel):
596
bailout("can't rename: new working file %r already exists" % to_rel)
598
file_id = inv.path2id(from_rel)
600
bailout("can't rename: old name %r is not versioned" % from_rel)
602
if inv.path2id(to_rel):
603
bailout("can't rename: new name %r is already versioned" % to_rel)
605
to_dir, to_tail = os.path.split(to_rel)
606
to_dir_id = inv.path2id(to_dir)
607
if to_dir_id == None and to_dir != '':
608
bailout("can't determine destination directory id for %r" % to_dir)
610
mutter("rename_one:")
611
mutter(" file_id {%s}" % file_id)
612
mutter(" from_rel %r" % from_rel)
613
mutter(" to_rel %r" % to_rel)
614
mutter(" to_dir %r" % to_dir)
615
mutter(" to_dir_id {%s}" % to_dir_id)
617
inv.rename(file_id, to_dir_id, to_tail)
619
print "%s => %s" % (from_rel, to_rel)
621
from_abs = self.abspath(from_rel)
622
to_abs = self.abspath(to_rel)
624
os.rename(from_abs, to_abs)
626
bailout("failed to rename %r to %r: %s"
627
% (from_abs, to_abs, e[1]),
628
["rename rolled back"])
630
self._write_inventory(inv)
1101
tree = self.working_tree()
1102
inv = tree.inventory
1103
if not tree.has_filename(from_rel):
1104
raise BzrError("can't rename: old working file %r does not exist" % from_rel)
1105
if tree.has_filename(to_rel):
1106
raise BzrError("can't rename: new working file %r already exists" % to_rel)
1108
file_id = inv.path2id(from_rel)
1110
raise BzrError("can't rename: old name %r is not versioned" % from_rel)
1112
if inv.path2id(to_rel):
1113
raise BzrError("can't rename: new name %r is already versioned" % to_rel)
1115
to_dir, to_tail = os.path.split(to_rel)
1116
to_dir_id = inv.path2id(to_dir)
1117
if to_dir_id == None and to_dir != '':
1118
raise BzrError("can't determine destination directory id for %r" % to_dir)
1120
mutter("rename_one:")
1121
mutter(" file_id {%s}" % file_id)
1122
mutter(" from_rel %r" % from_rel)
1123
mutter(" to_rel %r" % to_rel)
1124
mutter(" to_dir %r" % to_dir)
1125
mutter(" to_dir_id {%s}" % to_dir_id)
1127
inv.rename(file_id, to_dir_id, to_tail)
1129
from_abs = self.abspath(from_rel)
1130
to_abs = self.abspath(to_rel)
1132
os.rename(from_abs, to_abs)
1134
raise BzrError("failed to rename %r to %r: %s"
1135
% (from_abs, to_abs, e[1]),
1136
["rename rolled back"])
1138
self._write_inventory(inv)
634
1143
def move(self, from_paths, to_name):
642
1151
Note that to_name is only the last component of the new name;
643
1152
this doesn't change the directory.
645
self._need_writelock()
646
## TODO: Option to move IDs only
647
assert not isinstance(from_paths, basestring)
648
tree = self.working_tree()
650
to_abs = self.abspath(to_name)
651
if not isdir(to_abs):
652
bailout("destination %r is not a directory" % to_abs)
653
if not tree.has_filename(to_name):
654
bailout("destination %r not in working directory" % to_abs)
655
to_dir_id = inv.path2id(to_name)
656
if to_dir_id == None and to_name != '':
657
bailout("destination %r is not a versioned directory" % to_name)
658
to_dir_ie = inv[to_dir_id]
659
if to_dir_ie.kind not in ('directory', 'root_directory'):
660
bailout("destination %r is not a directory" % to_abs)
662
to_idpath = Set(inv.get_idpath(to_dir_id))
665
if not tree.has_filename(f):
666
bailout("%r does not exist in working tree" % f)
667
f_id = inv.path2id(f)
669
bailout("%r is not versioned" % f)
670
name_tail = splitpath(f)[-1]
671
dest_path = appendpath(to_name, name_tail)
672
if tree.has_filename(dest_path):
673
bailout("destination %r already exists" % dest_path)
674
if f_id in to_idpath:
675
bailout("can't move %r to a subdirectory of itself" % f)
677
# OK, so there's a race here, it's possible that someone will
678
# create a file in this interval and then the rename might be
679
# left half-done. But we should have caught most problems.
682
name_tail = splitpath(f)[-1]
683
dest_path = appendpath(to_name, name_tail)
684
print "%s => %s" % (f, dest_path)
685
inv.rename(inv.path2id(f), to_dir_id, name_tail)
687
os.rename(self.abspath(f), self.abspath(dest_path))
689
bailout("failed to rename %r to %r: %s" % (f, dest_path, e[1]),
690
["rename rolled back"])
692
self._write_inventory(inv)
1154
This returns a list of (from_path, to_path) pairs for each
1155
entry that is moved.
1160
## TODO: Option to move IDs only
1161
assert not isinstance(from_paths, basestring)
1162
tree = self.working_tree()
1163
inv = tree.inventory
1164
to_abs = self.abspath(to_name)
1165
if not isdir(to_abs):
1166
raise BzrError("destination %r is not a directory" % to_abs)
1167
if not tree.has_filename(to_name):
1168
raise BzrError("destination %r not in working directory" % to_abs)
1169
to_dir_id = inv.path2id(to_name)
1170
if to_dir_id == None and to_name != '':
1171
raise BzrError("destination %r is not a versioned directory" % to_name)
1172
to_dir_ie = inv[to_dir_id]
1173
if to_dir_ie.kind not in ('directory', 'root_directory'):
1174
raise BzrError("destination %r is not a directory" % to_abs)
1176
to_idpath = inv.get_idpath(to_dir_id)
1178
for f in from_paths:
1179
if not tree.has_filename(f):
1180
raise BzrError("%r does not exist in working tree" % f)
1181
f_id = inv.path2id(f)
1183
raise BzrError("%r is not versioned" % f)
1184
name_tail = splitpath(f)[-1]
1185
dest_path = appendpath(to_name, name_tail)
1186
if tree.has_filename(dest_path):
1187
raise BzrError("destination %r already exists" % dest_path)
1188
if f_id in to_idpath:
1189
raise BzrError("can't move %r to a subdirectory of itself" % f)
1191
# OK, so there's a race here, it's possible that someone will
1192
# create a file in this interval and then the rename might be
1193
# left half-done. But we should have caught most problems.
1195
for f in from_paths:
1196
name_tail = splitpath(f)[-1]
1197
dest_path = appendpath(to_name, name_tail)
1198
result.append((f, dest_path))
1199
inv.rename(inv.path2id(f), to_dir_id, name_tail)
1201
os.rename(self.abspath(f), self.abspath(dest_path))
1203
raise BzrError("failed to rename %r to %r: %s" % (f, dest_path, e[1]),
1204
["rename rolled back"])
1206
self._write_inventory(inv)
1213
def revert(self, filenames, old_tree=None, backups=True):
1214
"""Restore selected files to the versions from a previous tree.
1217
If true (default) backups are made of files before
1220
from bzrlib.errors import NotVersionedError, BzrError
1221
from bzrlib.atomicfile import AtomicFile
1222
from bzrlib.osutils import backup_file
1224
inv = self.read_working_inventory()
1225
if old_tree is None:
1226
old_tree = self.basis_tree()
1227
old_inv = old_tree.inventory
1230
for fn in filenames:
1231
file_id = inv.path2id(fn)
1233
raise NotVersionedError("not a versioned file", fn)
1234
if not old_inv.has_id(file_id):
1235
raise BzrError("file not present in old tree", fn, file_id)
1236
nids.append((fn, file_id))
1238
# TODO: Rename back if it was previously at a different location
1240
# TODO: If given a directory, restore the entire contents from
1241
# the previous version.
1243
# TODO: Make a backup to a temporary file.
1245
# TODO: If the file previously didn't exist, delete it?
1246
for fn, file_id in nids:
1249
f = AtomicFile(fn, 'wb')
1251
f.write(old_tree.get_file(file_id).read())
1257
def pending_merges(self):
1258
"""Return a list of pending merges.
1260
These are revisions that have been merged into the working
1261
directory but not yet committed.
1263
cfn = self.controlfilename('pending-merges')
1264
if not os.path.exists(cfn):
1267
for l in self.controlfile('pending-merges', 'r').readlines():
1268
p.append(l.rstrip('\n'))
1272
def add_pending_merge(self, revision_id):
1273
validate_revision_id(revision_id)
1274
# TODO: Perhaps should check at this point that the
1275
# history of the revision is actually present?
1276
p = self.pending_merges()
1277
if revision_id in p:
1279
p.append(revision_id)
1280
self.set_pending_merges(p)
1283
def set_pending_merges(self, rev_list):
1284
from bzrlib.atomicfile import AtomicFile
1287
f = AtomicFile(self.controlfilename('pending-merges'))
1298
def get_parent(self):
1299
"""Return the parent location of the branch.
1301
This is the default location for push/pull/missing. The usual
1302
pattern is that the user can override it by specifying a
1306
_locs = ['parent', 'pull', 'x-pull']
1309
return self.controlfile(l, 'r').read().strip('\n')
1311
if e.errno != errno.ENOENT:
1316
def set_parent(self, url):
1317
# TODO: Maybe delete old location files?
1318
from bzrlib.atomicfile import AtomicFile
1321
f = AtomicFile(self.controlfilename('parent'))
1330
def check_revno(self, revno):
1332
Check whether a revno corresponds to any revision.
1333
Zero (the NULL revision) is considered valid.
1336
self.check_real_revno(revno)
1338
def check_real_revno(self, revno):
1340
Check whether a revno corresponds to a real revision.
1341
Zero (the NULL revision) is considered invalid
1343
if revno < 1 or revno > self.revno():
1344
raise InvalidRevisionNumber(revno)
697
1349
class ScratchBranch(Branch):