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
22
from cStringIO import StringIO
26
from bzrlib.trace import mutter, note
27
from bzrlib.osutils import (isdir, quotefn, compact_date, rand_bytes,
28
rename, splitpath, sha_file, appendpath,
30
from bzrlib.errors import (BzrError, InvalidRevisionNumber, InvalidRevisionId,
31
NoSuchRevision, HistoryMissing, NotBranchError,
32
DivergedBranches, LockError, UnlistableStore,
33
UnlistableBranch, NoSuchFile)
34
from bzrlib.textui import show_status
35
from bzrlib.revision import Revision, validate_revision_id, is_ancestor
36
from bzrlib.delta import compare_trees
37
from bzrlib.tree import EmptyTree, RevisionTree
38
from bzrlib.inventory import Inventory
39
from bzrlib.weavestore import WeaveStore
40
from bzrlib.store import copy_all
41
from bzrlib.store.compressed_text import CompressedTextStore
42
from bzrlib.transport import Transport
47
BZR_BRANCH_FORMAT_4 = "Bazaar-NG branch, format 0.0.4\n"
48
BZR_BRANCH_FORMAT_5 = "Bazaar-NG branch, format 5\n"
49
## TODO: Maybe include checks for common corruption of newlines, etc?
52
# TODO: Some operations like log might retrieve the same revisions
53
# repeatedly to calculate deltas. We could perhaps have a weakref
54
# cache in memory to make this faster. In general anything can be
55
# cached in memory between lock and unlock operations.
57
def find_branch(*ignored, **ignored_too):
58
# XXX: leave this here for about one release, then remove it
59
raise NotImplementedError('find_branch() is not supported anymore, '
60
'please use one of the new branch constructors')
61
def _relpath(base, path):
62
"""Return path relative to base, or raise exception.
64
The path may be either an absolute path or a path relative to the
65
current working directory.
67
Lifted out of Branch.relpath for ease of testing.
69
os.path.commonprefix (python2.4) has a bad bug that it works just
70
on string prefixes, assuming that '/u' is a prefix of '/u2'. This
71
avoids that problem."""
72
rp = os.path.abspath(path)
76
while len(head) >= len(base):
79
head, tail = os.path.split(head)
83
raise NotBranchError("path %r is not within branch %r" % (rp, base))
88
def find_branch_root(t):
89
"""Find the branch root enclosing the transport's base.
91
t is a Transport object.
93
It is not necessary that the base of t exists.
95
Basically we keep looking up until we find the control directory or
96
run into the root. If there isn't one, raises NotBranchError.
100
if t.has(bzrlib.BZRDIR):
102
new_t = t.clone('..')
103
if new_t.base == t.base:
104
# reached the root, whatever that may be
105
raise NotBranchError('%s is not in a branch' % orig_base)
109
######################################################################
112
class Branch(object):
113
"""Branch holding a history of revisions.
116
Base directory/url of the branch.
120
def __init__(self, *ignored, **ignored_too):
121
raise NotImplementedError('The Branch class is abstract')
124
def open_downlevel(base):
125
"""Open a branch which may be of an old format.
127
Only local branches are supported."""
128
return _Branch(base, relax_version_check=True)
132
"""Open an existing branch, rooted at 'base' (url)"""
133
t = bzrlib.transport.transport(base)
137
def open_containing(url):
138
"""Open an existing branch which contains url.
140
This probes for a branch at url, and searches upwards from there.
142
t = bzrlib.transport.transport(url)
143
t = find_branch_root(t)
147
def initialize(base):
148
"""Create a new branch, rooted at 'base' (url)"""
149
t = bzrlib.transport.transport(base)
150
return _Branch(t, init=True)
152
def setup_caching(self, cache_root):
153
"""Subclasses that care about caching should override this, and set
154
up cached stores located under cache_root.
158
class _Branch(Branch):
159
"""A branch stored in the actual filesystem.
161
Note that it's "local" in the context of the filesystem; it doesn't
162
really matter if it's on an nfs/smb/afs/coda/... share, as long as
163
it's writable, and can be accessed via the normal filesystem API.
169
If _lock_mode is true, a positive count of the number of times the
173
Lock object from bzrlib.lock.
175
# We actually expect this class to be somewhat short-lived; part of its
176
# purpose is to try to isolate what bits of the branch logic are tied to
177
# filesystem access, so that in a later step, we can extricate them to
178
# a separarte ("storage") class.
182
_inventory_weave = None
184
# Map some sort of prefix into a namespace
185
# stuff like "revno:10", "revid:", etc.
186
# This should match a prefix with a function which accepts
187
REVISION_NAMESPACES = {}
189
def push_stores(self, branch_to):
190
"""Copy the content of this branches store to branch_to."""
191
if (self._branch_format != branch_to._branch_format
192
or self._branch_format != 4):
193
from bzrlib.fetch import greedy_fetch
194
mutter("falling back to fetch logic to push between %s(%s) and %s(%s)",
195
self, self._branch_format, branch_to, branch_to._branch_format)
196
greedy_fetch(to_branch=branch_to, from_branch=self,
197
revision=self.last_revision())
200
store_pairs = ((self.text_store, branch_to.text_store),
201
(self.inventory_store, branch_to.inventory_store),
202
(self.revision_store, branch_to.revision_store))
204
for from_store, to_store in store_pairs:
205
copy_all(from_store, to_store)
206
except UnlistableStore:
207
raise UnlistableBranch(from_store)
209
def __init__(self, transport, init=False,
210
relax_version_check=False):
211
"""Create new branch object at a particular location.
213
transport -- A Transport object, defining how to access files.
214
(If a string, transport.transport() will be used to
215
create a Transport object)
217
init -- If True, create new control files in a previously
218
unversioned directory. If False, the branch must already
221
relax_version_check -- If true, the usual check for the branch
222
version is not applied. This is intended only for
223
upgrade/recovery type use; it's not guaranteed that
224
all operations will work on old format branches.
226
In the test suite, creation of new trees is tested using the
227
`ScratchBranch` class.
229
assert isinstance(transport, Transport)
230
self._transport = transport
233
self._check_format(relax_version_check)
234
cfn = self.controlfilename
235
if self._branch_format == 4:
236
self.inventory_store = CompressedTextStore(cfn('inventory-store'))
237
self.text_store = CompressedTextStore(cfn('text-store'))
238
elif self._branch_format == 5:
239
self.control_weaves = WeaveStore(cfn([]))
240
self.weave_store = WeaveStore(cfn('weaves'))
242
# FIXME: Unify with make_control_files
243
self.control_weaves.put_empty_weave('inventory')
244
self.control_weaves.put_empty_weave('ancestry')
245
self.revision_store = CompressedTextStore(cfn('revision-store'))
248
return '%s(%r)' % (self.__class__.__name__, self._transport.base)
255
if self._lock_mode or self._lock:
256
# XXX: This should show something every time, and be suitable for
257
# headless operation and embedding
258
warn("branch %r was not explicitly unlocked" % self)
261
# TODO: It might be best to do this somewhere else,
262
# but it is nice for a Branch object to automatically
263
# cache it's information.
264
# Alternatively, we could have the Transport objects cache requests
265
# See the earlier discussion about how major objects (like Branch)
266
# should never expect their __del__ function to run.
267
if hasattr(self, 'cache_root') and self.cache_root is not None:
270
shutil.rmtree(self.cache_root)
273
self.cache_root = None
277
return self._transport.base
280
base = property(_get_base)
283
def lock_write(self):
284
# TODO: Upgrade locking to support using a Transport,
285
# and potentially a remote locking protocol
287
if self._lock_mode != 'w':
288
raise LockError("can't upgrade to a write lock from %r" %
290
self._lock_count += 1
292
self._lock = self._transport.lock_write(
293
self._rel_controlfilename('branch-lock'))
294
self._lock_mode = 'w'
300
assert self._lock_mode in ('r', 'w'), \
301
"invalid lock mode %r" % self._lock_mode
302
self._lock_count += 1
304
self._lock = self._transport.lock_read(
305
self._rel_controlfilename('branch-lock'))
306
self._lock_mode = 'r'
310
if not self._lock_mode:
311
raise LockError('branch %r is not locked' % (self))
313
if self._lock_count > 1:
314
self._lock_count -= 1
318
self._lock_mode = self._lock_count = None
320
def abspath(self, name):
321
"""Return absolute filename for something in the branch"""
322
return self._transport.abspath(name)
324
def relpath(self, path):
325
"""Return path relative to this branch of something inside it.
327
Raises an error if path is not in this branch."""
328
return self._transport.relpath(path)
331
def _rel_controlfilename(self, file_or_path):
332
if isinstance(file_or_path, basestring):
333
file_or_path = [file_or_path]
334
return [bzrlib.BZRDIR] + file_or_path
336
def controlfilename(self, file_or_path):
337
"""Return location relative to branch."""
338
return self._transport.abspath(self._rel_controlfilename(file_or_path))
341
def controlfile(self, file_or_path, mode='r'):
342
"""Open a control file for this branch.
344
There are two classes of file in the control directory: text
345
and binary. binary files are untranslated byte streams. Text
346
control files are stored with Unix newlines and in UTF-8, even
347
if the platform or locale defaults are different.
349
Controlfiles should almost never be opened in write mode but
350
rather should be atomically copied and replaced using atomicfile.
354
relpath = self._rel_controlfilename(file_or_path)
355
#TODO: codecs.open() buffers linewise, so it was overloaded with
356
# a much larger buffer, do we need to do the same for getreader/getwriter?
358
return self._transport.get(relpath)
360
raise BzrError("Branch.controlfile(mode='wb') is not supported, use put_controlfiles")
362
return codecs.getreader('utf-8')(self._transport.get(relpath), errors='replace')
364
raise BzrError("Branch.controlfile(mode='w') is not supported, use put_controlfiles")
366
raise BzrError("invalid controlfile mode %r" % mode)
368
def put_controlfile(self, path, f, encode=True):
369
"""Write an entry as a controlfile.
371
:param path: The path to put the file, relative to the .bzr control
373
:param f: A file-like or string object whose contents should be copied.
374
:param encode: If true, encode the contents as utf-8
376
self.put_controlfiles([(path, f)], encode=encode)
378
def put_controlfiles(self, files, encode=True):
379
"""Write several entries as controlfiles.
381
:param files: A list of [(path, file)] pairs, where the path is the directory
382
underneath the bzr control directory
383
:param encode: If true, encode the contents as utf-8
387
for path, f in files:
389
if isinstance(f, basestring):
390
f = f.encode('utf-8', 'replace')
392
f = codecs.getwriter('utf-8')(f, errors='replace')
393
path = self._rel_controlfilename(path)
394
ctrl_files.append((path, f))
395
self._transport.put_multi(ctrl_files)
397
def _make_control(self):
398
from bzrlib.inventory import Inventory
400
# Create an empty inventory
402
# if we want per-tree root ids then this is the place to set
403
# them; they're not needed for now and so ommitted for
405
bzrlib.xml5.serializer_v5.write_inventory(Inventory(), sio)
407
dirs = [[], 'revision-store', 'weaves']
409
"This is a Bazaar-NG control directory.\n"
410
"Do not change any files in this directory.\n"),
411
('branch-format', BZR_BRANCH_FORMAT_5),
412
('revision-history', ''),
415
('pending-merges', ''),
416
('inventory', sio.getvalue())
418
cfn = self._rel_controlfilename
419
self._transport.mkdir_multi([cfn(d) for d in dirs])
420
self.put_controlfiles(files)
421
mutter('created control directory in ' + self._transport.base)
423
def _check_format(self, relax_version_check):
424
"""Check this branch format is supported.
426
The format level is stored, as an integer, in
427
self._branch_format for code that needs to check it later.
429
In the future, we might need different in-memory Branch
430
classes to support downlevel branches. But not yet.
433
fmt = self.controlfile('branch-format', 'r').read()
435
raise NotBranchError(self.base)
437
if fmt == BZR_BRANCH_FORMAT_5:
438
self._branch_format = 5
439
elif fmt == BZR_BRANCH_FORMAT_4:
440
self._branch_format = 4
442
if (not relax_version_check
443
and self._branch_format != 5):
444
raise BzrError('sorry, branch format %r not supported' % fmt,
445
['use a different bzr version',
446
'or remove the .bzr directory'
447
' and "bzr init" again'])
449
def get_root_id(self):
450
"""Return the id of this branches root"""
451
inv = self.read_working_inventory()
452
return inv.root.file_id
454
def set_root_id(self, file_id):
455
inv = self.read_working_inventory()
456
orig_root_id = inv.root.file_id
457
del inv._byid[inv.root.file_id]
458
inv.root.file_id = file_id
459
inv._byid[inv.root.file_id] = inv.root
462
if entry.parent_id in (None, orig_root_id):
463
entry.parent_id = inv.root.file_id
464
self._write_inventory(inv)
466
def read_working_inventory(self):
467
"""Read the working inventory."""
470
# ElementTree does its own conversion from UTF-8, so open in
472
f = self.controlfile('inventory', 'rb')
473
return bzrlib.xml5.serializer_v5.read_inventory(f)
478
def _write_inventory(self, inv):
479
"""Update the working inventory.
481
That is to say, the inventory describing changes underway, that
482
will be committed to the next revision.
484
from cStringIO import StringIO
488
bzrlib.xml5.serializer_v5.write_inventory(inv, sio)
490
# Transport handles atomicity
491
self.put_controlfile('inventory', sio)
495
mutter('wrote working inventory')
498
inventory = property(read_working_inventory, _write_inventory, None,
499
"""Inventory for the working copy.""")
502
def add(self, files, ids=None):
503
"""Make files versioned.
505
Note that the command line normally calls smart_add instead,
506
which can automatically recurse.
508
This puts the files in the Added state, so that they will be
509
recorded by the next commit.
512
List of paths to add, relative to the base of the tree.
515
If set, use these instead of automatically generated ids.
516
Must be the same length as the list of files, but may
517
contain None for ids that are to be autogenerated.
519
TODO: Perhaps have an option to add the ids even if the files do
522
TODO: Perhaps yield the ids and paths as they're added.
524
# TODO: Re-adding a file that is removed in the working copy
525
# should probably put it back with the previous ID.
526
if isinstance(files, basestring):
527
assert(ids is None or isinstance(ids, basestring))
533
ids = [None] * len(files)
535
assert(len(ids) == len(files))
539
inv = self.read_working_inventory()
540
for f,file_id in zip(files, ids):
541
if is_control_file(f):
542
raise BzrError("cannot add control file %s" % quotefn(f))
547
raise BzrError("cannot add top-level %r" % f)
549
fullpath = os.path.normpath(self.abspath(f))
552
kind = file_kind(fullpath)
554
# maybe something better?
555
raise BzrError('cannot add: not a regular file or directory: %s' % quotefn(f))
557
if kind != 'file' and kind != 'directory':
558
raise BzrError('cannot add: not a regular file or directory: %s' % quotefn(f))
561
file_id = gen_file_id(f)
562
inv.add_path(f, kind=kind, file_id=file_id)
564
mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
566
self._write_inventory(inv)
571
def print_file(self, file, revno):
572
"""Print `file` to stdout."""
575
tree = self.revision_tree(self.get_rev_id(revno))
576
# use inventory as it was in that revision
577
file_id = tree.inventory.path2id(file)
579
raise BzrError("%r is not present in revision %s" % (file, revno))
580
tree.print_file(file_id)
585
def remove(self, files, verbose=False):
586
"""Mark nominated files for removal from the inventory.
588
This does not remove their text. This does not run on
590
TODO: Refuse to remove modified files unless --force is given?
592
TODO: Do something useful with directories.
594
TODO: Should this remove the text or not? Tough call; not
595
removing may be useful and the user can just use use rm, and
596
is the opposite of add. Removing it is consistent with most
597
other tools. Maybe an option.
599
## TODO: Normalize names
600
## TODO: Remove nested loops; better scalability
601
if isinstance(files, basestring):
607
tree = self.working_tree()
610
# do this before any modifications
614
raise BzrError("cannot remove unversioned file %s" % quotefn(f))
615
mutter("remove inventory entry %s {%s}" % (quotefn(f), fid))
617
# having remove it, it must be either ignored or unknown
618
if tree.is_ignored(f):
622
show_status(new_status, inv[fid].kind, quotefn(f))
625
self._write_inventory(inv)
630
# FIXME: this doesn't need to be a branch method
631
def set_inventory(self, new_inventory_list):
632
from bzrlib.inventory import Inventory, InventoryEntry
633
inv = Inventory(self.get_root_id())
634
for path, file_id, parent, kind in new_inventory_list:
635
name = os.path.basename(path)
638
inv.add(InventoryEntry(file_id, name, kind, parent))
639
self._write_inventory(inv)
643
"""Return all unknown files.
645
These are files in the working directory that are not versioned or
646
control files or ignored.
648
>>> b = ScratchBranch(files=['foo', 'foo~'])
649
>>> list(b.unknowns())
652
>>> list(b.unknowns())
655
>>> list(b.unknowns())
658
return self.working_tree().unknowns()
661
def append_revision(self, *revision_ids):
662
for revision_id in revision_ids:
663
mutter("add {%s} to revision-history" % revision_id)
665
rev_history = self.revision_history()
666
rev_history.extend(revision_ids)
670
self.put_controlfile('revision-history', '\n'.join(rev_history))
675
def has_revision(self, revision_id):
676
"""True if this branch has a copy of the revision.
678
This does not necessarily imply the revision is merge
679
or on the mainline."""
680
return (revision_id is None
681
or revision_id in self.revision_store)
684
def get_revision_xml_file(self, revision_id):
685
"""Return XML file object for revision object."""
686
if not revision_id or not isinstance(revision_id, basestring):
687
raise InvalidRevisionId(revision_id)
692
return self.revision_store[revision_id]
693
except (IndexError, KeyError):
694
raise bzrlib.errors.NoSuchRevision(self, revision_id)
699
def get_revision_xml(self, revision_id):
700
return self.get_revision_xml_file(revision_id).read()
703
def get_revision(self, revision_id):
704
"""Return the Revision object for a named revision"""
705
xml_file = self.get_revision_xml_file(revision_id)
708
r = bzrlib.xml5.serializer_v5.read_revision(xml_file)
709
except SyntaxError, e:
710
raise bzrlib.errors.BzrError('failed to unpack revision_xml',
714
assert r.revision_id == revision_id
718
def get_revision_delta(self, revno):
719
"""Return the delta for one revision.
721
The delta is relative to its mainline predecessor, or the
722
empty tree for revision 1.
724
assert isinstance(revno, int)
725
rh = self.revision_history()
726
if not (1 <= revno <= len(rh)):
727
raise InvalidRevisionNumber(revno)
729
# revno is 1-based; list is 0-based
731
new_tree = self.revision_tree(rh[revno-1])
733
old_tree = EmptyTree()
735
old_tree = self.revision_tree(rh[revno-2])
737
return compare_trees(old_tree, new_tree)
739
def get_revision_sha1(self, revision_id):
740
"""Hash the stored value of a revision, and return it."""
741
return bzrlib.osutils.sha_file(self.get_revision_xml_file(revision_id))
744
def _get_ancestry_weave(self):
745
return self.control_weaves.get_weave('ancestry')
748
def get_ancestry(self, revision_id):
749
"""Return a list of revision-ids integrated by a revision.
752
if revision_id is None:
754
w = self._get_ancestry_weave()
755
return [None] + [l[:-1] for l in w.get_iter(w.lookup(revision_id))]
758
def get_inventory_weave(self):
759
return self.control_weaves.get_weave('inventory')
762
def get_inventory(self, revision_id):
763
"""Get Inventory object by hash."""
764
xml = self.get_inventory_xml(revision_id)
765
return bzrlib.xml5.serializer_v5.read_inventory_from_string(xml)
768
def get_inventory_xml(self, revision_id):
769
"""Get inventory XML as a file object."""
771
assert isinstance(revision_id, basestring), type(revision_id)
772
iw = self.get_inventory_weave()
773
return iw.get_text(iw.lookup(revision_id))
775
raise bzrlib.errors.HistoryMissing(self, 'inventory', revision_id)
778
def get_inventory_sha1(self, revision_id):
779
"""Return the sha1 hash of the inventory entry
781
return self.get_revision(revision_id).inventory_sha1
784
def get_revision_inventory(self, revision_id):
785
"""Return inventory of a past revision."""
786
# TODO: Unify this with get_inventory()
787
# bzr 0.0.6 and later imposes the constraint that the inventory_id
788
# must be the same as its revision, so this is trivial.
789
if revision_id == None:
790
return Inventory(self.get_root_id())
792
return self.get_inventory(revision_id)
795
def revision_history(self):
796
"""Return sequence of revision hashes on to this branch."""
799
return [l.rstrip('\r\n') for l in
800
self.controlfile('revision-history', 'r').readlines()]
805
def common_ancestor(self, other, self_revno=None, other_revno=None):
807
>>> from bzrlib.commit import commit
808
>>> sb = ScratchBranch(files=['foo', 'foo~'])
809
>>> sb.common_ancestor(sb) == (None, None)
811
>>> commit(sb, "Committing first revision", verbose=False)
812
>>> sb.common_ancestor(sb)[0]
814
>>> clone = sb.clone()
815
>>> commit(sb, "Committing second revision", verbose=False)
816
>>> sb.common_ancestor(sb)[0]
818
>>> sb.common_ancestor(clone)[0]
820
>>> commit(clone, "Committing divergent second revision",
822
>>> sb.common_ancestor(clone)[0]
824
>>> sb.common_ancestor(clone) == clone.common_ancestor(sb)
826
>>> sb.common_ancestor(sb) != clone.common_ancestor(clone)
828
>>> clone2 = sb.clone()
829
>>> sb.common_ancestor(clone2)[0]
831
>>> sb.common_ancestor(clone2, self_revno=1)[0]
833
>>> sb.common_ancestor(clone2, other_revno=1)[0]
836
my_history = self.revision_history()
837
other_history = other.revision_history()
838
if self_revno is None:
839
self_revno = len(my_history)
840
if other_revno is None:
841
other_revno = len(other_history)
842
indices = range(min((self_revno, other_revno)))
845
if my_history[r] == other_history[r]:
846
return r+1, my_history[r]
851
"""Return current revision number for this branch.
853
That is equivalent to the number of revisions committed to
856
return len(self.revision_history())
859
def last_revision(self):
860
"""Return last patch hash, or None if no history.
862
ph = self.revision_history()
869
def missing_revisions(self, other, stop_revision=None, diverged_ok=False):
870
"""Return a list of new revisions that would perfectly fit.
872
If self and other have not diverged, return a list of the revisions
873
present in other, but missing from self.
875
>>> from bzrlib.commit import commit
876
>>> bzrlib.trace.silent = True
877
>>> br1 = ScratchBranch()
878
>>> br2 = ScratchBranch()
879
>>> br1.missing_revisions(br2)
881
>>> commit(br2, "lala!", rev_id="REVISION-ID-1")
882
>>> br1.missing_revisions(br2)
884
>>> br2.missing_revisions(br1)
886
>>> commit(br1, "lala!", rev_id="REVISION-ID-1")
887
>>> br1.missing_revisions(br2)
889
>>> commit(br2, "lala!", rev_id="REVISION-ID-2A")
890
>>> br1.missing_revisions(br2)
892
>>> commit(br1, "lala!", rev_id="REVISION-ID-2B")
893
>>> br1.missing_revisions(br2)
894
Traceback (most recent call last):
895
DivergedBranches: These branches have diverged.
897
# FIXME: If the branches have diverged, but the latest
898
# revision in this branch is completely merged into the other,
899
# then we should still be able to pull.
900
self_history = self.revision_history()
901
self_len = len(self_history)
902
other_history = other.revision_history()
903
other_len = len(other_history)
904
common_index = min(self_len, other_len) -1
905
if common_index >= 0 and \
906
self_history[common_index] != other_history[common_index]:
907
raise DivergedBranches(self, other)
909
if stop_revision is None:
910
stop_revision = other_len
912
assert isinstance(stop_revision, int)
913
if stop_revision > other_len:
914
raise bzrlib.errors.NoSuchRevision(self, stop_revision)
915
return other_history[self_len:stop_revision]
917
def update_revisions(self, other, stop_revision=None):
918
"""Pull in new perfect-fit revisions."""
919
from bzrlib.fetch import greedy_fetch
920
from bzrlib.revision import get_intervening_revisions
921
if stop_revision is None:
922
stop_revision = other.last_revision()
923
greedy_fetch(to_branch=self, from_branch=other,
924
revision=stop_revision)
925
pullable_revs = self.missing_revisions(
926
other, other.revision_id_to_revno(stop_revision))
928
greedy_fetch(to_branch=self,
930
revision=pullable_revs[-1])
931
self.append_revision(*pullable_revs)
934
def commit(self, *args, **kw):
935
from bzrlib.commit import Commit
936
Commit().commit(self, *args, **kw)
938
def revision_id_to_revno(self, revision_id):
939
"""Given a revision id, return its revno"""
940
if revision_id is None:
942
history = self.revision_history()
944
return history.index(revision_id) + 1
946
raise bzrlib.errors.NoSuchRevision(self, revision_id)
948
def get_rev_id(self, revno, history=None):
949
"""Find the revision id of the specified revno."""
953
history = self.revision_history()
954
elif revno <= 0 or revno > len(history):
955
raise bzrlib.errors.NoSuchRevision(self, revno)
956
return history[revno - 1]
958
def revision_tree(self, revision_id):
959
"""Return Tree for a revision on this branch.
961
`revision_id` may be None for the null revision, in which case
962
an `EmptyTree` is returned."""
963
# TODO: refactor this to use an existing revision object
964
# so we don't need to read it in twice.
965
if revision_id == None:
968
inv = self.get_revision_inventory(revision_id)
969
return RevisionTree(self.weave_store, inv, revision_id)
972
def working_tree(self):
973
"""Return a `Tree` for the working copy."""
974
from bzrlib.workingtree import WorkingTree
975
# TODO: In the future, WorkingTree should utilize Transport
976
return WorkingTree(self._transport.base, self.read_working_inventory())
979
def basis_tree(self):
980
"""Return `Tree` object for last revision.
982
If there are no revisions yet, return an `EmptyTree`.
984
return self.revision_tree(self.last_revision())
987
def rename_one(self, from_rel, to_rel):
990
This can change the directory or the filename or both.
994
tree = self.working_tree()
996
if not tree.has_filename(from_rel):
997
raise BzrError("can't rename: old working file %r does not exist" % from_rel)
998
if tree.has_filename(to_rel):
999
raise BzrError("can't rename: new working file %r already exists" % to_rel)
1001
file_id = inv.path2id(from_rel)
1003
raise BzrError("can't rename: old name %r is not versioned" % from_rel)
1005
if inv.path2id(to_rel):
1006
raise BzrError("can't rename: new name %r is already versioned" % to_rel)
1008
to_dir, to_tail = os.path.split(to_rel)
1009
to_dir_id = inv.path2id(to_dir)
1010
if to_dir_id == None and to_dir != '':
1011
raise BzrError("can't determine destination directory id for %r" % to_dir)
1013
mutter("rename_one:")
1014
mutter(" file_id {%s}" % file_id)
1015
mutter(" from_rel %r" % from_rel)
1016
mutter(" to_rel %r" % to_rel)
1017
mutter(" to_dir %r" % to_dir)
1018
mutter(" to_dir_id {%s}" % to_dir_id)
1020
inv.rename(file_id, to_dir_id, to_tail)
1022
from_abs = self.abspath(from_rel)
1023
to_abs = self.abspath(to_rel)
1025
rename(from_abs, to_abs)
1027
raise BzrError("failed to rename %r to %r: %s"
1028
% (from_abs, to_abs, e[1]),
1029
["rename rolled back"])
1031
self._write_inventory(inv)
1036
def move(self, from_paths, to_name):
1039
to_name must exist as a versioned directory.
1041
If to_name exists and is a directory, the files are moved into
1042
it, keeping their old names. If it is a directory,
1044
Note that to_name is only the last component of the new name;
1045
this doesn't change the directory.
1047
This returns a list of (from_path, to_path) pairs for each
1048
entry that is moved.
1053
## TODO: Option to move IDs only
1054
assert not isinstance(from_paths, basestring)
1055
tree = self.working_tree()
1056
inv = tree.inventory
1057
to_abs = self.abspath(to_name)
1058
if not isdir(to_abs):
1059
raise BzrError("destination %r is not a directory" % to_abs)
1060
if not tree.has_filename(to_name):
1061
raise BzrError("destination %r not in working directory" % to_abs)
1062
to_dir_id = inv.path2id(to_name)
1063
if to_dir_id == None and to_name != '':
1064
raise BzrError("destination %r is not a versioned directory" % to_name)
1065
to_dir_ie = inv[to_dir_id]
1066
if to_dir_ie.kind not in ('directory', 'root_directory'):
1067
raise BzrError("destination %r is not a directory" % to_abs)
1069
to_idpath = inv.get_idpath(to_dir_id)
1071
for f in from_paths:
1072
if not tree.has_filename(f):
1073
raise BzrError("%r does not exist in working tree" % f)
1074
f_id = inv.path2id(f)
1076
raise BzrError("%r is not versioned" % f)
1077
name_tail = splitpath(f)[-1]
1078
dest_path = appendpath(to_name, name_tail)
1079
if tree.has_filename(dest_path):
1080
raise BzrError("destination %r already exists" % dest_path)
1081
if f_id in to_idpath:
1082
raise BzrError("can't move %r to a subdirectory of itself" % f)
1084
# OK, so there's a race here, it's possible that someone will
1085
# create a file in this interval and then the rename might be
1086
# left half-done. But we should have caught most problems.
1088
for f in from_paths:
1089
name_tail = splitpath(f)[-1]
1090
dest_path = appendpath(to_name, name_tail)
1091
result.append((f, dest_path))
1092
inv.rename(inv.path2id(f), to_dir_id, name_tail)
1094
rename(self.abspath(f), self.abspath(dest_path))
1096
raise BzrError("failed to rename %r to %r: %s" % (f, dest_path, e[1]),
1097
["rename rolled back"])
1099
self._write_inventory(inv)
1106
def revert(self, filenames, old_tree=None, backups=True):
1107
"""Restore selected files to the versions from a previous tree.
1110
If true (default) backups are made of files before
1113
from bzrlib.errors import NotVersionedError, BzrError
1114
from bzrlib.atomicfile import AtomicFile
1115
from bzrlib.osutils import backup_file
1117
inv = self.read_working_inventory()
1118
if old_tree is None:
1119
old_tree = self.basis_tree()
1120
old_inv = old_tree.inventory
1123
for fn in filenames:
1124
file_id = inv.path2id(fn)
1126
raise NotVersionedError("not a versioned file", fn)
1127
if not old_inv.has_id(file_id):
1128
raise BzrError("file not present in old tree", fn, file_id)
1129
nids.append((fn, file_id))
1131
# TODO: Rename back if it was previously at a different location
1133
# TODO: If given a directory, restore the entire contents from
1134
# the previous version.
1136
# TODO: Make a backup to a temporary file.
1138
# TODO: If the file previously didn't exist, delete it?
1139
for fn, file_id in nids:
1142
f = AtomicFile(fn, 'wb')
1144
f.write(old_tree.get_file(file_id).read())
1150
def pending_merges(self):
1151
"""Return a list of pending merges.
1153
These are revisions that have been merged into the working
1154
directory but not yet committed.
1156
cfn = self._rel_controlfilename('pending-merges')
1157
if not self._transport.has(cfn):
1160
for l in self.controlfile('pending-merges', 'r').readlines():
1161
p.append(l.rstrip('\n'))
1165
def add_pending_merge(self, *revision_ids):
1166
# TODO: Perhaps should check at this point that the
1167
# history of the revision is actually present?
1168
for rev_id in revision_ids:
1169
validate_revision_id(rev_id)
1171
p = self.pending_merges()
1173
for rev_id in revision_ids:
1179
self.set_pending_merges(p)
1181
def set_pending_merges(self, rev_list):
1184
self.put_controlfile('pending-merges', '\n'.join(rev_list))
1189
def get_parent(self):
1190
"""Return the parent location of the branch.
1192
This is the default location for push/pull/missing. The usual
1193
pattern is that the user can override it by specifying a
1197
_locs = ['parent', 'pull', 'x-pull']
1200
return self.controlfile(l, 'r').read().strip('\n')
1202
if e.errno != errno.ENOENT:
1207
def set_parent(self, url):
1208
# TODO: Maybe delete old location files?
1209
from bzrlib.atomicfile import AtomicFile
1212
f = AtomicFile(self.controlfilename('parent'))
1221
def check_revno(self, revno):
1223
Check whether a revno corresponds to any revision.
1224
Zero (the NULL revision) is considered valid.
1227
self.check_real_revno(revno)
1229
def check_real_revno(self, revno):
1231
Check whether a revno corresponds to a real revision.
1232
Zero (the NULL revision) is considered invalid
1234
if revno < 1 or revno > self.revno():
1235
raise InvalidRevisionNumber(revno)
1241
class ScratchBranch(_Branch):
1242
"""Special test class: a branch that cleans up after itself.
1244
>>> b = ScratchBranch()
1252
def __init__(self, files=[], dirs=[], base=None):
1253
"""Make a test branch.
1255
This creates a temporary directory and runs init-tree in it.
1257
If any files are listed, they are created in the working copy.
1259
from tempfile import mkdtemp
1264
_Branch.__init__(self, base, init=init)
1266
self._transport.mkdir(d)
1269
self._transport.put(f, 'content of %s' % f)
1274
>>> orig = ScratchBranch(files=["file1", "file2"])
1275
>>> clone = orig.clone()
1276
>>> if os.name != 'nt':
1277
... os.path.samefile(orig.base, clone.base)
1279
... orig.base == clone.base
1282
>>> os.path.isfile(os.path.join(clone.base, "file1"))
1285
from shutil import copytree
1286
from tempfile import mkdtemp
1289
copytree(self.base, base, symlinks=True)
1290
return ScratchBranch(base=base)
1298
"""Destroy the test branch, removing the scratch directory."""
1299
from shutil import rmtree
1302
mutter("delete ScratchBranch %s" % self.base)
1305
# Work around for shutil.rmtree failing on Windows when
1306
# readonly files are encountered
1307
mutter("hit exception in destroying ScratchBranch: %s" % e)
1308
for root, dirs, files in os.walk(self.base, topdown=False):
1310
os.chmod(os.path.join(root, name), 0700)
1312
self._transport = None
1316
######################################################################
1320
def is_control_file(filename):
1321
## FIXME: better check
1322
filename = os.path.normpath(filename)
1323
while filename != '':
1324
head, tail = os.path.split(filename)
1325
## mutter('check %r for control file' % ((head, tail), ))
1326
if tail == bzrlib.BZRDIR:
1328
if filename == head:
1335
def gen_file_id(name):
1336
"""Return new file id.
1338
This should probably generate proper UUIDs, but for the moment we
1339
cope with just randomness because running uuidgen every time is
1342
from binascii import hexlify
1343
from time import time
1345
# get last component
1346
idx = name.rfind('/')
1348
name = name[idx+1 : ]
1349
idx = name.rfind('\\')
1351
name = name[idx+1 : ]
1353
# make it not a hidden file
1354
name = name.lstrip('.')
1356
# remove any wierd characters; we don't escape them but rather
1357
# just pull them out
1358
name = re.sub(r'[^\w.]', '', name)
1360
s = hexlify(rand_bytes(8))
1361
return '-'.join((name, compact_date(time()), s))
1365
"""Return a new tree-root file id."""
1366
return gen_file_id('TREE_ROOT')