1
# Copyright (C) 2005 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22
from bzrlib.trace import mutter, note
23
from bzrlib.osutils import isdir, quotefn, compact_date, rand_bytes, \
25
sha_file, appendpath, file_kind
26
from bzrlib.errors import BzrError, InvalidRevisionNumber, InvalidRevisionId
27
from bzrlib.textui import show_status
28
from bzrlib.revision import Revision
29
from bzrlib.xml import unpack_xml
32
BZR_BRANCH_FORMAT = "Bazaar-NG branch, format 0.0.4\n"
33
## TODO: Maybe include checks for common corruption of newlines, etc?
36
# TODO: Some operations like log might retrieve the same revisions
37
# repeatedly to calculate deltas. We could perhaps have a weakref
38
# cache in memory to make this faster.
41
def find_branch(f, **args):
42
if f and (f.startswith('http://') or f.startswith('https://')):
44
return remotebranch.RemoteBranch(f, **args)
46
return Branch(f, **args)
49
def find_cached_branch(f, cache_root, **args):
50
from remotebranch import RemoteBranch
51
br = find_branch(f, **args)
52
def cacheify(br, store_name):
53
from meta_store import CachedStore
54
cache_path = os.path.join(cache_root, store_name)
56
new_store = CachedStore(getattr(br, store_name), cache_path)
57
setattr(br, store_name, new_store)
59
if isinstance(br, RemoteBranch):
60
cacheify(br, 'inventory_store')
61
cacheify(br, 'text_store')
62
cacheify(br, 'revision_store')
66
def _relpath(base, path):
67
"""Return path relative to base, or raise exception.
69
The path may be either an absolute path or a path relative to the
70
current working directory.
72
Lifted out of Branch.relpath for ease of testing.
74
os.path.commonprefix (python2.4) has a bad bug that it works just
75
on string prefixes, assuming that '/u' is a prefix of '/u2'. This
76
avoids that problem."""
77
rp = os.path.abspath(path)
81
while len(head) >= len(base):
84
head, tail = os.path.split(head)
88
from errors import NotBranchError
89
raise NotBranchError("path %r is not within branch %r" % (rp, base))
94
def find_branch_root(f=None):
95
"""Find the branch root enclosing f, or pwd.
97
f may be a filename or a URL.
99
It is not necessary that f exists.
101
Basically we keep looking up until we find the control directory or
102
run into the root."""
105
elif hasattr(os.path, 'realpath'):
106
f = os.path.realpath(f)
108
f = os.path.abspath(f)
109
if not os.path.exists(f):
110
raise BzrError('%r does not exist' % f)
116
if os.path.exists(os.path.join(f, bzrlib.BZRDIR)):
118
head, tail = os.path.split(f)
120
# reached the root, whatever that may be
121
raise BzrError('%r is not in a branch' % orig_f)
124
class DivergedBranches(Exception):
125
def __init__(self, branch1, branch2):
126
self.branch1 = branch1
127
self.branch2 = branch2
128
Exception.__init__(self, "These branches have diverged.")
131
class NoSuchRevision(BzrError):
132
def __init__(self, branch, revision):
134
self.revision = revision
135
msg = "Branch %s has no revision %d" % (branch, revision)
136
BzrError.__init__(self, msg)
139
######################################################################
142
class Branch(object):
143
"""Branch holding a history of revisions.
146
Base directory of the branch.
152
If _lock_mode is true, a positive count of the number of times the
156
Lock object from bzrlib.lock.
163
# Map some sort of prefix into a namespace
164
# stuff like "revno:10", "revid:", etc.
165
# This should match a prefix with a function which accepts
166
REVISION_NAMESPACES = {}
168
def __init__(self, base, init=False, find_root=True):
169
"""Create new branch object at a particular location.
171
base -- Base directory for the branch.
173
init -- If True, create new control files in a previously
174
unversioned directory. If False, the branch must already
177
find_root -- If true and init is false, find the root of the
178
existing branch containing base.
180
In the test suite, creation of new trees is tested using the
181
`ScratchBranch` class.
183
from bzrlib.store import ImmutableStore
185
self.base = os.path.realpath(base)
188
self.base = find_branch_root(base)
190
self.base = os.path.realpath(base)
191
if not isdir(self.controlfilename('.')):
192
from errors import NotBranchError
193
raise NotBranchError("not a bzr branch: %s" % quotefn(base),
194
['use "bzr init" to initialize a new working tree',
195
'current bzr can only operate from top-of-tree'])
198
self.text_store = ImmutableStore(self.controlfilename('text-store'))
199
self.revision_store = ImmutableStore(self.controlfilename('revision-store'))
200
self.inventory_store = ImmutableStore(self.controlfilename('inventory-store'))
204
return '%s(%r)' % (self.__class__.__name__, self.base)
211
if self._lock_mode or self._lock:
212
from warnings import warn
213
warn("branch %r was not explicitly unlocked" % self)
218
def lock_write(self):
220
if self._lock_mode != 'w':
221
from errors import LockError
222
raise LockError("can't upgrade to a write lock from %r" %
224
self._lock_count += 1
226
from bzrlib.lock import WriteLock
228
self._lock = WriteLock(self.controlfilename('branch-lock'))
229
self._lock_mode = 'w'
236
assert self._lock_mode in ('r', 'w'), \
237
"invalid lock mode %r" % self._lock_mode
238
self._lock_count += 1
240
from bzrlib.lock import ReadLock
242
self._lock = ReadLock(self.controlfilename('branch-lock'))
243
self._lock_mode = 'r'
249
if not self._lock_mode:
250
from errors import LockError
251
raise LockError('branch %r is not locked' % (self))
253
if self._lock_count > 1:
254
self._lock_count -= 1
258
self._lock_mode = self._lock_count = None
261
def abspath(self, name):
262
"""Return absolute filename for something in the branch"""
263
return os.path.join(self.base, name)
266
def relpath(self, path):
267
"""Return path relative to this branch of something inside it.
269
Raises an error if path is not in this branch."""
270
return _relpath(self.base, path)
273
def controlfilename(self, file_or_path):
274
"""Return location relative to branch."""
275
if isinstance(file_or_path, basestring):
276
file_or_path = [file_or_path]
277
return os.path.join(self.base, bzrlib.BZRDIR, *file_or_path)
280
def controlfile(self, file_or_path, mode='r'):
281
"""Open a control file for this branch.
283
There are two classes of file in the control directory: text
284
and binary. binary files are untranslated byte streams. Text
285
control files are stored with Unix newlines and in UTF-8, even
286
if the platform or locale defaults are different.
288
Controlfiles should almost never be opened in write mode but
289
rather should be atomically copied and replaced using atomicfile.
292
fn = self.controlfilename(file_or_path)
294
if mode == 'rb' or mode == 'wb':
295
return file(fn, mode)
296
elif mode == 'r' or mode == 'w':
297
# open in binary mode anyhow so there's no newline translation;
298
# codecs uses line buffering by default; don't want that.
300
return codecs.open(fn, mode + 'b', 'utf-8',
303
raise BzrError("invalid controlfile mode %r" % mode)
307
def _make_control(self):
308
from bzrlib.inventory import Inventory
309
from bzrlib.xml import pack_xml
311
os.mkdir(self.controlfilename([]))
312
self.controlfile('README', 'w').write(
313
"This is a Bazaar-NG control directory.\n"
314
"Do not change any files in this directory.\n")
315
self.controlfile('branch-format', 'w').write(BZR_BRANCH_FORMAT)
316
for d in ('text-store', 'inventory-store', 'revision-store'):
317
os.mkdir(self.controlfilename(d))
318
for f in ('revision-history', 'merged-patches',
319
'pending-merged-patches', 'branch-name',
322
self.controlfile(f, 'w').write('')
323
mutter('created control directory in ' + self.base)
325
pack_xml(Inventory(gen_root_id()), self.controlfile('inventory','w'))
328
def _check_format(self):
329
"""Check this branch format is supported.
331
The current tool only supports the current unstable format.
333
In the future, we might need different in-memory Branch
334
classes to support downlevel branches. But not yet.
336
# This ignores newlines so that we can open branches created
337
# on Windows from Linux and so on. I think it might be better
338
# to always make all internal files in unix format.
339
fmt = self.controlfile('branch-format', 'r').read()
340
fmt.replace('\r\n', '')
341
if fmt != BZR_BRANCH_FORMAT:
342
raise BzrError('sorry, branch format %r not supported' % fmt,
343
['use a different bzr version',
344
'or remove the .bzr directory and "bzr init" again'])
346
def get_root_id(self):
347
"""Return the id of this branches root"""
348
inv = self.read_working_inventory()
349
return inv.root.file_id
351
def set_root_id(self, file_id):
352
inv = self.read_working_inventory()
353
orig_root_id = inv.root.file_id
354
del inv._byid[inv.root.file_id]
355
inv.root.file_id = file_id
356
inv._byid[inv.root.file_id] = inv.root
359
if entry.parent_id in (None, orig_root_id):
360
entry.parent_id = inv.root.file_id
361
self._write_inventory(inv)
363
def read_working_inventory(self):
364
"""Read the working inventory."""
365
from bzrlib.inventory import Inventory
366
from bzrlib.xml import unpack_xml
367
from time import time
371
# ElementTree does its own conversion from UTF-8, so open in
373
inv = unpack_xml(Inventory,
374
self.controlfile('inventory', 'rb'))
375
mutter("loaded inventory of %d items in %f"
376
% (len(inv), time() - before))
382
def _write_inventory(self, inv):
383
"""Update the working inventory.
385
That is to say, the inventory describing changes underway, that
386
will be committed to the next revision.
388
from bzrlib.atomicfile import AtomicFile
389
from bzrlib.xml import pack_xml
393
f = AtomicFile(self.controlfilename('inventory'), 'wb')
402
mutter('wrote working inventory')
405
inventory = property(read_working_inventory, _write_inventory, None,
406
"""Inventory for the working copy.""")
409
def add(self, files, verbose=False, ids=None):
410
"""Make files versioned.
412
Note that the command line normally calls smart_add instead.
414
This puts the files in the Added state, so that they will be
415
recorded by the next commit.
418
List of paths to add, relative to the base of the tree.
421
If set, use these instead of automatically generated ids.
422
Must be the same length as the list of files, but may
423
contain None for ids that are to be autogenerated.
425
TODO: Perhaps have an option to add the ids even if the files do
428
TODO: Perhaps return the ids of the files? But then again it
429
is easy to retrieve them if they're needed.
431
TODO: Adding a directory should optionally recurse down and
432
add all non-ignored children. Perhaps do that in a
435
# TODO: Re-adding a file that is removed in the working copy
436
# should probably put it back with the previous ID.
437
if isinstance(files, basestring):
438
assert(ids is None or isinstance(ids, basestring))
444
ids = [None] * len(files)
446
assert(len(ids) == len(files))
450
inv = self.read_working_inventory()
451
for f,file_id in zip(files, ids):
452
if is_control_file(f):
453
raise BzrError("cannot add control file %s" % quotefn(f))
458
raise BzrError("cannot add top-level %r" % f)
460
fullpath = os.path.normpath(self.abspath(f))
463
kind = file_kind(fullpath)
465
# maybe something better?
466
raise BzrError('cannot add: not a regular file or directory: %s' % quotefn(f))
468
if kind != 'file' and kind != 'directory':
469
raise BzrError('cannot add: not a regular file or directory: %s' % quotefn(f))
472
file_id = gen_file_id(f)
473
inv.add_path(f, kind=kind, file_id=file_id)
476
print 'added', quotefn(f)
478
mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
480
self._write_inventory(inv)
485
def print_file(self, file, revno):
486
"""Print `file` to stdout."""
489
tree = self.revision_tree(self.lookup_revision(revno))
490
# use inventory as it was in that revision
491
file_id = tree.inventory.path2id(file)
493
raise BzrError("%r is not present in revision %s" % (file, revno))
494
tree.print_file(file_id)
499
def remove(self, files, verbose=False):
500
"""Mark nominated files for removal from the inventory.
502
This does not remove their text. This does not run on
504
TODO: Refuse to remove modified files unless --force is given?
506
TODO: Do something useful with directories.
508
TODO: Should this remove the text or not? Tough call; not
509
removing may be useful and the user can just use use rm, and
510
is the opposite of add. Removing it is consistent with most
511
other tools. Maybe an option.
513
## TODO: Normalize names
514
## TODO: Remove nested loops; better scalability
515
if isinstance(files, basestring):
521
tree = self.working_tree()
524
# do this before any modifications
528
raise BzrError("cannot remove unversioned file %s" % quotefn(f))
529
mutter("remove inventory entry %s {%s}" % (quotefn(f), fid))
531
# having remove it, it must be either ignored or unknown
532
if tree.is_ignored(f):
536
show_status(new_status, inv[fid].kind, quotefn(f))
539
self._write_inventory(inv)
544
# FIXME: this doesn't need to be a branch method
545
def set_inventory(self, new_inventory_list):
546
from bzrlib.inventory import Inventory, InventoryEntry
547
inv = Inventory(self.get_root_id())
548
for path, file_id, parent, kind in new_inventory_list:
549
name = os.path.basename(path)
552
inv.add(InventoryEntry(file_id, name, kind, parent))
553
self._write_inventory(inv)
557
"""Return all unknown files.
559
These are files in the working directory that are not versioned or
560
control files or ignored.
562
>>> b = ScratchBranch(files=['foo', 'foo~'])
563
>>> list(b.unknowns())
566
>>> list(b.unknowns())
569
>>> list(b.unknowns())
572
return self.working_tree().unknowns()
575
def append_revision(self, *revision_ids):
576
from bzrlib.atomicfile import AtomicFile
578
for revision_id in revision_ids:
579
mutter("add {%s} to revision-history" % revision_id)
581
rev_history = self.revision_history()
582
rev_history.extend(revision_ids)
584
f = AtomicFile(self.controlfilename('revision-history'))
586
for rev_id in rev_history:
593
def get_revision(self, revision_id):
594
"""Return the Revision object for a named revision"""
597
if not revision_id or not isinstance(revision_id, basestring):
598
raise InvalidRevisionId(revision_id)
599
r = unpack_xml(Revision, self.revision_store[revision_id])
603
assert r.revision_id == revision_id
607
def get_revision_delta(self, revno):
608
"""Return the delta for one revision.
610
The delta is relative to its mainline predecessor, or the
611
empty tree for revision 1.
613
assert isinstance(revno, int)
614
rh = self.revision_history()
615
if revno <= 0 or revno >= len(rh):
616
raise InvalidRevisionNumber(revno)
618
new_tree = self.revision_tree(rh[revno])
620
old_tree = EmptyTree()
622
old_tree = self.revision_tree(rh[revno-1])
624
return compare_trees(old_tree, new_tree)
628
def get_revision_sha1(self, revision_id):
629
"""Hash the stored value of a revision, and return it."""
630
# In the future, revision entries will be signed. At that
631
# point, it is probably best *not* to include the signature
632
# in the revision hash. Because that lets you re-sign
633
# the revision, (add signatures/remove signatures) and still
634
# have all hash pointers stay consistent.
635
# But for now, just hash the contents.
636
return sha_file(self.revision_store[revision_id])
639
def get_inventory(self, inventory_id):
640
"""Get Inventory object by hash.
642
TODO: Perhaps for this and similar methods, take a revision
643
parameter which can be either an integer revno or a
645
from bzrlib.inventory import Inventory
646
from bzrlib.xml import unpack_xml
648
return unpack_xml(Inventory, self.inventory_store[inventory_id])
651
def get_inventory_sha1(self, inventory_id):
652
"""Return the sha1 hash of the inventory entry
654
return sha_file(self.inventory_store[inventory_id])
657
def get_revision_inventory(self, revision_id):
658
"""Return inventory of a past revision."""
659
# bzr 0.0.6 imposes the constraint that the inventory_id
660
# must be the same as its revision, so this is trivial.
661
if revision_id == None:
662
from bzrlib.inventory import Inventory
663
return Inventory(self.get_root_id())
665
return self.get_inventory(revision_id)
668
def revision_history(self):
669
"""Return sequence of revision hashes on to this branch.
671
>>> ScratchBranch().revision_history()
676
return [l.rstrip('\r\n') for l in
677
self.controlfile('revision-history', 'r').readlines()]
682
def common_ancestor(self, other, self_revno=None, other_revno=None):
685
>>> sb = ScratchBranch(files=['foo', 'foo~'])
686
>>> sb.common_ancestor(sb) == (None, None)
688
>>> commit.commit(sb, "Committing first revision", verbose=False)
689
>>> sb.common_ancestor(sb)[0]
691
>>> clone = sb.clone()
692
>>> commit.commit(sb, "Committing second revision", verbose=False)
693
>>> sb.common_ancestor(sb)[0]
695
>>> sb.common_ancestor(clone)[0]
697
>>> commit.commit(clone, "Committing divergent second revision",
699
>>> sb.common_ancestor(clone)[0]
701
>>> sb.common_ancestor(clone) == clone.common_ancestor(sb)
703
>>> sb.common_ancestor(sb) != clone.common_ancestor(clone)
705
>>> clone2 = sb.clone()
706
>>> sb.common_ancestor(clone2)[0]
708
>>> sb.common_ancestor(clone2, self_revno=1)[0]
710
>>> sb.common_ancestor(clone2, other_revno=1)[0]
713
my_history = self.revision_history()
714
other_history = other.revision_history()
715
if self_revno is None:
716
self_revno = len(my_history)
717
if other_revno is None:
718
other_revno = len(other_history)
719
indices = range(min((self_revno, other_revno)))
722
if my_history[r] == other_history[r]:
723
return r+1, my_history[r]
726
def enum_history(self, direction):
727
"""Return (revno, revision_id) for history of branch.
730
'forward' is from earliest to latest
731
'reverse' is from latest to earliest
733
rh = self.revision_history()
734
if direction == 'forward':
739
elif direction == 'reverse':
745
raise ValueError('invalid history direction', direction)
749
"""Return current revision number for this branch.
751
That is equivalent to the number of revisions committed to
754
return len(self.revision_history())
757
def last_patch(self):
758
"""Return last patch hash, or None if no history.
760
ph = self.revision_history()
767
def missing_revisions(self, other, stop_revision=None):
769
If self and other have not diverged, return a list of the revisions
770
present in other, but missing from self.
772
>>> from bzrlib.commit import commit
773
>>> bzrlib.trace.silent = True
774
>>> br1 = ScratchBranch()
775
>>> br2 = ScratchBranch()
776
>>> br1.missing_revisions(br2)
778
>>> commit(br2, "lala!", rev_id="REVISION-ID-1")
779
>>> br1.missing_revisions(br2)
781
>>> br2.missing_revisions(br1)
783
>>> commit(br1, "lala!", rev_id="REVISION-ID-1")
784
>>> br1.missing_revisions(br2)
786
>>> commit(br2, "lala!", rev_id="REVISION-ID-2A")
787
>>> br1.missing_revisions(br2)
789
>>> commit(br1, "lala!", rev_id="REVISION-ID-2B")
790
>>> br1.missing_revisions(br2)
791
Traceback (most recent call last):
792
DivergedBranches: These branches have diverged.
794
self_history = self.revision_history()
795
self_len = len(self_history)
796
other_history = other.revision_history()
797
other_len = len(other_history)
798
common_index = min(self_len, other_len) -1
799
if common_index >= 0 and \
800
self_history[common_index] != other_history[common_index]:
801
raise DivergedBranches(self, other)
803
if stop_revision is None:
804
stop_revision = other_len
805
elif stop_revision > other_len:
806
raise NoSuchRevision(self, stop_revision)
808
return other_history[self_len:stop_revision]
811
def update_revisions(self, other, stop_revision=None):
812
"""Pull in all new revisions from other branch.
814
>>> from bzrlib.commit import commit
815
>>> bzrlib.trace.silent = True
816
>>> br1 = ScratchBranch(files=['foo', 'bar'])
819
>>> commit(br1, "lala!", rev_id="REVISION-ID-1", verbose=False)
820
>>> br2 = ScratchBranch()
821
>>> br2.update_revisions(br1)
825
>>> br2.revision_history()
827
>>> br2.update_revisions(br1)
831
>>> br1.text_store.total_size() == br2.text_store.total_size()
834
from bzrlib.progress import ProgressBar
838
pb.update('comparing histories')
839
revision_ids = self.missing_revisions(other, stop_revision)
841
if hasattr(other.revision_store, "prefetch"):
842
other.revision_store.prefetch(revision_ids)
843
if hasattr(other.inventory_store, "prefetch"):
844
inventory_ids = [other.get_revision(r).inventory_id
845
for r in revision_ids]
846
other.inventory_store.prefetch(inventory_ids)
851
for rev_id in revision_ids:
853
pb.update('fetching revision', i, len(revision_ids))
854
rev = other.get_revision(rev_id)
855
revisions.append(rev)
856
inv = other.get_inventory(str(rev.inventory_id))
857
for key, entry in inv.iter_entries():
858
if entry.text_id is None:
860
if entry.text_id not in self.text_store:
861
needed_texts.add(entry.text_id)
865
count = self.text_store.copy_multi(other.text_store, needed_texts)
866
print "Added %d texts." % count
867
inventory_ids = [ f.inventory_id for f in revisions ]
868
count = self.inventory_store.copy_multi(other.inventory_store,
870
print "Added %d inventories." % count
871
revision_ids = [ f.revision_id for f in revisions]
872
count = self.revision_store.copy_multi(other.revision_store,
874
for revision_id in revision_ids:
875
self.append_revision(revision_id)
876
print "Added %d revisions." % count
879
def commit(self, *args, **kw):
880
from bzrlib.commit import commit
881
commit(self, *args, **kw)
884
def lookup_revision(self, revision):
885
"""Return the revision identifier for a given revision information."""
886
revno, info = self.get_revision_info(revision)
889
def get_revision_info(self, revision):
890
"""Return (revno, revision id) for revision identifier.
892
revision can be an integer, in which case it is assumed to be revno (though
893
this will translate negative values into positive ones)
894
revision can also be a string, in which case it is parsed for something like
895
'date:' or 'revid:' etc.
900
try:# Convert to int if possible
901
revision = int(revision)
904
revs = self.revision_history()
905
if isinstance(revision, int):
908
# Mabye we should do this first, but we don't need it if revision == 0
910
revno = len(revs) + revision + 1
913
elif isinstance(revision, basestring):
914
for prefix, func in Branch.REVISION_NAMESPACES.iteritems():
915
if revision.startswith(prefix):
916
revno = func(self, revs, revision)
919
raise BzrError('No namespace registered for string: %r' % revision)
921
if revno is None or revno <= 0 or revno > len(revs):
922
raise BzrError("no such revision %s" % revision)
923
return revno, revs[revno-1]
925
def _namespace_revno(self, revs, revision):
926
"""Lookup a revision by revision number"""
927
assert revision.startswith('revno:')
929
return int(revision[6:])
932
REVISION_NAMESPACES['revno:'] = _namespace_revno
934
def _namespace_revid(self, revs, revision):
935
assert revision.startswith('revid:')
937
return revs.index(revision[6:]) + 1
940
REVISION_NAMESPACES['revid:'] = _namespace_revid
942
def _namespace_last(self, revs, revision):
943
assert revision.startswith('last:')
945
offset = int(revision[5:])
950
raise BzrError('You must supply a positive value for --revision last:XXX')
951
return len(revs) - offset + 1
952
REVISION_NAMESPACES['last:'] = _namespace_last
954
def _namespace_tag(self, revs, revision):
955
assert revision.startswith('tag:')
956
raise BzrError('tag: namespace registered, but not implemented.')
957
REVISION_NAMESPACES['tag:'] = _namespace_tag
959
def _namespace_date(self, revs, revision):
960
assert revision.startswith('date:')
962
# Spec for date revisions:
964
# value can be 'yesterday', 'today', 'tomorrow' or a YYYY-MM-DD string.
965
# it can also start with a '+/-/='. '+' says match the first
966
# entry after the given date. '-' is match the first entry before the date
967
# '=' is match the first entry after, but still on the given date.
969
# +2005-05-12 says find the first matching entry after May 12th, 2005 at 0:00
970
# -2005-05-12 says find the first matching entry before May 12th, 2005 at 0:00
971
# =2005-05-12 says find the first match after May 12th, 2005 at 0:00 but before
972
# May 13th, 2005 at 0:00
974
# So the proper way of saying 'give me all entries for today' is:
975
# -r {date:+today}:{date:-tomorrow}
976
# The default is '=' when not supplied
979
if val[:1] in ('+', '-', '='):
980
match_style = val[:1]
983
today = datetime.datetime.today().replace(hour=0,minute=0,second=0,microsecond=0)
984
if val.lower() == 'yesterday':
985
dt = today - datetime.timedelta(days=1)
986
elif val.lower() == 'today':
988
elif val.lower() == 'tomorrow':
989
dt = today + datetime.timedelta(days=1)
992
# This should be done outside the function to avoid recompiling it.
993
_date_re = re.compile(
994
r'(?P<date>(?P<year>\d\d\d\d)-(?P<month>\d\d)-(?P<day>\d\d))?'
996
r'(?P<time>(?P<hour>\d\d):(?P<minute>\d\d)(:(?P<second>\d\d))?)?'
998
m = _date_re.match(val)
999
if not m or (not m.group('date') and not m.group('time')):
1000
raise BzrError('Invalid revision date %r' % revision)
1003
year, month, day = int(m.group('year')), int(m.group('month')), int(m.group('day'))
1005
year, month, day = today.year, today.month, today.day
1007
hour = int(m.group('hour'))
1008
minute = int(m.group('minute'))
1009
if m.group('second'):
1010
second = int(m.group('second'))
1014
hour, minute, second = 0,0,0
1016
dt = datetime.datetime(year=year, month=month, day=day,
1017
hour=hour, minute=minute, second=second)
1021
if match_style == '-':
1023
elif match_style == '=':
1024
last = dt + datetime.timedelta(days=1)
1027
for i in range(len(revs)-1, -1, -1):
1028
r = self.get_revision(revs[i])
1029
# TODO: Handle timezone.
1030
dt = datetime.datetime.fromtimestamp(r.timestamp)
1031
if first >= dt and (last is None or dt >= last):
1034
for i in range(len(revs)):
1035
r = self.get_revision(revs[i])
1036
# TODO: Handle timezone.
1037
dt = datetime.datetime.fromtimestamp(r.timestamp)
1038
if first <= dt and (last is None or dt <= last):
1040
REVISION_NAMESPACES['date:'] = _namespace_date
1042
def revision_tree(self, revision_id):
1043
"""Return Tree for a revision on this branch.
1045
`revision_id` may be None for the null revision, in which case
1046
an `EmptyTree` is returned."""
1047
from bzrlib.tree import EmptyTree, RevisionTree
1048
# TODO: refactor this to use an existing revision object
1049
# so we don't need to read it in twice.
1050
if revision_id == None:
1051
return EmptyTree(self.get_root_id())
1053
inv = self.get_revision_inventory(revision_id)
1054
return RevisionTree(self.text_store, inv)
1057
def working_tree(self):
1058
"""Return a `Tree` for the working copy."""
1059
from workingtree import WorkingTree
1060
return WorkingTree(self.base, self.read_working_inventory())
1063
def basis_tree(self):
1064
"""Return `Tree` object for last revision.
1066
If there are no revisions yet, return an `EmptyTree`.
1068
from bzrlib.tree import EmptyTree, RevisionTree
1069
r = self.last_patch()
1071
return EmptyTree(self.get_root_id())
1073
return RevisionTree(self.text_store, self.get_revision_inventory(r))
1077
def rename_one(self, from_rel, to_rel):
1080
This can change the directory or the filename or both.
1084
tree = self.working_tree()
1085
inv = tree.inventory
1086
if not tree.has_filename(from_rel):
1087
raise BzrError("can't rename: old working file %r does not exist" % from_rel)
1088
if tree.has_filename(to_rel):
1089
raise BzrError("can't rename: new working file %r already exists" % to_rel)
1091
file_id = inv.path2id(from_rel)
1093
raise BzrError("can't rename: old name %r is not versioned" % from_rel)
1095
if inv.path2id(to_rel):
1096
raise BzrError("can't rename: new name %r is already versioned" % to_rel)
1098
to_dir, to_tail = os.path.split(to_rel)
1099
to_dir_id = inv.path2id(to_dir)
1100
if to_dir_id == None and to_dir != '':
1101
raise BzrError("can't determine destination directory id for %r" % to_dir)
1103
mutter("rename_one:")
1104
mutter(" file_id {%s}" % file_id)
1105
mutter(" from_rel %r" % from_rel)
1106
mutter(" to_rel %r" % to_rel)
1107
mutter(" to_dir %r" % to_dir)
1108
mutter(" to_dir_id {%s}" % to_dir_id)
1110
inv.rename(file_id, to_dir_id, to_tail)
1112
print "%s => %s" % (from_rel, to_rel)
1114
from_abs = self.abspath(from_rel)
1115
to_abs = self.abspath(to_rel)
1117
os.rename(from_abs, to_abs)
1119
raise BzrError("failed to rename %r to %r: %s"
1120
% (from_abs, to_abs, e[1]),
1121
["rename rolled back"])
1123
self._write_inventory(inv)
1128
def move(self, from_paths, to_name):
1131
to_name must exist as a versioned directory.
1133
If to_name exists and is a directory, the files are moved into
1134
it, keeping their old names. If it is a directory,
1136
Note that to_name is only the last component of the new name;
1137
this doesn't change the directory.
1141
## TODO: Option to move IDs only
1142
assert not isinstance(from_paths, basestring)
1143
tree = self.working_tree()
1144
inv = tree.inventory
1145
to_abs = self.abspath(to_name)
1146
if not isdir(to_abs):
1147
raise BzrError("destination %r is not a directory" % to_abs)
1148
if not tree.has_filename(to_name):
1149
raise BzrError("destination %r not in working directory" % to_abs)
1150
to_dir_id = inv.path2id(to_name)
1151
if to_dir_id == None and to_name != '':
1152
raise BzrError("destination %r is not a versioned directory" % to_name)
1153
to_dir_ie = inv[to_dir_id]
1154
if to_dir_ie.kind not in ('directory', 'root_directory'):
1155
raise BzrError("destination %r is not a directory" % to_abs)
1157
to_idpath = inv.get_idpath(to_dir_id)
1159
for f in from_paths:
1160
if not tree.has_filename(f):
1161
raise BzrError("%r does not exist in working tree" % f)
1162
f_id = inv.path2id(f)
1164
raise BzrError("%r is not versioned" % f)
1165
name_tail = splitpath(f)[-1]
1166
dest_path = appendpath(to_name, name_tail)
1167
if tree.has_filename(dest_path):
1168
raise BzrError("destination %r already exists" % dest_path)
1169
if f_id in to_idpath:
1170
raise BzrError("can't move %r to a subdirectory of itself" % f)
1172
# OK, so there's a race here, it's possible that someone will
1173
# create a file in this interval and then the rename might be
1174
# left half-done. But we should have caught most problems.
1176
for f in from_paths:
1177
name_tail = splitpath(f)[-1]
1178
dest_path = appendpath(to_name, name_tail)
1179
print "%s => %s" % (f, dest_path)
1180
inv.rename(inv.path2id(f), to_dir_id, name_tail)
1182
os.rename(self.abspath(f), self.abspath(dest_path))
1184
raise BzrError("failed to rename %r to %r: %s" % (f, dest_path, e[1]),
1185
["rename rolled back"])
1187
self._write_inventory(inv)
1192
def revert(self, filenames, old_tree=None, backups=True):
1193
"""Restore selected files to the versions from a previous tree.
1196
If true (default) backups are made of files before
1199
from bzrlib.errors import NotVersionedError, BzrError
1200
from bzrlib.atomicfile import AtomicFile
1201
from bzrlib.osutils import backup_file
1203
inv = self.read_working_inventory()
1204
if old_tree is None:
1205
old_tree = self.basis_tree()
1206
old_inv = old_tree.inventory
1209
for fn in filenames:
1210
file_id = inv.path2id(fn)
1212
raise NotVersionedError("not a versioned file", fn)
1213
if not old_inv.has_id(file_id):
1214
raise BzrError("file not present in old tree", fn, file_id)
1215
nids.append((fn, file_id))
1217
# TODO: Rename back if it was previously at a different location
1219
# TODO: If given a directory, restore the entire contents from
1220
# the previous version.
1222
# TODO: Make a backup to a temporary file.
1224
# TODO: If the file previously didn't exist, delete it?
1225
for fn, file_id in nids:
1228
f = AtomicFile(fn, 'wb')
1230
f.write(old_tree.get_file(file_id).read())
1236
def pending_merges(self):
1237
"""Return a list of pending merges.
1239
These are revisions that have been merged into the working
1240
directory but not yet committed.
1242
cfn = self.controlfilename('pending-merges')
1243
if not os.path.exists(cfn):
1246
for l in self.controlfile('pending-merges', 'r').readlines():
1247
p.append(l.rstrip('\n'))
1251
def add_pending_merge(self, revision_id):
1252
from bzrlib.revision import validate_revision_id
1254
validate_revision_id(revision_id)
1256
p = self.pending_merges()
1257
if revision_id in p:
1259
p.append(revision_id)
1260
self.set_pending_merges(p)
1263
def set_pending_merges(self, rev_list):
1264
from bzrlib.atomicfile import AtomicFile
1267
f = AtomicFile(self.controlfilename('pending-merges'))
1279
class ScratchBranch(Branch):
1280
"""Special test class: a branch that cleans up after itself.
1282
>>> b = ScratchBranch()
1290
def __init__(self, files=[], dirs=[], base=None):
1291
"""Make a test branch.
1293
This creates a temporary directory and runs init-tree in it.
1295
If any files are listed, they are created in the working copy.
1297
from tempfile import mkdtemp
1302
Branch.__init__(self, base, init=init)
1304
os.mkdir(self.abspath(d))
1307
file(os.path.join(self.base, f), 'w').write('content of %s' % f)
1312
>>> orig = ScratchBranch(files=["file1", "file2"])
1313
>>> clone = orig.clone()
1314
>>> os.path.samefile(orig.base, clone.base)
1316
>>> os.path.isfile(os.path.join(clone.base, "file1"))
1319
from shutil import copytree
1320
from tempfile import mkdtemp
1323
copytree(self.base, base, symlinks=True)
1324
return ScratchBranch(base=base)
1330
"""Destroy the test branch, removing the scratch directory."""
1331
from shutil import rmtree
1334
mutter("delete ScratchBranch %s" % self.base)
1337
# Work around for shutil.rmtree failing on Windows when
1338
# readonly files are encountered
1339
mutter("hit exception in destroying ScratchBranch: %s" % e)
1340
for root, dirs, files in os.walk(self.base, topdown=False):
1342
os.chmod(os.path.join(root, name), 0700)
1348
######################################################################
1352
def is_control_file(filename):
1353
## FIXME: better check
1354
filename = os.path.normpath(filename)
1355
while filename != '':
1356
head, tail = os.path.split(filename)
1357
## mutter('check %r for control file' % ((head, tail), ))
1358
if tail == bzrlib.BZRDIR:
1360
if filename == head:
1367
def gen_file_id(name):
1368
"""Return new file id.
1370
This should probably generate proper UUIDs, but for the moment we
1371
cope with just randomness because running uuidgen every time is
1374
from binascii import hexlify
1375
from time import time
1377
# get last component
1378
idx = name.rfind('/')
1380
name = name[idx+1 : ]
1381
idx = name.rfind('\\')
1383
name = name[idx+1 : ]
1385
# make it not a hidden file
1386
name = name.lstrip('.')
1388
# remove any wierd characters; we don't escape them but rather
1389
# just pull them out
1390
name = re.sub(r'[^\w.]', '', name)
1392
s = hexlify(rand_bytes(8))
1393
return '-'.join((name, compact_date(time()), s))
1397
"""Return a new tree-root file id."""
1398
return gen_file_id('TREE_ROOT')