837
829
def merge_modified(self):
838
"""Return a dictionary of files modified by a merge.
840
The list is initialized by WorkingTree.set_merge_modified, which is
841
typically called after we make some automatic updates to the tree
844
This returns a map of file_id->sha1, containing only files which are
845
still in the working inventory and have that text hash.
848
831
hashfile = self._control_files.get('merge-hashes')
849
except errors.NoSuchFile:
851
834
merge_hashes = {}
853
836
if hashfile.next() != MERGE_MODIFIED_HEADER_1 + '\n':
854
raise errors.MergeModifiedFormatError()
837
raise MergeModifiedFormatError()
855
838
except StopIteration:
856
raise errors.MergeModifiedFormatError()
839
raise MergeModifiedFormatError()
857
840
for s in RioReader(hashfile):
858
# RioReader reads in Unicode, so convert file_ids back to utf8
859
file_id = osutils.safe_file_id(s.get("file_id"), warn=False)
841
file_id = s.get("file_id")
860
842
if file_id not in self.inventory:
862
text_hash = s.get("hash")
863
if text_hash == self.get_file_sha1(file_id):
864
merge_hashes[file_id] = text_hash
845
if hash == self.get_file_sha1(file_id):
846
merge_hashes[file_id] = hash
865
847
return merge_hashes
867
849
@needs_write_lock
868
850
def mkdir(self, path, file_id=None):
869
851
"""See MutableTree.mkdir()."""
870
852
if file_id is None:
871
file_id = generate_ids.gen_file_id(os.path.basename(path))
853
file_id = gen_file_id(os.path.basename(path))
872
854
os.mkdir(self.abspath(path))
873
855
self.add(path, file_id, 'directory')
876
858
def get_symlink_target(self, file_id):
877
file_id = osutils.safe_file_id(file_id)
878
859
return os.readlink(self.id2abspath(file_id))
881
def subsume(self, other_tree):
882
def add_children(inventory, entry):
883
for child_entry in entry.children.values():
884
inventory._byid[child_entry.file_id] = child_entry
885
if child_entry.kind == 'directory':
886
add_children(inventory, child_entry)
887
if other_tree.get_root_id() == self.get_root_id():
888
raise errors.BadSubsumeSource(self, other_tree,
889
'Trees have the same root')
891
other_tree_path = self.relpath(other_tree.basedir)
892
except errors.PathNotChild:
893
raise errors.BadSubsumeSource(self, other_tree,
894
'Tree is not contained by the other')
895
new_root_parent = self.path2id(osutils.dirname(other_tree_path))
896
if new_root_parent is None:
897
raise errors.BadSubsumeSource(self, other_tree,
898
'Parent directory is not versioned.')
899
# We need to ensure that the result of a fetch will have a
900
# versionedfile for the other_tree root, and only fetching into
901
# RepositoryKnit2 guarantees that.
902
if not self.branch.repository.supports_rich_root():
903
raise errors.SubsumeTargetNeedsUpgrade(other_tree)
904
other_tree.lock_tree_write()
906
new_parents = other_tree.get_parent_ids()
907
other_root = other_tree.inventory.root
908
other_root.parent_id = new_root_parent
909
other_root.name = osutils.basename(other_tree_path)
910
self.inventory.add(other_root)
911
add_children(self.inventory, other_root)
912
self._write_inventory(self.inventory)
913
# normally we don't want to fetch whole repositories, but i think
914
# here we really do want to consolidate the whole thing.
915
for parent_id in other_tree.get_parent_ids():
916
self.branch.fetch(other_tree.branch, parent_id)
917
self.add_parent_tree_id(parent_id)
920
other_tree.bzrdir.retire_bzrdir()
922
@needs_tree_write_lock
923
def extract(self, file_id, format=None):
924
"""Extract a subtree from this tree.
926
A new branch will be created, relative to the path for this tree.
930
segments = osutils.splitpath(path)
931
transport = self.branch.bzrdir.root_transport
932
for name in segments:
933
transport = transport.clone(name)
934
transport.ensure_base()
937
sub_path = self.id2path(file_id)
938
branch_transport = mkdirs(sub_path)
940
format = bzrdir.format_registry.make_bzrdir('dirstate-with-subtree')
941
branch_transport.ensure_base()
942
branch_bzrdir = format.initialize_on_transport(branch_transport)
944
repo = branch_bzrdir.find_repository()
945
except errors.NoRepositoryPresent:
946
repo = branch_bzrdir.create_repository()
947
assert repo.supports_rich_root()
949
if not repo.supports_rich_root():
950
raise errors.RootNotRich()
951
new_branch = branch_bzrdir.create_branch()
952
new_branch.pull(self.branch)
953
for parent_id in self.get_parent_ids():
954
new_branch.fetch(self.branch, parent_id)
955
tree_transport = self.bzrdir.root_transport.clone(sub_path)
956
if tree_transport.base != branch_transport.base:
957
tree_bzrdir = format.initialize_on_transport(tree_transport)
958
branch.BranchReferenceFormat().initialize(tree_bzrdir, new_branch)
960
tree_bzrdir = branch_bzrdir
961
wt = tree_bzrdir.create_workingtree(NULL_REVISION)
962
wt.set_parent_ids(self.get_parent_ids())
963
my_inv = self.inventory
964
child_inv = Inventory(root_id=None)
965
new_root = my_inv[file_id]
966
my_inv.remove_recursive_id(file_id)
967
new_root.parent_id = None
968
child_inv.add(new_root)
969
self._write_inventory(my_inv)
970
wt._write_inventory(child_inv)
973
def _serialize(self, inventory, out_file):
974
xml5.serializer_v5.write_inventory(self._inventory, out_file)
976
def _deserialize(selt, in_file):
977
return xml5.serializer_v5.read_inventory(in_file)
861
def file_class(self, filename):
862
if self.path2id(filename):
864
elif self.is_ignored(filename):
980
870
"""Write the in memory inventory to disk."""
1094
982
new_children.sort()
1095
983
new_children = collections.deque(new_children)
1096
984
stack.append((f_ie.file_id, fp, fap, new_children))
1097
# Break out of inner loop,
1098
# so that we start outer loop with child
985
# Break out of inner loop, so that we start outer loop with child
1101
988
# if we finished all children, pop it off the stack
1104
991
@needs_tree_write_lock
1105
def move(self, from_paths, to_dir=None, after=False, **kwargs):
992
def move(self, from_paths, to_name):
1106
993
"""Rename files.
1108
to_dir must exist in the inventory.
995
to_name must exist in the inventory.
1110
If to_dir exists and is a directory, the files are moved into
997
If to_name exists and is a directory, the files are moved into
1111
998
it, keeping their old names.
1113
Note that to_dir is only the last component of the new name;
1000
Note that to_name is only the last component of the new name;
1114
1001
this doesn't change the directory.
1116
For each entry in from_paths the move mode will be determined
1119
The first mode moves the file in the filesystem and updates the
1120
inventory. The second mode only updates the inventory without
1121
touching the file on the filesystem. This is the new mode introduced
1124
move uses the second mode if 'after == True' and the target is not
1125
versioned but present in the working tree.
1127
move uses the second mode if 'after == False' and the source is
1128
versioned but no longer in the working tree, and the target is not
1129
versioned but present in the working tree.
1131
move uses the first mode if 'after == False' and the source is
1132
versioned and present in the working tree, and the target is not
1133
versioned and not present in the working tree.
1135
Everything else results in an error.
1137
1003
This returns a list of (from_path, to_path) pairs for each
1138
1004
entry that is moved.
1143
# check for deprecated use of signature
1145
to_dir = kwargs.get('to_name', None)
1147
raise TypeError('You must supply a target directory')
1149
symbol_versioning.warn('The parameter to_name was deprecated'
1150
' in version 0.13. Use to_dir instead',
1153
# check destination directory
1007
## TODO: Option to move IDs only
1154
1008
assert not isinstance(from_paths, basestring)
1155
1009
inv = self.inventory
1156
to_abs = self.abspath(to_dir)
1010
to_abs = self.abspath(to_name)
1157
1011
if not isdir(to_abs):
1158
raise errors.BzrMoveFailedError('',to_dir,
1159
errors.NotADirectory(to_abs))
1160
if not self.has_filename(to_dir):
1161
raise errors.BzrMoveFailedError('',to_dir,
1162
errors.NotInWorkingDirectory(to_dir))
1163
to_dir_id = inv.path2id(to_dir)
1164
if to_dir_id is None:
1165
raise errors.BzrMoveFailedError('',to_dir,
1166
errors.NotVersionedError(path=str(to_dir)))
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)
1168
1018
to_dir_ie = inv[to_dir_id]
1169
1019
if to_dir_ie.kind != 'directory':
1170
raise errors.BzrMoveFailedError('',to_dir,
1171
errors.NotADirectory(to_abs))
1173
# create rename entries and tuples
1174
for from_rel in from_paths:
1175
from_tail = splitpath(from_rel)[-1]
1176
from_id = inv.path2id(from_rel)
1178
raise errors.BzrMoveFailedError(from_rel,to_dir,
1179
errors.NotVersionedError(path=str(from_rel)))
1181
from_entry = inv[from_id]
1182
from_parent_id = from_entry.parent_id
1183
to_rel = pathjoin(to_dir, from_tail)
1184
rename_entry = WorkingTree._RenameEntry(from_rel=from_rel,
1186
from_tail=from_tail,
1187
from_parent_id=from_parent_id,
1188
to_rel=to_rel, to_tail=from_tail,
1189
to_parent_id=to_dir_id)
1190
rename_entries.append(rename_entry)
1191
rename_tuples.append((from_rel, to_rel))
1193
# determine which move mode to use. checks also for movability
1194
rename_entries = self._determine_mv_mode(rename_entries, after)
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)
1196
1041
original_modified = self._inventory_is_modified
1198
1043
if len(from_paths):
1199
1044
self._inventory_is_modified = True
1200
self._move(rename_entries)
1045
for f in from_paths:
1046
name_tail = splitpath(f)[-1]
1047
dest_path = pathjoin(to_name, name_tail)
1048
result.append((f, dest_path))
1049
inv.rename(inv.path2id(f), to_dir_id, name_tail)
1051
osutils.rename(self.abspath(f), self.abspath(dest_path))
1053
raise BzrError("failed to rename %r to %r: %s" %
1054
(f, dest_path, e[1]))
1202
1056
# restore the inventory on error
1203
self._inventory_is_modified = original_modified
1057
self._set_inventory(orig_inv, dirty=original_modified)
1205
1059
self._write_inventory(inv)
1206
return rename_tuples
1208
def _determine_mv_mode(self, rename_entries, after=False):
1209
"""Determines for each from-to pair if both inventory and working tree
1210
or only the inventory has to be changed.
1212
Also does basic plausability tests.
1214
inv = self.inventory
1216
for rename_entry in rename_entries:
1217
# store to local variables for easier reference
1218
from_rel = rename_entry.from_rel
1219
from_id = rename_entry.from_id
1220
to_rel = rename_entry.to_rel
1221
to_id = inv.path2id(to_rel)
1222
only_change_inv = False
1224
# check the inventory for source and destination
1226
raise errors.BzrMoveFailedError(from_rel,to_rel,
1227
errors.NotVersionedError(path=str(from_rel)))
1228
if to_id is not None:
1229
raise errors.BzrMoveFailedError(from_rel,to_rel,
1230
errors.AlreadyVersionedError(path=str(to_rel)))
1232
# try to determine the mode for rename (only change inv or change
1233
# inv and file system)
1235
if not self.has_filename(to_rel):
1236
raise errors.BzrMoveFailedError(from_id,to_rel,
1237
errors.NoSuchFile(path=str(to_rel),
1238
extra="New file has not been created yet"))
1239
only_change_inv = True
1240
elif not self.has_filename(from_rel) and self.has_filename(to_rel):
1241
only_change_inv = True
1242
elif self.has_filename(from_rel) and not self.has_filename(to_rel):
1243
only_change_inv = False
1245
# something is wrong, so lets determine what exactly
1246
if not self.has_filename(from_rel) and \
1247
not self.has_filename(to_rel):
1248
raise errors.BzrRenameFailedError(from_rel,to_rel,
1249
errors.PathsDoNotExist(paths=(str(from_rel),
1252
raise errors.RenameFailedFilesExist(from_rel, to_rel,
1253
extra="(Use --after to update the Bazaar id)")
1254
rename_entry.only_change_inv = only_change_inv
1255
return rename_entries
1257
def _move(self, rename_entries):
1258
"""Moves a list of files.
1260
Depending on the value of the flag 'only_change_inv', the
1261
file will be moved on the file system or not.
1263
inv = self.inventory
1266
for entry in rename_entries:
1268
self._move_entry(entry)
1270
self._rollback_move(moved)
1274
def _rollback_move(self, moved):
1275
"""Try to rollback a previous move in case of an filesystem error."""
1276
inv = self.inventory
1279
self._move_entry(_RenameEntry(entry.to_rel, entry.from_id,
1280
entry.to_tail, entry.to_parent_id, entry.from_rel,
1281
entry.from_tail, entry.from_parent_id,
1282
entry.only_change_inv))
1283
except errors.BzrMoveFailedError, e:
1284
raise errors.BzrMoveFailedError( '', '', "Rollback failed."
1285
" The working tree is in an inconsistent state."
1286
" Please consider doing a 'bzr revert'."
1287
" Error message is: %s" % e)
1289
def _move_entry(self, entry):
1290
inv = self.inventory
1291
from_rel_abs = self.abspath(entry.from_rel)
1292
to_rel_abs = self.abspath(entry.to_rel)
1293
if from_rel_abs == to_rel_abs:
1294
raise errors.BzrMoveFailedError(entry.from_rel, entry.to_rel,
1295
"Source and target are identical.")
1297
if not entry.only_change_inv:
1299
osutils.rename(from_rel_abs, to_rel_abs)
1301
raise errors.BzrMoveFailedError(entry.from_rel,
1303
inv.rename(entry.from_id, entry.to_parent_id, entry.to_tail)
1305
1062
@needs_tree_write_lock
1306
def rename_one(self, from_rel, to_rel, after=False):
1063
def rename_one(self, from_rel, to_rel):
1307
1064
"""Rename one file.
1309
1066
This can change the directory or the filename or both.
1311
rename_one has several 'modes' to work. First, it can rename a physical
1312
file and change the file_id. That is the normal mode. Second, it can
1313
only change the file_id without touching any physical file. This is
1314
the new mode introduced in version 0.15.
1316
rename_one uses the second mode if 'after == True' and 'to_rel' is not
1317
versioned but present in the working tree.
1319
rename_one uses the second mode if 'after == False' and 'from_rel' is
1320
versioned but no longer in the working tree, and 'to_rel' is not
1321
versioned but present in the working tree.
1323
rename_one uses the first mode if 'after == False' and 'from_rel' is
1324
versioned and present in the working tree, and 'to_rel' is not
1325
versioned and not present in the working tree.
1327
Everything else results in an error.
1329
1068
inv = self.inventory
1332
# create rename entries and tuples
1333
from_tail = splitpath(from_rel)[-1]
1334
from_id = inv.path2id(from_rel)
1336
raise errors.BzrRenameFailedError(from_rel,to_rel,
1337
errors.NotVersionedError(path=str(from_rel)))
1338
from_entry = inv[from_id]
1339
from_parent_id = from_entry.parent_id
1069
if not self.has_filename(from_rel):
1070
raise BzrError("can't rename: old working file %r does not exist" % from_rel)
1071
if self.has_filename(to_rel):
1072
raise BzrError("can't rename: new working file %r already exists" % to_rel)
1074
file_id = inv.path2id(from_rel)
1076
raise BzrError("can't rename: old name %r is not versioned" % from_rel)
1078
entry = inv[file_id]
1079
from_parent = entry.parent_id
1080
from_name = entry.name
1082
if inv.path2id(to_rel):
1083
raise BzrError("can't rename: new name %r is already versioned" % to_rel)
1340
1085
to_dir, to_tail = os.path.split(to_rel)
1341
1086
to_dir_id = inv.path2id(to_dir)
1342
rename_entry = WorkingTree._RenameEntry(from_rel=from_rel,
1344
from_tail=from_tail,
1345
from_parent_id=from_parent_id,
1346
to_rel=to_rel, to_tail=to_tail,
1347
to_parent_id=to_dir_id)
1348
rename_entries.append(rename_entry)
1350
# determine which move mode to use. checks also for movability
1351
rename_entries = self._determine_mv_mode(rename_entries, after)
1353
# check if the target changed directory and if the target directory is
1355
if to_dir_id is None:
1356
raise errors.BzrMoveFailedError(from_rel,to_rel,
1357
errors.NotVersionedError(path=str(to_dir)))
1359
# all checks done. now we can continue with our actual work
1360
mutter('rename_one:\n'
1365
' to_dir_id {%s}\n',
1366
from_id, from_rel, to_rel, to_dir, to_dir_id)
1368
self._move(rename_entries)
1087
if to_dir_id is None and to_dir != '':
1088
raise BzrError("can't determine destination directory id for %r" % to_dir)
1090
mutter("rename_one:")
1091
mutter(" file_id {%s}" % file_id)
1092
mutter(" from_rel %r" % from_rel)
1093
mutter(" to_rel %r" % to_rel)
1094
mutter(" to_dir %r" % to_dir)
1095
mutter(" to_dir_id {%s}" % to_dir_id)
1097
inv.rename(file_id, to_dir_id, to_tail)
1099
from_abs = self.abspath(from_rel)
1100
to_abs = self.abspath(to_rel)
1102
osutils.rename(from_abs, to_abs)
1104
inv.rename(file_id, from_parent, from_name)
1105
raise BzrError("failed to rename %r to %r: %s"
1106
% (from_abs, to_abs, e[1]))
1369
1107
self._write_inventory(inv)
1371
class _RenameEntry(object):
1372
def __init__(self, from_rel, from_id, from_tail, from_parent_id,
1373
to_rel, to_tail, to_parent_id, only_change_inv=False):
1374
self.from_rel = from_rel
1375
self.from_id = from_id
1376
self.from_tail = from_tail
1377
self.from_parent_id = from_parent_id
1378
self.to_rel = to_rel
1379
self.to_tail = to_tail
1380
self.to_parent_id = to_parent_id
1381
self.only_change_inv = only_change_inv
1383
1109
@needs_read_lock
1384
1110
def unknowns(self):
1385
1111
"""Return all unknown files.
1756
1515
if self._inventory_is_modified:
1757
1516
raise errors.InventoryModified(self)
1758
result = self._deserialize(self._control_files.get('inventory'))
1517
result = xml5.serializer_v5.read_inventory(
1518
self._control_files.get('inventory'))
1759
1519
self._set_inventory(result, dirty=False)
1762
1522
@needs_tree_write_lock
1763
def remove(self, files, verbose=False, to_file=None, keep_files=True,
1765
"""Remove nominated files from the working inventor.
1767
:files: File paths relative to the basedir.
1768
:keep_files: If true, the files will also be kept.
1769
:force: Delete files and directories, even if they are changed and
1770
even if the directories are not empty.
1523
def remove(self, files, verbose=False, to_file=None):
1524
"""Remove nominated files from the working inventory..
1526
This does not remove their text. This does not run on XXX on what? RBC
1528
TODO: Refuse to remove modified files unless --force is given?
1530
TODO: Do something useful with directories.
1532
TODO: Should this remove the text or not? Tough call; not
1533
removing may be useful and the user can just use use rm, and
1534
is the opposite of add. Removing it is consistent with most
1535
other tools. Maybe an option.
1772
1537
## TODO: Normalize names
1538
## TODO: Remove nested loops; better scalability
1774
1539
if isinstance(files, basestring):
1775
1540
files = [files]
1780
unknown_files_in_directory=set()
1782
def recurse_directory_to_add_files(directory):
1783
# recurse directory and add all files
1784
# so we can check if they have changed.
1785
for parent_info, file_infos in\
1786
osutils.walkdirs(self.abspath(directory),
1788
for relpath, basename, kind, lstat, abspath in file_infos:
1790
if self.path2id(relpath): #is it versioned?
1791
new_files.add(relpath)
1793
unknown_files_in_directory.add(
1794
(relpath, None, kind))
1796
for filename in files:
1797
# Get file name into canonical form.
1798
abspath = self.abspath(filename)
1799
filename = self.relpath(abspath)
1800
if len(filename) > 0:
1801
new_files.add(filename)
1802
if osutils.isdir(abspath):
1803
recurse_directory_to_add_files(filename)
1804
files = [f for f in new_files]
1806
# Sort needed to first handle directory content before the directory
1807
files.sort(reverse=True)
1808
if not keep_files and not force:
1809
tree_delta = self.changes_from(self.basis_tree(),
1810
specific_files=files)
1811
for unknown_file in unknown_files_in_directory:
1812
tree_delta.unversioned.extend((unknown_file,))
1813
if bool(tree_delta.modified
1815
or tree_delta.renamed
1816
or tree_delta.kind_changed
1817
or tree_delta.unversioned):
1818
raise errors.BzrRemoveChangedFilesError(tree_delta)
1542
inv = self.inventory
1820
1544
# do this before any modifications
1821
1545
for f in files:
1822
fid = self.path2id(f)
1546
fid = inv.path2id(f)
1825
message="%s is not versioned." % (f,)
1828
# having removed it, it must be either ignored or unknown
1829
if self.is_ignored(f):
1833
textui.show_status(new_status, self.kind(fid), f,
1836
inv_delta.append((f, None, fid, None))
1837
message="removed %s" % (f,)
1840
abs_path = self.abspath(f)
1841
if osutils.lexists(abs_path):
1842
if (osutils.isdir(abs_path) and
1843
len(os.listdir(abs_path)) > 0):
1844
message="%s is not empty directory "\
1845
"and won't be deleted." % (f,)
1847
osutils.delete_any(abs_path)
1848
message="deleted %s" % (f,)
1849
elif message is not None:
1850
# only care if we haven't done anything yet.
1851
message="%s does not exist." % (f,)
1853
# print only one message (if any) per file.
1854
if message is not None:
1856
self.apply_inventory_delta(inv_delta)
1548
# TODO: Perhaps make this just a warning, and continue?
1549
# This tends to happen when
1550
raise NotVersionedError(path=f)
1552
# having remove it, it must be either ignored or unknown
1553
if self.is_ignored(f):
1557
textui.show_status(new_status, inv[fid].kind, f,
1561
self._write_inventory(inv)
1858
1563
@needs_tree_write_lock
1859
1564
def revert(self, filenames, old_tree=None, backups=True,
1860
pb=DummyProgress(), report_changes=False):
1565
pb=DummyProgress()):
1861
1566
from bzrlib.conflicts import resolve
1862
1567
if old_tree is None:
1863
1568
old_tree = self.basis_tree()
1864
conflicts = transform.revert(self, old_tree, filenames, backups, pb,
1569
conflicts = transform.revert(self, old_tree, filenames, backups, pb)
1866
1570
if not len(filenames):
1867
1571
self.set_parent_ids(self.get_parent_ids()[:1])
2150
1794
file_id=self.path2id(conflicted)))
2151
1795
return conflicts
2153
def walkdirs(self, prefix=""):
2154
"""Walk the directories of this tree.
2156
returns a generator which yields items in the form:
2157
((curren_directory_path, fileid),
2158
[(file1_path, file1_name, file1_kind, (lstat), file1_id,
2161
This API returns a generator, which is only valid during the current
2162
tree transaction - within a single lock_read or lock_write duration.
2164
If the tree is not locked, it may cause an error to be raised,
2165
depending on the tree implementation.
2167
disk_top = self.abspath(prefix)
2168
if disk_top.endswith('/'):
2169
disk_top = disk_top[:-1]
2170
top_strip_len = len(disk_top) + 1
2171
inventory_iterator = self._walkdirs(prefix)
2172
disk_iterator = osutils.walkdirs(disk_top, prefix)
2174
current_disk = disk_iterator.next()
2175
disk_finished = False
2177
if not (e.errno == errno.ENOENT or
2178
(sys.platform == 'win32' and e.errno == ERROR_PATH_NOT_FOUND)):
2181
disk_finished = True
2183
current_inv = inventory_iterator.next()
2184
inv_finished = False
2185
except StopIteration:
2188
while not inv_finished or not disk_finished:
2189
if not disk_finished:
2190
# strip out .bzr dirs
2191
if current_disk[0][1][top_strip_len:] == '':
2192
# osutils.walkdirs can be made nicer -
2193
# yield the path-from-prefix rather than the pathjoined
2195
bzrdir_loc = bisect_left(current_disk[1], ('.bzr', '.bzr'))
2196
if current_disk[1][bzrdir_loc][0] == '.bzr':
2197
# we dont yield the contents of, or, .bzr itself.
2198
del current_disk[1][bzrdir_loc]
2200
# everything is unknown
2203
# everything is missing
2206
direction = cmp(current_inv[0][0], current_disk[0][0])
2208
# disk is before inventory - unknown
2209
dirblock = [(relpath, basename, kind, stat, None, None) for
2210
relpath, basename, kind, stat, top_path in current_disk[1]]
2211
yield (current_disk[0][0], None), dirblock
2213
current_disk = disk_iterator.next()
2214
except StopIteration:
2215
disk_finished = True
2217
# inventory is before disk - missing.
2218
dirblock = [(relpath, basename, 'unknown', None, fileid, kind)
2219
for relpath, basename, dkind, stat, fileid, kind in
2221
yield (current_inv[0][0], current_inv[0][1]), dirblock
2223
current_inv = inventory_iterator.next()
2224
except StopIteration:
2227
# versioned present directory
2228
# merge the inventory and disk data together
2230
for relpath, subiterator in itertools.groupby(sorted(
2231
current_inv[1] + current_disk[1], key=operator.itemgetter(0)), operator.itemgetter(1)):
2232
path_elements = list(subiterator)
2233
if len(path_elements) == 2:
2234
inv_row, disk_row = path_elements
2235
# versioned, present file
2236
dirblock.append((inv_row[0],
2237
inv_row[1], disk_row[2],
2238
disk_row[3], inv_row[4],
2240
elif len(path_elements[0]) == 5:
2242
dirblock.append((path_elements[0][0],
2243
path_elements[0][1], path_elements[0][2],
2244
path_elements[0][3], None, None))
2245
elif len(path_elements[0]) == 6:
2246
# versioned, absent file.
2247
dirblock.append((path_elements[0][0],
2248
path_elements[0][1], 'unknown', None,
2249
path_elements[0][4], path_elements[0][5]))
2251
raise NotImplementedError('unreachable code')
2252
yield current_inv[0], dirblock
2254
current_inv = inventory_iterator.next()
2255
except StopIteration:
2258
current_disk = disk_iterator.next()
2259
except StopIteration:
2260
disk_finished = True
2262
def _walkdirs(self, prefix=""):
2263
"""Walk the directories of this tree.
2265
:prefix: is used as the directrory to start with.
2266
returns a generator which yields items in the form:
2267
((curren_directory_path, fileid),
2268
[(file1_path, file1_name, file1_kind, None, file1_id,
2271
_directory = 'directory'
2272
# get the root in the inventory
2273
inv = self.inventory
2274
top_id = inv.path2id(prefix)
2278
pending = [(prefix, '', _directory, None, top_id, None)]
2281
currentdir = pending.pop()
2282
# 0 - relpath, 1- basename, 2- kind, 3- stat, 4-id, 5-kind
2283
top_id = currentdir[4]
2285
relroot = currentdir[0] + '/'
2288
# FIXME: stash the node in pending
2290
for name, child in entry.sorted_children():
2291
dirblock.append((relroot + name, name, child.kind, None,
2292
child.file_id, child.kind
2294
yield (currentdir[0], entry.file_id), dirblock
2295
# push the user specified dirs from dirblock
2296
for dir in reversed(dirblock):
2297
if dir[2] == _directory:
2300
@needs_tree_write_lock
2301
def auto_resolve(self):
2302
"""Automatically resolve text conflicts according to contents.
2304
Only text conflicts are auto_resolvable. Files with no conflict markers
2305
are considered 'resolved', because bzr always puts conflict markers
2306
into files that have text conflicts. The corresponding .THIS .BASE and
2307
.OTHER files are deleted, as per 'resolve'.
2308
:return: a tuple of ConflictLists: (un_resolved, resolved).
2310
un_resolved = _mod_conflicts.ConflictList()
2311
resolved = _mod_conflicts.ConflictList()
2312
conflict_re = re.compile('^(<{7}|={7}|>{7})')
2313
for conflict in self.conflicts():
2314
if (conflict.typestring != 'text conflict' or
2315
self.kind(conflict.file_id) != 'file'):
2316
un_resolved.append(conflict)
2318
my_file = open(self.id2abspath(conflict.file_id), 'rb')
2320
for line in my_file:
2321
if conflict_re.search(line):
2322
un_resolved.append(conflict)
2325
resolved.append(conflict)
2328
resolved.remove_files(self)
2329
self.set_conflicts(un_resolved)
2330
return un_resolved, resolved
2332
def _validate(self):
2333
"""Validate internal structures.
2335
This is meant mostly for the test suite. To give it a chance to detect
2336
corruption after actions have occurred. The default implementation is a
2339
:return: None. An exception should be raised if there is an error.
2344
1798
class WorkingTree2(WorkingTree):
2345
1799
"""This is the Format 2 working tree.