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
21
from warnings import warn
25
from bzrlib.trace import mutter, note
26
from bzrlib.osutils import isdir, quotefn, compact_date, rand_bytes, \
28
sha_file, appendpath, file_kind
30
from bzrlib.errors import (BzrError, InvalidRevisionNumber, InvalidRevisionId,
31
NoSuchRevision, HistoryMissing, NotBranchError,
33
from bzrlib.textui import show_status
34
from bzrlib.revision import Revision, validate_revision_id
35
from bzrlib.delta import compare_trees
36
from bzrlib.tree import EmptyTree, RevisionTree
37
from bzrlib.inventory import Inventory
38
from bzrlib.weavestore import WeaveStore
39
from bzrlib.store import ImmutableStore
44
BZR_BRANCH_FORMAT_4 = "Bazaar-NG branch, format 0.0.4\n"
45
BZR_BRANCH_FORMAT_5 = "Bazaar-NG branch, format 5\n"
46
## TODO: Maybe include checks for common corruption of newlines, etc?
49
# TODO: Some operations like log might retrieve the same revisions
50
# repeatedly to calculate deltas. We could perhaps have a weakref
51
# cache in memory to make this faster. In general anything can be
52
# cached in memory between lock and unlock operations.
54
# TODO: please move the revision-string syntax stuff out of the branch
55
# object; it's clutter
58
def find_branch(f, **args):
59
if f and (f.startswith('http://') or f.startswith('https://')):
61
return remotebranch.RemoteBranch(f, **args)
63
return Branch(f, **args)
66
def find_cached_branch(f, cache_root, **args):
67
from remotebranch import RemoteBranch
68
br = find_branch(f, **args)
69
def cacheify(br, store_name):
70
from meta_store import CachedStore
71
cache_path = os.path.join(cache_root, store_name)
73
new_store = CachedStore(getattr(br, store_name), cache_path)
74
setattr(br, store_name, new_store)
76
if isinstance(br, RemoteBranch):
77
cacheify(br, 'inventory_store')
78
cacheify(br, 'text_store')
79
cacheify(br, 'revision_store')
83
def _relpath(base, path):
84
"""Return path relative to base, or raise exception.
86
The path may be either an absolute path or a path relative to the
87
current working directory.
89
Lifted out of Branch.relpath for ease of testing.
91
os.path.commonprefix (python2.4) has a bad bug that it works just
92
on string prefixes, assuming that '/u' is a prefix of '/u2'. This
93
avoids that problem."""
94
rp = os.path.abspath(path)
98
while len(head) >= len(base):
101
head, tail = os.path.split(head)
105
raise NotBranchError("path %r is not within branch %r" % (rp, base))
107
return os.sep.join(s)
110
def find_branch_root(f=None):
111
"""Find the branch root enclosing f, or pwd.
113
f may be a filename or a URL.
115
It is not necessary that f exists.
117
Basically we keep looking up until we find the control directory or
118
run into the root. If there isn't one, raises NotBranchError.
122
elif hasattr(os.path, 'realpath'):
123
f = os.path.realpath(f)
125
f = os.path.abspath(f)
126
if not os.path.exists(f):
127
raise BzrError('%r does not exist' % f)
133
if os.path.exists(os.path.join(f, bzrlib.BZRDIR)):
135
head, tail = os.path.split(f)
137
# reached the root, whatever that may be
138
raise NotBranchError('%s is not in a branch' % orig_f)
143
# XXX: move into bzrlib.errors; subclass BzrError
144
class DivergedBranches(Exception):
145
def __init__(self, branch1, branch2):
146
self.branch1 = branch1
147
self.branch2 = branch2
148
Exception.__init__(self, "These branches have diverged.")
151
######################################################################
154
class Branch(object):
155
"""Branch holding a history of revisions.
158
Base directory of the branch.
164
If _lock_mode is true, a positive count of the number of times the
168
Lock object from bzrlib.lock.
174
_inventory_weave = None
176
# Map some sort of prefix into a namespace
177
# stuff like "revno:10", "revid:", etc.
178
# This should match a prefix with a function which accepts
179
REVISION_NAMESPACES = {}
181
def __init__(self, base, init=False, find_root=True,
182
relax_version_check=False):
183
"""Create new branch object at a particular location.
185
base -- Base directory for the branch.
187
init -- If True, create new control files in a previously
188
unversioned directory. If False, the branch must already
191
find_root -- If true and init is false, find the root of the
192
existing branch containing base.
194
relax_version_check -- If true, the usual check for the branch
195
version is not applied. This is intended only for
196
upgrade/recovery type use; it's not guaranteed that
197
all operations will work on old format branches.
199
In the test suite, creation of new trees is tested using the
200
`ScratchBranch` class.
203
self.base = os.path.realpath(base)
206
self.base = find_branch_root(base)
208
self.base = os.path.realpath(base)
209
if not isdir(self.controlfilename('.')):
210
raise NotBranchError('not a bzr branch: %s' % quotefn(base),
211
['use "bzr init" to initialize a '
213
self._check_format(relax_version_check)
214
cfn = self.controlfilename
215
if self._branch_format == 4:
216
self.inventory_store = ImmutableStore(cfn('inventory-store'))
217
self.text_store = ImmutableStore(cfn('text-store'))
218
elif self._branch_format == 5:
219
self.control_weaves = WeaveStore(cfn([]))
220
self.weave_store = WeaveStore(cfn('weaves'))
221
self.revision_store = ImmutableStore(cfn('revision-store'))
225
return '%s(%r)' % (self.__class__.__name__, self.base)
232
if self._lock_mode or self._lock:
233
warn("branch %r was not explicitly unlocked" % self)
237
def lock_write(self):
239
if self._lock_mode != 'w':
240
raise LockError("can't upgrade to a write lock from %r" %
242
self._lock_count += 1
244
from bzrlib.lock import WriteLock
246
self._lock = WriteLock(self.controlfilename('branch-lock'))
247
self._lock_mode = 'w'
253
assert self._lock_mode in ('r', 'w'), \
254
"invalid lock mode %r" % self._lock_mode
255
self._lock_count += 1
257
from bzrlib.lock import ReadLock
259
self._lock = ReadLock(self.controlfilename('branch-lock'))
260
self._lock_mode = 'r'
264
if not self._lock_mode:
265
raise LockError('branch %r is not locked' % (self))
267
if self._lock_count > 1:
268
self._lock_count -= 1
272
self._lock_mode = self._lock_count = None
274
def abspath(self, name):
275
"""Return absolute filename for something in the branch"""
276
return os.path.join(self.base, name)
278
def relpath(self, path):
279
"""Return path relative to this branch of something inside it.
281
Raises an error if path is not in this branch."""
282
return _relpath(self.base, path)
284
def controlfilename(self, file_or_path):
285
"""Return location relative to branch."""
286
if isinstance(file_or_path, basestring):
287
file_or_path = [file_or_path]
288
return os.path.join(self.base, bzrlib.BZRDIR, *file_or_path)
291
def controlfile(self, file_or_path, mode='r'):
292
"""Open a control file for this branch.
294
There are two classes of file in the control directory: text
295
and binary. binary files are untranslated byte streams. Text
296
control files are stored with Unix newlines and in UTF-8, even
297
if the platform or locale defaults are different.
299
Controlfiles should almost never be opened in write mode but
300
rather should be atomically copied and replaced using atomicfile.
303
fn = self.controlfilename(file_or_path)
305
if mode == 'rb' or mode == 'wb':
306
return file(fn, mode)
307
elif mode == 'r' or mode == 'w':
308
# open in binary mode anyhow so there's no newline translation;
309
# codecs uses line buffering by default; don't want that.
311
return codecs.open(fn, mode + 'b', 'utf-8',
314
raise BzrError("invalid controlfile mode %r" % mode)
316
def _make_control(self):
317
os.mkdir(self.controlfilename([]))
318
self.controlfile('README', 'w').write(
319
"This is a Bazaar-NG control directory.\n"
320
"Do not change any files in this directory.\n")
321
self.controlfile('branch-format', 'w').write(BZR_BRANCH_FORMAT_5)
322
for d in ('text-store', 'revision-store',
324
os.mkdir(self.controlfilename(d))
325
for f in ('revision-history',
329
self.controlfile(f, 'w').write('')
330
mutter('created control directory in ' + self.base)
332
# if we want per-tree root ids then this is the place to set
333
# them; they're not needed for now and so ommitted for
335
f = self.controlfile('inventory','w')
336
bzrlib.xml5.serializer_v5.write_inventory(Inventory(), f)
340
def _check_format(self, relax_version_check):
341
"""Check this branch format is supported.
343
The format level is stored, as an integer, in
344
self._branch_format for code that needs to check it later.
346
In the future, we might need different in-memory Branch
347
classes to support downlevel branches. But not yet.
350
fmt = self.controlfile('branch-format', 'r').read()
352
if e.errno == errno.ENOENT:
353
raise NotBranchError(self.base)
357
if fmt == BZR_BRANCH_FORMAT_5:
358
self._branch_format = 5
359
elif fmt == BZR_BRANCH_FORMAT_4:
360
self._branch_format = 4
362
if (not relax_version_check
363
and self._branch_format != 5):
364
raise BzrError('sorry, branch format "%s" not supported; '
365
'use a different bzr version, '
366
'or run "bzr upgrade"'
367
% fmt.rstrip('\n\r'))
370
def get_root_id(self):
371
"""Return the id of this branches root"""
372
inv = self.read_working_inventory()
373
return inv.root.file_id
375
def set_root_id(self, file_id):
376
inv = self.read_working_inventory()
377
orig_root_id = inv.root.file_id
378
del inv._byid[inv.root.file_id]
379
inv.root.file_id = file_id
380
inv._byid[inv.root.file_id] = inv.root
383
if entry.parent_id in (None, orig_root_id):
384
entry.parent_id = inv.root.file_id
385
self._write_inventory(inv)
387
def read_working_inventory(self):
388
"""Read the working inventory."""
391
# ElementTree does its own conversion from UTF-8, so open in
393
f = self.controlfile('inventory', 'rb')
394
return bzrlib.xml5.serializer_v5.read_inventory(f)
399
def _write_inventory(self, inv):
400
"""Update the working inventory.
402
That is to say, the inventory describing changes underway, that
403
will be committed to the next revision.
405
from bzrlib.atomicfile import AtomicFile
409
f = AtomicFile(self.controlfilename('inventory'), 'wb')
411
bzrlib.xml5.serializer_v5.write_inventory(inv, f)
418
mutter('wrote working inventory')
421
inventory = property(read_working_inventory, _write_inventory, None,
422
"""Inventory for the working copy.""")
425
def add(self, files, ids=None):
426
"""Make files versioned.
428
Note that the command line normally calls smart_add instead,
429
which can automatically recurse.
431
This puts the files in the Added state, so that they will be
432
recorded by the next commit.
435
List of paths to add, relative to the base of the tree.
438
If set, use these instead of automatically generated ids.
439
Must be the same length as the list of files, but may
440
contain None for ids that are to be autogenerated.
442
TODO: Perhaps have an option to add the ids even if the files do
445
TODO: Perhaps yield the ids and paths as they're added.
447
# TODO: Re-adding a file that is removed in the working copy
448
# should probably put it back with the previous ID.
449
if isinstance(files, basestring):
450
assert(ids is None or isinstance(ids, basestring))
456
ids = [None] * len(files)
458
assert(len(ids) == len(files))
462
inv = self.read_working_inventory()
463
for f,file_id in zip(files, ids):
464
if is_control_file(f):
465
raise BzrError("cannot add control file %s" % quotefn(f))
470
raise BzrError("cannot add top-level %r" % f)
472
fullpath = os.path.normpath(self.abspath(f))
475
kind = file_kind(fullpath)
477
# maybe something better?
478
raise BzrError('cannot add: not a regular file or directory: %s' % quotefn(f))
480
if kind != 'file' and kind != 'directory':
481
raise BzrError('cannot add: not a regular file or directory: %s' % quotefn(f))
484
file_id = gen_file_id(f)
485
inv.add_path(f, kind=kind, file_id=file_id)
487
mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
489
self._write_inventory(inv)
494
def print_file(self, file, revno):
495
"""Print `file` to stdout."""
498
tree = self.revision_tree(self.lookup_revision(revno))
499
# use inventory as it was in that revision
500
file_id = tree.inventory.path2id(file)
502
raise BzrError("%r is not present in revision %s" % (file, revno))
503
tree.print_file(file_id)
508
def remove(self, files, verbose=False):
509
"""Mark nominated files for removal from the inventory.
511
This does not remove their text. This does not run on
513
TODO: Refuse to remove modified files unless --force is given?
515
TODO: Do something useful with directories.
517
TODO: Should this remove the text or not? Tough call; not
518
removing may be useful and the user can just use use rm, and
519
is the opposite of add. Removing it is consistent with most
520
other tools. Maybe an option.
522
## TODO: Normalize names
523
## TODO: Remove nested loops; better scalability
524
if isinstance(files, basestring):
530
tree = self.working_tree()
533
# do this before any modifications
537
raise BzrError("cannot remove unversioned file %s" % quotefn(f))
538
mutter("remove inventory entry %s {%s}" % (quotefn(f), fid))
540
# having remove it, it must be either ignored or unknown
541
if tree.is_ignored(f):
545
show_status(new_status, inv[fid].kind, quotefn(f))
548
self._write_inventory(inv)
553
# FIXME: this doesn't need to be a branch method
554
def set_inventory(self, new_inventory_list):
555
from bzrlib.inventory import Inventory, InventoryEntry
556
inv = Inventory(self.get_root_id())
557
for path, file_id, parent, kind in new_inventory_list:
558
name = os.path.basename(path)
561
inv.add(InventoryEntry(file_id, name, kind, parent))
562
self._write_inventory(inv)
566
"""Return all unknown files.
568
These are files in the working directory that are not versioned or
569
control files or ignored.
571
>>> b = ScratchBranch(files=['foo', 'foo~'])
572
>>> list(b.unknowns())
575
>>> list(b.unknowns())
578
>>> list(b.unknowns())
581
return self.working_tree().unknowns()
584
def append_revision(self, *revision_ids):
585
from bzrlib.atomicfile import AtomicFile
587
for revision_id in revision_ids:
588
mutter("add {%s} to revision-history" % revision_id)
590
rev_history = self.revision_history()
591
rev_history.extend(revision_ids)
593
f = AtomicFile(self.controlfilename('revision-history'))
595
for rev_id in rev_history:
602
def has_revision(self, revision_id):
603
"""True if this branch has a copy of the revision.
605
This does not necessarily imply the revision is merge
606
or on the mainline."""
607
return revision_id in self.revision_store
610
def get_revision_xml_file(self, revision_id):
611
"""Return XML file object for revision object."""
612
if not revision_id or not isinstance(revision_id, basestring):
613
raise InvalidRevisionId(revision_id)
618
return self.revision_store[revision_id]
620
raise bzrlib.errors.NoSuchRevision(self, revision_id)
625
def get_revision_xml(self, revision_id):
626
return self.get_revision_xml_file(revision_id).read()
629
def get_revision(self, revision_id):
630
"""Return the Revision object for a named revision"""
631
xml_file = self.get_revision_xml_file(revision_id)
634
r = bzrlib.xml5.serializer_v5.read_revision(xml_file)
635
except SyntaxError, e:
636
raise bzrlib.errors.BzrError('failed to unpack revision_xml',
640
assert r.revision_id == revision_id
644
def get_revision_delta(self, revno):
645
"""Return the delta for one revision.
647
The delta is relative to its mainline predecessor, or the
648
empty tree for revision 1.
650
assert isinstance(revno, int)
651
rh = self.revision_history()
652
if not (1 <= revno <= len(rh)):
653
raise InvalidRevisionNumber(revno)
655
# revno is 1-based; list is 0-based
657
new_tree = self.revision_tree(rh[revno-1])
659
old_tree = EmptyTree()
661
old_tree = self.revision_tree(rh[revno-2])
663
return compare_trees(old_tree, new_tree)
667
def get_revision_sha1(self, revision_id):
668
"""Hash the stored value of a revision, and return it."""
669
return bzrlib.osutils.sha_file(self.get_revision_xml_file(revision_id))
672
def _get_ancestry_weave(self):
673
return self.control_weaves.get_weave('ancestry')
676
def get_ancestry(self, revision_id):
677
"""Return a list of revision-ids integrated by a revision.
680
w = self._get_ancestry_weave()
681
return [l[:-1] for l in w.get_iter(w.lookup(revision_id))]
684
def get_inventory_weave(self):
685
return self.control_weaves.get_weave('inventory')
688
def get_inventory(self, revision_id):
689
"""Get Inventory object by hash."""
690
xml = self.get_inventory_xml(revision_id)
691
return bzrlib.xml5.serializer_v5.read_inventory_from_string(xml)
694
def get_inventory_xml(self, revision_id):
695
"""Get inventory XML as a file object."""
697
assert isinstance(revision_id, basestring), type(revision_id)
698
iw = self.get_inventory_weave()
699
return iw.get_text(iw.lookup(revision_id))
701
raise bzrlib.errors.HistoryMissing(self, 'inventory', revision_id)
704
def get_inventory_sha1(self, revision_id):
705
"""Return the sha1 hash of the inventory entry
707
return self.get_revision(revision_id).inventory_sha1
710
def get_revision_inventory(self, revision_id):
711
"""Return inventory of a past revision."""
712
# TODO: Unify this with get_inventory()
713
# bzr 0.0.6 and later imposes the constraint that the inventory_id
714
# must be the same as its revision, so this is trivial.
715
if revision_id == None:
716
return Inventory(self.get_root_id())
718
return self.get_inventory(revision_id)
721
def revision_history(self):
722
"""Return sequence of revision hashes on to this branch."""
725
return [l.rstrip('\r\n') for l in
726
self.controlfile('revision-history', 'r').readlines()]
731
def common_ancestor(self, other, self_revno=None, other_revno=None):
734
>>> sb = ScratchBranch(files=['foo', 'foo~'])
735
>>> sb.common_ancestor(sb) == (None, None)
737
>>> commit.commit(sb, "Committing first revision")
738
>>> sb.common_ancestor(sb)[0]
740
>>> clone = sb.clone()
741
>>> commit.commit(sb, "Committing second revision")
742
>>> sb.common_ancestor(sb)[0]
744
>>> sb.common_ancestor(clone)[0]
746
>>> commit.commit(clone, "Committing divergent second revision")
747
>>> sb.common_ancestor(clone)[0]
749
>>> sb.common_ancestor(clone) == clone.common_ancestor(sb)
751
>>> sb.common_ancestor(sb) != clone.common_ancestor(clone)
753
>>> clone2 = sb.clone()
754
>>> sb.common_ancestor(clone2)[0]
756
>>> sb.common_ancestor(clone2, self_revno=1)[0]
758
>>> sb.common_ancestor(clone2, other_revno=1)[0]
761
my_history = self.revision_history()
762
other_history = other.revision_history()
763
if self_revno is None:
764
self_revno = len(my_history)
765
if other_revno is None:
766
other_revno = len(other_history)
767
indices = range(min((self_revno, other_revno)))
770
if my_history[r] == other_history[r]:
771
return r+1, my_history[r]
776
"""Return current revision number for this branch.
778
That is equivalent to the number of revisions committed to
781
return len(self.revision_history())
784
def last_revision(self):
785
"""Return last patch hash, or None if no history.
787
ph = self.revision_history()
794
def missing_revisions(self, other, stop_revision=None, diverged_ok=False):
795
"""Return a list of new revisions that would perfectly fit.
797
If self and other have not diverged, return a list of the revisions
798
present in other, but missing from self.
800
>>> from bzrlib.commit import commit
801
>>> bzrlib.trace.silent = True
802
>>> br1 = ScratchBranch()
803
>>> br2 = ScratchBranch()
804
>>> br1.missing_revisions(br2)
806
>>> commit(br2, "lala!", rev_id="REVISION-ID-1")
807
>>> br1.missing_revisions(br2)
809
>>> br2.missing_revisions(br1)
811
>>> commit(br1, "lala!", rev_id="REVISION-ID-1")
812
>>> br1.missing_revisions(br2)
814
>>> commit(br2, "lala!", rev_id="REVISION-ID-2A")
815
>>> br1.missing_revisions(br2)
817
>>> commit(br1, "lala!", rev_id="REVISION-ID-2B")
818
>>> br1.missing_revisions(br2)
819
Traceback (most recent call last):
820
DivergedBranches: These branches have diverged.
822
# FIXME: If the branches have diverged, but the latest
823
# revision in this branch is completely merged into the other,
824
# then we should still be able to pull.
825
self_history = self.revision_history()
826
self_len = len(self_history)
827
other_history = other.revision_history()
828
other_len = len(other_history)
829
common_index = min(self_len, other_len) -1
830
if common_index >= 0 and \
831
self_history[common_index] != other_history[common_index]:
832
raise DivergedBranches(self, other)
834
if stop_revision is None:
835
stop_revision = other_len
837
assert isinstance(stop_revision, int)
838
if stop_revision > other_len:
839
raise bzrlib.errors.NoSuchRevision(self, stop_revision)
841
return other_history[self_len:stop_revision]
844
def update_revisions(self, other, stop_revno=None):
845
"""Pull in new perfect-fit revisions.
847
from bzrlib.fetch import greedy_fetch
850
stop_revision = other.lookup_revision(stop_revno)
853
greedy_fetch(to_branch=self, from_branch=other,
854
revision=stop_revision)
856
pullable_revs = self.missing_revisions(other, stop_revision)
859
greedy_fetch(to_branch=self,
861
revision=pullable_revs[-1])
862
self.append_revision(*pullable_revs)
865
def commit(self, *args, **kw):
866
from bzrlib.commit import Commit
867
Commit().commit(self, *args, **kw)
870
def lookup_revision(self, revision):
871
"""Return the revision identifier for a given revision information."""
872
revno, info = self._get_revision_info(revision)
876
def revision_id_to_revno(self, revision_id):
877
"""Given a revision id, return its revno"""
878
history = self.revision_history()
880
return history.index(revision_id) + 1
882
raise bzrlib.errors.NoSuchRevision(self, revision_id)
885
def get_revision_info(self, revision):
886
"""Return (revno, revision id) for revision identifier.
888
revision can be an integer, in which case it is assumed to be revno (though
889
this will translate negative values into positive ones)
890
revision can also be a string, in which case it is parsed for something like
891
'date:' or 'revid:' etc.
893
revno, rev_id = self._get_revision_info(revision)
895
raise bzrlib.errors.NoSuchRevision(self, revision)
898
def get_rev_id(self, revno, history=None):
899
"""Find the revision id of the specified revno."""
903
history = self.revision_history()
904
elif revno <= 0 or revno > len(history):
905
raise bzrlib.errors.NoSuchRevision(self, revno)
906
return history[revno - 1]
908
def _get_revision_info(self, revision):
909
"""Return (revno, revision id) for revision specifier.
911
revision can be an integer, in which case it is assumed to be revno
912
(though this will translate negative values into positive ones)
913
revision can also be a string, in which case it is parsed for something
914
like 'date:' or 'revid:' etc.
916
A revid is always returned. If it is None, the specifier referred to
917
the null revision. If the revid does not occur in the revision
918
history, revno will be None.
924
try:# Convert to int if possible
925
revision = int(revision)
928
revs = self.revision_history()
929
if isinstance(revision, int):
931
revno = len(revs) + revision + 1
934
rev_id = self.get_rev_id(revno, revs)
935
elif isinstance(revision, basestring):
936
for prefix, func in Branch.REVISION_NAMESPACES.iteritems():
937
if revision.startswith(prefix):
938
result = func(self, revs, revision)
940
revno, rev_id = result
943
rev_id = self.get_rev_id(revno, revs)
946
raise BzrError('No namespace registered for string: %r' %
949
raise TypeError('Unhandled revision type %s' % revision)
953
raise bzrlib.errors.NoSuchRevision(self, revision)
956
def _namespace_revno(self, revs, revision):
957
"""Lookup a revision by revision number"""
958
assert revision.startswith('revno:')
960
return (int(revision[6:]),)
963
REVISION_NAMESPACES['revno:'] = _namespace_revno
965
def _namespace_revid(self, revs, revision):
966
assert revision.startswith('revid:')
967
rev_id = revision[len('revid:'):]
969
return revs.index(rev_id) + 1, rev_id
972
REVISION_NAMESPACES['revid:'] = _namespace_revid
974
def _namespace_last(self, revs, revision):
975
assert revision.startswith('last:')
977
offset = int(revision[5:])
982
raise BzrError('You must supply a positive value for --revision last:XXX')
983
return (len(revs) - offset + 1,)
984
REVISION_NAMESPACES['last:'] = _namespace_last
986
def _namespace_tag(self, revs, revision):
987
assert revision.startswith('tag:')
988
raise BzrError('tag: namespace registered, but not implemented.')
989
REVISION_NAMESPACES['tag:'] = _namespace_tag
991
def _namespace_date(self, revs, revision):
992
assert revision.startswith('date:')
994
# Spec for date revisions:
996
# value can be 'yesterday', 'today', 'tomorrow' or a YYYY-MM-DD string.
997
# it can also start with a '+/-/='. '+' says match the first
998
# entry after the given date. '-' is match the first entry before the date
999
# '=' is match the first entry after, but still on the given date.
1001
# +2005-05-12 says find the first matching entry after May 12th, 2005 at 0:00
1002
# -2005-05-12 says find the first matching entry before May 12th, 2005 at 0:00
1003
# =2005-05-12 says find the first match after May 12th, 2005 at 0:00 but before
1004
# May 13th, 2005 at 0:00
1006
# So the proper way of saying 'give me all entries for today' is:
1007
# -r {date:+today}:{date:-tomorrow}
1008
# The default is '=' when not supplied
1011
if val[:1] in ('+', '-', '='):
1012
match_style = val[:1]
1015
today = datetime.datetime.today().replace(hour=0,minute=0,second=0,microsecond=0)
1016
if val.lower() == 'yesterday':
1017
dt = today - datetime.timedelta(days=1)
1018
elif val.lower() == 'today':
1020
elif val.lower() == 'tomorrow':
1021
dt = today + datetime.timedelta(days=1)
1024
# This should be done outside the function to avoid recompiling it.
1025
_date_re = re.compile(
1026
r'(?P<date>(?P<year>\d\d\d\d)-(?P<month>\d\d)-(?P<day>\d\d))?'
1028
r'(?P<time>(?P<hour>\d\d):(?P<minute>\d\d)(:(?P<second>\d\d))?)?'
1030
m = _date_re.match(val)
1031
if not m or (not m.group('date') and not m.group('time')):
1032
raise BzrError('Invalid revision date %r' % revision)
1035
year, month, day = int(m.group('year')), int(m.group('month')), int(m.group('day'))
1037
year, month, day = today.year, today.month, today.day
1039
hour = int(m.group('hour'))
1040
minute = int(m.group('minute'))
1041
if m.group('second'):
1042
second = int(m.group('second'))
1046
hour, minute, second = 0,0,0
1048
dt = datetime.datetime(year=year, month=month, day=day,
1049
hour=hour, minute=minute, second=second)
1053
if match_style == '-':
1055
elif match_style == '=':
1056
last = dt + datetime.timedelta(days=1)
1059
for i in range(len(revs)-1, -1, -1):
1060
r = self.get_revision(revs[i])
1061
# TODO: Handle timezone.
1062
dt = datetime.datetime.fromtimestamp(r.timestamp)
1063
if first >= dt and (last is None or dt >= last):
1066
for i in range(len(revs)):
1067
r = self.get_revision(revs[i])
1068
# TODO: Handle timezone.
1069
dt = datetime.datetime.fromtimestamp(r.timestamp)
1070
if first <= dt and (last is None or dt <= last):
1072
REVISION_NAMESPACES['date:'] = _namespace_date
1074
def revision_tree(self, revision_id):
1075
"""Return Tree for a revision on this branch.
1077
`revision_id` may be None for the null revision, in which case
1078
an `EmptyTree` is returned."""
1079
# TODO: refactor this to use an existing revision object
1080
# so we don't need to read it in twice.
1081
if revision_id == None:
1084
inv = self.get_revision_inventory(revision_id)
1085
return RevisionTree(self.weave_store, inv, revision_id)
1088
def working_tree(self):
1089
"""Return a `Tree` for the working copy."""
1090
from workingtree import WorkingTree
1091
return WorkingTree(self.base, self.read_working_inventory())
1094
def basis_tree(self):
1095
"""Return `Tree` object for last revision.
1097
If there are no revisions yet, return an `EmptyTree`.
1099
return self.revision_tree(self.last_revision())
1102
def rename_one(self, from_rel, to_rel):
1105
This can change the directory or the filename or both.
1109
tree = self.working_tree()
1110
inv = tree.inventory
1111
if not tree.has_filename(from_rel):
1112
raise BzrError("can't rename: old working file %r does not exist" % from_rel)
1113
if tree.has_filename(to_rel):
1114
raise BzrError("can't rename: new working file %r already exists" % to_rel)
1116
file_id = inv.path2id(from_rel)
1118
raise BzrError("can't rename: old name %r is not versioned" % from_rel)
1120
if inv.path2id(to_rel):
1121
raise BzrError("can't rename: new name %r is already versioned" % to_rel)
1123
to_dir, to_tail = os.path.split(to_rel)
1124
to_dir_id = inv.path2id(to_dir)
1125
if to_dir_id == None and to_dir != '':
1126
raise BzrError("can't determine destination directory id for %r" % to_dir)
1128
mutter("rename_one:")
1129
mutter(" file_id {%s}" % file_id)
1130
mutter(" from_rel %r" % from_rel)
1131
mutter(" to_rel %r" % to_rel)
1132
mutter(" to_dir %r" % to_dir)
1133
mutter(" to_dir_id {%s}" % to_dir_id)
1135
inv.rename(file_id, to_dir_id, to_tail)
1137
from_abs = self.abspath(from_rel)
1138
to_abs = self.abspath(to_rel)
1140
os.rename(from_abs, to_abs)
1142
raise BzrError("failed to rename %r to %r: %s"
1143
% (from_abs, to_abs, e[1]),
1144
["rename rolled back"])
1146
self._write_inventory(inv)
1151
def move(self, from_paths, to_name):
1154
to_name must exist as a versioned directory.
1156
If to_name exists and is a directory, the files are moved into
1157
it, keeping their old names. If it is a directory,
1159
Note that to_name is only the last component of the new name;
1160
this doesn't change the directory.
1162
This returns a list of (from_path, to_path) pairs for each
1163
entry that is moved.
1168
## TODO: Option to move IDs only
1169
assert not isinstance(from_paths, basestring)
1170
tree = self.working_tree()
1171
inv = tree.inventory
1172
to_abs = self.abspath(to_name)
1173
if not isdir(to_abs):
1174
raise BzrError("destination %r is not a directory" % to_abs)
1175
if not tree.has_filename(to_name):
1176
raise BzrError("destination %r not in working directory" % to_abs)
1177
to_dir_id = inv.path2id(to_name)
1178
if to_dir_id == None and to_name != '':
1179
raise BzrError("destination %r is not a versioned directory" % to_name)
1180
to_dir_ie = inv[to_dir_id]
1181
if to_dir_ie.kind not in ('directory', 'root_directory'):
1182
raise BzrError("destination %r is not a directory" % to_abs)
1184
to_idpath = inv.get_idpath(to_dir_id)
1186
for f in from_paths:
1187
if not tree.has_filename(f):
1188
raise BzrError("%r does not exist in working tree" % f)
1189
f_id = inv.path2id(f)
1191
raise BzrError("%r is not versioned" % f)
1192
name_tail = splitpath(f)[-1]
1193
dest_path = appendpath(to_name, name_tail)
1194
if tree.has_filename(dest_path):
1195
raise BzrError("destination %r already exists" % dest_path)
1196
if f_id in to_idpath:
1197
raise BzrError("can't move %r to a subdirectory of itself" % f)
1199
# OK, so there's a race here, it's possible that someone will
1200
# create a file in this interval and then the rename might be
1201
# left half-done. But we should have caught most problems.
1203
for f in from_paths:
1204
name_tail = splitpath(f)[-1]
1205
dest_path = appendpath(to_name, name_tail)
1206
result.append((f, dest_path))
1207
inv.rename(inv.path2id(f), to_dir_id, name_tail)
1209
os.rename(self.abspath(f), self.abspath(dest_path))
1211
raise BzrError("failed to rename %r to %r: %s" % (f, dest_path, e[1]),
1212
["rename rolled back"])
1214
self._write_inventory(inv)
1221
def revert(self, filenames, old_tree=None, backups=True):
1222
"""Restore selected files to the versions from a previous tree.
1225
If true (default) backups are made of files before
1228
from bzrlib.errors import NotVersionedError, BzrError
1229
from bzrlib.atomicfile import AtomicFile
1230
from bzrlib.osutils import backup_file
1232
inv = self.read_working_inventory()
1233
if old_tree is None:
1234
old_tree = self.basis_tree()
1235
old_inv = old_tree.inventory
1238
for fn in filenames:
1239
file_id = inv.path2id(fn)
1241
raise NotVersionedError("not a versioned file", fn)
1242
if not old_inv.has_id(file_id):
1243
raise BzrError("file not present in old tree", fn, file_id)
1244
nids.append((fn, file_id))
1246
# TODO: Rename back if it was previously at a different location
1248
# TODO: If given a directory, restore the entire contents from
1249
# the previous version.
1251
# TODO: Make a backup to a temporary file.
1253
# TODO: If the file previously didn't exist, delete it?
1254
for fn, file_id in nids:
1257
f = AtomicFile(fn, 'wb')
1259
f.write(old_tree.get_file(file_id).read())
1265
def pending_merges(self):
1266
"""Return a list of pending merges.
1268
These are revisions that have been merged into the working
1269
directory but not yet committed.
1271
cfn = self.controlfilename('pending-merges')
1272
if not os.path.exists(cfn):
1275
for l in self.controlfile('pending-merges', 'r').readlines():
1276
p.append(l.rstrip('\n'))
1280
def add_pending_merge(self, revision_id):
1281
validate_revision_id(revision_id)
1282
# TODO: Perhaps should check at this point that the
1283
# history of the revision is actually present?
1284
p = self.pending_merges()
1285
if revision_id in p:
1287
p.append(revision_id)
1288
self.set_pending_merges(p)
1291
def set_pending_merges(self, rev_list):
1292
from bzrlib.atomicfile import AtomicFile
1295
f = AtomicFile(self.controlfilename('pending-merges'))
1306
def get_parent(self):
1307
"""Return the parent location of the branch.
1309
This is the default location for push/pull/missing. The usual
1310
pattern is that the user can override it by specifying a
1314
_locs = ['parent', 'pull', 'x-pull']
1317
return self.controlfile(l, 'r').read().strip('\n')
1319
if e.errno != errno.ENOENT:
1324
def set_parent(self, url):
1325
# TODO: Maybe delete old location files?
1326
from bzrlib.atomicfile import AtomicFile
1329
f = AtomicFile(self.controlfilename('parent'))
1338
def check_revno(self, revno):
1340
Check whether a revno corresponds to any revision.
1341
Zero (the NULL revision) is considered valid.
1344
self.check_real_revno(revno)
1346
def check_real_revno(self, revno):
1348
Check whether a revno corresponds to a real revision.
1349
Zero (the NULL revision) is considered invalid
1351
if revno < 1 or revno > self.revno():
1352
raise InvalidRevisionNumber(revno)
1357
class ScratchBranch(Branch):
1358
"""Special test class: a branch that cleans up after itself.
1360
>>> b = ScratchBranch()
1368
def __init__(self, files=[], dirs=[], base=None):
1369
"""Make a test branch.
1371
This creates a temporary directory and runs init-tree in it.
1373
If any files are listed, they are created in the working copy.
1375
from tempfile import mkdtemp
1380
Branch.__init__(self, base, init=init)
1382
os.mkdir(self.abspath(d))
1385
file(os.path.join(self.base, f), 'w').write('content of %s' % f)
1390
>>> orig = ScratchBranch(files=["file1", "file2"])
1391
>>> clone = orig.clone()
1392
>>> os.path.samefile(orig.base, clone.base)
1394
>>> os.path.isfile(os.path.join(clone.base, "file1"))
1397
from shutil import copytree
1398
from tempfile import mkdtemp
1401
copytree(self.base, base, symlinks=True)
1402
return ScratchBranch(base=base)
1410
"""Destroy the test branch, removing the scratch directory."""
1411
from shutil import rmtree
1414
mutter("delete ScratchBranch %s" % self.base)
1417
# Work around for shutil.rmtree failing on Windows when
1418
# readonly files are encountered
1419
mutter("hit exception in destroying ScratchBranch: %s" % e)
1420
for root, dirs, files in os.walk(self.base, topdown=False):
1422
os.chmod(os.path.join(root, name), 0700)
1428
######################################################################
1432
def is_control_file(filename):
1433
## FIXME: better check
1434
filename = os.path.normpath(filename)
1435
while filename != '':
1436
head, tail = os.path.split(filename)
1437
## mutter('check %r for control file' % ((head, tail), ))
1438
if tail == bzrlib.BZRDIR:
1440
if filename == head:
1447
def gen_file_id(name):
1448
"""Return new file id.
1450
This should probably generate proper UUIDs, but for the moment we
1451
cope with just randomness because running uuidgen every time is
1454
from binascii import hexlify
1455
from time import time
1457
# get last component
1458
idx = name.rfind('/')
1460
name = name[idx+1 : ]
1461
idx = name.rfind('\\')
1463
name = name[idx+1 : ]
1465
# make it not a hidden file
1466
name = name.lstrip('.')
1468
# remove any wierd characters; we don't escape them but rather
1469
# just pull them out
1470
name = re.sub(r'[^\w.]', '', name)
1472
s = hexlify(rand_bytes(8))
1473
return '-'.join((name, compact_date(time()), s))
1477
"""Return a new tree-root file id."""
1478
return gen_file_id('TREE_ROOT')
1481
def pull_loc(branch):
1482
# TODO: Should perhaps just make attribute be 'base' in
1483
# RemoteBranch and Branch?
1484
if hasattr(branch, "baseurl"):
1485
return branch.baseurl
1490
def copy_branch(branch_from, to_location, revision=None):
1491
"""Copy branch_from into the existing directory to_location.
1494
If not None, only revisions up to this point will be copied.
1495
The head of the new branch will be that revision. Can be a
1499
The name of a local directory that exists but is empty.
1501
# TODO: This could be done *much* more efficiently by just copying
1502
# all the whole weaves and revisions, rather than getting one
1503
# revision at a time.
1504
from bzrlib.merge import merge
1505
from bzrlib.branch import Branch
1507
assert isinstance(branch_from, Branch)
1508
assert isinstance(to_location, basestring)
1510
br_to = Branch(to_location, init=True)
1511
br_to.set_root_id(branch_from.get_root_id())
1512
if revision is None:
1515
revno, rev_id = branch_from.get_revision_info(revision)
1516
br_to.update_revisions(branch_from, stop_revno=revno)
1517
merge((to_location, -1), (to_location, 0), this_dir=to_location,
1518
check_clean=False, ignore_zero=True)
1520
from_location = pull_loc(branch_from)
1521
br_to.set_parent(pull_loc(branch_from))