210
679
return self.inventory.has_id(file_id)
212
681
__contains__ = has_id
215
683
def get_file_size(self, file_id):
216
return os.path.getsize(self.id2abspath(file_id))
218
def get_file_sha1(self, file_id):
219
path = self._inventory.id2path(file_id)
220
return self._hashcache.get_sha1(path)
223
def is_executable(self, file_id):
684
"""See Tree.get_file_size"""
685
# XXX: this returns the on-disk size; it should probably return the
688
return os.path.getsize(self.id2abspath(file_id))
690
if e.errno != errno.ENOENT:
696
def get_file_sha1(self, file_id, path=None, stat_value=None):
698
path = self._inventory.id2path(file_id)
699
return self._hashcache.get_sha1(path, stat_value)
701
def get_file_mtime(self, file_id, path=None):
703
path = self.inventory.id2path(file_id)
704
return os.lstat(self.abspath(path)).st_mtime
706
def _is_executable_from_path_and_stat_from_basis(self, path, stat_result):
707
file_id = self.path2id(path)
709
# For unversioned files on win32, we just assume they are not
712
return self._inventory[file_id].executable
714
def _is_executable_from_path_and_stat_from_stat(self, path, stat_result):
715
mode = stat_result.st_mode
716
return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
718
if not supports_executable():
719
def is_executable(self, file_id, path=None):
225
720
return self._inventory[file_id].executable
227
path = self._inventory.id2path(file_id)
722
_is_executable_from_path_and_stat = \
723
_is_executable_from_path_and_stat_from_basis
725
def is_executable(self, file_id, path=None):
727
path = self.id2path(file_id)
228
728
mode = os.lstat(self.abspath(path)).st_mode
229
return bool(stat.S_ISREG(mode) and stat.S_IEXEC&mode)
729
return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
731
_is_executable_from_path_and_stat = \
732
_is_executable_from_path_and_stat_from_stat
734
@needs_tree_write_lock
735
def _add(self, files, ids, kinds):
736
"""See MutableTree._add."""
737
# TODO: Re-adding a file that is removed in the working copy
738
# should probably put it back with the previous ID.
739
# the read and write working inventory should not occur in this
740
# function - they should be part of lock_write and unlock.
742
for f, file_id, kind in zip(files, ids, kinds):
744
inv.add_path(f, kind=kind)
746
inv.add_path(f, kind=kind, file_id=file_id)
747
self._inventory_is_modified = True
749
@needs_tree_write_lock
750
def _gather_kinds(self, files, kinds):
751
"""See MutableTree._gather_kinds."""
752
for pos, f in enumerate(files):
753
if kinds[pos] is None:
754
fullpath = normpath(self.abspath(f))
756
kinds[pos] = file_kind(fullpath)
758
if e.errno == errno.ENOENT:
759
raise errors.NoSuchFile(fullpath)
762
def add_parent_tree_id(self, revision_id, allow_leftmost_as_ghost=False):
763
"""Add revision_id as a parent.
765
This is equivalent to retrieving the current list of parent ids
766
and setting the list to its value plus revision_id.
768
:param revision_id: The revision id to add to the parent list. It may
769
be a ghost revision as long as its not the first parent to be added,
770
or the allow_leftmost_as_ghost parameter is set True.
771
:param allow_leftmost_as_ghost: Allow the first parent to be a ghost.
773
parents = self.get_parent_ids() + [revision_id]
774
self.set_parent_ids(parents, allow_leftmost_as_ghost=len(parents) > 1
775
or allow_leftmost_as_ghost)
777
@needs_tree_write_lock
778
def add_parent_tree(self, parent_tuple, allow_leftmost_as_ghost=False):
779
"""Add revision_id, tree tuple as a parent.
781
This is equivalent to retrieving the current list of parent trees
782
and setting the list to its value plus parent_tuple. See also
783
add_parent_tree_id - if you only have a parent id available it will be
784
simpler to use that api. If you have the parent already available, using
785
this api is preferred.
787
:param parent_tuple: The (revision id, tree) to add to the parent list.
788
If the revision_id is a ghost, pass None for the tree.
789
:param allow_leftmost_as_ghost: Allow the first parent to be a ghost.
791
parent_ids = self.get_parent_ids() + [parent_tuple[0]]
792
if len(parent_ids) > 1:
793
# the leftmost may have already been a ghost, preserve that if it
795
allow_leftmost_as_ghost = True
796
self.set_parent_ids(parent_ids,
797
allow_leftmost_as_ghost=allow_leftmost_as_ghost)
799
@needs_tree_write_lock
800
def add_pending_merge(self, *revision_ids):
801
# TODO: Perhaps should check at this point that the
802
# history of the revision is actually present?
803
parents = self.get_parent_ids()
805
for rev_id in revision_ids:
806
if rev_id in parents:
808
parents.append(rev_id)
811
self.set_parent_ids(parents, allow_leftmost_as_ghost=True)
813
def path_content_summary(self, path, _lstat=os.lstat,
814
_mapper=osutils.file_kind_from_stat_mode):
815
"""See Tree.path_content_summary."""
816
abspath = self.abspath(path)
818
stat_result = _lstat(abspath)
820
if getattr(e, 'errno', None) == errno.ENOENT:
822
return ('missing', None, None, None)
823
# propagate other errors
825
kind = _mapper(stat_result.st_mode)
827
return self._file_content_summary(path, stat_result)
828
elif kind == 'directory':
829
# perhaps it looks like a plain directory, but it's really a
831
if self._directory_is_tree_reference(path):
832
kind = 'tree-reference'
833
return kind, None, None, None
834
elif kind == 'symlink':
835
target = osutils.readlink(abspath)
836
return ('symlink', None, None, target)
838
return (kind, None, None, None)
840
def _file_content_summary(self, path, stat_result):
841
size = stat_result.st_size
842
executable = self._is_executable_from_path_and_stat(path, stat_result)
843
# try for a stat cache lookup
844
return ('file', size, executable, self._sha_from_stat(
847
def _check_parents_for_ghosts(self, revision_ids, allow_leftmost_as_ghost):
848
"""Common ghost checking functionality from set_parent_*.
850
This checks that the left hand-parent exists if there are any
853
if len(revision_ids) > 0:
854
leftmost_id = revision_ids[0]
855
if (not allow_leftmost_as_ghost and not
856
self.branch.repository.has_revision(leftmost_id)):
857
raise errors.GhostRevisionUnusableHere(leftmost_id)
859
def _set_merges_from_parent_ids(self, parent_ids):
860
merges = parent_ids[1:]
861
self._transport.put_bytes('pending-merges', '\n'.join(merges),
862
mode=self.bzrdir._get_file_mode())
864
def _filter_parent_ids_by_ancestry(self, revision_ids):
865
"""Check that all merged revisions are proper 'heads'.
867
This will always return the first revision_id, and any merged revisions
870
if len(revision_ids) == 0:
872
graph = self.branch.repository.get_graph()
873
heads = graph.heads(revision_ids)
874
new_revision_ids = revision_ids[:1]
875
for revision_id in revision_ids[1:]:
876
if revision_id in heads and revision_id not in new_revision_ids:
877
new_revision_ids.append(revision_id)
878
if new_revision_ids != revision_ids:
879
trace.mutter('requested to set revision_ids = %s,'
880
' but filtered to %s', revision_ids, new_revision_ids)
881
return new_revision_ids
883
@needs_tree_write_lock
884
def set_parent_ids(self, revision_ids, allow_leftmost_as_ghost=False):
885
"""Set the parent ids to revision_ids.
887
See also set_parent_trees. This api will try to retrieve the tree data
888
for each element of revision_ids from the trees repository. If you have
889
tree data already available, it is more efficient to use
890
set_parent_trees rather than set_parent_ids. set_parent_ids is however
891
an easier API to use.
893
:param revision_ids: The revision_ids to set as the parent ids of this
894
working tree. Any of these may be ghosts.
896
self._check_parents_for_ghosts(revision_ids,
897
allow_leftmost_as_ghost=allow_leftmost_as_ghost)
898
for revision_id in revision_ids:
899
_mod_revision.check_not_reserved_id(revision_id)
901
revision_ids = self._filter_parent_ids_by_ancestry(revision_ids)
903
if len(revision_ids) > 0:
904
self.set_last_revision(revision_ids[0])
906
self.set_last_revision(_mod_revision.NULL_REVISION)
908
self._set_merges_from_parent_ids(revision_ids)
910
@needs_tree_write_lock
911
def set_parent_trees(self, parents_list, allow_leftmost_as_ghost=False):
912
"""See MutableTree.set_parent_trees."""
913
parent_ids = [rev for (rev, tree) in parents_list]
914
for revision_id in parent_ids:
915
_mod_revision.check_not_reserved_id(revision_id)
917
self._check_parents_for_ghosts(parent_ids,
918
allow_leftmost_as_ghost=allow_leftmost_as_ghost)
920
parent_ids = self._filter_parent_ids_by_ancestry(parent_ids)
922
if len(parent_ids) == 0:
923
leftmost_parent_id = _mod_revision.NULL_REVISION
924
leftmost_parent_tree = None
926
leftmost_parent_id, leftmost_parent_tree = parents_list[0]
928
if self._change_last_revision(leftmost_parent_id):
929
if leftmost_parent_tree is None:
930
# If we don't have a tree, fall back to reading the
931
# parent tree from the repository.
932
self._cache_basis_inventory(leftmost_parent_id)
934
inv = leftmost_parent_tree.inventory
935
xml = self._create_basis_xml_from_inventory(
936
leftmost_parent_id, inv)
937
self._write_basis_inventory(xml)
938
self._set_merges_from_parent_ids(parent_ids)
940
@needs_tree_write_lock
941
def set_pending_merges(self, rev_list):
942
parents = self.get_parent_ids()
943
leftmost = parents[:1]
944
new_parents = leftmost + rev_list
945
self.set_parent_ids(new_parents)
947
@needs_tree_write_lock
948
def set_merge_modified(self, modified_hashes):
950
for file_id, hash in modified_hashes.iteritems():
951
yield Stanza(file_id=file_id.decode('utf8'), hash=hash)
952
self._put_rio('merge-hashes', iter_stanzas(), MERGE_MODIFIED_HEADER_1)
954
def _sha_from_stat(self, path, stat_result):
955
"""Get a sha digest from the tree's stat cache.
957
The default implementation assumes no stat cache is present.
959
:param path: The path.
960
:param stat_result: The stat result being looked up.
964
def _put_rio(self, filename, stanzas, header):
965
self._must_be_locked()
966
my_file = rio_file(stanzas, header)
967
self._transport.put_file(filename, my_file,
968
mode=self.bzrdir._get_file_mode())
970
@needs_write_lock # because merge pulls data into the branch.
971
def merge_from_branch(self, branch, to_revision=None, from_revision=None,
972
merge_type=None, force=False):
973
"""Merge from a branch into this working tree.
975
:param branch: The branch to merge from.
976
:param to_revision: If non-None, the merge will merge to to_revision,
977
but not beyond it. to_revision does not need to be in the history
978
of the branch when it is supplied. If None, to_revision defaults to
979
branch.last_revision().
981
from bzrlib.merge import Merger, Merge3Merger
982
merger = Merger(self.branch, this_tree=self)
983
# check that there are no local alterations
984
if not force and self.has_changes():
985
raise errors.UncommittedChanges(self)
986
if to_revision is None:
987
to_revision = _mod_revision.ensure_null(branch.last_revision())
988
merger.other_rev_id = to_revision
989
if _mod_revision.is_null(merger.other_rev_id):
990
raise errors.NoCommits(branch)
991
self.branch.fetch(branch, last_revision=merger.other_rev_id)
992
merger.other_basis = merger.other_rev_id
993
merger.other_tree = self.branch.repository.revision_tree(
995
merger.other_branch = branch
996
if from_revision is None:
999
merger.set_base_revision(from_revision, branch)
1000
if merger.base_rev_id == merger.other_rev_id:
1001
raise errors.PointlessMerge
1002
merger.backup_files = False
1003
if merge_type is None:
1004
merger.merge_type = Merge3Merger
1006
merger.merge_type = merge_type
1007
merger.set_interesting_files(None)
1008
merger.show_base = False
1009
merger.reprocess = False
1010
conflicts = merger.do_merge()
1011
merger.set_pending()
1015
def merge_modified(self):
1016
"""Return a dictionary of files modified by a merge.
1018
The list is initialized by WorkingTree.set_merge_modified, which is
1019
typically called after we make some automatic updates to the tree
1022
This returns a map of file_id->sha1, containing only files which are
1023
still in the working inventory and have that text hash.
1026
hashfile = self._transport.get('merge-hashes')
1027
except errors.NoSuchFile:
1032
if hashfile.next() != MERGE_MODIFIED_HEADER_1 + '\n':
1033
raise errors.MergeModifiedFormatError()
1034
except StopIteration:
1035
raise errors.MergeModifiedFormatError()
1036
for s in RioReader(hashfile):
1037
# RioReader reads in Unicode, so convert file_ids back to utf8
1038
file_id = osutils.safe_file_id(s.get("file_id"), warn=False)
1039
if file_id not in self.inventory:
1041
text_hash = s.get("hash")
1042
if text_hash == self.get_file_sha1(file_id):
1043
merge_hashes[file_id] = text_hash
1049
def mkdir(self, path, file_id=None):
1050
"""See MutableTree.mkdir()."""
1052
file_id = generate_ids.gen_file_id(os.path.basename(path))
1053
os.mkdir(self.abspath(path))
1054
self.add(path, file_id, 'directory')
231
1057
def get_symlink_target(self, file_id):
232
return os.readlink(self.id2abspath(file_id))
234
def file_class(self, filename):
235
if self.path2id(filename):
237
elif self.is_ignored(filename):
243
def list_files(self):
244
"""Recursively list all files as (path, class, kind, id).
1058
abspath = self.id2abspath(file_id)
1059
target = osutils.readlink(abspath)
1063
def subsume(self, other_tree):
1064
def add_children(inventory, entry):
1065
for child_entry in entry.children.values():
1066
inventory._byid[child_entry.file_id] = child_entry
1067
if child_entry.kind == 'directory':
1068
add_children(inventory, child_entry)
1069
if other_tree.get_root_id() == self.get_root_id():
1070
raise errors.BadSubsumeSource(self, other_tree,
1071
'Trees have the same root')
1073
other_tree_path = self.relpath(other_tree.basedir)
1074
except errors.PathNotChild:
1075
raise errors.BadSubsumeSource(self, other_tree,
1076
'Tree is not contained by the other')
1077
new_root_parent = self.path2id(osutils.dirname(other_tree_path))
1078
if new_root_parent is None:
1079
raise errors.BadSubsumeSource(self, other_tree,
1080
'Parent directory is not versioned.')
1081
# We need to ensure that the result of a fetch will have a
1082
# versionedfile for the other_tree root, and only fetching into
1083
# RepositoryKnit2 guarantees that.
1084
if not self.branch.repository.supports_rich_root():
1085
raise errors.SubsumeTargetNeedsUpgrade(other_tree)
1086
other_tree.lock_tree_write()
1088
new_parents = other_tree.get_parent_ids()
1089
other_root = other_tree.inventory.root
1090
other_root.parent_id = new_root_parent
1091
other_root.name = osutils.basename(other_tree_path)
1092
self.inventory.add(other_root)
1093
add_children(self.inventory, other_root)
1094
self._write_inventory(self.inventory)
1095
# normally we don't want to fetch whole repositories, but i think
1096
# here we really do want to consolidate the whole thing.
1097
for parent_id in other_tree.get_parent_ids():
1098
self.branch.fetch(other_tree.branch, parent_id)
1099
self.add_parent_tree_id(parent_id)
1102
other_tree.bzrdir.retire_bzrdir()
1104
def _setup_directory_is_tree_reference(self):
1105
if self._branch.repository._format.supports_tree_reference:
1106
self._directory_is_tree_reference = \
1107
self._directory_may_be_tree_reference
1109
self._directory_is_tree_reference = \
1110
self._directory_is_never_tree_reference
1112
def _directory_is_never_tree_reference(self, relpath):
1115
def _directory_may_be_tree_reference(self, relpath):
1116
# as a special case, if a directory contains control files then
1117
# it's a tree reference, except that the root of the tree is not
1118
return relpath and osutils.isdir(self.abspath(relpath) + u"/.bzr")
1119
# TODO: We could ask all the control formats whether they
1120
# recognize this directory, but at the moment there's no cheap api
1121
# to do that. Since we probably can only nest bzr checkouts and
1122
# they always use this name it's ok for now. -- mbp 20060306
1124
# FIXME: There is an unhandled case here of a subdirectory
1125
# containing .bzr but not a branch; that will probably blow up
1126
# when you try to commit it. It might happen if there is a
1127
# checkout in a subdirectory. This can be avoided by not adding
1130
@needs_tree_write_lock
1131
def extract(self, file_id, format=None):
1132
"""Extract a subtree from this tree.
1134
A new branch will be created, relative to the path for this tree.
1138
segments = osutils.splitpath(path)
1139
transport = self.branch.bzrdir.root_transport
1140
for name in segments:
1141
transport = transport.clone(name)
1142
transport.ensure_base()
1145
sub_path = self.id2path(file_id)
1146
branch_transport = mkdirs(sub_path)
1148
format = self.bzrdir.cloning_metadir()
1149
branch_transport.ensure_base()
1150
branch_bzrdir = format.initialize_on_transport(branch_transport)
1152
repo = branch_bzrdir.find_repository()
1153
except errors.NoRepositoryPresent:
1154
repo = branch_bzrdir.create_repository()
1155
if not repo.supports_rich_root():
1156
raise errors.RootNotRich()
1157
new_branch = branch_bzrdir.create_branch()
1158
new_branch.pull(self.branch)
1159
for parent_id in self.get_parent_ids():
1160
new_branch.fetch(self.branch, parent_id)
1161
tree_transport = self.bzrdir.root_transport.clone(sub_path)
1162
if tree_transport.base != branch_transport.base:
1163
tree_bzrdir = format.initialize_on_transport(tree_transport)
1164
branch.BranchReferenceFormat().initialize(tree_bzrdir,
1165
target_branch=new_branch)
1167
tree_bzrdir = branch_bzrdir
1168
wt = tree_bzrdir.create_workingtree(_mod_revision.NULL_REVISION)
1169
wt.set_parent_ids(self.get_parent_ids())
1170
my_inv = self.inventory
1171
child_inv = inventory.Inventory(root_id=None)
1172
new_root = my_inv[file_id]
1173
my_inv.remove_recursive_id(file_id)
1174
new_root.parent_id = None
1175
child_inv.add(new_root)
1176
self._write_inventory(my_inv)
1177
wt._write_inventory(child_inv)
1180
def _serialize(self, inventory, out_file):
1181
xml5.serializer_v5.write_inventory(self._inventory, out_file,
1184
def _deserialize(selt, in_file):
1185
return xml5.serializer_v5.read_inventory(in_file)
1188
"""Write the in memory inventory to disk."""
1189
# TODO: Maybe this should only write on dirty ?
1190
if self._control_files._lock_mode != 'w':
1191
raise errors.NotWriteLocked(self)
1193
self._serialize(self._inventory, sio)
1195
self._transport.put_file('inventory', sio,
1196
mode=self.bzrdir._get_file_mode())
1197
self._inventory_is_modified = False
1199
def _kind(self, relpath):
1200
return osutils.file_kind(self.abspath(relpath))
1202
def list_files(self, include_root=False, from_dir=None, recursive=True):
1203
"""List all files as (path, class, kind, id, entry).
246
1205
Lists, but does not descend into unversioned directories.
248
1206
This does not include files that have been deleted in this
1207
tree. Skips the control directory.
251
Skips the control directory.
1209
:param include_root: if True, return an entry for the root
1210
:param from_dir: start from this directory or None for the root
1211
:param recursive: whether to recurse into subdirectories or not
253
inv = self._inventory
255
def descend(from_dir_relpath, from_dir_id, dp):
1213
# list_files is an iterator, so @needs_read_lock doesn't work properly
1214
# with it. So callers should be careful to always read_lock the tree.
1215
if not self.is_locked():
1216
raise errors.ObjectNotLocked(self)
1218
inv = self.inventory
1219
if from_dir is None and include_root is True:
1220
yield ('', 'V', 'directory', inv.root.file_id, inv.root)
1221
# Convert these into local objects to save lookup times
1222
pathjoin = osutils.pathjoin
1223
file_kind = self._kind
1225
# transport.base ends in a slash, we want the piece
1226
# between the last two slashes
1227
transport_base_dir = self.bzrdir.transport.base.rsplit('/', 2)[1]
1229
fk_entries = {'directory':TreeDirectory, 'file':TreeFile, 'symlink':TreeLink}
1231
# directory file_id, relative path, absolute path, reverse sorted children
1232
if from_dir is not None:
1233
from_dir_id = inv.path2id(from_dir)
1234
if from_dir_id is None:
1235
# Directory not versioned
1237
from_dir_abspath = pathjoin(self.basedir, from_dir)
1239
from_dir_id = inv.root.file_id
1240
from_dir_abspath = self.basedir
1241
children = os.listdir(from_dir_abspath)
1243
# jam 20060527 The kernel sized tree seems equivalent whether we
1244
# use a deque and popleft to keep them sorted, or if we use a plain
1245
# list and just reverse() them.
1246
children = collections.deque(children)
1247
stack = [(from_dir_id, u'', from_dir_abspath, children)]
1249
from_dir_id, from_dir_relpath, from_dir_abspath, children = stack[-1]
1252
f = children.popleft()
259
1253
## TODO: If we find a subdirectory with its own .bzr
260
1254
## directory, then that is a separate tree and we
261
1255
## should exclude it.
262
if bzrlib.BZRDIR == f:
1257
# the bzrdir for this tree
1258
if transport_base_dir == f:
266
fp = appendpath(from_dir_relpath, f)
1261
# we know that from_dir_relpath and from_dir_abspath never end in a slash
1262
# and 'f' doesn't begin with one, we can do a string op, rather
1263
# than the checks of pathjoin(), all relative paths will have an extra slash
1265
fp = from_dir_relpath + '/' + f
269
fap = appendpath(dp, f)
271
f_ie = inv.get_child(from_dir_id, f)
1268
fap = from_dir_abspath + '/' + f
1270
dir_ie = inv[from_dir_id]
1271
if dir_ie.kind == 'directory':
1272
f_ie = dir_ie.children.get(f)
274
elif self.is_ignored(fp):
1277
elif self.is_ignored(fp[1:]):
1280
# we may not have found this file, because of a unicode
1281
# issue, or because the directory was actually a symlink.
1282
f_norm, can_access = osutils.normalized_filename(f)
1283
if f == f_norm or not can_access:
1284
# No change, so treat this file normally
1287
# this file can be accessed by a normalized path
1288
# check again if it is versioned
1289
# these lines are repeated here for performance
1291
fp = from_dir_relpath + '/' + f
1292
fap = from_dir_abspath + '/' + f
1293
f_ie = inv.get_child(from_dir_id, f)
1296
elif self.is_ignored(fp[1:]):
279
1301
fk = file_kind(fap)
283
raise BzrCheckError("file %r entered as kind %r id %r, "
285
% (fap, f_ie.kind, f_ie.file_id, fk))
287
1303
# make a last minute entry
1305
yield fp[1:], c, fk, f_ie.file_id, f_ie
291
if fk == 'directory':
292
entry = TreeDirectory()
295
elif fk == 'symlink':
300
yield fp, c, fk, (f_ie and f_ie.file_id), entry
1308
yield fp[1:], c, fk, None, fk_entries[fk]()
1310
yield fp[1:], c, fk, None, TreeEntry()
302
1313
if fk != 'directory':
306
# don't descend unversioned directories
309
for ff in descend(fp, f_ie.file_id, fap):
312
for f in descend('', inv.root.file_id, self.basedir):
1316
# But do this child first if recursing down
1318
new_children = os.listdir(fap)
1320
new_children = collections.deque(new_children)
1321
stack.append((f_ie.file_id, fp, fap, new_children))
1322
# Break out of inner loop,
1323
# so that we start outer loop with child
1326
# if we finished all children, pop it off the stack
1329
@needs_tree_write_lock
1330
def move(self, from_paths, to_dir=None, after=False):
1333
to_dir must exist in the inventory.
1335
If to_dir exists and is a directory, the files are moved into
1336
it, keeping their old names.
1338
Note that to_dir is only the last component of the new name;
1339
this doesn't change the directory.
1341
For each entry in from_paths the move mode will be determined
1344
The first mode moves the file in the filesystem and updates the
1345
inventory. The second mode only updates the inventory without
1346
touching the file on the filesystem. This is the new mode introduced
1349
move uses the second mode if 'after == True' and the target is not
1350
versioned but present in the working tree.
1352
move uses the second mode if 'after == False' and the source is
1353
versioned but no longer in the working tree, and the target is not
1354
versioned but present in the working tree.
1356
move uses the first mode if 'after == False' and the source is
1357
versioned and present in the working tree, and the target is not
1358
versioned and not present in the working tree.
1360
Everything else results in an error.
1362
This returns a list of (from_path, to_path) pairs for each
1363
entry that is moved.
1368
# check for deprecated use of signature
1370
raise TypeError('You must supply a target directory')
1371
# check destination directory
1372
if isinstance(from_paths, basestring):
1374
inv = self.inventory
1375
to_abs = self.abspath(to_dir)
1376
if not isdir(to_abs):
1377
raise errors.BzrMoveFailedError('',to_dir,
1378
errors.NotADirectory(to_abs))
1379
if not self.has_filename(to_dir):
1380
raise errors.BzrMoveFailedError('',to_dir,
1381
errors.NotInWorkingDirectory(to_dir))
1382
to_dir_id = inv.path2id(to_dir)
1383
if to_dir_id is None:
1384
raise errors.BzrMoveFailedError('',to_dir,
1385
errors.NotVersionedError(path=str(to_dir)))
1387
to_dir_ie = inv[to_dir_id]
1388
if to_dir_ie.kind != 'directory':
1389
raise errors.BzrMoveFailedError('',to_dir,
1390
errors.NotADirectory(to_abs))
1392
# create rename entries and tuples
1393
for from_rel in from_paths:
1394
from_tail = splitpath(from_rel)[-1]
1395
from_id = inv.path2id(from_rel)
1397
raise errors.BzrMoveFailedError(from_rel,to_dir,
1398
errors.NotVersionedError(path=str(from_rel)))
1400
from_entry = inv[from_id]
1401
from_parent_id = from_entry.parent_id
1402
to_rel = pathjoin(to_dir, from_tail)
1403
rename_entry = WorkingTree._RenameEntry(from_rel=from_rel,
1405
from_tail=from_tail,
1406
from_parent_id=from_parent_id,
1407
to_rel=to_rel, to_tail=from_tail,
1408
to_parent_id=to_dir_id)
1409
rename_entries.append(rename_entry)
1410
rename_tuples.append((from_rel, to_rel))
1412
# determine which move mode to use. checks also for movability
1413
rename_entries = self._determine_mv_mode(rename_entries, after)
1415
original_modified = self._inventory_is_modified
1418
self._inventory_is_modified = True
1419
self._move(rename_entries)
1421
# restore the inventory on error
1422
self._inventory_is_modified = original_modified
1424
self._write_inventory(inv)
1425
return rename_tuples
1427
def _determine_mv_mode(self, rename_entries, after=False):
1428
"""Determines for each from-to pair if both inventory and working tree
1429
or only the inventory has to be changed.
1431
Also does basic plausability tests.
1433
inv = self.inventory
1435
for rename_entry in rename_entries:
1436
# store to local variables for easier reference
1437
from_rel = rename_entry.from_rel
1438
from_id = rename_entry.from_id
1439
to_rel = rename_entry.to_rel
1440
to_id = inv.path2id(to_rel)
1441
only_change_inv = False
1443
# check the inventory for source and destination
1445
raise errors.BzrMoveFailedError(from_rel,to_rel,
1446
errors.NotVersionedError(path=str(from_rel)))
1447
if to_id is not None:
1448
raise errors.BzrMoveFailedError(from_rel,to_rel,
1449
errors.AlreadyVersionedError(path=str(to_rel)))
1451
# try to determine the mode for rename (only change inv or change
1452
# inv and file system)
1454
if not self.has_filename(to_rel):
1455
raise errors.BzrMoveFailedError(from_id,to_rel,
1456
errors.NoSuchFile(path=str(to_rel),
1457
extra="New file has not been created yet"))
1458
only_change_inv = True
1459
elif not self.has_filename(from_rel) and self.has_filename(to_rel):
1460
only_change_inv = True
1461
elif self.has_filename(from_rel) and not self.has_filename(to_rel):
1462
only_change_inv = False
1463
elif (not self.case_sensitive
1464
and from_rel.lower() == to_rel.lower()
1465
and self.has_filename(from_rel)):
1466
only_change_inv = False
1468
# something is wrong, so lets determine what exactly
1469
if not self.has_filename(from_rel) and \
1470
not self.has_filename(to_rel):
1471
raise errors.BzrRenameFailedError(from_rel,to_rel,
1472
errors.PathsDoNotExist(paths=(str(from_rel),
1475
raise errors.RenameFailedFilesExist(from_rel, to_rel)
1476
rename_entry.only_change_inv = only_change_inv
1477
return rename_entries
1479
def _move(self, rename_entries):
1480
"""Moves a list of files.
1482
Depending on the value of the flag 'only_change_inv', the
1483
file will be moved on the file system or not.
1485
inv = self.inventory
1488
for entry in rename_entries:
1490
self._move_entry(entry)
1492
self._rollback_move(moved)
1496
def _rollback_move(self, moved):
1497
"""Try to rollback a previous move in case of an filesystem error."""
1498
inv = self.inventory
1501
self._move_entry(WorkingTree._RenameEntry(
1502
entry.to_rel, entry.from_id,
1503
entry.to_tail, entry.to_parent_id, entry.from_rel,
1504
entry.from_tail, entry.from_parent_id,
1505
entry.only_change_inv))
1506
except errors.BzrMoveFailedError, e:
1507
raise errors.BzrMoveFailedError( '', '', "Rollback failed."
1508
" The working tree is in an inconsistent state."
1509
" Please consider doing a 'bzr revert'."
1510
" Error message is: %s" % e)
1512
def _move_entry(self, entry):
1513
inv = self.inventory
1514
from_rel_abs = self.abspath(entry.from_rel)
1515
to_rel_abs = self.abspath(entry.to_rel)
1516
if from_rel_abs == to_rel_abs:
1517
raise errors.BzrMoveFailedError(entry.from_rel, entry.to_rel,
1518
"Source and target are identical.")
1520
if not entry.only_change_inv:
1522
osutils.rename(from_rel_abs, to_rel_abs)
1524
raise errors.BzrMoveFailedError(entry.from_rel,
1526
inv.rename(entry.from_id, entry.to_parent_id, entry.to_tail)
1528
@needs_tree_write_lock
1529
def rename_one(self, from_rel, to_rel, after=False):
1532
This can change the directory or the filename or both.
1534
rename_one has several 'modes' to work. First, it can rename a physical
1535
file and change the file_id. That is the normal mode. Second, it can
1536
only change the file_id without touching any physical file. This is
1537
the new mode introduced in version 0.15.
1539
rename_one uses the second mode if 'after == True' and 'to_rel' is not
1540
versioned but present in the working tree.
1542
rename_one uses the second mode if 'after == False' and 'from_rel' is
1543
versioned but no longer in the working tree, and 'to_rel' is not
1544
versioned but present in the working tree.
1546
rename_one uses the first mode if 'after == False' and 'from_rel' is
1547
versioned and present in the working tree, and 'to_rel' is not
1548
versioned and not present in the working tree.
1550
Everything else results in an error.
1552
inv = self.inventory
1555
# create rename entries and tuples
1556
from_tail = splitpath(from_rel)[-1]
1557
from_id = inv.path2id(from_rel)
1559
# if file is missing in the inventory maybe it's in the basis_tree
1560
basis_tree = self.branch.basis_tree()
1561
from_id = basis_tree.path2id(from_rel)
1563
raise errors.BzrRenameFailedError(from_rel,to_rel,
1564
errors.NotVersionedError(path=str(from_rel)))
1565
# put entry back in the inventory so we can rename it
1566
from_entry = basis_tree.inventory[from_id].copy()
1569
from_entry = inv[from_id]
1570
from_parent_id = from_entry.parent_id
1571
to_dir, to_tail = os.path.split(to_rel)
1572
to_dir_id = inv.path2id(to_dir)
1573
rename_entry = WorkingTree._RenameEntry(from_rel=from_rel,
1575
from_tail=from_tail,
1576
from_parent_id=from_parent_id,
1577
to_rel=to_rel, to_tail=to_tail,
1578
to_parent_id=to_dir_id)
1579
rename_entries.append(rename_entry)
1581
# determine which move mode to use. checks also for movability
1582
rename_entries = self._determine_mv_mode(rename_entries, after)
1584
# check if the target changed directory and if the target directory is
1586
if to_dir_id is None:
1587
raise errors.BzrMoveFailedError(from_rel,to_rel,
1588
errors.NotVersionedError(path=str(to_dir)))
1590
# all checks done. now we can continue with our actual work
1591
mutter('rename_one:\n'
1596
' to_dir_id {%s}\n',
1597
from_id, from_rel, to_rel, to_dir, to_dir_id)
1599
self._move(rename_entries)
1600
self._write_inventory(inv)
1602
class _RenameEntry(object):
1603
def __init__(self, from_rel, from_id, from_tail, from_parent_id,
1604
to_rel, to_tail, to_parent_id, only_change_inv=False):
1605
self.from_rel = from_rel
1606
self.from_id = from_id
1607
self.from_tail = from_tail
1608
self.from_parent_id = from_parent_id
1609
self.to_rel = to_rel
1610
self.to_tail = to_tail
1611
self.to_parent_id = to_parent_id
1612
self.only_change_inv = only_change_inv
317
1615
def unknowns(self):
318
for subp in self.extras():
319
if not self.is_ignored(subp):
322
def iter_conflicts(self):
1616
"""Return all unknown files.
1618
These are files in the working directory that are not versioned or
1619
control files or ignored.
1621
# force the extras method to be fully executed before returning, to
1622
# prevent race conditions with the lock
1624
[subp for subp in self.extras() if not self.is_ignored(subp)])
1626
@needs_tree_write_lock
1627
def unversion(self, file_ids):
1628
"""Remove the file ids in file_ids from the current versioned set.
1630
When a file_id is unversioned, all of its children are automatically
1633
:param file_ids: The file ids to stop versioning.
1634
:raises: NoSuchId if any fileid is not currently versioned.
1636
for file_id in file_ids:
1637
if file_id not in self._inventory:
1638
raise errors.NoSuchId(self, file_id)
1639
for file_id in file_ids:
1640
if self._inventory.has_id(file_id):
1641
self._inventory.remove_recursive_id(file_id)
1643
# in the future this should just set a dirty bit to wait for the
1644
# final unlock. However, until all methods of workingtree start
1645
# with the current in -memory inventory rather than triggering
1646
# a read, it is more complex - we need to teach read_inventory
1647
# to know when to read, and when to not read first... and possibly
1648
# to save first when the in memory one may be corrupted.
1649
# so for now, we just only write it if it is indeed dirty.
1651
self._write_inventory(self._inventory)
1653
def _iter_conflicts(self):
323
1654
conflicted = set()
324
for path in (s[0] for s in self.list_files()):
1655
for info in self.list_files():
325
1657
stem = get_conflicted_stem(path)
326
1658
if stem is None:
376
1742
for subf in os.listdir(dirabs):
378
and (subf not in dir_entry.children)):
1743
if self.bzrdir.is_control_filename(subf):
1745
if subf not in dir_entry.children:
1748
can_access) = osutils.normalized_filename(subf)
1749
except UnicodeDecodeError:
1750
path_os_enc = path.encode(osutils._fs_enc)
1751
relpath = path_os_enc + '/' + subf
1752
raise errors.BadFilenameEncoding(relpath,
1754
if subf_norm != subf and can_access:
1755
if subf_norm not in dir_entry.children:
1756
fl.append(subf_norm)
383
subp = appendpath(path, subf)
1762
subp = pathjoin(path, subf)
387
1765
def ignored_files(self):
388
1766
"""Yield list of PATH, IGNORE_PATTERN"""
389
1767
for subp in self.extras():
390
1768
pat = self.is_ignored(subp)
395
1772
def get_ignore_list(self):
396
1773
"""Return list of ignore patterns.
398
1775
Cached in the Tree object after the first call.
400
if hasattr(self, '_ignorelist'):
401
return self._ignorelist
1777
ignoreset = getattr(self, '_ignoreset', None)
1778
if ignoreset is not None:
403
l = bzrlib.DEFAULT_IGNORE[:]
1781
ignore_globs = set()
1782
ignore_globs.update(ignores.get_runtime_ignores())
1783
ignore_globs.update(ignores.get_user_ignores())
404
1784
if self.has_filename(bzrlib.IGNORE_FILENAME):
405
1785
f = self.get_file_byname(bzrlib.IGNORE_FILENAME)
406
l.extend([line.rstrip("\n\r") for line in f.readlines()])
1787
ignore_globs.update(ignores.parse_ignore_file(f))
1790
self._ignoreset = ignore_globs
1793
def _flush_ignore_list_cache(self):
1794
"""Resets the cached ignore list to force a cache rebuild."""
1795
self._ignoreset = None
1796
self._ignoreglobster = None
411
1798
def is_ignored(self, filename):
412
1799
r"""Check whether the filename matches an ignore pattern.
414
1801
Patterns containing '/' or '\' need to match the whole path;
415
others match against only the last component.
1802
others match against only the last component. Patterns starting
1803
with '!' are ignore exceptions. Exceptions take precedence
1804
over regular patterns and cause the filename to not be ignored.
417
1806
If the file is ignored, returns the pattern which caused it to
418
1807
be ignored, otherwise None. So this can simply be used as a
419
1808
boolean if desired."""
421
# TODO: Use '**' to match directories, and other extended
422
# globbing stuff from cvs/rsync.
424
# XXX: fnmatch is actually not quite what we want: it's only
425
# approximately the same as real Unix fnmatch, and doesn't
426
# treat dotfiles correctly and allows * to match /.
427
# Eventually it should be replaced with something more
430
for pat in self.get_ignore_list():
431
if '/' in pat or '\\' in pat:
433
# as a special case, you can put ./ at the start of a
434
# pattern; this is good to match in the top-level
437
if (pat[:2] == './') or (pat[:2] == '.\\'):
441
if fnmatch.fnmatchcase(filename, newpat):
444
if fnmatch.fnmatchcase(splitpath(filename)[-1], pat):
1809
if getattr(self, '_ignoreglobster', None) is None:
1810
self._ignoreglobster = globbing.ExceptionGlobster(self.get_ignore_list())
1811
return self._ignoreglobster.match(filename)
449
1813
def kind(self, file_id):
450
1814
return file_kind(self.id2abspath(file_id))
1816
def stored_kind(self, file_id):
1817
"""See Tree.stored_kind"""
1818
return self.inventory[file_id].kind
1820
def _comparison_data(self, entry, path):
1821
abspath = self.abspath(path)
1823
stat_value = os.lstat(abspath)
1825
if getattr(e, 'errno', None) == errno.ENOENT:
1832
mode = stat_value.st_mode
1833
kind = osutils.file_kind_from_stat_mode(mode)
1834
if not supports_executable():
1835
executable = entry is not None and entry.executable
1837
executable = bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
1838
return kind, executable, stat_value
1840
def _file_size(self, entry, stat_value):
1841
return stat_value.st_size
1843
def last_revision(self):
1844
"""Return the last revision of the branch for this tree.
1846
This format tree does not support a separate marker for last-revision
1847
compared to the branch.
1849
See MutableTree.last_revision
1851
return self._last_revision()
1854
def _last_revision(self):
1855
"""helper for get_parent_ids."""
1856
return _mod_revision.ensure_null(self.branch.last_revision())
1858
def is_locked(self):
1859
return self._control_files.is_locked()
1861
def _must_be_locked(self):
1862
if not self.is_locked():
1863
raise errors.ObjectNotLocked(self)
452
1865
def lock_read(self):
453
"""See Branch.lock_read, and WorkingTree.unlock."""
454
return self.branch.lock_read()
1866
"""Lock the tree for reading.
1868
This also locks the branch, and can be unlocked via self.unlock().
1870
:return: A bzrlib.lock.LogicalLockResult.
1872
if not self.is_locked():
1874
self.branch.lock_read()
1876
self._control_files.lock_read()
1877
return LogicalLockResult(self.unlock)
1879
self.branch.unlock()
1882
def lock_tree_write(self):
1883
"""See MutableTree.lock_tree_write, and WorkingTree.unlock.
1885
:return: A bzrlib.lock.LogicalLockResult.
1887
if not self.is_locked():
1889
self.branch.lock_read()
1891
self._control_files.lock_write()
1892
return LogicalLockResult(self.unlock)
1894
self.branch.unlock()
456
1897
def lock_write(self):
457
"""See Branch.lock_write, and WorkingTree.unlock."""
458
return self.branch.lock_write()
461
def remove(self, files, verbose=False):
462
"""Remove nominated files from the working inventory..
464
This does not remove their text. This does not run on XXX on what? RBC
466
TODO: Refuse to remove modified files unless --force is given?
468
TODO: Do something useful with directories.
470
TODO: Should this remove the text or not? Tough call; not
471
removing may be useful and the user can just use use rm, and
472
is the opposite of add. Removing it is consistent with most
473
other tools. Maybe an option.
475
## TODO: Normalize names
476
## TODO: Remove nested loops; better scalability
1898
"""See MutableTree.lock_write, and WorkingTree.unlock.
1900
:return: A bzrlib.lock.LogicalLockResult.
1902
if not self.is_locked():
1904
self.branch.lock_write()
1906
self._control_files.lock_write()
1907
return LogicalLockResult(self.unlock)
1909
self.branch.unlock()
1912
def get_physical_lock_status(self):
1913
return self._control_files.get_physical_lock_status()
1915
def _basis_inventory_name(self):
1916
return 'basis-inventory-cache'
1918
def _reset_data(self):
1919
"""Reset transient data that cannot be revalidated."""
1920
self._inventory_is_modified = False
1921
f = self._transport.get('inventory')
1923
result = self._deserialize(f)
1926
self._set_inventory(result, dirty=False)
1928
@needs_tree_write_lock
1929
def set_last_revision(self, new_revision):
1930
"""Change the last revision in the working tree."""
1931
if self._change_last_revision(new_revision):
1932
self._cache_basis_inventory(new_revision)
1934
def _change_last_revision(self, new_revision):
1935
"""Template method part of set_last_revision to perform the change.
1937
This is used to allow WorkingTree3 instances to not affect branch
1938
when their last revision is set.
1940
if _mod_revision.is_null(new_revision):
1941
self.branch.set_revision_history([])
1944
self.branch.generate_revision_history(new_revision)
1945
except errors.NoSuchRevision:
1946
# not present in the repo - dont try to set it deeper than the tip
1947
self.branch.set_revision_history([new_revision])
1950
def _write_basis_inventory(self, xml):
1951
"""Write the basis inventory XML to the basis-inventory file"""
1952
path = self._basis_inventory_name()
1954
self._transport.put_file(path, sio,
1955
mode=self.bzrdir._get_file_mode())
1957
def _create_basis_xml_from_inventory(self, revision_id, inventory):
1958
"""Create the text that will be saved in basis-inventory"""
1959
inventory.revision_id = revision_id
1960
return xml7.serializer_v7.write_inventory_to_string(inventory)
1962
def _cache_basis_inventory(self, new_revision):
1963
"""Cache new_revision as the basis inventory."""
1964
# TODO: this should allow the ready-to-use inventory to be passed in,
1965
# as commit already has that ready-to-use [while the format is the
1968
# this double handles the inventory - unpack and repack -
1969
# but is easier to understand. We can/should put a conditional
1970
# in here based on whether the inventory is in the latest format
1971
# - perhaps we should repack all inventories on a repository
1973
# the fast path is to copy the raw xml from the repository. If the
1974
# xml contains 'revision_id="', then we assume the right
1975
# revision_id is set. We must check for this full string, because a
1976
# root node id can legitimately look like 'revision_id' but cannot
1978
xml = self.branch.repository._get_inventory_xml(new_revision)
1979
firstline = xml.split('\n', 1)[0]
1980
if (not 'revision_id="' in firstline or
1981
'format="7"' not in firstline):
1982
inv = self.branch.repository._serializer.read_inventory_from_string(
1984
xml = self._create_basis_xml_from_inventory(new_revision, inv)
1985
self._write_basis_inventory(xml)
1986
except (errors.NoSuchRevision, errors.RevisionNotPresent):
1989
def read_basis_inventory(self):
1990
"""Read the cached basis inventory."""
1991
path = self._basis_inventory_name()
1992
return self._transport.get_bytes(path)
1995
def read_working_inventory(self):
1996
"""Read the working inventory.
1998
:raises errors.InventoryModified: read_working_inventory will fail
1999
when the current in memory inventory has been modified.
2001
# conceptually this should be an implementation detail of the tree.
2002
# XXX: Deprecate this.
2003
# ElementTree does its own conversion from UTF-8, so open in
2005
if self._inventory_is_modified:
2006
raise errors.InventoryModified(self)
2007
f = self._transport.get('inventory')
2009
result = self._deserialize(f)
2012
self._set_inventory(result, dirty=False)
2015
@needs_tree_write_lock
2016
def remove(self, files, verbose=False, to_file=None, keep_files=True,
2018
"""Remove nominated files from the working inventory.
2020
:files: File paths relative to the basedir.
2021
:keep_files: If true, the files will also be kept.
2022
:force: Delete files and directories, even if they are changed and
2023
even if the directories are not empty.
477
2025
if isinstance(files, basestring):
482
# do this before any modifications
2030
all_files = set() # specified and nested files
2031
unknown_nested_files=set()
2033
to_file = sys.stdout
2035
files_to_backup = []
2037
def recurse_directory_to_add_files(directory):
2038
# Recurse directory and add all files
2039
# so we can check if they have changed.
2040
for parent_info, file_infos in self.walkdirs(directory):
2041
for relpath, basename, kind, lstat, fileid, kind in file_infos:
2042
# Is it versioned or ignored?
2043
if self.path2id(relpath):
2044
# Add nested content for deletion.
2045
all_files.add(relpath)
2047
# Files which are not versioned
2048
# should be treated as unknown.
2049
files_to_backup.append(relpath)
2051
for filename in files:
2052
# Get file name into canonical form.
2053
abspath = self.abspath(filename)
2054
filename = self.relpath(abspath)
2055
if len(filename) > 0:
2056
all_files.add(filename)
2057
recurse_directory_to_add_files(filename)
2059
files = list(all_files)
2062
return # nothing to do
2064
# Sort needed to first handle directory content before the directory
2065
files.sort(reverse=True)
2067
# Bail out if we are going to delete files we shouldn't
2068
if not keep_files and not force:
2069
for (file_id, path, content_change, versioned, parent_id, name,
2070
kind, executable) in self.iter_changes(self.basis_tree(),
2071
include_unchanged=True, require_versioned=False,
2072
want_unversioned=True, specific_files=files):
2073
if versioned[0] == False:
2074
# The record is unknown or newly added
2075
files_to_backup.append(path[1])
2076
elif (content_change and (kind[1] is not None) and
2077
osutils.is_inside_any(files, path[1])):
2078
# Versioned and changed, but not deleted, and still
2079
# in one of the dirs to be deleted.
2080
files_to_backup.append(path[1])
2082
def backup(file_to_backup):
2083
backup_name = self.bzrdir.generate_backup_name(file_to_backup)
2084
osutils.rename(abs_path, self.abspath(backup_name))
2085
return "removed %s (but kept a copy: %s)" % (file_to_backup, backup_name)
2087
# Build inv_delta and delete files where applicable,
2088
# do this before any modifications to inventory.
2090
fid = self.path2id(f)
486
# TODO: Perhaps make this just a warning, and continue?
487
# This tends to happen when
488
raise NotVersionedError(path=f)
489
mutter("remove inventory entry %s {%s}" % (quotefn(f), fid))
491
# having remove it, it must be either ignored or unknown
492
if self.is_ignored(f):
496
show_status(new_status, inv[fid].kind, quotefn(f))
499
self.branch._write_inventory(inv)
2093
message = "%s is not versioned." % (f,)
2096
# having removed it, it must be either ignored or unknown
2097
if self.is_ignored(f):
2101
# XXX: Really should be a more abstract reporter interface
2102
kind_ch = osutils.kind_marker(self.kind(fid))
2103
to_file.write(new_status + ' ' + f + kind_ch + '\n')
2105
inv_delta.append((f, None, fid, None))
2106
message = "removed %s" % (f,)
2109
abs_path = self.abspath(f)
2110
if osutils.lexists(abs_path):
2111
if (osutils.isdir(abs_path) and
2112
len(os.listdir(abs_path)) > 0):
2114
osutils.rmtree(abs_path)
2115
message = "deleted %s" % (f,)
2119
if f in files_to_backup:
2122
osutils.delete_any(abs_path)
2123
message = "deleted %s" % (f,)
2124
elif message is not None:
2125
# Only care if we haven't done anything yet.
2126
message = "%s does not exist." % (f,)
2128
# Print only one message (if any) per file.
2129
if message is not None:
2131
self.apply_inventory_delta(inv_delta)
2133
@needs_tree_write_lock
2134
def revert(self, filenames=None, old_tree=None, backups=True,
2135
pb=None, report_changes=False):
2136
from bzrlib.conflicts import resolve
2139
symbol_versioning.warn('Using [] to revert all files is deprecated'
2140
' as of bzr 0.91. Please use None (the default) instead.',
2141
DeprecationWarning, stacklevel=2)
2142
if old_tree is None:
2143
basis_tree = self.basis_tree()
2144
basis_tree.lock_read()
2145
old_tree = basis_tree
2149
conflicts = transform.revert(self, old_tree, filenames, backups, pb,
2151
if filenames is None and len(self.get_parent_ids()) > 1:
2153
last_revision = self.last_revision()
2154
if last_revision != _mod_revision.NULL_REVISION:
2155
if basis_tree is None:
2156
basis_tree = self.basis_tree()
2157
basis_tree.lock_read()
2158
parent_trees.append((last_revision, basis_tree))
2159
self.set_parent_trees(parent_trees)
2162
resolve(self, filenames, ignore_misses=True, recursive=True)
2164
if basis_tree is not None:
2168
def revision_tree(self, revision_id):
2169
"""See Tree.revision_tree.
2171
WorkingTree can supply revision_trees for the basis revision only
2172
because there is only one cached inventory in the bzr directory.
2174
if revision_id == self.last_revision():
2176
xml = self.read_basis_inventory()
2177
except errors.NoSuchFile:
2181
inv = xml7.serializer_v7.read_inventory_from_string(xml)
2182
# dont use the repository revision_tree api because we want
2183
# to supply the inventory.
2184
if inv.revision_id == revision_id:
2185
return revisiontree.RevisionTree(self.branch.repository,
2187
except errors.BadInventoryFormat:
2189
# raise if there was no inventory, or if we read the wrong inventory.
2190
raise errors.NoSuchRevisionInTree(self, revision_id)
2192
# XXX: This method should be deprecated in favour of taking in a proper
2193
# new Inventory object.
2194
@needs_tree_write_lock
2195
def set_inventory(self, new_inventory_list):
2196
from bzrlib.inventory import (Inventory,
2200
inv = Inventory(self.get_root_id())
2201
for path, file_id, parent, kind in new_inventory_list:
2202
name = os.path.basename(path)
2205
# fixme, there should be a factory function inv,add_??
2206
if kind == 'directory':
2207
inv.add(InventoryDirectory(file_id, name, parent))
2208
elif kind == 'file':
2209
inv.add(InventoryFile(file_id, name, parent))
2210
elif kind == 'symlink':
2211
inv.add(InventoryLink(file_id, name, parent))
2213
raise errors.BzrError("unknown kind %r" % kind)
2214
self._write_inventory(inv)
2216
@needs_tree_write_lock
2217
def set_root_id(self, file_id):
2218
"""Set the root id for this tree."""
2222
'WorkingTree.set_root_id with fileid=None')
2223
file_id = osutils.safe_file_id(file_id)
2224
self._set_root_id(file_id)
2226
def _set_root_id(self, file_id):
2227
"""Set the root id for this tree, in a format specific manner.
2229
:param file_id: The file id to assign to the root. It must not be
2230
present in the current inventory or an error will occur. It must
2231
not be None, but rather a valid file id.
2233
inv = self._inventory
2234
orig_root_id = inv.root.file_id
2235
# TODO: it might be nice to exit early if there was nothing
2236
# to do, saving us from trigger a sync on unlock.
2237
self._inventory_is_modified = True
2238
# we preserve the root inventory entry object, but
2239
# unlinkit from the byid index
2240
del inv._byid[inv.root.file_id]
2241
inv.root.file_id = file_id
2242
# and link it into the index with the new changed id.
2243
inv._byid[inv.root.file_id] = inv.root
2244
# and finally update all children to reference the new id.
2245
# XXX: this should be safe to just look at the root.children
2246
# list, not the WHOLE INVENTORY.
2249
if entry.parent_id == orig_root_id:
2250
entry.parent_id = inv.root.file_id
501
2252
def unlock(self):
502
2253
"""See Branch.unlock.
504
2255
WorkingTree locking just uses the Branch locking facilities.
505
2256
This is current because all working trees have an embedded branch
506
2257
within them. IF in the future, we were to make branch data shareable
507
between multiple working trees, i.e. via shared storage, then we
2258
between multiple working trees, i.e. via shared storage, then we
508
2259
would probably want to lock both the local tree, and the branch.
510
return self.branch.unlock()
513
CONFLICT_SUFFIXES = ('.THIS', '.BASE', '.OTHER')
2261
raise NotImplementedError(self.unlock)
2265
def update(self, change_reporter=None, possible_transports=None,
2266
revision=None, old_tip=_marker, show_base=False):
2267
"""Update a working tree along its branch.
2269
This will update the branch if its bound too, which means we have
2270
multiple trees involved:
2272
- The new basis tree of the master.
2273
- The old basis tree of the branch.
2274
- The old basis tree of the working tree.
2275
- The current working tree state.
2277
Pathologically, all three may be different, and non-ancestors of each
2278
other. Conceptually we want to:
2280
- Preserve the wt.basis->wt.state changes
2281
- Transform the wt.basis to the new master basis.
2282
- Apply a merge of the old branch basis to get any 'local' changes from
2284
- Restore the wt.basis->wt.state changes.
2286
There isn't a single operation at the moment to do that, so we:
2287
- Merge current state -> basis tree of the master w.r.t. the old tree
2289
- Do a 'normal' merge of the old branch basis if it is relevant.
2291
:param revision: The target revision to update to. Must be in the
2293
:param old_tip: If branch.update() has already been run, the value it
2294
returned (old tip of the branch or None). _marker is used
2297
if self.branch.get_bound_location() is not None:
2299
update_branch = (old_tip is self._marker)
2301
self.lock_tree_write()
2302
update_branch = False
2305
old_tip = self.branch.update(possible_transports)
2307
if old_tip is self._marker:
2309
return self._update_tree(old_tip, change_reporter, revision, show_base)
2313
@needs_tree_write_lock
2314
def _update_tree(self, old_tip=None, change_reporter=None, revision=None,
2316
"""Update a tree to the master branch.
2318
:param old_tip: if supplied, the previous tip revision the branch,
2319
before it was changed to the master branch's tip.
2321
# here if old_tip is not None, it is the old tip of the branch before
2322
# it was updated from the master branch. This should become a pending
2323
# merge in the working tree to preserve the user existing work. we
2324
# cant set that until we update the working trees last revision to be
2325
# one from the new branch, because it will just get absorbed by the
2326
# parent de-duplication logic.
2328
# We MUST save it even if an error occurs, because otherwise the users
2329
# local work is unreferenced and will appear to have been lost.
2333
last_rev = self.get_parent_ids()[0]
2335
last_rev = _mod_revision.NULL_REVISION
2336
if revision is None:
2337
revision = self.branch.last_revision()
2339
old_tip = old_tip or _mod_revision.NULL_REVISION
2341
if not _mod_revision.is_null(old_tip) and old_tip != last_rev:
2342
# the branch we are bound to was updated
2343
# merge those changes in first
2344
base_tree = self.basis_tree()
2345
other_tree = self.branch.repository.revision_tree(old_tip)
2346
nb_conflicts = merge.merge_inner(self.branch, other_tree,
2347
base_tree, this_tree=self,
2348
change_reporter=change_reporter,
2349
show_base=show_base)
2351
self.add_parent_tree((old_tip, other_tree))
2352
trace.note('Rerun update after fixing the conflicts.')
2355
if last_rev != _mod_revision.ensure_null(revision):
2356
# the working tree is up to date with the branch
2357
# we can merge the specified revision from master
2358
to_tree = self.branch.repository.revision_tree(revision)
2359
to_root_id = to_tree.get_root_id()
2361
basis = self.basis_tree()
2364
if (basis.inventory.root is None
2365
or basis.inventory.root.file_id != to_root_id):
2366
self.set_root_id(to_root_id)
2371
# determine the branch point
2372
graph = self.branch.repository.get_graph()
2373
base_rev_id = graph.find_unique_lca(self.branch.last_revision(),
2375
base_tree = self.branch.repository.revision_tree(base_rev_id)
2377
nb_conflicts = merge.merge_inner(self.branch, to_tree, base_tree,
2379
change_reporter=change_reporter,
2380
show_base=show_base)
2381
self.set_last_revision(revision)
2382
# TODO - dedup parents list with things merged by pull ?
2383
# reuse the tree we've updated to to set the basis:
2384
parent_trees = [(revision, to_tree)]
2385
merges = self.get_parent_ids()[1:]
2386
# Ideally we ask the tree for the trees here, that way the working
2387
# tree can decide whether to give us the entire tree or give us a
2388
# lazy initialised tree. dirstate for instance will have the trees
2389
# in ram already, whereas a last-revision + basis-inventory tree
2390
# will not, but also does not need them when setting parents.
2391
for parent in merges:
2392
parent_trees.append(
2393
(parent, self.branch.repository.revision_tree(parent)))
2394
if not _mod_revision.is_null(old_tip):
2395
parent_trees.append(
2396
(old_tip, self.branch.repository.revision_tree(old_tip)))
2397
self.set_parent_trees(parent_trees)
2398
last_rev = parent_trees[0][0]
2401
def _write_hashcache_if_dirty(self):
2402
"""Write out the hashcache if it is dirty."""
2403
if self._hashcache.needs_write:
2405
self._hashcache.write()
2407
if e.errno not in (errno.EPERM, errno.EACCES):
2409
# TODO: jam 20061219 Should this be a warning? A single line
2410
# warning might be sufficient to let the user know what
2412
mutter('Could not write hashcache for %s\nError: %s',
2413
self._hashcache.cache_file_name(), e)
2415
@needs_tree_write_lock
2416
def _write_inventory(self, inv):
2417
"""Write inventory as the current inventory."""
2418
self._set_inventory(inv, dirty=True)
2421
def set_conflicts(self, arg):
2422
raise errors.UnsupportedOperation(self.set_conflicts, self)
2424
def add_conflicts(self, arg):
2425
raise errors.UnsupportedOperation(self.add_conflicts, self)
2428
def conflicts(self):
2429
conflicts = _mod_conflicts.ConflictList()
2430
for conflicted in self._iter_conflicts():
2433
if file_kind(self.abspath(conflicted)) != "file":
2435
except errors.NoSuchFile:
2438
for suffix in ('.THIS', '.OTHER'):
2440
kind = file_kind(self.abspath(conflicted+suffix))
2443
except errors.NoSuchFile:
2447
ctype = {True: 'text conflict', False: 'contents conflict'}[text]
2448
conflicts.append(_mod_conflicts.Conflict.factory(ctype,
2450
file_id=self.path2id(conflicted)))
2453
def walkdirs(self, prefix=""):
2454
"""Walk the directories of this tree.
2456
returns a generator which yields items in the form:
2457
((curren_directory_path, fileid),
2458
[(file1_path, file1_name, file1_kind, (lstat), file1_id,
2461
This API returns a generator, which is only valid during the current
2462
tree transaction - within a single lock_read or lock_write duration.
2464
If the tree is not locked, it may cause an error to be raised,
2465
depending on the tree implementation.
2467
disk_top = self.abspath(prefix)
2468
if disk_top.endswith('/'):
2469
disk_top = disk_top[:-1]
2470
top_strip_len = len(disk_top) + 1
2471
inventory_iterator = self._walkdirs(prefix)
2472
disk_iterator = osutils.walkdirs(disk_top, prefix)
2474
current_disk = disk_iterator.next()
2475
disk_finished = False
2477
if not (e.errno == errno.ENOENT or
2478
(sys.platform == 'win32' and e.errno == ERROR_PATH_NOT_FOUND)):
2481
disk_finished = True
2483
current_inv = inventory_iterator.next()
2484
inv_finished = False
2485
except StopIteration:
2488
while not inv_finished or not disk_finished:
2490
((cur_disk_dir_relpath, cur_disk_dir_path_from_top),
2491
cur_disk_dir_content) = current_disk
2493
((cur_disk_dir_relpath, cur_disk_dir_path_from_top),
2494
cur_disk_dir_content) = ((None, None), None)
2495
if not disk_finished:
2496
# strip out .bzr dirs
2497
if (cur_disk_dir_path_from_top[top_strip_len:] == '' and
2498
len(cur_disk_dir_content) > 0):
2499
# osutils.walkdirs can be made nicer -
2500
# yield the path-from-prefix rather than the pathjoined
2502
bzrdir_loc = bisect_left(cur_disk_dir_content,
2504
if (bzrdir_loc < len(cur_disk_dir_content)
2505
and self.bzrdir.is_control_filename(
2506
cur_disk_dir_content[bzrdir_loc][0])):
2507
# we dont yield the contents of, or, .bzr itself.
2508
del cur_disk_dir_content[bzrdir_loc]
2510
# everything is unknown
2513
# everything is missing
2516
direction = cmp(current_inv[0][0], cur_disk_dir_relpath)
2518
# disk is before inventory - unknown
2519
dirblock = [(relpath, basename, kind, stat, None, None) for
2520
relpath, basename, kind, stat, top_path in
2521
cur_disk_dir_content]
2522
yield (cur_disk_dir_relpath, None), dirblock
2524
current_disk = disk_iterator.next()
2525
except StopIteration:
2526
disk_finished = True
2528
# inventory is before disk - missing.
2529
dirblock = [(relpath, basename, 'unknown', None, fileid, kind)
2530
for relpath, basename, dkind, stat, fileid, kind in
2532
yield (current_inv[0][0], current_inv[0][1]), dirblock
2534
current_inv = inventory_iterator.next()
2535
except StopIteration:
2538
# versioned present directory
2539
# merge the inventory and disk data together
2541
for relpath, subiterator in itertools.groupby(sorted(
2542
current_inv[1] + cur_disk_dir_content,
2543
key=operator.itemgetter(0)), operator.itemgetter(1)):
2544
path_elements = list(subiterator)
2545
if len(path_elements) == 2:
2546
inv_row, disk_row = path_elements
2547
# versioned, present file
2548
dirblock.append((inv_row[0],
2549
inv_row[1], disk_row[2],
2550
disk_row[3], inv_row[4],
2552
elif len(path_elements[0]) == 5:
2554
dirblock.append((path_elements[0][0],
2555
path_elements[0][1], path_elements[0][2],
2556
path_elements[0][3], None, None))
2557
elif len(path_elements[0]) == 6:
2558
# versioned, absent file.
2559
dirblock.append((path_elements[0][0],
2560
path_elements[0][1], 'unknown', None,
2561
path_elements[0][4], path_elements[0][5]))
2563
raise NotImplementedError('unreachable code')
2564
yield current_inv[0], dirblock
2566
current_inv = inventory_iterator.next()
2567
except StopIteration:
2570
current_disk = disk_iterator.next()
2571
except StopIteration:
2572
disk_finished = True
2574
def _walkdirs(self, prefix=""):
2575
"""Walk the directories of this tree.
2577
:prefix: is used as the directrory to start with.
2578
returns a generator which yields items in the form:
2579
((curren_directory_path, fileid),
2580
[(file1_path, file1_name, file1_kind, None, file1_id,
2583
_directory = 'directory'
2584
# get the root in the inventory
2585
inv = self.inventory
2586
top_id = inv.path2id(prefix)
2590
pending = [(prefix, '', _directory, None, top_id, None)]
2593
currentdir = pending.pop()
2594
# 0 - relpath, 1- basename, 2- kind, 3- stat, 4-id, 5-kind
2595
top_id = currentdir[4]
2597
relroot = currentdir[0] + '/'
2600
# FIXME: stash the node in pending
2602
if entry.kind == 'directory':
2603
for name, child in entry.sorted_children():
2604
dirblock.append((relroot + name, name, child.kind, None,
2605
child.file_id, child.kind
2607
yield (currentdir[0], entry.file_id), dirblock
2608
# push the user specified dirs from dirblock
2609
for dir in reversed(dirblock):
2610
if dir[2] == _directory:
2613
@needs_tree_write_lock
2614
def auto_resolve(self):
2615
"""Automatically resolve text conflicts according to contents.
2617
Only text conflicts are auto_resolvable. Files with no conflict markers
2618
are considered 'resolved', because bzr always puts conflict markers
2619
into files that have text conflicts. The corresponding .THIS .BASE and
2620
.OTHER files are deleted, as per 'resolve'.
2621
:return: a tuple of ConflictLists: (un_resolved, resolved).
2623
un_resolved = _mod_conflicts.ConflictList()
2624
resolved = _mod_conflicts.ConflictList()
2625
conflict_re = re.compile('^(<{7}|={7}|>{7})')
2626
for conflict in self.conflicts():
2627
if (conflict.typestring != 'text conflict' or
2628
self.kind(conflict.file_id) != 'file'):
2629
un_resolved.append(conflict)
2631
my_file = open(self.id2abspath(conflict.file_id), 'rb')
2633
for line in my_file:
2634
if conflict_re.search(line):
2635
un_resolved.append(conflict)
2638
resolved.append(conflict)
2641
resolved.remove_files(self)
2642
self.set_conflicts(un_resolved)
2643
return un_resolved, resolved
2646
def _check(self, references):
2647
"""Check the tree for consistency.
2649
:param references: A dict with keys matching the items returned by
2650
self._get_check_refs(), and values from looking those keys up in
2653
tree_basis = self.basis_tree()
2654
tree_basis.lock_read()
2656
repo_basis = references[('trees', self.last_revision())]
2657
if len(list(repo_basis.iter_changes(tree_basis))) > 0:
2658
raise errors.BzrCheckError(
2659
"Mismatched basis inventory content.")
2664
def _validate(self):
2665
"""Validate internal structures.
2667
This is meant mostly for the test suite. To give it a chance to detect
2668
corruption after actions have occurred. The default implementation is a
2671
:return: None. An exception should be raised if there is an error.
2675
def _get_rules_searcher(self, default_searcher):
2676
"""See Tree._get_rules_searcher."""
2677
if self._rules_searcher is None:
2678
self._rules_searcher = super(WorkingTree,
2679
self)._get_rules_searcher(default_searcher)
2680
return self._rules_searcher
2682
def get_shelf_manager(self):
2683
"""Return the ShelfManager for this WorkingTree."""
2684
from bzrlib.shelf import ShelfManager
2685
return ShelfManager(self, self._transport)
2688
class WorkingTree2(WorkingTree):
2689
"""This is the Format 2 working tree.
2691
This was the first weave based working tree.
2692
- uses os locks for locking.
2693
- uses the branch last-revision.
2696
def __init__(self, *args, **kwargs):
2697
super(WorkingTree2, self).__init__(*args, **kwargs)
2698
# WorkingTree2 has more of a constraint that self._inventory must
2699
# exist. Because this is an older format, we don't mind the overhead
2700
# caused by the extra computation here.
2702
# Newer WorkingTree's should only have self._inventory set when they
2704
if self._inventory is None:
2705
self.read_working_inventory()
2707
def _get_check_refs(self):
2708
"""Return the references needed to perform a check of this tree."""
2709
return [('trees', self.last_revision())]
2711
def lock_tree_write(self):
2712
"""See WorkingTree.lock_tree_write().
2714
In Format2 WorkingTrees we have a single lock for the branch and tree
2715
so lock_tree_write() degrades to lock_write().
2717
:return: An object with an unlock method which will release the lock
2720
self.branch.lock_write()
2722
self._control_files.lock_write()
2725
self.branch.unlock()
2729
# do non-implementation specific cleanup
2732
# we share control files:
2733
if self._control_files._lock_count == 3:
2734
# _inventory_is_modified is always False during a read lock.
2735
if self._inventory_is_modified:
2737
self._write_hashcache_if_dirty()
2739
# reverse order of locking.
2741
return self._control_files.unlock()
2743
self.branch.unlock()
2746
class WorkingTree3(WorkingTree):
2747
"""This is the Format 3 working tree.
2749
This differs from the base WorkingTree by:
2750
- having its own file lock
2751
- having its own last-revision property.
2753
This is new in bzr 0.8
2757
def _last_revision(self):
2758
"""See Mutable.last_revision."""
2760
return self._transport.get_bytes('last-revision')
2761
except errors.NoSuchFile:
2762
return _mod_revision.NULL_REVISION
2764
def _change_last_revision(self, revision_id):
2765
"""See WorkingTree._change_last_revision."""
2766
if revision_id is None or revision_id == _mod_revision.NULL_REVISION:
2768
self._transport.delete('last-revision')
2769
except errors.NoSuchFile:
2773
self._transport.put_bytes('last-revision', revision_id,
2774
mode=self.bzrdir._get_file_mode())
2777
def _get_check_refs(self):
2778
"""Return the references needed to perform a check of this tree."""
2779
return [('trees', self.last_revision())]
2781
@needs_tree_write_lock
2782
def set_conflicts(self, conflicts):
2783
self._put_rio('conflicts', conflicts.to_stanzas(),
2786
@needs_tree_write_lock
2787
def add_conflicts(self, new_conflicts):
2788
conflict_set = set(self.conflicts())
2789
conflict_set.update(set(list(new_conflicts)))
2790
self.set_conflicts(_mod_conflicts.ConflictList(sorted(conflict_set,
2791
key=_mod_conflicts.Conflict.sort_key)))
2794
def conflicts(self):
2796
confile = self._transport.get('conflicts')
2797
except errors.NoSuchFile:
2798
return _mod_conflicts.ConflictList()
2801
if confile.next() != CONFLICT_HEADER_1 + '\n':
2802
raise errors.ConflictFormatError()
2803
except StopIteration:
2804
raise errors.ConflictFormatError()
2805
return _mod_conflicts.ConflictList.from_stanzas(RioReader(confile))
2810
# do non-implementation specific cleanup
2812
if self._control_files._lock_count == 1:
2813
# _inventory_is_modified is always False during a read lock.
2814
if self._inventory_is_modified:
2816
self._write_hashcache_if_dirty()
2817
# reverse order of locking.
2819
return self._control_files.unlock()
2821
self.branch.unlock()
514
2824
def get_conflicted_stem(path):
515
for suffix in CONFLICT_SUFFIXES:
2825
for suffix in _mod_conflicts.CONFLICT_SUFFIXES:
516
2826
if path.endswith(suffix):
517
2827
return path[:-len(suffix)]
2830
class WorkingTreeFormat(object):
2831
"""An encapsulation of the initialization and open routines for a format.
2833
Formats provide three things:
2834
* An initialization routine,
2838
Formats are placed in an dict by their format string for reference
2839
during workingtree opening. Its not required that these be instances, they
2840
can be classes themselves with class methods - it simply depends on
2841
whether state is needed for a given format or not.
2843
Once a format is deprecated, just deprecate the initialize and open
2844
methods on the format class. Do not deprecate the object, as the
2845
object will be created every time regardless.
2848
_default_format = None
2849
"""The default format used for new trees."""
2852
"""The known formats."""
2854
requires_rich_root = False
2856
upgrade_recommended = False
2859
def find_format(klass, a_bzrdir):
2860
"""Return the format for the working tree object in a_bzrdir."""
2862
transport = a_bzrdir.get_workingtree_transport(None)
2863
format_string = transport.get_bytes("format")
2864
return klass._formats[format_string]
2865
except errors.NoSuchFile:
2866
raise errors.NoWorkingTree(base=transport.base)
2868
raise errors.UnknownFormatError(format=format_string,
2869
kind="working tree")
2871
def __eq__(self, other):
2872
return self.__class__ is other.__class__
2874
def __ne__(self, other):
2875
return not (self == other)
2878
def get_default_format(klass):
2879
"""Return the current default format."""
2880
return klass._default_format
2882
def get_format_string(self):
2883
"""Return the ASCII format string that identifies this format."""
2884
raise NotImplementedError(self.get_format_string)
2886
def get_format_description(self):
2887
"""Return the short description for this format."""
2888
raise NotImplementedError(self.get_format_description)
2890
def is_supported(self):
2891
"""Is this format supported?
2893
Supported formats can be initialized and opened.
2894
Unsupported formats may not support initialization or committing or
2895
some other features depending on the reason for not being supported.
2899
def supports_content_filtering(self):
2900
"""True if this format supports content filtering."""
2903
def supports_views(self):
2904
"""True if this format supports stored views."""
2908
def register_format(klass, format):
2909
klass._formats[format.get_format_string()] = format
2912
def set_default_format(klass, format):
2913
klass._default_format = format
2916
def unregister_format(klass, format):
2917
del klass._formats[format.get_format_string()]
2920
class WorkingTreeFormat2(WorkingTreeFormat):
2921
"""The second working tree format.
2923
This format modified the hash cache from the format 1 hash cache.
2926
upgrade_recommended = True
2928
def get_format_description(self):
2929
"""See WorkingTreeFormat.get_format_description()."""
2930
return "Working tree format 2"
2932
def _stub_initialize_on_transport(self, transport, file_mode):
2933
"""Workaround: create control files for a remote working tree.
2935
This ensures that it can later be updated and dealt with locally,
2936
since BzrDirFormat6 and BzrDirFormat5 cannot represent dirs with
2937
no working tree. (See bug #43064).
2940
inv = inventory.Inventory()
2941
xml5.serializer_v5.write_inventory(inv, sio, working=True)
2943
transport.put_file('inventory', sio, file_mode)
2944
transport.put_bytes('pending-merges', '', file_mode)
2946
def initialize(self, a_bzrdir, revision_id=None, from_branch=None,
2947
accelerator_tree=None, hardlink=False):
2948
"""See WorkingTreeFormat.initialize()."""
2949
if not isinstance(a_bzrdir.transport, LocalTransport):
2950
raise errors.NotLocalUrl(a_bzrdir.transport.base)
2951
if from_branch is not None:
2952
branch = from_branch
2954
branch = a_bzrdir.open_branch()
2955
if revision_id is None:
2956
revision_id = _mod_revision.ensure_null(branch.last_revision())
2959
branch.generate_revision_history(revision_id)
2962
inv = inventory.Inventory()
2963
wt = WorkingTree2(a_bzrdir.root_transport.local_abspath('.'),
2969
basis_tree = branch.repository.revision_tree(revision_id)
2970
if basis_tree.inventory.root is not None:
2971
wt.set_root_id(basis_tree.get_root_id())
2972
# set the parent list and cache the basis tree.
2973
if _mod_revision.is_null(revision_id):
2976
parent_trees = [(revision_id, basis_tree)]
2977
wt.set_parent_trees(parent_trees)
2978
transform.build_tree(basis_tree, wt)
2982
super(WorkingTreeFormat2, self).__init__()
2983
self._matchingbzrdir = bzrdir.BzrDirFormat6()
2985
def open(self, a_bzrdir, _found=False):
2986
"""Return the WorkingTree object for a_bzrdir
2988
_found is a private parameter, do not use it. It is used to indicate
2989
if format probing has already been done.
2992
# we are being called directly and must probe.
2993
raise NotImplementedError
2994
if not isinstance(a_bzrdir.transport, LocalTransport):
2995
raise errors.NotLocalUrl(a_bzrdir.transport.base)
2996
wt = WorkingTree2(a_bzrdir.root_transport.local_abspath('.'),
3002
class WorkingTreeFormat3(WorkingTreeFormat):
3003
"""The second working tree format updated to record a format marker.
3006
- exists within a metadir controlling .bzr
3007
- includes an explicit version marker for the workingtree control
3008
files, separate from the BzrDir format
3009
- modifies the hash cache format
3011
- uses a LockDir to guard access for writes.
3014
upgrade_recommended = True
3016
def get_format_string(self):
3017
"""See WorkingTreeFormat.get_format_string()."""
3018
return "Bazaar-NG Working Tree format 3"
3020
def get_format_description(self):
3021
"""See WorkingTreeFormat.get_format_description()."""
3022
return "Working tree format 3"
3024
_lock_file_name = 'lock'
3025
_lock_class = LockDir
3027
_tree_class = WorkingTree3
3029
def __get_matchingbzrdir(self):
3030
return bzrdir.BzrDirMetaFormat1()
3032
_matchingbzrdir = property(__get_matchingbzrdir)
3034
def _open_control_files(self, a_bzrdir):
3035
transport = a_bzrdir.get_workingtree_transport(None)
3036
return LockableFiles(transport, self._lock_file_name,
3039
def initialize(self, a_bzrdir, revision_id=None, from_branch=None,
3040
accelerator_tree=None, hardlink=False):
3041
"""See WorkingTreeFormat.initialize().
3043
:param revision_id: if supplied, create a working tree at a different
3044
revision than the branch is at.
3045
:param accelerator_tree: A tree which can be used for retrieving file
3046
contents more quickly than the revision tree, i.e. a workingtree.
3047
The revision tree will be used for cases where accelerator_tree's
3048
content is different.
3049
:param hardlink: If true, hard-link files from accelerator_tree,
3052
if not isinstance(a_bzrdir.transport, LocalTransport):
3053
raise errors.NotLocalUrl(a_bzrdir.transport.base)
3054
transport = a_bzrdir.get_workingtree_transport(self)
3055
control_files = self._open_control_files(a_bzrdir)
3056
control_files.create_lock()
3057
control_files.lock_write()
3058
transport.put_bytes('format', self.get_format_string(),
3059
mode=a_bzrdir._get_file_mode())
3060
if from_branch is not None:
3061
branch = from_branch
3063
branch = a_bzrdir.open_branch()
3064
if revision_id is None:
3065
revision_id = _mod_revision.ensure_null(branch.last_revision())
3066
# WorkingTree3 can handle an inventory which has a unique root id.
3067
# as of bzr 0.12. However, bzr 0.11 and earlier fail to handle
3068
# those trees. And because there isn't a format bump inbetween, we
3069
# are maintaining compatibility with older clients.
3070
# inv = Inventory(root_id=gen_root_id())
3071
inv = self._initial_inventory()
3072
wt = self._tree_class(a_bzrdir.root_transport.local_abspath('.'),
3078
_control_files=control_files)
3079
wt.lock_tree_write()
3081
basis_tree = branch.repository.revision_tree(revision_id)
3082
# only set an explicit root id if there is one to set.
3083
if basis_tree.inventory.root is not None:
3084
wt.set_root_id(basis_tree.get_root_id())
3085
if revision_id == _mod_revision.NULL_REVISION:
3086
wt.set_parent_trees([])
3088
wt.set_parent_trees([(revision_id, basis_tree)])
3089
transform.build_tree(basis_tree, wt)
3091
# Unlock in this order so that the unlock-triggers-flush in
3092
# WorkingTree is given a chance to fire.
3093
control_files.unlock()
3097
def _initial_inventory(self):
3098
return inventory.Inventory()
3101
super(WorkingTreeFormat3, self).__init__()
3103
def open(self, a_bzrdir, _found=False):
3104
"""Return the WorkingTree object for a_bzrdir
3106
_found is a private parameter, do not use it. It is used to indicate
3107
if format probing has already been done.
3110
# we are being called directly and must probe.
3111
raise NotImplementedError
3112
if not isinstance(a_bzrdir.transport, LocalTransport):
3113
raise errors.NotLocalUrl(a_bzrdir.transport.base)
3114
wt = self._open(a_bzrdir, self._open_control_files(a_bzrdir))
3117
def _open(self, a_bzrdir, control_files):
3118
"""Open the tree itself.
3120
:param a_bzrdir: the dir for the tree.
3121
:param control_files: the control files for the tree.
3123
return self._tree_class(a_bzrdir.root_transport.local_abspath('.'),
3127
_control_files=control_files)
3130
return self.get_format_string()
3133
__default_format = WorkingTreeFormat6()
3134
WorkingTreeFormat.register_format(__default_format)
3135
WorkingTreeFormat.register_format(WorkingTreeFormat5())
3136
WorkingTreeFormat.register_format(WorkingTreeFormat4())
3137
WorkingTreeFormat.register_format(WorkingTreeFormat3())
3138
WorkingTreeFormat.set_default_format(__default_format)
3139
# formats which have no format string are not discoverable
3140
# and not independently creatable, so are not registered.
3141
_legacy_formats = [WorkingTreeFormat2(),