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
20
from cStringIO import StringIO
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"
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
56
def find_branch(f, **args):
57
if f and (f.startswith('http://') or f.startswith('https://')):
59
return remotebranch.RemoteBranch(f, **args)
61
return Branch(f, **args)
64
def find_cached_branch(f, cache_root, **args):
65
from remotebranch import RemoteBranch
66
br = find_branch(f, **args)
67
def cacheify(br, store_name):
68
from meta_store import CachedStore
69
cache_path = os.path.join(cache_root, store_name)
71
new_store = CachedStore(getattr(br, store_name), cache_path)
72
setattr(br, store_name, new_store)
74
if isinstance(br, RemoteBranch):
75
cacheify(br, 'inventory_store')
76
cacheify(br, 'text_store')
77
cacheify(br, 'revision_store')
81
def _relpath(base, path):
82
"""Return path relative to base, or raise exception.
84
The path may be either an absolute path or a path relative to the
85
current working directory.
87
Lifted out of Branch.relpath for ease of testing.
89
os.path.commonprefix (python2.4) has a bad bug that it works just
90
on string prefixes, assuming that '/u' is a prefix of '/u2'. This
91
avoids that problem."""
92
rp = os.path.abspath(path)
96
while len(head) >= len(base):
99
head, tail = os.path.split(head)
103
raise NotBranchError("path %r is not within branch %r" % (rp, base))
105
return os.sep.join(s)
108
def find_branch_root(f=None):
109
"""Find the branch root enclosing f, or pwd.
111
f may be a filename or a URL.
113
It is not necessary that f exists.
115
Basically we keep looking up until we find the control directory or
116
run into the root. If there isn't one, raises NotBranchError.
120
elif hasattr(os.path, 'realpath'):
121
f = os.path.realpath(f)
123
f = os.path.abspath(f)
124
if not os.path.exists(f):
125
raise BzrError('%r does not exist' % f)
131
if os.path.exists(os.path.join(f, bzrlib.BZRDIR)):
133
head, tail = os.path.split(f)
135
# reached the root, whatever that may be
136
raise NotBranchError('%s is not in a branch' % orig_f)
141
# XXX: move into bzrlib.errors; subclass BzrError
142
class DivergedBranches(Exception):
143
def __init__(self, branch1, branch2):
144
self.branch1 = branch1
145
self.branch2 = branch2
146
Exception.__init__(self, "These branches have diverged.")
149
######################################################################
152
class Branch(object):
153
"""Branch holding a history of revisions.
156
Base directory of the branch.
162
If _lock_mode is true, a positive count of the number of times the
166
Lock object from bzrlib.lock.
172
_inventory_weave = None
174
# Map some sort of prefix into a namespace
175
# stuff like "revno:10", "revid:", etc.
176
# This should match a prefix with a function which accepts
177
REVISION_NAMESPACES = {}
179
def __init__(self, base, init=False, find_root=True,
180
relax_version_check=False):
181
"""Create new branch object at a particular location.
183
base -- Base directory for the branch.
185
init -- If True, create new control files in a previously
186
unversioned directory. If False, the branch must already
189
find_root -- If true and init is false, find the root of the
190
existing branch containing base.
192
relax_version_check -- If true, the usual check for the branch
193
version is not applied. This is intended only for
194
upgrade/recovery type use; it's not guaranteed that
195
all operations will work on old format branches.
197
In the test suite, creation of new trees is tested using the
198
`ScratchBranch` class.
201
self.base = os.path.realpath(base)
204
self.base = find_branch_root(base)
206
self.base = os.path.realpath(base)
207
if not isdir(self.controlfilename('.')):
208
raise NotBranchError('not a bzr branch: %s' % quotefn(base),
209
['use "bzr init" to initialize a '
211
self._check_format(relax_version_check)
212
cfn = self.controlfilename
213
if self._branch_format == 4:
214
self.inventory_store = ImmutableStore(cfn('inventory-store'))
215
self.text_store = ImmutableStore(cfn('text-store'))
216
elif self._branch_format == 5:
217
self.control_weaves = WeaveStore(cfn([]))
218
self.weave_store = WeaveStore(cfn('weaves'))
219
self.revision_store = ImmutableStore(cfn('revision-store'))
223
return '%s(%r)' % (self.__class__.__name__, self.base)
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
273
def abspath(self, name):
274
"""Return absolute filename for something in the branch"""
275
return os.path.join(self.base, name)
277
def relpath(self, path):
278
"""Return path relative to this branch of something inside it.
280
Raises an error if path is not in this branch."""
281
return _relpath(self.base, path)
283
def controlfilename(self, file_or_path):
284
"""Return location relative to branch."""
285
if isinstance(file_or_path, basestring):
286
file_or_path = [file_or_path]
287
return os.path.join(self.base, bzrlib.BZRDIR, *file_or_path)
290
def controlfile(self, file_or_path, mode='r'):
291
"""Open a control file for this branch.
293
There are two classes of file in the control directory: text
294
and binary. binary files are untranslated byte streams. Text
295
control files are stored with Unix newlines and in UTF-8, even
296
if the platform or locale defaults are different.
298
Controlfiles should almost never be opened in write mode but
299
rather should be atomically copied and replaced using atomicfile.
302
fn = self.controlfilename(file_or_path)
304
if mode == 'rb' or mode == 'wb':
305
return file(fn, mode)
306
elif mode == 'r' or mode == 'w':
307
# open in binary mode anyhow so there's no newline translation;
308
# codecs uses line buffering by default; don't want that.
310
return codecs.open(fn, mode + 'b', 'utf-8',
313
raise BzrError("invalid controlfile mode %r" % mode)
315
def _make_control(self):
316
os.mkdir(self.controlfilename([]))
317
self.controlfile('README', 'w').write(
318
"This is a Bazaar-NG control directory.\n"
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',
323
os.mkdir(self.controlfilename(d))
324
for f in ('revision-history', 'merged-patches',
325
'pending-merged-patches', 'branch-name',
328
self.controlfile(f, 'w').write('')
329
mutter('created control directory in ' + self.base)
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):
340
"""Check this branch format is supported.
342
The format level is stored, as an integer, in
343
self._branch_format for code that needs to check it later.
345
In the future, we might need different in-memory Branch
346
classes to support downlevel branches. But not yet.
348
fmt = self.controlfile('branch-format', 'r').read()
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)
379
def read_working_inventory(self):
380
"""Read the working inventory."""
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)
391
def _write_inventory(self, inv):
392
"""Update the working inventory.
394
That is to say, the inventory describing changes underway, that
395
will be committed to the next revision.
397
from bzrlib.atomicfile import AtomicFile
401
f = AtomicFile(self.controlfilename('inventory'), 'wb')
403
bzrlib.xml5.serializer_v5.write_inventory(inv, f)
410
mutter('wrote working inventory')
413
inventory = property(read_working_inventory, _write_inventory, None,
414
"""Inventory for the working copy.""")
417
def add(self, files, ids=None):
418
"""Make files versioned.
420
Note that the command line normally calls smart_add instead,
421
which can automatically recurse.
423
This puts the files in the Added state, so that they will be
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.
434
TODO: Perhaps have an option to add the ids even if the files do
437
TODO: Perhaps yield the ids and paths as they're added.
439
# TODO: Re-adding a file that is removed in the working copy
440
# should probably put it back with the previous ID.
441
if isinstance(files, basestring):
442
assert(ids is None or isinstance(ids, basestring))
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)
486
def print_file(self, file, revno):
487
"""Print `file` to stdout."""
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)
500
def remove(self, files, verbose=False):
501
"""Mark nominated files for removal from the inventory.
503
This does not remove their text. This does not run on
505
TODO: Refuse to remove modified files unless --force is given?
507
TODO: Do something useful with directories.
509
TODO: Should this remove the text or not? Tough call; not
510
removing may be useful and the user can just use use rm, and
511
is the opposite of add. Removing it is consistent with most
512
other tools. Maybe an option.
514
## TODO: Normalize names
515
## TODO: Remove nested loops; better scalability
516
if isinstance(files, basestring):
522
tree = self.working_tree()
525
# do this before any modifications
529
raise BzrError("cannot remove unversioned file %s" % quotefn(f))
530
mutter("remove inventory entry %s {%s}" % (quotefn(f), fid))
532
# having remove it, it must be either ignored or unknown
533
if tree.is_ignored(f):
537
show_status(new_status, inv[fid].kind, quotefn(f))
540
self._write_inventory(inv)
545
# FIXME: this doesn't need to be a branch method
546
def set_inventory(self, new_inventory_list):
547
from bzrlib.inventory import Inventory, InventoryEntry
548
inv = Inventory(self.get_root_id())
549
for path, file_id, parent, kind in new_inventory_list:
550
name = os.path.basename(path)
553
inv.add(InventoryEntry(file_id, name, kind, parent))
554
self._write_inventory(inv)
558
"""Return all unknown files.
560
These are files in the working directory that are not versioned or
561
control files or ignored.
563
>>> b = ScratchBranch(files=['foo', 'foo~'])
564
>>> list(b.unknowns())
567
>>> list(b.unknowns())
570
>>> list(b.unknowns())
573
return self.working_tree().unknowns()
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)
582
rev_history = self.revision_history()
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()
621
def get_revision(self, revision_id):
622
"""Return the Revision object for a named revision"""
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',
632
assert r.revision_id == revision_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
703
def get_revision_inventory(self, revision_id):
704
"""Return inventory of a past revision."""
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.
707
if revision_id == None:
708
return Inventory(self.get_root_id())
710
return self.get_inventory(revision_id)
713
def revision_history(self):
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]
768
"""Return current revision number for this branch.
770
That is equivalent to the number of revisions committed to
773
return len(self.revision_history())
776
def last_revision(self):
777
"""Return last patch hash, or None if no history.
779
ph = self.revision_history()
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)
857
def commit(self, *args, **kw):
858
from bzrlib.commit import Commit
859
Commit().commit(self, *args, **kw)
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."""
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
1066
def revision_tree(self, revision_id):
1067
"""Return Tree for a revision on this branch.
1069
`revision_id` may be None for the null revision, in which case
1070
an `EmptyTree` is returned."""
1071
# TODO: refactor this to use an existing revision object
1072
# so we don't need to read it in twice.
1073
if revision_id == None:
1076
inv = self.get_revision_inventory(revision_id)
1077
return RevisionTree(self.weave_store, inv, revision_id)
1080
def working_tree(self):
1081
"""Return a `Tree` for the working copy."""
1082
from workingtree import WorkingTree
1083
return WorkingTree(self.base, self.read_working_inventory())
1086
def basis_tree(self):
1087
"""Return `Tree` object for last revision.
1089
If there are no revisions yet, return an `EmptyTree`.
1091
return self.revision_tree(self.last_revision())
1094
def rename_one(self, from_rel, to_rel):
1097
This can change the directory or the filename or both.
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)
1143
def move(self, from_paths, to_name):
1146
to_name must exist as a versioned directory.
1148
If to_name exists and is a directory, the files are moved into
1149
it, keeping their old names. If it is a directory,
1151
Note that to_name is only the last component of the new name;
1152
this doesn't change the directory.
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)
1349
class ScratchBranch(Branch):
1350
"""Special test class: a branch that cleans up after itself.
1352
>>> b = ScratchBranch()
1360
def __init__(self, files=[], dirs=[], base=None):
1361
"""Make a test branch.
1363
This creates a temporary directory and runs init-tree in it.
1365
If any files are listed, they are created in the working copy.
1367
from tempfile import mkdtemp
1372
Branch.__init__(self, base, init=init)
1374
os.mkdir(self.abspath(d))
1377
file(os.path.join(self.base, f), 'w').write('content of %s' % f)
1382
>>> orig = ScratchBranch(files=["file1", "file2"])
1383
>>> clone = orig.clone()
1384
>>> os.path.samefile(orig.base, clone.base)
1386
>>> os.path.isfile(os.path.join(clone.base, "file1"))
1389
from shutil import copytree
1390
from tempfile import mkdtemp
1393
copytree(self.base, base, symlinks=True)
1394
return ScratchBranch(base=base)
1402
"""Destroy the test branch, removing the scratch directory."""
1403
from shutil import rmtree
1406
mutter("delete ScratchBranch %s" % self.base)
1409
# Work around for shutil.rmtree failing on Windows when
1410
# readonly files are encountered
1411
mutter("hit exception in destroying ScratchBranch: %s" % e)
1412
for root, dirs, files in os.walk(self.base, topdown=False):
1414
os.chmod(os.path.join(root, name), 0700)
1420
######################################################################
1424
def is_control_file(filename):
1425
## FIXME: better check
1426
filename = os.path.normpath(filename)
1427
while filename != '':
1428
head, tail = os.path.split(filename)
1429
## mutter('check %r for control file' % ((head, tail), ))
1430
if tail == bzrlib.BZRDIR:
1432
if filename == head:
1439
def gen_file_id(name):
1440
"""Return new file id.
1442
This should probably generate proper UUIDs, but for the moment we
1443
cope with just randomness because running uuidgen every time is
1446
from binascii import hexlify
1447
from time import time
1449
# get last component
1450
idx = name.rfind('/')
1452
name = name[idx+1 : ]
1453
idx = name.rfind('\\')
1455
name = name[idx+1 : ]
1457
# make it not a hidden file
1458
name = name.lstrip('.')
1460
# remove any wierd characters; we don't escape them but rather
1461
# just pull them out
1462
name = re.sub(r'[^\w.]', '', name)
1464
s = hexlify(rand_bytes(8))
1465
return '-'.join((name, compact_date(time()), s))
1469
"""Return a new tree-root file id."""
1470
return gen_file_id('TREE_ROOT')
1473
def pull_loc(branch):
1474
# TODO: Should perhaps just make attribute be 'base' in
1475
# RemoteBranch and Branch?
1476
if hasattr(branch, "baseurl"):
1477
return branch.baseurl
1482
def copy_branch(branch_from, to_location, revision=None):
1483
"""Copy branch_from into the existing directory to_location.
1486
If not None, only revisions up to this point will be copied.
1487
The head of the new branch will be that revision. Can be a
1491
The name of a local directory that exists but is empty.
1493
# TODO: This could be done *much* more efficiently by just copying
1494
# all the whole weaves and revisions, rather than getting one
1495
# revision at a time.
1496
from bzrlib.merge import merge
1497
from bzrlib.branch import Branch
1499
assert isinstance(branch_from, Branch)
1500
assert isinstance(to_location, basestring)
1502
br_to = Branch(to_location, init=True)
1503
br_to.set_root_id(branch_from.get_root_id())
1504
if revision is None:
1507
revno, rev_id = branch_from.get_revision_info(revision)
1508
br_to.update_revisions(branch_from, stop_revno=revno)
1509
merge((to_location, -1), (to_location, 0), this_dir=to_location,
1510
check_clean=False, ignore_zero=True)
1512
from_location = pull_loc(branch_from)
1513
br_to.set_parent(pull_loc(branch_from))