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
27
from bzrlib.errors import BzrError, InvalidRevisionNumber, InvalidRevisionId, \
28
DivergedBranches, NotBranchError
29
from bzrlib.textui import show_status
30
from bzrlib.revision import Revision
31
from bzrlib.delta import compare_trees
32
from bzrlib.tree import EmptyTree, RevisionTree
38
BZR_BRANCH_FORMAT = "Bazaar-NG branch, format 0.0.4\n"
39
## TODO: Maybe include checks for common corruption of newlines, etc?
42
# TODO: Some operations like log might retrieve the same revisions
43
# repeatedly to calculate deltas. We could perhaps have a weakref
44
# cache in memory to make this faster.
46
# TODO: please move the revision-string syntax stuff out of the branch
47
# object; it's clutter
50
def find_branch(f, **args):
51
if f and (f.startswith('http://') or f.startswith('https://')):
52
from bzrlib.remotebranch import RemoteBranch
53
return RemoteBranch(f, **args)
55
return LocalBranch(f, **args)
58
def find_cached_branch(f, cache_root, **args):
59
from bzrlib.remotebranch import RemoteBranch
60
br = find_branch(f, **args)
61
def cacheify(br, store_name):
62
from bzrlib.meta_store import CachedStore
63
cache_path = os.path.join(cache_root, store_name)
65
new_store = CachedStore(getattr(br, store_name), cache_path)
66
setattr(br, store_name, new_store)
68
if isinstance(br, RemoteBranch):
69
cacheify(br, 'inventory_store')
70
cacheify(br, 'text_store')
71
cacheify(br, 'revision_store')
75
def _relpath(base, path):
76
"""Return path relative to base, or raise exception.
78
The path may be either an absolute path or a path relative to the
79
current working directory.
81
Lifted out of Branch.relpath for ease of testing.
83
os.path.commonprefix (python2.4) has a bad bug that it works just
84
on string prefixes, assuming that '/u' is a prefix of '/u2'. This
85
avoids that problem."""
86
rp = os.path.abspath(path)
90
while len(head) >= len(base):
93
head, tail = os.path.split(head)
97
raise NotBranchError("path %r is not within branch %r" % (rp, base))
102
def find_branch_root(f=None):
103
"""Find the branch root enclosing f, or pwd.
105
f may be a filename or a URL.
107
It is not necessary that f exists.
109
Basically we keep looking up until we find the control directory or
110
run into the root. If there isn't one, raises NotBranchError.
114
elif hasattr(os.path, 'realpath'):
115
f = os.path.realpath(f)
117
f = os.path.abspath(f)
118
if not os.path.exists(f):
119
raise BzrError('%r does not exist' % f)
125
if os.path.exists(os.path.join(f, bzrlib.BZRDIR)):
127
head, tail = os.path.split(f)
129
# reached the root, whatever that may be
130
raise NotBranchError('%s is not in a branch' % orig_f)
136
######################################################################
139
class Branch(object):
140
"""Branch holding a history of revisions.
143
Base directory/url of the branch.
147
# Map some sort of prefix into a namespace
148
# stuff like "revno:10", "revid:", etc.
149
# This should match a prefix with a function which accepts
150
REVISION_NAMESPACES = {}
152
def __new__(cls, *a, **kw):
153
"""this is temporary, till we get rid of all code that does
156
# AAARGH! MY EYES! UUUUGLY!!!
159
b = object.__new__(cls)
162
def _namespace_revno(self, revs, revision):
163
"""Lookup a revision by revision number"""
164
assert revision.startswith('revno:')
166
return (int(revision[6:]),)
169
REVISION_NAMESPACES['revno:'] = _namespace_revno
171
def _namespace_revid(self, revs, revision):
172
assert revision.startswith('revid:')
173
rev_id = revision[len('revid:'):]
175
return revs.index(rev_id) + 1, rev_id
178
REVISION_NAMESPACES['revid:'] = _namespace_revid
180
def _namespace_last(self, revs, revision):
181
assert revision.startswith('last:')
183
offset = int(revision[5:])
188
raise BzrError('You must supply a positive value for --revision last:XXX')
189
return (len(revs) - offset + 1,)
190
REVISION_NAMESPACES['last:'] = _namespace_last
192
def _namespace_tag(self, revs, revision):
193
assert revision.startswith('tag:')
194
raise BzrError('tag: namespace registered, but not implemented.')
195
REVISION_NAMESPACES['tag:'] = _namespace_tag
197
def _namespace_date(self, revs, revision):
198
assert revision.startswith('date:')
200
# Spec for date revisions:
202
# value can be 'yesterday', 'today', 'tomorrow' or a YYYY-MM-DD string.
203
# it can also start with a '+/-/='. '+' says match the first
204
# entry after the given date. '-' is match the first entry before the date
205
# '=' is match the first entry after, but still on the given date.
207
# +2005-05-12 says find the first matching entry after May 12th, 2005 at 0:00
208
# -2005-05-12 says find the first matching entry before May 12th, 2005 at 0:00
209
# =2005-05-12 says find the first match after May 12th, 2005 at 0:00 but before
210
# May 13th, 2005 at 0:00
212
# So the proper way of saying 'give me all entries for today' is:
213
# -r {date:+today}:{date:-tomorrow}
214
# The default is '=' when not supplied
217
if val[:1] in ('+', '-', '='):
218
match_style = val[:1]
221
today = datetime.datetime.today().replace(hour=0,minute=0,second=0,microsecond=0)
222
if val.lower() == 'yesterday':
223
dt = today - datetime.timedelta(days=1)
224
elif val.lower() == 'today':
226
elif val.lower() == 'tomorrow':
227
dt = today + datetime.timedelta(days=1)
230
# This should be done outside the function to avoid recompiling it.
231
_date_re = re.compile(
232
r'(?P<date>(?P<year>\d\d\d\d)-(?P<month>\d\d)-(?P<day>\d\d))?'
234
r'(?P<time>(?P<hour>\d\d):(?P<minute>\d\d)(:(?P<second>\d\d))?)?'
236
m = _date_re.match(val)
237
if not m or (not m.group('date') and not m.group('time')):
238
raise BzrError('Invalid revision date %r' % revision)
241
year, month, day = int(m.group('year')), int(m.group('month')), int(m.group('day'))
243
year, month, day = today.year, today.month, today.day
245
hour = int(m.group('hour'))
246
minute = int(m.group('minute'))
247
if m.group('second'):
248
second = int(m.group('second'))
252
hour, minute, second = 0,0,0
254
dt = datetime.datetime(year=year, month=month, day=day,
255
hour=hour, minute=minute, second=second)
259
if match_style == '-':
261
elif match_style == '=':
262
last = dt + datetime.timedelta(days=1)
265
for i in range(len(revs)-1, -1, -1):
266
r = self.get_revision(revs[i])
267
# TODO: Handle timezone.
268
dt = datetime.datetime.fromtimestamp(r.timestamp)
269
if first >= dt and (last is None or dt >= last):
272
for i in range(len(revs)):
273
r = self.get_revision(revs[i])
274
# TODO: Handle timezone.
275
dt = datetime.datetime.fromtimestamp(r.timestamp)
276
if first <= dt and (last is None or dt <= last):
278
REVISION_NAMESPACES['date:'] = _namespace_date
281
class LocalBranch(Branch):
282
"""A branch stored in the actual filesystem.
284
Note that it's "local" in the context of the filesystem; it doesn't
285
really matter if it's on an nfs/smb/afs/coda/... share, as long as
286
it's writable, and can be accessed via the normal filesystem API.
292
If _lock_mode is true, a positive count of the number of times the
296
Lock object from bzrlib.lock.
298
# We actually expect this class to be somewhat short-lived; part of its
299
# purpose is to try to isolate what bits of the branch logic are tied to
300
# filesystem access, so that in a later step, we can extricate them to
301
# a separarte ("storage") class.
306
def __init__(self, base, init=False, find_root=True):
307
"""Create new branch object at a particular location.
309
base -- Base directory for the branch.
311
init -- If True, create new control files in a previously
312
unversioned directory. If False, the branch must already
315
find_root -- If true and init is false, find the root of the
316
existing branch containing base.
318
In the test suite, creation of new trees is tested using the
319
`ScratchBranch` class.
321
from bzrlib.store import ImmutableStore
323
self.base = os.path.realpath(base)
326
self.base = find_branch_root(base)
328
self.base = os.path.realpath(base)
329
if not isdir(self.controlfilename('.')):
330
raise NotBranchError("not a bzr branch: %s" % quotefn(base),
331
['use "bzr init" to initialize a new working tree',
332
'current bzr can only operate from top-of-tree'])
335
self.text_store = ImmutableStore(self.controlfilename('text-store'))
336
self.revision_store = ImmutableStore(self.controlfilename('revision-store'))
337
self.inventory_store = ImmutableStore(self.controlfilename('inventory-store'))
341
return '%s(%r)' % (self.__class__.__name__, self.base)
348
if self._lock_mode or self._lock:
349
from bzrlib.warnings import warn
350
warn("branch %r was not explicitly unlocked" % self)
354
def lock_write(self):
356
if self._lock_mode != 'w':
357
from bzrlib.errors import LockError
358
raise LockError("can't upgrade to a write lock from %r" %
360
self._lock_count += 1
362
from bzrlib.lock import WriteLock
364
self._lock = WriteLock(self.controlfilename('branch-lock'))
365
self._lock_mode = 'w'
371
assert self._lock_mode in ('r', 'w'), \
372
"invalid lock mode %r" % self._lock_mode
373
self._lock_count += 1
375
from bzrlib.lock import ReadLock
377
self._lock = ReadLock(self.controlfilename('branch-lock'))
378
self._lock_mode = 'r'
382
if not self._lock_mode:
383
from bzrlib.errors import LockError
384
raise LockError('branch %r is not locked' % (self))
386
if self._lock_count > 1:
387
self._lock_count -= 1
391
self._lock_mode = self._lock_count = None
393
def abspath(self, name):
394
"""Return absolute filename for something in the branch"""
395
return os.path.join(self.base, name)
397
def relpath(self, path):
398
"""Return path relative to this branch of something inside it.
400
Raises an error if path is not in this branch."""
401
return _relpath(self.base, path)
403
def controlfilename(self, file_or_path):
404
"""Return location relative to branch."""
405
if isinstance(file_or_path, basestring):
406
file_or_path = [file_or_path]
407
return os.path.join(self.base, bzrlib.BZRDIR, *file_or_path)
410
def controlfile(self, file_or_path, mode='r'):
411
"""Open a control file for this branch.
413
There are two classes of file in the control directory: text
414
and binary. binary files are untranslated byte streams. Text
415
control files are stored with Unix newlines and in UTF-8, even
416
if the platform or locale defaults are different.
418
Controlfiles should almost never be opened in write mode but
419
rather should be atomically copied and replaced using atomicfile.
422
fn = self.controlfilename(file_or_path)
424
if mode == 'rb' or mode == 'wb':
425
return file(fn, mode)
426
elif mode == 'r' or mode == 'w':
427
# open in binary mode anyhow so there's no newline translation;
428
# codecs uses line buffering by default; don't want that.
430
return codecs.open(fn, mode + 'b', 'utf-8',
433
raise BzrError("invalid controlfile mode %r" % mode)
435
def _make_control(self):
436
from bzrlib.inventory import Inventory
438
os.mkdir(self.controlfilename([]))
439
self.controlfile('README', 'w').write(
440
"This is a Bazaar-NG control directory.\n"
441
"Do not change any files in this directory.\n")
442
self.controlfile('branch-format', 'w').write(BZR_BRANCH_FORMAT)
443
for d in ('text-store', 'inventory-store', 'revision-store'):
444
os.mkdir(self.controlfilename(d))
445
for f in ('revision-history', 'merged-patches',
446
'pending-merged-patches', 'branch-name',
449
self.controlfile(f, 'w').write('')
450
mutter('created control directory in ' + self.base)
452
# if we want per-tree root ids then this is the place to set
453
# them; they're not needed for now and so ommitted for
455
f = self.controlfile('inventory','w')
456
bzrlib.xml.serializer_v4.write_inventory(Inventory(), f)
459
def _check_format(self):
460
"""Check this branch format is supported.
462
The current tool only supports the current unstable format.
464
In the future, we might need different in-memory Branch
465
classes to support downlevel branches. But not yet.
467
# This ignores newlines so that we can open branches created
468
# on Windows from Linux and so on. I think it might be better
469
# to always make all internal files in unix format.
470
fmt = self.controlfile('branch-format', 'r').read()
471
fmt = fmt.replace('\r\n', '\n')
472
if fmt != BZR_BRANCH_FORMAT:
473
raise BzrError('sorry, branch format %r not supported' % fmt,
474
['use a different bzr version',
475
'or remove the .bzr directory and "bzr init" again'])
477
def get_root_id(self):
478
"""Return the id of this branches root"""
479
inv = self.read_working_inventory()
480
return inv.root.file_id
482
def set_root_id(self, file_id):
483
inv = self.read_working_inventory()
484
orig_root_id = inv.root.file_id
485
del inv._byid[inv.root.file_id]
486
inv.root.file_id = file_id
487
inv._byid[inv.root.file_id] = inv.root
490
if entry.parent_id in (None, orig_root_id):
491
entry.parent_id = inv.root.file_id
492
self._write_inventory(inv)
494
def read_working_inventory(self):
495
"""Read the working inventory."""
496
from bzrlib.inventory import Inventory
499
# ElementTree does its own conversion from UTF-8, so open in
501
f = self.controlfile('inventory', 'rb')
502
return bzrlib.xml.serializer_v4.read_inventory(f)
507
def _write_inventory(self, inv):
508
"""Update the working inventory.
510
That is to say, the inventory describing changes underway, that
511
will be committed to the next revision.
513
from bzrlib.atomicfile import AtomicFile
517
f = AtomicFile(self.controlfilename('inventory'), 'wb')
519
bzrlib.xml.serializer_v4.write_inventory(inv, f)
526
mutter('wrote working inventory')
529
inventory = property(read_working_inventory, _write_inventory, None,
530
"""Inventory for the working copy.""")
533
def add(self, files, ids=None):
534
"""Make files versioned.
536
Note that the command line normally calls smart_add instead,
537
which can automatically recurse.
539
This puts the files in the Added state, so that they will be
540
recorded by the next commit.
543
List of paths to add, relative to the base of the tree.
546
If set, use these instead of automatically generated ids.
547
Must be the same length as the list of files, but may
548
contain None for ids that are to be autogenerated.
550
TODO: Perhaps have an option to add the ids even if the files do
553
TODO: Perhaps yield the ids and paths as they're added.
555
# TODO: Re-adding a file that is removed in the working copy
556
# should probably put it back with the previous ID.
557
if isinstance(files, basestring):
558
assert(ids is None or isinstance(ids, basestring))
564
ids = [None] * len(files)
566
assert(len(ids) == len(files))
570
inv = self.read_working_inventory()
571
for f,file_id in zip(files, ids):
572
if is_control_file(f):
573
raise BzrError("cannot add control file %s" % quotefn(f))
578
raise BzrError("cannot add top-level %r" % f)
580
fullpath = os.path.normpath(self.abspath(f))
583
kind = file_kind(fullpath)
585
# maybe something better?
586
raise BzrError('cannot add: not a regular file or directory: %s' % quotefn(f))
588
if kind != 'file' and kind != 'directory':
589
raise BzrError('cannot add: not a regular file or directory: %s' % quotefn(f))
592
file_id = gen_file_id(f)
593
inv.add_path(f, kind=kind, file_id=file_id)
595
mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
597
self._write_inventory(inv)
602
def print_file(self, file, revno):
603
"""Print `file` to stdout."""
606
tree = self.revision_tree(self.lookup_revision(revno))
607
# use inventory as it was in that revision
608
file_id = tree.inventory.path2id(file)
610
raise BzrError("%r is not present in revision %s" % (file, revno))
611
tree.print_file(file_id)
616
def remove(self, files, verbose=False):
617
"""Mark nominated files for removal from the inventory.
619
This does not remove their text. This does not run on
621
TODO: Refuse to remove modified files unless --force is given?
623
TODO: Do something useful with directories.
625
TODO: Should this remove the text or not? Tough call; not
626
removing may be useful and the user can just use use rm, and
627
is the opposite of add. Removing it is consistent with most
628
other tools. Maybe an option.
630
## TODO: Normalize names
631
## TODO: Remove nested loops; better scalability
632
if isinstance(files, basestring):
638
tree = self.working_tree()
641
# do this before any modifications
645
raise BzrError("cannot remove unversioned file %s" % quotefn(f))
646
mutter("remove inventory entry %s {%s}" % (quotefn(f), fid))
648
# having remove it, it must be either ignored or unknown
649
if tree.is_ignored(f):
653
show_status(new_status, inv[fid].kind, quotefn(f))
656
self._write_inventory(inv)
661
# FIXME: this doesn't need to be a branch method
662
def set_inventory(self, new_inventory_list):
663
from bzrlib.inventory import Inventory, InventoryEntry
664
inv = Inventory(self.get_root_id())
665
for path, file_id, parent, kind in new_inventory_list:
666
name = os.path.basename(path)
669
inv.add(InventoryEntry(file_id, name, kind, parent))
670
self._write_inventory(inv)
674
"""Return all unknown files.
676
These are files in the working directory that are not versioned or
677
control files or ignored.
679
>>> b = ScratchBranch(files=['foo', 'foo~'])
680
>>> list(b.unknowns())
683
>>> list(b.unknowns())
686
>>> list(b.unknowns())
689
return self.working_tree().unknowns()
692
def append_revision(self, *revision_ids):
693
from bzrlib.atomicfile import AtomicFile
695
for revision_id in revision_ids:
696
mutter("add {%s} to revision-history" % revision_id)
698
rev_history = self.revision_history()
699
rev_history.extend(revision_ids)
701
f = AtomicFile(self.controlfilename('revision-history'))
703
for rev_id in rev_history:
710
def get_revision_xml_file(self, revision_id):
711
"""Return XML file object for revision object."""
712
if not revision_id or not isinstance(revision_id, basestring):
713
raise InvalidRevisionId(revision_id)
718
return self.revision_store[revision_id]
720
raise bzrlib.errors.NoSuchRevision(self, revision_id)
726
get_revision_xml = get_revision_xml_file
729
def get_revision(self, revision_id):
730
"""Return the Revision object for a named revision"""
731
xml_file = self.get_revision_xml_file(revision_id)
734
r = bzrlib.xml.serializer_v4.read_revision(xml_file)
735
except SyntaxError, e:
736
raise bzrlib.errors.BzrError('failed to unpack revision_xml',
740
assert r.revision_id == revision_id
744
def get_revision_delta(self, revno):
745
"""Return the delta for one revision.
747
The delta is relative to its mainline predecessor, or the
748
empty tree for revision 1.
750
assert isinstance(revno, int)
751
rh = self.revision_history()
752
if not (1 <= revno <= len(rh)):
753
raise InvalidRevisionNumber(revno)
755
# revno is 1-based; list is 0-based
757
new_tree = self.revision_tree(rh[revno-1])
759
old_tree = EmptyTree()
761
old_tree = self.revision_tree(rh[revno-2])
763
return compare_trees(old_tree, new_tree)
767
def get_revision_sha1(self, revision_id):
768
"""Hash the stored value of a revision, and return it."""
769
# In the future, revision entries will be signed. At that
770
# point, it is probably best *not* to include the signature
771
# in the revision hash. Because that lets you re-sign
772
# the revision, (add signatures/remove signatures) and still
773
# have all hash pointers stay consistent.
774
# But for now, just hash the contents.
775
return bzrlib.osutils.sha_file(self.get_revision_xml(revision_id))
778
def get_inventory(self, inventory_id):
779
"""Get Inventory object by hash.
781
TODO: Perhaps for this and similar methods, take a revision
782
parameter which can be either an integer revno or a
784
from bzrlib.inventory import Inventory
786
f = self.get_inventory_xml_file(inventory_id)
787
return bzrlib.xml.serializer_v4.read_inventory(f)
790
def get_inventory_xml(self, inventory_id):
791
"""Get inventory XML as a file object."""
792
return self.inventory_store[inventory_id]
794
get_inventory_xml_file = get_inventory_xml
797
def get_inventory_sha1(self, inventory_id):
798
"""Return the sha1 hash of the inventory entry
800
return sha_file(self.get_inventory_xml(inventory_id))
803
def get_revision_inventory(self, revision_id):
804
"""Return inventory of a past revision."""
805
# bzr 0.0.6 imposes the constraint that the inventory_id
806
# must be the same as its revision, so this is trivial.
807
if revision_id == None:
808
from bzrlib.inventory import Inventory
809
return Inventory(self.get_root_id())
811
return self.get_inventory(revision_id)
814
def revision_history(self):
815
"""Return sequence of revision hashes on to this branch.
817
>>> ScratchBranch().revision_history()
822
return [l.rstrip('\r\n') for l in
823
self.controlfile('revision-history', 'r').readlines()]
828
def common_ancestor(self, other, self_revno=None, other_revno=None):
830
>>> from bzrlib.commit import commit
831
>>> sb = ScratchBranch(files=['foo', 'foo~'])
832
>>> sb.common_ancestor(sb) == (None, None)
834
>>> commit(sb, "Committing first revision", verbose=False)
835
>>> sb.common_ancestor(sb)[0]
837
>>> clone = sb.clone()
838
>>> commit(sb, "Committing second revision", verbose=False)
839
>>> sb.common_ancestor(sb)[0]
841
>>> sb.common_ancestor(clone)[0]
843
>>> commit(clone, "Committing divergent second revision",
845
>>> sb.common_ancestor(clone)[0]
847
>>> sb.common_ancestor(clone) == clone.common_ancestor(sb)
849
>>> sb.common_ancestor(sb) != clone.common_ancestor(clone)
851
>>> clone2 = sb.clone()
852
>>> sb.common_ancestor(clone2)[0]
854
>>> sb.common_ancestor(clone2, self_revno=1)[0]
856
>>> sb.common_ancestor(clone2, other_revno=1)[0]
859
my_history = self.revision_history()
860
other_history = other.revision_history()
861
if self_revno is None:
862
self_revno = len(my_history)
863
if other_revno is None:
864
other_revno = len(other_history)
865
indices = range(min((self_revno, other_revno)))
868
if my_history[r] == other_history[r]:
869
return r+1, my_history[r]
874
"""Return current revision number for this branch.
876
That is equivalent to the number of revisions committed to
879
return len(self.revision_history())
882
def last_patch(self):
883
"""Return last patch hash, or None if no history.
885
ph = self.revision_history()
892
def missing_revisions(self, other, stop_revision=None, diverged_ok=False):
894
If self and other have not diverged, return a list of the revisions
895
present in other, but missing from self.
897
>>> from bzrlib.commit import commit
898
>>> bzrlib.trace.silent = True
899
>>> br1 = ScratchBranch()
900
>>> br2 = ScratchBranch()
901
>>> br1.missing_revisions(br2)
903
>>> commit(br2, "lala!", rev_id="REVISION-ID-1")
904
>>> br1.missing_revisions(br2)
906
>>> br2.missing_revisions(br1)
908
>>> commit(br1, "lala!", rev_id="REVISION-ID-1")
909
>>> br1.missing_revisions(br2)
911
>>> commit(br2, "lala!", rev_id="REVISION-ID-2A")
912
>>> br1.missing_revisions(br2)
914
>>> commit(br1, "lala!", rev_id="REVISION-ID-2B")
915
>>> br1.missing_revisions(br2)
916
Traceback (most recent call last):
917
DivergedBranches: These branches have diverged.
919
self_history = self.revision_history()
920
self_len = len(self_history)
921
other_history = other.revision_history()
922
other_len = len(other_history)
923
common_index = min(self_len, other_len) -1
924
if common_index >= 0 and \
925
self_history[common_index] != other_history[common_index]:
926
raise DivergedBranches(self, other)
928
if stop_revision is None:
929
stop_revision = other_len
930
elif stop_revision > other_len:
931
raise bzrlib.errors.NoSuchRevision(self, stop_revision)
933
return other_history[self_len:stop_revision]
936
def update_revisions(self, other, stop_revision=None):
937
"""Pull in all new revisions from other branch.
939
from bzrlib.fetch import greedy_fetch
941
pb = bzrlib.ui.ui_factory.progress_bar()
942
pb.update('comparing histories')
944
revision_ids = self.missing_revisions(other, stop_revision)
946
if len(revision_ids) > 0:
947
count = greedy_fetch(self, other, revision_ids[-1], pb)[0]
950
self.append_revision(*revision_ids)
951
## note("Added %d revisions." % count)
954
def install_revisions(self, other, revision_ids, pb):
955
if hasattr(other.revision_store, "prefetch"):
956
other.revision_store.prefetch(revision_ids)
957
if hasattr(other.inventory_store, "prefetch"):
958
inventory_ids = [other.get_revision(r).inventory_id
959
for r in revision_ids]
960
other.inventory_store.prefetch(inventory_ids)
963
pb = bzrlib.ui.ui_factory.progress_bar()
970
for i, rev_id in enumerate(revision_ids):
971
pb.update('fetching revision', i+1, len(revision_ids))
973
rev = other.get_revision(rev_id)
974
except bzrlib.errors.NoSuchRevision:
978
revisions.append(rev)
979
inv = other.get_inventory(str(rev.inventory_id))
980
for key, entry in inv.iter_entries():
981
if entry.text_id is None:
983
if entry.text_id not in self.text_store:
984
needed_texts.add(entry.text_id)
988
count, cp_fail = self.text_store.copy_multi(other.text_store,
990
#print "Added %d texts." % count
991
inventory_ids = [ f.inventory_id for f in revisions ]
992
count, cp_fail = self.inventory_store.copy_multi(other.inventory_store,
994
#print "Added %d inventories." % count
995
revision_ids = [ f.revision_id for f in revisions]
997
count, cp_fail = self.revision_store.copy_multi(other.revision_store,
1000
assert len(cp_fail) == 0
1001
return count, failures
1004
def commit(self, *args, **kw):
1005
from bzrlib.commit import commit
1006
commit(self, *args, **kw)
1009
def lookup_revision(self, revision):
1010
"""Return the revision identifier for a given revision information."""
1011
revno, info = self._get_revision_info(revision)
1015
def revision_id_to_revno(self, revision_id):
1016
"""Given a revision id, return its revno"""
1017
history = self.revision_history()
1019
return history.index(revision_id) + 1
1021
raise bzrlib.errors.NoSuchRevision(self, revision_id)
1024
def get_revision_info(self, revision):
1025
"""Return (revno, revision id) for revision identifier.
1027
revision can be an integer, in which case it is assumed to be revno (though
1028
this will translate negative values into positive ones)
1029
revision can also be a string, in which case it is parsed for something like
1030
'date:' or 'revid:' etc.
1032
revno, rev_id = self._get_revision_info(revision)
1034
raise bzrlib.errors.NoSuchRevision(self, revision)
1035
return revno, rev_id
1037
def get_rev_id(self, revno, history=None):
1038
"""Find the revision id of the specified revno."""
1042
history = self.revision_history()
1043
elif revno <= 0 or revno > len(history):
1044
raise bzrlib.errors.NoSuchRevision(self, revno)
1045
return history[revno - 1]
1047
def _get_revision_info(self, revision):
1048
"""Return (revno, revision id) for revision specifier.
1050
revision can be an integer, in which case it is assumed to be revno
1051
(though this will translate negative values into positive ones)
1052
revision can also be a string, in which case it is parsed for something
1053
like 'date:' or 'revid:' etc.
1055
A revid is always returned. If it is None, the specifier referred to
1056
the null revision. If the revid does not occur in the revision
1057
history, revno will be None.
1060
if revision is None:
1063
try:# Convert to int if possible
1064
revision = int(revision)
1067
revs = self.revision_history()
1068
if isinstance(revision, int):
1070
revno = len(revs) + revision + 1
1073
rev_id = self.get_rev_id(revno, revs)
1074
elif isinstance(revision, basestring):
1075
for prefix, func in Branch.REVISION_NAMESPACES.iteritems():
1076
if revision.startswith(prefix):
1077
result = func(self, revs, revision)
1079
revno, rev_id = result
1082
rev_id = self.get_rev_id(revno, revs)
1085
raise BzrError('No namespace registered for string: %r' %
1088
raise TypeError('Unhandled revision type %s' % revision)
1092
raise bzrlib.errors.NoSuchRevision(self, revision)
1093
return revno, rev_id
1095
def revision_tree(self, revision_id):
1096
"""Return Tree for a revision on this branch.
1098
`revision_id` may be None for the null revision, in which case
1099
an `EmptyTree` is returned."""
1100
# TODO: refactor this to use an existing revision object
1101
# so we don't need to read it in twice.
1102
if revision_id == None:
1105
inv = self.get_revision_inventory(revision_id)
1106
return RevisionTree(self.text_store, inv)
1109
def working_tree(self):
1110
"""Return a `Tree` for the working copy."""
1111
from bzrlib.workingtree import WorkingTree
1112
return WorkingTree(self.base, self.read_working_inventory())
1115
def basis_tree(self):
1116
"""Return `Tree` object for last revision.
1118
If there are no revisions yet, return an `EmptyTree`.
1120
r = self.last_patch()
1124
return RevisionTree(self.text_store, self.get_revision_inventory(r))
1128
def rename_one(self, from_rel, to_rel):
1131
This can change the directory or the filename or both.
1135
tree = self.working_tree()
1136
inv = tree.inventory
1137
if not tree.has_filename(from_rel):
1138
raise BzrError("can't rename: old working file %r does not exist" % from_rel)
1139
if tree.has_filename(to_rel):
1140
raise BzrError("can't rename: new working file %r already exists" % to_rel)
1142
file_id = inv.path2id(from_rel)
1144
raise BzrError("can't rename: old name %r is not versioned" % from_rel)
1146
if inv.path2id(to_rel):
1147
raise BzrError("can't rename: new name %r is already versioned" % to_rel)
1149
to_dir, to_tail = os.path.split(to_rel)
1150
to_dir_id = inv.path2id(to_dir)
1151
if to_dir_id == None and to_dir != '':
1152
raise BzrError("can't determine destination directory id for %r" % to_dir)
1154
mutter("rename_one:")
1155
mutter(" file_id {%s}" % file_id)
1156
mutter(" from_rel %r" % from_rel)
1157
mutter(" to_rel %r" % to_rel)
1158
mutter(" to_dir %r" % to_dir)
1159
mutter(" to_dir_id {%s}" % to_dir_id)
1161
inv.rename(file_id, to_dir_id, to_tail)
1163
from_abs = self.abspath(from_rel)
1164
to_abs = self.abspath(to_rel)
1166
os.rename(from_abs, to_abs)
1168
raise BzrError("failed to rename %r to %r: %s"
1169
% (from_abs, to_abs, e[1]),
1170
["rename rolled back"])
1172
self._write_inventory(inv)
1177
def move(self, from_paths, to_name):
1180
to_name must exist as a versioned directory.
1182
If to_name exists and is a directory, the files are moved into
1183
it, keeping their old names. If it is a directory,
1185
Note that to_name is only the last component of the new name;
1186
this doesn't change the directory.
1188
This returns a list of (from_path, to_path) pairs for each
1189
entry that is moved.
1194
## TODO: Option to move IDs only
1195
assert not isinstance(from_paths, basestring)
1196
tree = self.working_tree()
1197
inv = tree.inventory
1198
to_abs = self.abspath(to_name)
1199
if not isdir(to_abs):
1200
raise BzrError("destination %r is not a directory" % to_abs)
1201
if not tree.has_filename(to_name):
1202
raise BzrError("destination %r not in working directory" % to_abs)
1203
to_dir_id = inv.path2id(to_name)
1204
if to_dir_id == None and to_name != '':
1205
raise BzrError("destination %r is not a versioned directory" % to_name)
1206
to_dir_ie = inv[to_dir_id]
1207
if to_dir_ie.kind not in ('directory', 'root_directory'):
1208
raise BzrError("destination %r is not a directory" % to_abs)
1210
to_idpath = inv.get_idpath(to_dir_id)
1212
for f in from_paths:
1213
if not tree.has_filename(f):
1214
raise BzrError("%r does not exist in working tree" % f)
1215
f_id = inv.path2id(f)
1217
raise BzrError("%r is not versioned" % f)
1218
name_tail = splitpath(f)[-1]
1219
dest_path = appendpath(to_name, name_tail)
1220
if tree.has_filename(dest_path):
1221
raise BzrError("destination %r already exists" % dest_path)
1222
if f_id in to_idpath:
1223
raise BzrError("can't move %r to a subdirectory of itself" % f)
1225
# OK, so there's a race here, it's possible that someone will
1226
# create a file in this interval and then the rename might be
1227
# left half-done. But we should have caught most problems.
1229
for f in from_paths:
1230
name_tail = splitpath(f)[-1]
1231
dest_path = appendpath(to_name, name_tail)
1232
result.append((f, dest_path))
1233
inv.rename(inv.path2id(f), to_dir_id, name_tail)
1235
os.rename(self.abspath(f), self.abspath(dest_path))
1237
raise BzrError("failed to rename %r to %r: %s" % (f, dest_path, e[1]),
1238
["rename rolled back"])
1240
self._write_inventory(inv)
1247
def revert(self, filenames, old_tree=None, backups=True):
1248
"""Restore selected files to the versions from a previous tree.
1251
If true (default) backups are made of files before
1254
from bzrlib.errors import NotVersionedError, BzrError
1255
from bzrlib.atomicfile import AtomicFile
1256
from bzrlib.osutils import backup_file
1258
inv = self.read_working_inventory()
1259
if old_tree is None:
1260
old_tree = self.basis_tree()
1261
old_inv = old_tree.inventory
1264
for fn in filenames:
1265
file_id = inv.path2id(fn)
1267
raise NotVersionedError("not a versioned file", fn)
1268
if not old_inv.has_id(file_id):
1269
raise BzrError("file not present in old tree", fn, file_id)
1270
nids.append((fn, file_id))
1272
# TODO: Rename back if it was previously at a different location
1274
# TODO: If given a directory, restore the entire contents from
1275
# the previous version.
1277
# TODO: Make a backup to a temporary file.
1279
# TODO: If the file previously didn't exist, delete it?
1280
for fn, file_id in nids:
1283
f = AtomicFile(fn, 'wb')
1285
f.write(old_tree.get_file(file_id).read())
1291
def pending_merges(self):
1292
"""Return a list of pending merges.
1294
These are revisions that have been merged into the working
1295
directory but not yet committed.
1297
cfn = self.controlfilename('pending-merges')
1298
if not os.path.exists(cfn):
1301
for l in self.controlfile('pending-merges', 'r').readlines():
1302
p.append(l.rstrip('\n'))
1306
def add_pending_merge(self, revision_id):
1307
from bzrlib.revision import validate_revision_id
1309
validate_revision_id(revision_id)
1311
p = self.pending_merges()
1312
if revision_id in p:
1314
p.append(revision_id)
1315
self.set_pending_merges(p)
1318
def set_pending_merges(self, rev_list):
1319
from bzrlib.atomicfile import AtomicFile
1322
f = AtomicFile(self.controlfilename('pending-merges'))
1333
def get_parent(self):
1334
"""Return the parent location of the branch.
1336
This is the default location for push/pull/missing. The usual
1337
pattern is that the user can override it by specifying a
1341
_locs = ['parent', 'pull', 'x-pull']
1344
return self.controlfile(l, 'r').read().strip('\n')
1346
if e.errno != errno.ENOENT:
1351
def set_parent(self, url):
1352
# TODO: Maybe delete old location files?
1353
from bzrlib.atomicfile import AtomicFile
1356
f = AtomicFile(self.controlfilename('parent'))
1365
def check_revno(self, revno):
1367
Check whether a revno corresponds to any revision.
1368
Zero (the NULL revision) is considered valid.
1371
self.check_real_revno(revno)
1373
def check_real_revno(self, revno):
1375
Check whether a revno corresponds to a real revision.
1376
Zero (the NULL revision) is considered invalid
1378
if revno < 1 or revno > self.revno():
1379
raise InvalidRevisionNumber(revno)
1384
class ScratchBranch(LocalBranch):
1385
"""Special test class: a branch that cleans up after itself.
1387
>>> b = ScratchBranch()
1395
def __init__(self, files=[], dirs=[], base=None):
1396
"""Make a test branch.
1398
This creates a temporary directory and runs init-tree in it.
1400
If any files are listed, they are created in the working copy.
1402
from tempfile import mkdtemp
1407
LocalBranch.__init__(self, base, init=init)
1409
os.mkdir(self.abspath(d))
1412
file(os.path.join(self.base, f), 'w').write('content of %s' % f)
1417
>>> orig = ScratchBranch(files=["file1", "file2"])
1418
>>> clone = orig.clone()
1419
>>> os.path.samefile(orig.base, clone.base)
1421
>>> os.path.isfile(os.path.join(clone.base, "file1"))
1424
from shutil import copytree
1425
from tempfile import mkdtemp
1428
copytree(self.base, base, symlinks=True)
1429
return ScratchBranch(base=base)
1437
"""Destroy the test branch, removing the scratch directory."""
1438
from shutil import rmtree
1441
mutter("delete ScratchBranch %s" % self.base)
1444
# Work around for shutil.rmtree failing on Windows when
1445
# readonly files are encountered
1446
mutter("hit exception in destroying ScratchBranch: %s" % e)
1447
for root, dirs, files in os.walk(self.base, topdown=False):
1449
os.chmod(os.path.join(root, name), 0700)
1455
######################################################################
1459
def is_control_file(filename):
1460
## FIXME: better check
1461
filename = os.path.normpath(filename)
1462
while filename != '':
1463
head, tail = os.path.split(filename)
1464
## mutter('check %r for control file' % ((head, tail), ))
1465
if tail == bzrlib.BZRDIR:
1467
if filename == head:
1474
def gen_file_id(name):
1475
"""Return new file id.
1477
This should probably generate proper UUIDs, but for the moment we
1478
cope with just randomness because running uuidgen every time is
1481
from binascii import hexlify
1482
from time import time
1484
# get last component
1485
idx = name.rfind('/')
1487
name = name[idx+1 : ]
1488
idx = name.rfind('\\')
1490
name = name[idx+1 : ]
1492
# make it not a hidden file
1493
name = name.lstrip('.')
1495
# remove any wierd characters; we don't escape them but rather
1496
# just pull them out
1497
name = re.sub(r'[^\w.]', '', name)
1499
s = hexlify(rand_bytes(8))
1500
return '-'.join((name, compact_date(time()), s))
1504
"""Return a new tree-root file id."""
1505
return gen_file_id('TREE_ROOT')
1508
def copy_branch(branch_from, to_location, revision=None):
1509
"""Copy branch_from into the existing directory to_location.
1512
If not None, only revisions up to this point will be copied.
1513
The head of the new branch will be that revision.
1516
The name of a local directory that exists but is empty.
1518
from bzrlib.merge import merge
1520
assert isinstance(branch_from, Branch)
1521
assert isinstance(to_location, basestring)
1523
br_to = Branch(to_location, init=True)
1524
br_to.set_root_id(branch_from.get_root_id())
1525
if revision is None:
1526
revno = branch_from.revno()
1528
revno, rev_id = branch_from.get_revision_info(revision)
1529
br_to.update_revisions(branch_from, stop_revision=revno)
1530
merge((to_location, -1), (to_location, 0), this_dir=to_location,
1531
check_clean=False, ignore_zero=True)
1533
from_location = branch_from.base
1534
br_to.set_parent(branch_from.base)