39
36
# At the moment they may alias the inventory and have old copies of it in
40
37
# memory. (Now done? -- mbp 20060309)
42
from binascii import hexlify
39
from cStringIO import StringIO
43
from bzrlib.lazy_import import lazy_import
44
lazy_import(globals(), """
45
from bisect import bisect_left
44
from copy import deepcopy
45
from cStringIO import StringIO
51
51
from time import time
55
from bzrlib import bzrdir, errors, ignores, osutils, urlutils
56
from bzrlib.atomicfile import AtomicFile
59
conflicts as _mod_conflicts,
67
revision as _mod_revision,
57
79
import bzrlib.branch
58
from bzrlib.conflicts import Conflict, ConflictList, CONFLICT_SUFFIXES
80
from bzrlib.transport import get_transport
82
from bzrlib.workingtree_4 import WorkingTreeFormat4
85
from bzrlib import symbol_versioning
59
86
from bzrlib.decorators import needs_read_lock, needs_write_lock
60
from bzrlib.errors import (BzrCheckError,
63
WeaveRevisionNotPresent,
67
MergeModifiedFormatError,
70
from bzrlib.inventory import InventoryEntry, Inventory
87
from bzrlib.inventory import InventoryEntry, Inventory, ROOT_ID, TreeReference
71
88
from bzrlib.lockable_files import LockableFiles, TransportLock
72
89
from bzrlib.lockdir import LockDir
73
from bzrlib.merge import merge_inner, transform_tree
90
import bzrlib.mutabletree
91
from bzrlib.mutabletree import needs_tree_write_lock
92
from bzrlib import osutils
74
93
from bzrlib.osutils import (
105
from bzrlib.trace import mutter, note
106
from bzrlib.transport.local import LocalTransport
91
107
from bzrlib.progress import DummyProgress, ProgressPhase
92
from bzrlib.revision import NULL_REVISION
108
from bzrlib.revision import NULL_REVISION, CURRENT_REVISION
93
109
from bzrlib.rio import RioReader, rio_file, Stanza
94
110
from bzrlib.symbol_versioning import (deprecated_passed,
95
111
deprecated_method,
96
112
deprecated_function,
97
113
DEPRECATED_PARAMETER,
101
from bzrlib.trace import mutter, note
102
from bzrlib.transform import build_tree
103
from bzrlib.transport import get_transport
104
from bzrlib.transport.local import LocalTransport
105
from bzrlib.textui import show_status
111
# the regex removes any weird characters; we don't escape them
112
# but rather just pull them out
113
_gen_file_id_re = re.compile(r'[^\w.]')
114
_gen_id_suffix = None
118
def _next_id_suffix():
119
"""Create a new file id suffix that is reasonably unique.
121
On the first call we combine the current time with 64 bits of randomness
122
to give a highly probably globally unique number. Then each call in the same
123
process adds 1 to a serial number we append to that unique value.
125
# XXX TODO: change bzrlib.add.smart_add to call workingtree.add() rather
126
# than having to move the id randomness out of the inner loop like this.
127
# XXX TODO: for the global randomness this uses we should add the thread-id
128
# before the serial #.
129
global _gen_id_suffix, _gen_id_serial
130
if _gen_id_suffix is None:
131
_gen_id_suffix = "-%s-%s-" % (compact_date(time()), rand_chars(16))
133
return _gen_id_suffix + str(_gen_id_serial)
136
def gen_file_id(name):
137
"""Return new file id for the basename 'name'.
139
The uniqueness is supplied from _next_id_suffix.
141
# The real randomness is in the _next_id_suffix, the
142
# rest of the identifier is just to be nice.
144
# 1) Remove non-ascii word characters to keep the ids portable
145
# 2) squash to lowercase, so the file id doesn't have to
146
# be escaped (case insensitive filesystems would bork for ids
147
# that only differred in case without escaping).
148
# 3) truncate the filename to 20 chars. Long filenames also bork on some
150
# 4) Removing starting '.' characters to prevent the file ids from
151
# being considered hidden.
152
ascii_word_only = _gen_file_id_re.sub('', name.lower())
153
short_no_dots = ascii_word_only.lstrip('.')[:20]
154
return short_no_dots + _next_id_suffix()
158
"""Return a new tree-root file id."""
159
return gen_file_id('TREE_ROOT')
162
def needs_tree_write_lock(unbound):
163
"""Decorate unbound to take out and release a tree_write lock."""
164
def tree_write_locked(self, *args, **kwargs):
165
self.lock_tree_write()
167
return unbound(self, *args, **kwargs)
170
tree_write_locked.__doc__ = unbound.__doc__
171
tree_write_locked.__name__ = unbound.__name__
172
return tree_write_locked
117
MERGE_MODIFIED_HEADER_1 = "BZR merge-modified list format 1"
118
CONFLICT_HEADER_1 = "BZR conflict list format 1"
120
ERROR_PATH_NOT_FOUND = 3 # WindowsError errno code, equivalent to ENOENT
175
123
class TreeEntry(object):
501
431
def get_file_byname(self, filename):
502
432
return file(self.abspath(filename), 'rb')
435
def annotate_iter(self, file_id, default_revision=CURRENT_REVISION):
436
"""See Tree.annotate_iter
438
This implementation will use the basis tree implementation if possible.
439
Lines not in the basis are attributed to CURRENT_REVISION
441
If there are pending merges, lines added by those merges will be
442
incorrectly attributed to CURRENT_REVISION (but after committing, the
443
attribution will be correct).
445
basis = self.basis_tree()
448
changes = self.iter_changes(basis, True, [self.id2path(file_id)],
449
require_versioned=True).next()
450
changed_content, kind = changes[2], changes[6]
451
if not changed_content:
452
return basis.annotate_iter(file_id)
456
if kind[0] != 'file':
459
old_lines = list(basis.annotate_iter(file_id))
461
for tree in self.branch.repository.revision_trees(
462
self.get_parent_ids()[1:]):
463
if file_id not in tree:
465
old.append(list(tree.annotate_iter(file_id)))
466
return annotate.reannotate(old, self.get_file(file_id).readlines(),
471
def _get_ancestors(self, default_revision):
472
ancestors = set([default_revision])
473
for parent_id in self.get_parent_ids():
474
ancestors.update(self.branch.repository.get_ancestry(
475
parent_id, topo_sorted=False))
504
478
def get_parent_ids(self):
505
479
"""See Tree.get_parent_ids.
507
481
This implementation reads the pending merges list and last_revision
508
482
value and uses that to decide what the parents list should be.
510
last_rev = self._last_revision()
484
last_rev = _mod_revision.ensure_null(self._last_revision())
485
if _mod_revision.NULL_REVISION == last_rev:
514
488
parents = [last_rev]
516
merges_file = self._control_files.get_utf8('pending-merges')
490
merges_file = self._transport.get('pending-merges')
491
except errors.NoSuchFile:
520
494
for l in merges_file.readlines():
521
parents.append(l.rstrip('\n'))
495
revision_id = l.rstrip('\n')
496
parents.append(revision_id)
524
500
def get_root_id(self):
525
501
"""Return the id of this trees root"""
526
inv = self.read_working_inventory()
527
return inv.root.file_id
502
return self._inventory.root.file_id
529
504
def _get_store_filename(self, file_id):
530
505
## XXX: badly named; this is not in the store at all
531
506
return self.abspath(self.id2path(file_id))
534
def clone(self, to_bzrdir, revision_id=None, basis=None):
509
def clone(self, to_bzrdir, revision_id=None):
535
510
"""Duplicate this working tree into to_bzr, including all state.
537
512
Specifically modified files are kept as modified, but
599
555
__contains__ = has_id
601
557
def get_file_size(self, file_id):
602
return os.path.getsize(self.id2abspath(file_id))
558
"""See Tree.get_file_size"""
560
return os.path.getsize(self.id2abspath(file_id))
562
if e.errno != errno.ENOENT:
605
def get_file_sha1(self, file_id, path=None):
568
def get_file_sha1(self, file_id, path=None, stat_value=None):
607
570
path = self._inventory.id2path(file_id)
608
return self._hashcache.get_sha1(path)
571
return self._hashcache.get_sha1(path, stat_value)
610
573
def get_file_mtime(self, file_id, path=None):
612
path = self._inventory.id2path(file_id)
575
path = self.inventory.id2path(file_id)
613
576
return os.lstat(self.abspath(path)).st_mtime
578
def _is_executable_from_path_and_stat_from_basis(self, path, stat_result):
579
file_id = self.path2id(path)
580
return self._inventory[file_id].executable
582
def _is_executable_from_path_and_stat_from_stat(self, path, stat_result):
583
mode = stat_result.st_mode
584
return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
615
586
if not supports_executable():
616
587
def is_executable(self, file_id, path=None):
617
588
return self._inventory[file_id].executable
590
_is_executable_from_path_and_stat = \
591
_is_executable_from_path_and_stat_from_basis
619
593
def is_executable(self, file_id, path=None):
621
path = self._inventory.id2path(file_id)
595
path = self.id2path(file_id)
622
596
mode = os.lstat(self.abspath(path)).st_mode
623
597
return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
599
_is_executable_from_path_and_stat = \
600
_is_executable_from_path_and_stat_from_stat
625
602
@needs_tree_write_lock
626
def add(self, files, ids=None):
627
"""Make files versioned.
629
Note that the command line normally calls smart_add instead,
630
which can automatically recurse.
632
This adds the files to the inventory, so that they will be
633
recorded by the next commit.
636
List of paths to add, relative to the base of the tree.
639
If set, use these instead of automatically generated ids.
640
Must be the same length as the list of files, but may
641
contain None for ids that are to be autogenerated.
643
TODO: Perhaps have an option to add the ids even if the files do
646
TODO: Perhaps callback with the ids and paths as they're added.
603
def _add(self, files, ids, kinds):
604
"""See MutableTree._add."""
648
605
# TODO: Re-adding a file that is removed in the working copy
649
606
# should probably put it back with the previous ID.
650
if isinstance(files, basestring):
651
assert(ids is None or isinstance(ids, basestring))
657
ids = [None] * len(files)
659
assert(len(ids) == len(files))
661
inv = self.read_working_inventory()
662
for f,file_id in zip(files, ids):
663
if self.is_control_filename(f):
664
raise errors.ForbiddenControlFileError(filename=f)
669
raise BzrError("cannot add top-level %r" % f)
671
fullpath = normpath(self.abspath(f))
673
kind = file_kind(fullpath)
675
if e.errno == errno.ENOENT:
676
raise NoSuchFile(fullpath)
677
if not InventoryEntry.versionable_kind(kind):
678
raise errors.BadFileKindError(filename=f, kind=kind)
607
# the read and write working inventory should not occur in this
608
# function - they should be part of lock_write and unlock.
610
for f, file_id, kind in zip(files, ids, kinds):
679
611
if file_id is None:
680
612
inv.add_path(f, kind=kind)
682
614
inv.add_path(f, kind=kind, file_id=file_id)
684
self._write_inventory(inv)
615
self._inventory_is_modified = True
686
617
@needs_tree_write_lock
618
def _gather_kinds(self, files, kinds):
619
"""See MutableTree._gather_kinds."""
620
for pos, f in enumerate(files):
621
if kinds[pos] is None:
622
fullpath = normpath(self.abspath(f))
624
kinds[pos] = file_kind(fullpath)
626
if e.errno == errno.ENOENT:
627
raise errors.NoSuchFile(fullpath)
687
630
def add_parent_tree_id(self, revision_id, allow_leftmost_as_ghost=False):
688
631
"""Add revision_id as a parent.
736
679
self.set_parent_ids(parents, allow_leftmost_as_ghost=True)
738
@deprecated_method(zero_eleven)
740
def pending_merges(self):
741
"""Return a list of pending merges.
743
These are revisions that have been merged into the working
744
directory but not yet committed.
746
As of 0.11 this is deprecated. Please see WorkingTree.get_parent_ids()
747
instead - which is available on all tree objects.
749
return self.get_parent_ids()[1:]
681
def path_content_summary(self, path, _lstat=os.lstat,
682
_mapper=osutils.file_kind_from_stat_mode):
683
"""See Tree.path_content_summary."""
684
abspath = self.abspath(path)
686
stat_result = _lstat(abspath)
688
if getattr(e, 'errno', None) == errno.ENOENT:
690
return ('missing', None, None, None)
691
# propagate other errors
693
kind = _mapper(stat_result.st_mode)
695
size = stat_result.st_size
696
# try for a stat cache lookup
697
executable = self._is_executable_from_path_and_stat(path, stat_result)
698
return (kind, size, executable, self._sha_from_stat(
700
elif kind == 'directory':
701
# perhaps it looks like a plain directory, but it's really a
703
if self._directory_is_tree_reference(path):
704
kind = 'tree-reference'
705
return kind, None, None, None
706
elif kind == 'symlink':
707
return ('symlink', None, None, os.readlink(abspath))
709
return (kind, None, None, None)
711
def _check_parents_for_ghosts(self, revision_ids, allow_leftmost_as_ghost):
712
"""Common ghost checking functionality from set_parent_*.
714
This checks that the left hand-parent exists if there are any
717
if len(revision_ids) > 0:
718
leftmost_id = revision_ids[0]
719
if (not allow_leftmost_as_ghost and not
720
self.branch.repository.has_revision(leftmost_id)):
721
raise errors.GhostRevisionUnusableHere(leftmost_id)
723
def _set_merges_from_parent_ids(self, parent_ids):
724
merges = parent_ids[1:]
725
self._transport.put_bytes('pending-merges', '\n'.join(merges),
726
mode=self._control_files._file_mode)
728
def _filter_parent_ids_by_ancestry(self, revision_ids):
729
"""Check that all merged revisions are proper 'heads'.
731
This will always return the first revision_id, and any merged revisions
734
if len(revision_ids) == 0:
736
graph = self.branch.repository.get_graph()
737
heads = graph.heads(revision_ids)
738
new_revision_ids = revision_ids[:1]
739
for revision_id in revision_ids[1:]:
740
if revision_id in heads and revision_id not in new_revision_ids:
741
new_revision_ids.append(revision_id)
742
if new_revision_ids != revision_ids:
743
trace.mutter('requested to set revision_ids = %s,'
744
' but filtered to %s', revision_ids, new_revision_ids)
745
return new_revision_ids
751
747
@needs_tree_write_lock
752
748
def set_parent_ids(self, revision_ids, allow_leftmost_as_ghost=False):
761
757
:param revision_ids: The revision_ids to set as the parent ids of this
762
758
working tree. Any of these may be ghosts.
760
self._check_parents_for_ghosts(revision_ids,
761
allow_leftmost_as_ghost=allow_leftmost_as_ghost)
762
for revision_id in revision_ids:
763
_mod_revision.check_not_reserved_id(revision_id)
765
revision_ids = self._filter_parent_ids_by_ancestry(revision_ids)
764
767
if len(revision_ids) > 0:
765
leftmost_id = revision_ids[0]
766
if (not allow_leftmost_as_ghost and not
767
self.branch.repository.has_revision(leftmost_id)):
768
raise errors.GhostRevisionUnusableHere(leftmost_id)
769
self.set_last_revision(leftmost_id)
768
self.set_last_revision(revision_ids[0])
771
self.set_last_revision(None)
772
merges = revision_ids[1:]
773
self._control_files.put_utf8('pending-merges', '\n'.join(merges))
770
self.set_last_revision(_mod_revision.NULL_REVISION)
772
self._set_merges_from_parent_ids(revision_ids)
775
774
@needs_tree_write_lock
776
775
def set_parent_trees(self, parents_list, allow_leftmost_as_ghost=False):
777
"""Set the parents of the working tree.
776
"""See MutableTree.set_parent_trees."""
777
parent_ids = [rev for (rev, tree) in parents_list]
778
for revision_id in parent_ids:
779
_mod_revision.check_not_reserved_id(revision_id)
779
:param parents_list: A list of (revision_id, tree) tuples.
780
If tree is None, then that element is treated as an unreachable
781
parent tree - i.e. a ghost.
783
# parent trees are not used in current format trees, delegate to
785
self.set_parent_ids([rev for (rev, tree) in parents_list],
781
self._check_parents_for_ghosts(parent_ids,
786
782
allow_leftmost_as_ghost=allow_leftmost_as_ghost)
784
parent_ids = self._filter_parent_ids_by_ancestry(parent_ids)
786
if len(parent_ids) == 0:
787
leftmost_parent_id = _mod_revision.NULL_REVISION
788
leftmost_parent_tree = None
790
leftmost_parent_id, leftmost_parent_tree = parents_list[0]
792
if self._change_last_revision(leftmost_parent_id):
793
if leftmost_parent_tree is None:
794
# If we don't have a tree, fall back to reading the
795
# parent tree from the repository.
796
self._cache_basis_inventory(leftmost_parent_id)
798
inv = leftmost_parent_tree.inventory
799
xml = self._create_basis_xml_from_inventory(
800
leftmost_parent_id, inv)
801
self._write_basis_inventory(xml)
802
self._set_merges_from_parent_ids(parent_ids)
788
804
@needs_tree_write_lock
789
805
def set_pending_merges(self, rev_list):
790
806
parents = self.get_parent_ids()
851
886
def merge_modified(self):
887
"""Return a dictionary of files modified by a merge.
889
The list is initialized by WorkingTree.set_merge_modified, which is
890
typically called after we make some automatic updates to the tree
893
This returns a map of file_id->sha1, containing only files which are
894
still in the working inventory and have that text hash.
853
hashfile = self._control_files.get('merge-hashes')
897
hashfile = self._transport.get('merge-hashes')
898
except errors.NoSuchFile:
856
900
merge_hashes = {}
858
902
if hashfile.next() != MERGE_MODIFIED_HEADER_1 + '\n':
859
raise MergeModifiedFormatError()
903
raise errors.MergeModifiedFormatError()
860
904
except StopIteration:
861
raise MergeModifiedFormatError()
905
raise errors.MergeModifiedFormatError()
862
906
for s in RioReader(hashfile):
863
file_id = s.get("file_id")
907
# RioReader reads in Unicode, so convert file_ids back to utf8
908
file_id = osutils.safe_file_id(s.get("file_id"), warn=False)
864
909
if file_id not in self.inventory:
867
if hash == self.get_file_sha1(file_id):
868
merge_hashes[file_id] = hash
911
text_hash = s.get("hash")
912
if text_hash == self.get_file_sha1(file_id):
913
merge_hashes[file_id] = text_hash
869
914
return merge_hashes
917
def mkdir(self, path, file_id=None):
918
"""See MutableTree.mkdir()."""
920
file_id = generate_ids.gen_file_id(os.path.basename(path))
921
os.mkdir(self.abspath(path))
922
self.add(path, file_id, 'directory')
871
925
def get_symlink_target(self, file_id):
872
926
return os.readlink(self.id2abspath(file_id))
874
def file_class(self, filename):
875
if self.path2id(filename):
877
elif self.is_ignored(filename):
882
def list_files(self):
929
def subsume(self, other_tree):
930
def add_children(inventory, entry):
931
for child_entry in entry.children.values():
932
inventory._byid[child_entry.file_id] = child_entry
933
if child_entry.kind == 'directory':
934
add_children(inventory, child_entry)
935
if other_tree.get_root_id() == self.get_root_id():
936
raise errors.BadSubsumeSource(self, other_tree,
937
'Trees have the same root')
939
other_tree_path = self.relpath(other_tree.basedir)
940
except errors.PathNotChild:
941
raise errors.BadSubsumeSource(self, other_tree,
942
'Tree is not contained by the other')
943
new_root_parent = self.path2id(osutils.dirname(other_tree_path))
944
if new_root_parent is None:
945
raise errors.BadSubsumeSource(self, other_tree,
946
'Parent directory is not versioned.')
947
# We need to ensure that the result of a fetch will have a
948
# versionedfile for the other_tree root, and only fetching into
949
# RepositoryKnit2 guarantees that.
950
if not self.branch.repository.supports_rich_root():
951
raise errors.SubsumeTargetNeedsUpgrade(other_tree)
952
other_tree.lock_tree_write()
954
new_parents = other_tree.get_parent_ids()
955
other_root = other_tree.inventory.root
956
other_root.parent_id = new_root_parent
957
other_root.name = osutils.basename(other_tree_path)
958
self.inventory.add(other_root)
959
add_children(self.inventory, other_root)
960
self._write_inventory(self.inventory)
961
# normally we don't want to fetch whole repositories, but i think
962
# here we really do want to consolidate the whole thing.
963
for parent_id in other_tree.get_parent_ids():
964
self.branch.fetch(other_tree.branch, parent_id)
965
self.add_parent_tree_id(parent_id)
968
other_tree.bzrdir.retire_bzrdir()
970
def _setup_directory_is_tree_reference(self):
971
if self._branch.repository._format.supports_tree_reference:
972
self._directory_is_tree_reference = \
973
self._directory_may_be_tree_reference
975
self._directory_is_tree_reference = \
976
self._directory_is_never_tree_reference
978
def _directory_is_never_tree_reference(self, relpath):
981
def _directory_may_be_tree_reference(self, relpath):
982
# as a special case, if a directory contains control files then
983
# it's a tree reference, except that the root of the tree is not
984
return relpath and osutils.isdir(self.abspath(relpath) + u"/.bzr")
985
# TODO: We could ask all the control formats whether they
986
# recognize this directory, but at the moment there's no cheap api
987
# to do that. Since we probably can only nest bzr checkouts and
988
# they always use this name it's ok for now. -- mbp 20060306
990
# FIXME: There is an unhandled case here of a subdirectory
991
# containing .bzr but not a branch; that will probably blow up
992
# when you try to commit it. It might happen if there is a
993
# checkout in a subdirectory. This can be avoided by not adding
996
@needs_tree_write_lock
997
def extract(self, file_id, format=None):
998
"""Extract a subtree from this tree.
1000
A new branch will be created, relative to the path for this tree.
1004
segments = osutils.splitpath(path)
1005
transport = self.branch.bzrdir.root_transport
1006
for name in segments:
1007
transport = transport.clone(name)
1008
transport.ensure_base()
1011
sub_path = self.id2path(file_id)
1012
branch_transport = mkdirs(sub_path)
1014
format = self.bzrdir.cloning_metadir()
1015
branch_transport.ensure_base()
1016
branch_bzrdir = format.initialize_on_transport(branch_transport)
1018
repo = branch_bzrdir.find_repository()
1019
except errors.NoRepositoryPresent:
1020
repo = branch_bzrdir.create_repository()
1021
if not repo.supports_rich_root():
1022
raise errors.RootNotRich()
1023
new_branch = branch_bzrdir.create_branch()
1024
new_branch.pull(self.branch)
1025
for parent_id in self.get_parent_ids():
1026
new_branch.fetch(self.branch, parent_id)
1027
tree_transport = self.bzrdir.root_transport.clone(sub_path)
1028
if tree_transport.base != branch_transport.base:
1029
tree_bzrdir = format.initialize_on_transport(tree_transport)
1030
branch.BranchReferenceFormat().initialize(tree_bzrdir, new_branch)
1032
tree_bzrdir = branch_bzrdir
1033
wt = tree_bzrdir.create_workingtree(NULL_REVISION)
1034
wt.set_parent_ids(self.get_parent_ids())
1035
my_inv = self.inventory
1036
child_inv = Inventory(root_id=None)
1037
new_root = my_inv[file_id]
1038
my_inv.remove_recursive_id(file_id)
1039
new_root.parent_id = None
1040
child_inv.add(new_root)
1041
self._write_inventory(my_inv)
1042
wt._write_inventory(child_inv)
1045
def _serialize(self, inventory, out_file):
1046
xml5.serializer_v5.write_inventory(self._inventory, out_file,
1049
def _deserialize(selt, in_file):
1050
return xml5.serializer_v5.read_inventory(in_file)
1053
"""Write the in memory inventory to disk."""
1054
# TODO: Maybe this should only write on dirty ?
1055
if self._control_files._lock_mode != 'w':
1056
raise errors.NotWriteLocked(self)
1058
self._serialize(self._inventory, sio)
1060
self._transport.put_file('inventory', sio,
1061
mode=self._control_files._file_mode)
1062
self._inventory_is_modified = False
1064
def _kind(self, relpath):
1065
return osutils.file_kind(self.abspath(relpath))
1067
def list_files(self, include_root=False):
883
1068
"""Recursively list all files as (path, class, kind, id, entry).
885
1070
Lists, but does not descend into unversioned directories.
982
1168
new_children.sort()
983
1169
new_children = collections.deque(new_children)
984
1170
stack.append((f_ie.file_id, fp, fap, new_children))
985
# Break out of inner loop, so that we start outer loop with child
1171
# Break out of inner loop,
1172
# so that we start outer loop with child
988
1175
# if we finished all children, pop it off the stack
991
1178
@needs_tree_write_lock
992
def move(self, from_paths, to_name):
1179
def move(self, from_paths, to_dir=None, after=False, **kwargs):
993
1180
"""Rename files.
995
to_name must exist in the inventory.
1182
to_dir must exist in the inventory.
997
If to_name exists and is a directory, the files are moved into
1184
If to_dir exists and is a directory, the files are moved into
998
1185
it, keeping their old names.
1000
Note that to_name is only the last component of the new name;
1187
Note that to_dir is only the last component of the new name;
1001
1188
this doesn't change the directory.
1190
For each entry in from_paths the move mode will be determined
1193
The first mode moves the file in the filesystem and updates the
1194
inventory. The second mode only updates the inventory without
1195
touching the file on the filesystem. This is the new mode introduced
1198
move uses the second mode if 'after == True' and the target is not
1199
versioned but present in the working tree.
1201
move uses the second mode if 'after == False' and the source is
1202
versioned but no longer in the working tree, and the target is not
1203
versioned but present in the working tree.
1205
move uses the first mode if 'after == False' and the source is
1206
versioned and present in the working tree, and the target is not
1207
versioned and not present in the working tree.
1209
Everything else results in an error.
1003
1211
This returns a list of (from_path, to_path) pairs for each
1004
1212
entry that is moved.
1007
## TODO: Option to move IDs only
1008
assert not isinstance(from_paths, basestring)
1217
# check for deprecated use of signature
1219
to_dir = kwargs.get('to_name', None)
1221
raise TypeError('You must supply a target directory')
1223
symbol_versioning.warn('The parameter to_name was deprecated'
1224
' in version 0.13. Use to_dir instead',
1227
# check destination directory
1228
if isinstance(from_paths, basestring):
1009
1230
inv = self.inventory
1010
to_abs = self.abspath(to_name)
1231
to_abs = self.abspath(to_dir)
1011
1232
if not isdir(to_abs):
1012
raise BzrError("destination %r is not a directory" % to_abs)
1013
if not self.has_filename(to_name):
1014
raise BzrError("destination %r not in working directory" % to_abs)
1015
to_dir_id = inv.path2id(to_name)
1016
if to_dir_id is None and to_name != '':
1017
raise BzrError("destination %r is not a versioned directory" % to_name)
1233
raise errors.BzrMoveFailedError('',to_dir,
1234
errors.NotADirectory(to_abs))
1235
if not self.has_filename(to_dir):
1236
raise errors.BzrMoveFailedError('',to_dir,
1237
errors.NotInWorkingDirectory(to_dir))
1238
to_dir_id = inv.path2id(to_dir)
1239
if to_dir_id is None:
1240
raise errors.BzrMoveFailedError('',to_dir,
1241
errors.NotVersionedError(path=str(to_dir)))
1018
1243
to_dir_ie = inv[to_dir_id]
1019
1244
if to_dir_ie.kind != 'directory':
1020
raise BzrError("destination %r is not a directory" % to_abs)
1022
to_idpath = inv.get_idpath(to_dir_id)
1024
for f in from_paths:
1025
if not self.has_filename(f):
1026
raise BzrError("%r does not exist in working tree" % f)
1027
f_id = inv.path2id(f)
1029
raise BzrError("%r is not versioned" % f)
1030
name_tail = splitpath(f)[-1]
1031
dest_path = pathjoin(to_name, name_tail)
1032
if self.has_filename(dest_path):
1033
raise BzrError("destination %r already exists" % dest_path)
1034
if f_id in to_idpath:
1035
raise BzrError("can't move %r to a subdirectory of itself" % f)
1037
# OK, so there's a race here, it's possible that someone will
1038
# create a file in this interval and then the rename might be
1039
# left half-done. But we should have caught most problems.
1040
orig_inv = deepcopy(self.inventory)
1245
raise errors.BzrMoveFailedError('',to_dir,
1246
errors.NotADirectory(to_abs))
1248
# create rename entries and tuples
1249
for from_rel in from_paths:
1250
from_tail = splitpath(from_rel)[-1]
1251
from_id = inv.path2id(from_rel)
1253
raise errors.BzrMoveFailedError(from_rel,to_dir,
1254
errors.NotVersionedError(path=str(from_rel)))
1256
from_entry = inv[from_id]
1257
from_parent_id = from_entry.parent_id
1258
to_rel = pathjoin(to_dir, from_tail)
1259
rename_entry = WorkingTree._RenameEntry(from_rel=from_rel,
1261
from_tail=from_tail,
1262
from_parent_id=from_parent_id,
1263
to_rel=to_rel, to_tail=from_tail,
1264
to_parent_id=to_dir_id)
1265
rename_entries.append(rename_entry)
1266
rename_tuples.append((from_rel, to_rel))
1268
# determine which move mode to use. checks also for movability
1269
rename_entries = self._determine_mv_mode(rename_entries, after)
1271
original_modified = self._inventory_is_modified
1042
for f in from_paths:
1043
name_tail = splitpath(f)[-1]
1044
dest_path = pathjoin(to_name, name_tail)
1045
result.append((f, dest_path))
1046
inv.rename(inv.path2id(f), to_dir_id, name_tail)
1048
rename(self.abspath(f), self.abspath(dest_path))
1050
raise BzrError("failed to rename %r to %r: %s" %
1051
(f, dest_path, e[1]),
1052
["rename rolled back"])
1274
self._inventory_is_modified = True
1275
self._move(rename_entries)
1054
1277
# restore the inventory on error
1055
self._set_inventory(orig_inv)
1278
self._inventory_is_modified = original_modified
1057
1280
self._write_inventory(inv)
1281
return rename_tuples
1283
def _determine_mv_mode(self, rename_entries, after=False):
1284
"""Determines for each from-to pair if both inventory and working tree
1285
or only the inventory has to be changed.
1287
Also does basic plausability tests.
1289
inv = self.inventory
1291
for rename_entry in rename_entries:
1292
# store to local variables for easier reference
1293
from_rel = rename_entry.from_rel
1294
from_id = rename_entry.from_id
1295
to_rel = rename_entry.to_rel
1296
to_id = inv.path2id(to_rel)
1297
only_change_inv = False
1299
# check the inventory for source and destination
1301
raise errors.BzrMoveFailedError(from_rel,to_rel,
1302
errors.NotVersionedError(path=str(from_rel)))
1303
if to_id is not None:
1304
raise errors.BzrMoveFailedError(from_rel,to_rel,
1305
errors.AlreadyVersionedError(path=str(to_rel)))
1307
# try to determine the mode for rename (only change inv or change
1308
# inv and file system)
1310
if not self.has_filename(to_rel):
1311
raise errors.BzrMoveFailedError(from_id,to_rel,
1312
errors.NoSuchFile(path=str(to_rel),
1313
extra="New file has not been created yet"))
1314
only_change_inv = True
1315
elif not self.has_filename(from_rel) and self.has_filename(to_rel):
1316
only_change_inv = True
1317
elif self.has_filename(from_rel) and not self.has_filename(to_rel):
1318
only_change_inv = False
1319
elif (sys.platform == 'win32'
1320
and from_rel.lower() == to_rel.lower()
1321
and self.has_filename(from_rel)):
1322
only_change_inv = False
1324
# something is wrong, so lets determine what exactly
1325
if not self.has_filename(from_rel) and \
1326
not self.has_filename(to_rel):
1327
raise errors.BzrRenameFailedError(from_rel,to_rel,
1328
errors.PathsDoNotExist(paths=(str(from_rel),
1331
raise errors.RenameFailedFilesExist(from_rel, to_rel)
1332
rename_entry.only_change_inv = only_change_inv
1333
return rename_entries
1335
def _move(self, rename_entries):
1336
"""Moves a list of files.
1338
Depending on the value of the flag 'only_change_inv', the
1339
file will be moved on the file system or not.
1341
inv = self.inventory
1344
for entry in rename_entries:
1346
self._move_entry(entry)
1348
self._rollback_move(moved)
1352
def _rollback_move(self, moved):
1353
"""Try to rollback a previous move in case of an filesystem error."""
1354
inv = self.inventory
1357
self._move_entry(_RenameEntry(entry.to_rel, entry.from_id,
1358
entry.to_tail, entry.to_parent_id, entry.from_rel,
1359
entry.from_tail, entry.from_parent_id,
1360
entry.only_change_inv))
1361
except errors.BzrMoveFailedError, e:
1362
raise errors.BzrMoveFailedError( '', '', "Rollback failed."
1363
" The working tree is in an inconsistent state."
1364
" Please consider doing a 'bzr revert'."
1365
" Error message is: %s" % e)
1367
def _move_entry(self, entry):
1368
inv = self.inventory
1369
from_rel_abs = self.abspath(entry.from_rel)
1370
to_rel_abs = self.abspath(entry.to_rel)
1371
if from_rel_abs == to_rel_abs:
1372
raise errors.BzrMoveFailedError(entry.from_rel, entry.to_rel,
1373
"Source and target are identical.")
1375
if not entry.only_change_inv:
1377
osutils.rename(from_rel_abs, to_rel_abs)
1379
raise errors.BzrMoveFailedError(entry.from_rel,
1381
inv.rename(entry.from_id, entry.to_parent_id, entry.to_tail)
1060
1383
@needs_tree_write_lock
1061
def rename_one(self, from_rel, to_rel):
1384
def rename_one(self, from_rel, to_rel, after=False):
1062
1385
"""Rename one file.
1064
1387
This can change the directory or the filename or both.
1389
rename_one has several 'modes' to work. First, it can rename a physical
1390
file and change the file_id. That is the normal mode. Second, it can
1391
only change the file_id without touching any physical file. This is
1392
the new mode introduced in version 0.15.
1394
rename_one uses the second mode if 'after == True' and 'to_rel' is not
1395
versioned but present in the working tree.
1397
rename_one uses the second mode if 'after == False' and 'from_rel' is
1398
versioned but no longer in the working tree, and 'to_rel' is not
1399
versioned but present in the working tree.
1401
rename_one uses the first mode if 'after == False' and 'from_rel' is
1402
versioned and present in the working tree, and 'to_rel' is not
1403
versioned and not present in the working tree.
1405
Everything else results in an error.
1066
1407
inv = self.inventory
1067
if not self.has_filename(from_rel):
1068
raise BzrError("can't rename: old working file %r does not exist" % from_rel)
1069
if self.has_filename(to_rel):
1070
raise BzrError("can't rename: new working file %r already exists" % to_rel)
1072
file_id = inv.path2id(from_rel)
1074
raise BzrError("can't rename: old name %r is not versioned" % from_rel)
1076
entry = inv[file_id]
1077
from_parent = entry.parent_id
1078
from_name = entry.name
1080
if inv.path2id(to_rel):
1081
raise BzrError("can't rename: new name %r is already versioned" % to_rel)
1410
# create rename entries and tuples
1411
from_tail = splitpath(from_rel)[-1]
1412
from_id = inv.path2id(from_rel)
1414
raise errors.BzrRenameFailedError(from_rel,to_rel,
1415
errors.NotVersionedError(path=str(from_rel)))
1416
from_entry = inv[from_id]
1417
from_parent_id = from_entry.parent_id
1083
1418
to_dir, to_tail = os.path.split(to_rel)
1084
1419
to_dir_id = inv.path2id(to_dir)
1085
if to_dir_id is None and to_dir != '':
1086
raise BzrError("can't determine destination directory id for %r" % to_dir)
1088
mutter("rename_one:")
1089
mutter(" file_id {%s}" % file_id)
1090
mutter(" from_rel %r" % from_rel)
1091
mutter(" to_rel %r" % to_rel)
1092
mutter(" to_dir %r" % to_dir)
1093
mutter(" to_dir_id {%s}" % to_dir_id)
1095
inv.rename(file_id, to_dir_id, to_tail)
1097
from_abs = self.abspath(from_rel)
1098
to_abs = self.abspath(to_rel)
1100
rename(from_abs, to_abs)
1102
inv.rename(file_id, from_parent, from_name)
1103
raise BzrError("failed to rename %r to %r: %s"
1104
% (from_abs, to_abs, e[1]),
1105
["rename rolled back"])
1420
rename_entry = WorkingTree._RenameEntry(from_rel=from_rel,
1422
from_tail=from_tail,
1423
from_parent_id=from_parent_id,
1424
to_rel=to_rel, to_tail=to_tail,
1425
to_parent_id=to_dir_id)
1426
rename_entries.append(rename_entry)
1428
# determine which move mode to use. checks also for movability
1429
rename_entries = self._determine_mv_mode(rename_entries, after)
1431
# check if the target changed directory and if the target directory is
1433
if to_dir_id is None:
1434
raise errors.BzrMoveFailedError(from_rel,to_rel,
1435
errors.NotVersionedError(path=str(to_dir)))
1437
# all checks done. now we can continue with our actual work
1438
mutter('rename_one:\n'
1443
' to_dir_id {%s}\n',
1444
from_id, from_rel, to_rel, to_dir, to_dir_id)
1446
self._move(rename_entries)
1106
1447
self._write_inventory(inv)
1449
class _RenameEntry(object):
1450
def __init__(self, from_rel, from_id, from_tail, from_parent_id,
1451
to_rel, to_tail, to_parent_id, only_change_inv=False):
1452
self.from_rel = from_rel
1453
self.from_id = from_id
1454
self.from_tail = from_tail
1455
self.from_parent_id = from_parent_id
1456
self.to_rel = to_rel
1457
self.to_tail = to_tail
1458
self.to_parent_id = to_parent_id
1459
self.only_change_inv = only_change_inv
1108
1461
@needs_read_lock
1109
1462
def unknowns(self):
1110
1463
"""Return all unknown files.
1344
1653
If the file is ignored, returns the pattern which caused it to
1345
1654
be ignored, otherwise None. So this can simply be used as a
1346
1655
boolean if desired."""
1348
# TODO: Use '**' to match directories, and other extended
1349
# globbing stuff from cvs/rsync.
1351
# XXX: fnmatch is actually not quite what we want: it's only
1352
# approximately the same as real Unix fnmatch, and doesn't
1353
# treat dotfiles correctly and allows * to match /.
1354
# Eventually it should be replaced with something more
1357
rules = self._get_ignore_rules_as_regex()
1358
for regex, mapping in rules:
1359
match = regex.match(filename)
1360
if match is not None:
1361
# one or more of the groups in mapping will have a non-None
1363
groups = match.groups()
1364
rules = [mapping[group] for group in
1365
mapping if groups[group] is not None]
1656
if getattr(self, '_ignoreglobster', None) is None:
1657
self._ignoreglobster = globbing.Globster(self.get_ignore_list())
1658
return self._ignoreglobster.match(filename)
1369
1660
def kind(self, file_id):
1370
1661
return file_kind(self.id2abspath(file_id))
1663
def stored_kind(self, file_id):
1664
"""See Tree.stored_kind"""
1665
return self.inventory[file_id].kind
1667
def _comparison_data(self, entry, path):
1668
abspath = self.abspath(path)
1670
stat_value = os.lstat(abspath)
1672
if getattr(e, 'errno', None) == errno.ENOENT:
1679
mode = stat_value.st_mode
1680
kind = osutils.file_kind_from_stat_mode(mode)
1681
if not supports_executable():
1682
executable = entry is not None and entry.executable
1684
executable = bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
1685
return kind, executable, stat_value
1687
def _file_size(self, entry, stat_value):
1688
return stat_value.st_size
1372
1690
def last_revision(self):
1373
"""Return the last revision id of this working tree.
1375
In early branch formats this was the same as the branch last_revision,
1376
but that cannot be relied upon - for working tree operations,
1377
always use tree.last_revision(). This returns the left most parent id,
1378
or None if there are no parents.
1380
This was deprecated as of 0.11. Please use get_parent_ids instead.
1691
"""Return the last revision of the branch for this tree.
1693
This format tree does not support a separate marker for last-revision
1694
compared to the branch.
1696
See MutableTree.last_revision
1382
1698
return self._last_revision()
1384
1700
@needs_read_lock
1385
1701
def _last_revision(self):
1386
1702
"""helper for get_parent_ids."""
1387
return self.branch.last_revision()
1703
return _mod_revision.ensure_null(self.branch.last_revision())
1389
1705
def is_locked(self):
1390
1706
return self._control_files.is_locked()
1708
def _must_be_locked(self):
1709
if not self.is_locked():
1710
raise errors.ObjectNotLocked(self)
1392
1712
def lock_read(self):
1393
1713
"""See Branch.lock_read, and WorkingTree.unlock."""
1714
if not self.is_locked():
1394
1716
self.branch.lock_read()
1396
1718
return self._control_files.lock_read()
1470
1807
xml = self.branch.repository.get_inventory_xml(new_revision)
1471
1808
firstline = xml.split('\n', 1)[0]
1472
1809
if (not 'revision_id="' in firstline or
1473
'format="6"' not in firstline):
1810
'format="7"' not in firstline):
1474
1811
inv = self.branch.repository.deserialise_inventory(
1475
1812
new_revision, xml)
1476
inv.revision_id = new_revision
1477
xml = bzrlib.xml6.serializer_v6.write_inventory_to_string(inv)
1478
assert isinstance(xml, str), 'serialised xml must be bytestring.'
1479
path = self._basis_inventory_name()
1481
self._control_files.put(path, sio)
1813
xml = self._create_basis_xml_from_inventory(new_revision, inv)
1814
self._write_basis_inventory(xml)
1482
1815
except (errors.NoSuchRevision, errors.RevisionNotPresent):
1485
1818
def read_basis_inventory(self):
1486
1819
"""Read the cached basis inventory."""
1487
1820
path = self._basis_inventory_name()
1488
return self._control_files.get(path).read()
1821
return self._transport.get_bytes(path)
1490
1823
@needs_read_lock
1491
1824
def read_working_inventory(self):
1492
"""Read the working inventory."""
1825
"""Read the working inventory.
1827
:raises errors.InventoryModified: read_working_inventory will fail
1828
when the current in memory inventory has been modified.
1830
# conceptually this should be an implementation detail of the tree.
1831
# XXX: Deprecate this.
1493
1832
# ElementTree does its own conversion from UTF-8, so open in
1495
result = bzrlib.xml5.serializer_v5.read_inventory(
1496
self._control_files.get('inventory'))
1497
self._set_inventory(result)
1834
if self._inventory_is_modified:
1835
raise errors.InventoryModified(self)
1836
result = self._deserialize(self._transport.get('inventory'))
1837
self._set_inventory(result, dirty=False)
1500
1840
@needs_tree_write_lock
1501
def remove(self, files, verbose=False, to_file=None):
1502
"""Remove nominated files from the working inventory..
1504
This does not remove their text. This does not run on XXX on what? RBC
1506
TODO: Refuse to remove modified files unless --force is given?
1508
TODO: Do something useful with directories.
1510
TODO: Should this remove the text or not? Tough call; not
1511
removing may be useful and the user can just use use rm, and
1512
is the opposite of add. Removing it is consistent with most
1513
other tools. Maybe an option.
1841
def remove(self, files, verbose=False, to_file=None, keep_files=True,
1843
"""Remove nominated files from the working inventory.
1845
:files: File paths relative to the basedir.
1846
:keep_files: If true, the files will also be kept.
1847
:force: Delete files and directories, even if they are changed and
1848
even if the directories are not empty.
1515
## TODO: Normalize names
1516
## TODO: Remove nested loops; better scalability
1517
1850
if isinstance(files, basestring):
1518
1851
files = [files]
1520
inv = self.inventory
1522
# do this before any modifications
1856
unknown_nested_files=set()
1858
def recurse_directory_to_add_files(directory):
1859
# Recurse directory and add all files
1860
# so we can check if they have changed.
1861
for parent_info, file_infos in\
1862
self.walkdirs(directory):
1863
for relpath, basename, kind, lstat, fileid, kind in file_infos:
1864
# Is it versioned or ignored?
1865
if self.path2id(relpath) or self.is_ignored(relpath):
1866
# Add nested content for deletion.
1867
new_files.add(relpath)
1869
# Files which are not versioned and not ignored
1870
# should be treated as unknown.
1871
unknown_nested_files.add((relpath, None, kind))
1873
for filename in files:
1874
# Get file name into canonical form.
1875
abspath = self.abspath(filename)
1876
filename = self.relpath(abspath)
1877
if len(filename) > 0:
1878
new_files.add(filename)
1879
recurse_directory_to_add_files(filename)
1881
files = list(new_files)
1884
return # nothing to do
1886
# Sort needed to first handle directory content before the directory
1887
files.sort(reverse=True)
1889
# Bail out if we are going to delete files we shouldn't
1890
if not keep_files and not force:
1891
has_changed_files = len(unknown_nested_files) > 0
1892
if not has_changed_files:
1893
for (file_id, path, content_change, versioned, parent_id, name,
1894
kind, executable) in self.iter_changes(self.basis_tree(),
1895
include_unchanged=True, require_versioned=False,
1896
want_unversioned=True, specific_files=files):
1897
if versioned == (False, False):
1898
# The record is unknown ...
1899
if not self.is_ignored(path[1]):
1900
# ... but not ignored
1901
has_changed_files = True
1903
elif content_change and (kind[1] is not None):
1904
# Versioned and changed, but not deleted
1905
has_changed_files = True
1908
if has_changed_files:
1909
# Make delta show ALL applicable changes in error message.
1910
tree_delta = self.changes_from(self.basis_tree(),
1911
require_versioned=False, want_unversioned=True,
1912
specific_files=files)
1913
for unknown_file in unknown_nested_files:
1914
if unknown_file not in tree_delta.unversioned:
1915
tree_delta.unversioned.extend((unknown_file,))
1916
raise errors.BzrRemoveChangedFilesError(tree_delta)
1918
# Build inv_delta and delete files where applicaple,
1919
# do this before any modifications to inventory.
1523
1920
for f in files:
1524
fid = inv.path2id(f)
1921
fid = self.path2id(f)
1526
# TODO: Perhaps make this just a warning, and continue?
1527
# This tends to happen when
1528
raise NotVersionedError(path=f)
1530
# having remove it, it must be either ignored or unknown
1531
if self.is_ignored(f):
1535
show_status(new_status, inv[fid].kind, f, to_file=to_file)
1538
self._write_inventory(inv)
1924
message = "%s is not versioned." % (f,)
1927
# having removed it, it must be either ignored or unknown
1928
if self.is_ignored(f):
1932
textui.show_status(new_status, self.kind(fid), f,
1935
inv_delta.append((f, None, fid, None))
1936
message = "removed %s" % (f,)
1939
abs_path = self.abspath(f)
1940
if osutils.lexists(abs_path):
1941
if (osutils.isdir(abs_path) and
1942
len(os.listdir(abs_path)) > 0):
1944
osutils.rmtree(abs_path)
1946
message = "%s is not an empty directory "\
1947
"and won't be deleted." % (f,)
1949
osutils.delete_any(abs_path)
1950
message = "deleted %s" % (f,)
1951
elif message is not None:
1952
# Only care if we haven't done anything yet.
1953
message = "%s does not exist." % (f,)
1955
# Print only one message (if any) per file.
1956
if message is not None:
1958
self.apply_inventory_delta(inv_delta)
1540
1960
@needs_tree_write_lock
1541
def revert(self, filenames, old_tree=None, backups=True,
1542
pb=DummyProgress()):
1543
from transform import revert
1544
from conflicts import resolve
1961
def revert(self, filenames=None, old_tree=None, backups=True,
1962
pb=DummyProgress(), report_changes=False):
1963
from bzrlib.conflicts import resolve
1966
symbol_versioning.warn('Using [] to revert all files is deprecated'
1967
' as of bzr 0.91. Please use None (the default) instead.',
1968
DeprecationWarning, stacklevel=2)
1545
1969
if old_tree is None:
1546
old_tree = self.basis_tree()
1547
conflicts = revert(self, old_tree, filenames, backups, pb)
1548
if not len(filenames):
1549
self.set_parent_ids(self.get_parent_ids()[:1])
1970
basis_tree = self.basis_tree()
1971
basis_tree.lock_read()
1972
old_tree = basis_tree
1552
resolve(self, filenames, ignore_misses=True)
1976
conflicts = transform.revert(self, old_tree, filenames, backups, pb,
1978
if filenames is None and len(self.get_parent_ids()) > 1:
1980
last_revision = self.last_revision()
1981
if last_revision != NULL_REVISION:
1982
if basis_tree is None:
1983
basis_tree = self.basis_tree()
1984
basis_tree.lock_read()
1985
parent_trees.append((last_revision, basis_tree))
1986
self.set_parent_trees(parent_trees)
1989
resolve(self, filenames, ignore_misses=True, recursive=True)
1991
if basis_tree is not None:
1553
1993
return conflicts
1995
def revision_tree(self, revision_id):
1996
"""See Tree.revision_tree.
1998
WorkingTree can supply revision_trees for the basis revision only
1999
because there is only one cached inventory in the bzr directory.
2001
if revision_id == self.last_revision():
2003
xml = self.read_basis_inventory()
2004
except errors.NoSuchFile:
2008
inv = xml7.serializer_v7.read_inventory_from_string(xml)
2009
# dont use the repository revision_tree api because we want
2010
# to supply the inventory.
2011
if inv.revision_id == revision_id:
2012
return revisiontree.RevisionTree(self.branch.repository,
2014
except errors.BadInventoryFormat:
2016
# raise if there was no inventory, or if we read the wrong inventory.
2017
raise errors.NoSuchRevisionInTree(self, revision_id)
1555
2019
# XXX: This method should be deprecated in favour of taking in a proper
1556
2020
# new Inventory object.
1557
2021
@needs_tree_write_lock
1684
2203
# the working tree had the same last-revision as the master
1685
2204
# branch did. We may still have pivot local work from the local
1686
2205
# branch into old_tip:
1687
if old_tip is not None:
2206
if (old_tip is not None and not _mod_revision.is_null(old_tip)):
1688
2207
self.add_parent_tree_id(old_tip)
1689
if old_tip and old_tip != last_rev:
2208
if (old_tip is not None and not _mod_revision.is_null(old_tip)
2209
and old_tip != last_rev):
1690
2210
# our last revision was not the prior branch last revision
1691
2211
# and we have converted that last revision to a pending merge.
1692
2212
# base is somewhere between the branch tip now
1693
2213
# and the now pending merge
1694
from bzrlib.revision import common_ancestor
1696
base_rev_id = common_ancestor(revision,
1698
self.branch.repository)
1699
except errors.NoCommonAncestor:
2215
# Since we just modified the working tree and inventory, flush out
2216
# the current state, before we modify it again.
2217
# TODO: jam 20070214 WorkingTree3 doesn't require this, dirstate
2218
# requires it only because TreeTransform directly munges the
2219
# inventory and calls tree._write_inventory(). Ultimately we
2220
# should be able to remove this extra flush.
2222
graph = self.branch.repository.get_graph()
2223
base_rev_id = graph.find_unique_lca(revision, old_tip)
1701
2224
base_tree = self.branch.repository.revision_tree(base_rev_id)
1702
2225
other_tree = self.branch.repository.revision_tree(old_tip)
1703
result += merge_inner(self.branch,
2226
result += merge.merge_inner(
2231
change_reporter=change_reporter)
2234
def _write_hashcache_if_dirty(self):
2235
"""Write out the hashcache if it is dirty."""
2236
if self._hashcache.needs_write:
2238
self._hashcache.write()
2240
if e.errno not in (errno.EPERM, errno.EACCES):
2242
# TODO: jam 20061219 Should this be a warning? A single line
2243
# warning might be sufficient to let the user know what
2245
mutter('Could not write hashcache for %s\nError: %s',
2246
self._hashcache.cache_file_name(), e)
1709
2248
@needs_tree_write_lock
1710
2249
def _write_inventory(self, inv):
1711
2250
"""Write inventory as the current inventory."""
1713
bzrlib.xml5.serializer_v5.write_inventory(inv, sio)
1715
self._control_files.put('inventory', sio)
1716
self._set_inventory(inv)
1717
mutter('wrote working inventory')
2251
self._set_inventory(inv, dirty=True)
1719
2254
def set_conflicts(self, arg):
1720
raise UnsupportedOperation(self.set_conflicts, self)
2255
raise errors.UnsupportedOperation(self.set_conflicts, self)
1722
2257
def add_conflicts(self, arg):
1723
raise UnsupportedOperation(self.add_conflicts, self)
2258
raise errors.UnsupportedOperation(self.add_conflicts, self)
1725
2260
@needs_read_lock
1726
2261
def conflicts(self):
1727
conflicts = ConflictList()
2262
conflicts = _mod_conflicts.ConflictList()
1728
2263
for conflicted in self._iter_conflicts():
1743
2278
if text == False:
1745
2280
ctype = {True: 'text conflict', False: 'contents conflict'}[text]
1746
conflicts.append(Conflict.factory(ctype, path=conflicted,
2281
conflicts.append(_mod_conflicts.Conflict.factory(ctype,
1747
2283
file_id=self.path2id(conflicted)))
1748
2284
return conflicts
2286
def walkdirs(self, prefix=""):
2287
"""Walk the directories of this tree.
2289
returns a generator which yields items in the form:
2290
((curren_directory_path, fileid),
2291
[(file1_path, file1_name, file1_kind, (lstat), file1_id,
2294
This API returns a generator, which is only valid during the current
2295
tree transaction - within a single lock_read or lock_write duration.
2297
If the tree is not locked, it may cause an error to be raised,
2298
depending on the tree implementation.
2300
disk_top = self.abspath(prefix)
2301
if disk_top.endswith('/'):
2302
disk_top = disk_top[:-1]
2303
top_strip_len = len(disk_top) + 1
2304
inventory_iterator = self._walkdirs(prefix)
2305
disk_iterator = osutils.walkdirs(disk_top, prefix)
2307
current_disk = disk_iterator.next()
2308
disk_finished = False
2310
if not (e.errno == errno.ENOENT or
2311
(sys.platform == 'win32' and e.errno == ERROR_PATH_NOT_FOUND)):
2314
disk_finished = True
2316
current_inv = inventory_iterator.next()
2317
inv_finished = False
2318
except StopIteration:
2321
while not inv_finished or not disk_finished:
2323
((cur_disk_dir_relpath, cur_disk_dir_path_from_top),
2324
cur_disk_dir_content) = current_disk
2326
((cur_disk_dir_relpath, cur_disk_dir_path_from_top),
2327
cur_disk_dir_content) = ((None, None), None)
2328
if not disk_finished:
2329
# strip out .bzr dirs
2330
if (cur_disk_dir_path_from_top[top_strip_len:] == '' and
2331
len(cur_disk_dir_content) > 0):
2332
# osutils.walkdirs can be made nicer -
2333
# yield the path-from-prefix rather than the pathjoined
2335
bzrdir_loc = bisect_left(cur_disk_dir_content,
2337
if cur_disk_dir_content[bzrdir_loc][0] == '.bzr':
2338
# we dont yield the contents of, or, .bzr itself.
2339
del cur_disk_dir_content[bzrdir_loc]
2341
# everything is unknown
2344
# everything is missing
2347
direction = cmp(current_inv[0][0], cur_disk_dir_relpath)
2349
# disk is before inventory - unknown
2350
dirblock = [(relpath, basename, kind, stat, None, None) for
2351
relpath, basename, kind, stat, top_path in
2352
cur_disk_dir_content]
2353
yield (cur_disk_dir_relpath, None), dirblock
2355
current_disk = disk_iterator.next()
2356
except StopIteration:
2357
disk_finished = True
2359
# inventory is before disk - missing.
2360
dirblock = [(relpath, basename, 'unknown', None, fileid, kind)
2361
for relpath, basename, dkind, stat, fileid, kind in
2363
yield (current_inv[0][0], current_inv[0][1]), dirblock
2365
current_inv = inventory_iterator.next()
2366
except StopIteration:
2369
# versioned present directory
2370
# merge the inventory and disk data together
2372
for relpath, subiterator in itertools.groupby(sorted(
2373
current_inv[1] + cur_disk_dir_content,
2374
key=operator.itemgetter(0)), operator.itemgetter(1)):
2375
path_elements = list(subiterator)
2376
if len(path_elements) == 2:
2377
inv_row, disk_row = path_elements
2378
# versioned, present file
2379
dirblock.append((inv_row[0],
2380
inv_row[1], disk_row[2],
2381
disk_row[3], inv_row[4],
2383
elif len(path_elements[0]) == 5:
2385
dirblock.append((path_elements[0][0],
2386
path_elements[0][1], path_elements[0][2],
2387
path_elements[0][3], None, None))
2388
elif len(path_elements[0]) == 6:
2389
# versioned, absent file.
2390
dirblock.append((path_elements[0][0],
2391
path_elements[0][1], 'unknown', None,
2392
path_elements[0][4], path_elements[0][5]))
2394
raise NotImplementedError('unreachable code')
2395
yield current_inv[0], dirblock
2397
current_inv = inventory_iterator.next()
2398
except StopIteration:
2401
current_disk = disk_iterator.next()
2402
except StopIteration:
2403
disk_finished = True
2405
def _walkdirs(self, prefix=""):
2406
"""Walk the directories of this tree.
2408
:prefix: is used as the directrory to start with.
2409
returns a generator which yields items in the form:
2410
((curren_directory_path, fileid),
2411
[(file1_path, file1_name, file1_kind, None, file1_id,
2414
_directory = 'directory'
2415
# get the root in the inventory
2416
inv = self.inventory
2417
top_id = inv.path2id(prefix)
2421
pending = [(prefix, '', _directory, None, top_id, None)]
2424
currentdir = pending.pop()
2425
# 0 - relpath, 1- basename, 2- kind, 3- stat, 4-id, 5-kind
2426
top_id = currentdir[4]
2428
relroot = currentdir[0] + '/'
2431
# FIXME: stash the node in pending
2433
if entry.kind == 'directory':
2434
for name, child in entry.sorted_children():
2435
dirblock.append((relroot + name, name, child.kind, None,
2436
child.file_id, child.kind
2438
yield (currentdir[0], entry.file_id), dirblock
2439
# push the user specified dirs from dirblock
2440
for dir in reversed(dirblock):
2441
if dir[2] == _directory:
2444
@needs_tree_write_lock
2445
def auto_resolve(self):
2446
"""Automatically resolve text conflicts according to contents.
2448
Only text conflicts are auto_resolvable. Files with no conflict markers
2449
are considered 'resolved', because bzr always puts conflict markers
2450
into files that have text conflicts. The corresponding .THIS .BASE and
2451
.OTHER files are deleted, as per 'resolve'.
2452
:return: a tuple of ConflictLists: (un_resolved, resolved).
2454
un_resolved = _mod_conflicts.ConflictList()
2455
resolved = _mod_conflicts.ConflictList()
2456
conflict_re = re.compile('^(<{7}|={7}|>{7})')
2457
for conflict in self.conflicts():
2458
if (conflict.typestring != 'text conflict' or
2459
self.kind(conflict.file_id) != 'file'):
2460
un_resolved.append(conflict)
2462
my_file = open(self.id2abspath(conflict.file_id), 'rb')
2464
for line in my_file:
2465
if conflict_re.search(line):
2466
un_resolved.append(conflict)
2469
resolved.append(conflict)
2472
resolved.remove_files(self)
2473
self.set_conflicts(un_resolved)
2474
return un_resolved, resolved
2478
tree_basis = self.basis_tree()
2479
tree_basis.lock_read()
2481
repo_basis = self.branch.repository.revision_tree(
2482
self.last_revision())
2483
if len(list(repo_basis.iter_changes(tree_basis))) > 0:
2484
raise errors.BzrCheckError(
2485
"Mismatched basis inventory content.")
2490
def _validate(self):
2491
"""Validate internal structures.
2493
This is meant mostly for the test suite. To give it a chance to detect
2494
corruption after actions have occurred. The default implementation is a
2497
:return: None. An exception should be raised if there is an error.
2502
def _get_rules_searcher(self, default_searcher):
2503
"""See Tree._get_rules_searcher."""
2504
if self._rules_searcher is None:
2505
self._rules_searcher = super(WorkingTree,
2506
self)._get_rules_searcher(default_searcher)
2507
return self._rules_searcher
1751
2510
class WorkingTree2(WorkingTree):
1752
2511
"""This is the Format 2 working tree.