312
511
size = stat.st_size
313
512
packed_stat = pack_stat(stat)
314
513
parent_info = self._empty_parent_info()
315
entry_key = (dirname, basename, file_id.encode('utf8'))
514
minikind = DirState._kind_to_minikind[kind]
515
if rename_from is not None:
517
old_path_utf8 = '%s/%s' % rename_from
519
old_path_utf8 = rename_from[1]
520
parent_info[0] = ('r', old_path_utf8, 0, False, '')
316
521
if kind == 'file':
317
522
entry_data = entry_key, [
318
(kind, link_or_sha1, size, False, packed_stat),
523
(minikind, fingerprint, size, False, packed_stat),
320
525
elif kind == 'directory':
321
526
entry_data = entry_key, [
322
(kind, '', 0, False, packed_stat),
527
(minikind, '', 0, False, packed_stat),
324
529
elif kind == 'symlink':
325
530
entry_data = entry_key, [
326
(kind, link_or_sha1, size, False, packed_stat),
531
(minikind, fingerprint, size, False, packed_stat),
533
elif kind == 'tree-reference':
534
entry_data = entry_key, [
535
(minikind, fingerprint, 0, False, packed_stat),
329
538
raise errors.BzrError('unknown kind %r' % kind)
330
entry_index = bisect.bisect_left(block, entry_data)
331
if len(block) > entry_index:
332
assert block[entry_index][0][1] != basename, \
333
"basename %r already added" % basename
334
block.insert(entry_index, entry_data)
539
entry_index, present = self._find_entry_index(entry_key, block)
541
block.insert(entry_index, entry_data)
543
if block[entry_index][1][0][0] != 'a':
544
raise AssertionError(" %r(%r) already added" % (basename, file_id))
545
block[entry_index][1][0] = entry_data[1][0]
336
547
if kind == 'directory':
337
548
# insert a new dirblock
338
549
self._ensure_block(block_index, entry_index, utf8path)
339
550
self._dirblock_state = DirState.IN_MEMORY_MODIFIED
341
def add_deleted(self, fileid_utf8, parents):
342
"""Add fileid_utf8 with parents as deleted."""
552
self._add_to_id_index(self._id_index, entry_key)
554
def _bisect(self, paths):
555
"""Bisect through the disk structure for specific rows.
557
:param paths: A list of paths to find
558
:return: A dict mapping path => entries for found entries. Missing
559
entries will not be in the map.
560
The list is not sorted, and entries will be populated
561
based on when they were read.
563
self._requires_lock()
564
# We need the file pointer to be right after the initial header block
565
self._read_header_if_needed()
566
# If _dirblock_state was in memory, we should just return info from
567
# there, this function is only meant to handle when we want to read
569
if self._dirblock_state != DirState.NOT_IN_MEMORY:
570
raise AssertionError("bad dirblock state %r" % self._dirblock_state)
572
# The disk representation is generally info + '\0\n\0' at the end. But
573
# for bisecting, it is easier to treat this as '\0' + info + '\0\n'
574
# Because it means we can sync on the '\n'
575
state_file = self._state_file
576
file_size = os.fstat(state_file.fileno()).st_size
577
# We end up with 2 extra fields, we should have a trailing '\n' to
578
# ensure that we read the whole record, and we should have a precursur
579
# '' which ensures that we start after the previous '\n'
580
entry_field_count = self._fields_per_entry() + 1
582
low = self._end_of_header
583
high = file_size - 1 # Ignore the final '\0'
584
# Map from (dir, name) => entry
587
# Avoid infinite seeking
588
max_count = 30*len(paths)
590
# pending is a list of places to look.
591
# each entry is a tuple of low, high, dir_names
592
# low -> the first byte offset to read (inclusive)
593
# high -> the last byte offset (inclusive)
594
# dir_names -> The list of (dir, name) pairs that should be found in
595
# the [low, high] range
596
pending = [(low, high, paths)]
598
page_size = self._bisect_page_size
600
fields_to_entry = self._get_fields_to_entry()
603
low, high, cur_files = pending.pop()
605
if not cur_files or low >= high:
610
if count > max_count:
611
raise errors.BzrError('Too many seeks, most likely a bug.')
613
mid = max(low, (low+high-page_size)/2)
616
# limit the read size, so we don't end up reading data that we have
618
read_size = min(page_size, (high-mid)+1)
619
block = state_file.read(read_size)
622
entries = block.split('\n')
625
# We didn't find a '\n', so we cannot have found any records.
626
# So put this range back and try again. But we know we have to
627
# increase the page size, because a single read did not contain
628
# a record break (so records must be larger than page_size)
630
pending.append((low, high, cur_files))
633
# Check the first and last entries, in case they are partial, or if
634
# we don't care about the rest of this page
636
first_fields = entries[0].split('\0')
637
if len(first_fields) < entry_field_count:
638
# We didn't get the complete first entry
639
# so move start, and grab the next, which
640
# should be a full entry
641
start += len(entries[0])+1
642
first_fields = entries[1].split('\0')
645
if len(first_fields) <= 2:
646
# We didn't even get a filename here... what do we do?
647
# Try a large page size and repeat this query
649
pending.append((low, high, cur_files))
652
# Find what entries we are looking for, which occur before and
653
# after this first record.
656
first_path = first_fields[1] + '/' + first_fields[2]
658
first_path = first_fields[2]
659
first_loc = _bisect_path_left(cur_files, first_path)
661
# These exist before the current location
662
pre = cur_files[:first_loc]
663
# These occur after the current location, which may be in the
664
# data we read, or might be after the last entry
665
post = cur_files[first_loc:]
667
if post and len(first_fields) >= entry_field_count:
668
# We have files after the first entry
670
# Parse the last entry
671
last_entry_num = len(entries)-1
672
last_fields = entries[last_entry_num].split('\0')
673
if len(last_fields) < entry_field_count:
674
# The very last hunk was not complete,
675
# read the previous hunk
676
after = mid + len(block) - len(entries[-1])
678
last_fields = entries[last_entry_num].split('\0')
680
after = mid + len(block)
683
last_path = last_fields[1] + '/' + last_fields[2]
685
last_path = last_fields[2]
686
last_loc = _bisect_path_right(post, last_path)
688
middle_files = post[:last_loc]
689
post = post[last_loc:]
692
# We have files that should occur in this block
693
# (>= first, <= last)
694
# Either we will find them here, or we can mark them as
697
if middle_files[0] == first_path:
698
# We might need to go before this location
699
pre.append(first_path)
700
if middle_files[-1] == last_path:
701
post.insert(0, last_path)
703
# Find out what paths we have
704
paths = {first_path:[first_fields]}
705
# last_path might == first_path so we need to be
706
# careful if we should append rather than overwrite
707
if last_entry_num != first_entry_num:
708
paths.setdefault(last_path, []).append(last_fields)
709
for num in xrange(first_entry_num+1, last_entry_num):
710
# TODO: jam 20070223 We are already splitting here, so
711
# shouldn't we just split the whole thing rather
712
# than doing the split again in add_one_record?
713
fields = entries[num].split('\0')
715
path = fields[1] + '/' + fields[2]
718
paths.setdefault(path, []).append(fields)
720
for path in middle_files:
721
for fields in paths.get(path, []):
722
# offset by 1 because of the opening '\0'
723
# consider changing fields_to_entry to avoid the
725
entry = fields_to_entry(fields[1:])
726
found.setdefault(path, []).append(entry)
728
# Now we have split up everything into pre, middle, and post, and
729
# we have handled everything that fell in 'middle'.
730
# We add 'post' first, so that we prefer to seek towards the
731
# beginning, so that we will tend to go as early as we need, and
732
# then only seek forward after that.
734
pending.append((after, high, post))
736
pending.append((low, start-1, pre))
738
# Consider that we may want to return the directory entries in sorted
739
# order. For now, we just return them in whatever order we found them,
740
# and leave it up to the caller if they care if it is ordered or not.
743
def _bisect_dirblocks(self, dir_list):
744
"""Bisect through the disk structure to find entries in given dirs.
746
_bisect_dirblocks is meant to find the contents of directories, which
747
differs from _bisect, which only finds individual entries.
749
:param dir_list: A sorted list of directory names ['', 'dir', 'foo'].
750
:return: A map from dir => entries_for_dir
752
# TODO: jam 20070223 A lot of the bisecting logic could be shared
753
# between this and _bisect. It would require parameterizing the
754
# inner loop with a function, though. We should evaluate the
755
# performance difference.
756
self._requires_lock()
757
# We need the file pointer to be right after the initial header block
758
self._read_header_if_needed()
759
# If _dirblock_state was in memory, we should just return info from
760
# there, this function is only meant to handle when we want to read
762
if self._dirblock_state != DirState.NOT_IN_MEMORY:
763
raise AssertionError("bad dirblock state %r" % self._dirblock_state)
764
# The disk representation is generally info + '\0\n\0' at the end. But
765
# for bisecting, it is easier to treat this as '\0' + info + '\0\n'
766
# Because it means we can sync on the '\n'
767
state_file = self._state_file
768
file_size = os.fstat(state_file.fileno()).st_size
769
# We end up with 2 extra fields, we should have a trailing '\n' to
770
# ensure that we read the whole record, and we should have a precursur
771
# '' which ensures that we start after the previous '\n'
772
entry_field_count = self._fields_per_entry() + 1
774
low = self._end_of_header
775
high = file_size - 1 # Ignore the final '\0'
776
# Map from dir => entry
779
# Avoid infinite seeking
780
max_count = 30*len(dir_list)
782
# pending is a list of places to look.
783
# each entry is a tuple of low, high, dir_names
784
# low -> the first byte offset to read (inclusive)
785
# high -> the last byte offset (inclusive)
786
# dirs -> The list of directories that should be found in
787
# the [low, high] range
788
pending = [(low, high, dir_list)]
790
page_size = self._bisect_page_size
792
fields_to_entry = self._get_fields_to_entry()
795
low, high, cur_dirs = pending.pop()
797
if not cur_dirs or low >= high:
802
if count > max_count:
803
raise errors.BzrError('Too many seeks, most likely a bug.')
805
mid = max(low, (low+high-page_size)/2)
808
# limit the read size, so we don't end up reading data that we have
810
read_size = min(page_size, (high-mid)+1)
811
block = state_file.read(read_size)
814
entries = block.split('\n')
817
# We didn't find a '\n', so we cannot have found any records.
818
# So put this range back and try again. But we know we have to
819
# increase the page size, because a single read did not contain
820
# a record break (so records must be larger than page_size)
822
pending.append((low, high, cur_dirs))
825
# Check the first and last entries, in case they are partial, or if
826
# we don't care about the rest of this page
828
first_fields = entries[0].split('\0')
829
if len(first_fields) < entry_field_count:
830
# We didn't get the complete first entry
831
# so move start, and grab the next, which
832
# should be a full entry
833
start += len(entries[0])+1
834
first_fields = entries[1].split('\0')
837
if len(first_fields) <= 1:
838
# We didn't even get a dirname here... what do we do?
839
# Try a large page size and repeat this query
841
pending.append((low, high, cur_dirs))
844
# Find what entries we are looking for, which occur before and
845
# after this first record.
847
first_dir = first_fields[1]
848
first_loc = bisect.bisect_left(cur_dirs, first_dir)
850
# These exist before the current location
851
pre = cur_dirs[:first_loc]
852
# These occur after the current location, which may be in the
853
# data we read, or might be after the last entry
854
post = cur_dirs[first_loc:]
856
if post and len(first_fields) >= entry_field_count:
857
# We have records to look at after the first entry
859
# Parse the last entry
860
last_entry_num = len(entries)-1
861
last_fields = entries[last_entry_num].split('\0')
862
if len(last_fields) < entry_field_count:
863
# The very last hunk was not complete,
864
# read the previous hunk
865
after = mid + len(block) - len(entries[-1])
867
last_fields = entries[last_entry_num].split('\0')
869
after = mid + len(block)
871
last_dir = last_fields[1]
872
last_loc = bisect.bisect_right(post, last_dir)
874
middle_files = post[:last_loc]
875
post = post[last_loc:]
878
# We have files that should occur in this block
879
# (>= first, <= last)
880
# Either we will find them here, or we can mark them as
883
if middle_files[0] == first_dir:
884
# We might need to go before this location
885
pre.append(first_dir)
886
if middle_files[-1] == last_dir:
887
post.insert(0, last_dir)
889
# Find out what paths we have
890
paths = {first_dir:[first_fields]}
891
# last_dir might == first_dir so we need to be
892
# careful if we should append rather than overwrite
893
if last_entry_num != first_entry_num:
894
paths.setdefault(last_dir, []).append(last_fields)
895
for num in xrange(first_entry_num+1, last_entry_num):
896
# TODO: jam 20070223 We are already splitting here, so
897
# shouldn't we just split the whole thing rather
898
# than doing the split again in add_one_record?
899
fields = entries[num].split('\0')
900
paths.setdefault(fields[1], []).append(fields)
902
for cur_dir in middle_files:
903
for fields in paths.get(cur_dir, []):
904
# offset by 1 because of the opening '\0'
905
# consider changing fields_to_entry to avoid the
907
entry = fields_to_entry(fields[1:])
908
found.setdefault(cur_dir, []).append(entry)
910
# Now we have split up everything into pre, middle, and post, and
911
# we have handled everything that fell in 'middle'.
912
# We add 'post' first, so that we prefer to seek towards the
913
# beginning, so that we will tend to go as early as we need, and
914
# then only seek forward after that.
916
pending.append((after, high, post))
918
pending.append((low, start-1, pre))
922
def _bisect_recursive(self, paths):
923
"""Bisect for entries for all paths and their children.
925
This will use bisect to find all records for the supplied paths. It
926
will then continue to bisect for any records which are marked as
927
directories. (and renames?)
929
:param paths: A sorted list of (dir, name) pairs
930
eg: [('', 'a'), ('', 'f'), ('a/b', 'c')]
931
:return: A dictionary mapping (dir, name, file_id) => [tree_info]
933
# Map from (dir, name, file_id) => [tree_info]
936
found_dir_names = set()
938
# Directories that have been read
939
processed_dirs = set()
940
# Get the ball rolling with the first bisect for all entries.
941
newly_found = self._bisect(paths)
944
# Directories that need to be read
946
paths_to_search = set()
947
for entry_list in newly_found.itervalues():
948
for dir_name_id, trees_info in entry_list:
949
found[dir_name_id] = trees_info
950
found_dir_names.add(dir_name_id[:2])
952
for tree_info in trees_info:
953
minikind = tree_info[0]
956
# We already processed this one as a directory,
957
# we don't need to do the extra work again.
959
subdir, name, file_id = dir_name_id
960
path = osutils.pathjoin(subdir, name)
962
if path not in processed_dirs:
963
pending_dirs.add(path)
964
elif minikind == 'r':
965
# Rename, we need to directly search the target
966
# which is contained in the fingerprint column
967
dir_name = osutils.split(tree_info[1])
968
if dir_name[0] in pending_dirs:
969
# This entry will be found in the dir search
971
if dir_name not in found_dir_names:
972
paths_to_search.add(tree_info[1])
973
# Now we have a list of paths to look for directly, and
974
# directory blocks that need to be read.
975
# newly_found is mixing the keys between (dir, name) and path
976
# entries, but that is okay, because we only really care about the
978
newly_found = self._bisect(sorted(paths_to_search))
979
newly_found.update(self._bisect_dirblocks(sorted(pending_dirs)))
980
processed_dirs.update(pending_dirs)
983
def _discard_merge_parents(self):
984
"""Discard any parents trees beyond the first.
986
Note that if this fails the dirstate is corrupted.
988
After this function returns the dirstate contains 2 trees, neither of
991
self._read_header_if_needed()
992
parents = self.get_parent_ids()
995
# only require all dirblocks if we are doing a full-pass removal.
343
996
self._read_dirblocks_if_needed()
344
new_row = self._make_deleted_row(fileid_utf8, parents)
345
block_index = self._find_dirblock_index(new_row[0][0])
347
# no deleted block yet.
348
bisect.insort_left(self._dirblocks, (new_row[0][0], []))
349
block_index = self._find_dirblock_index(new_row[0][0])
350
block = self._dirblocks[block_index][1]
351
row_index = bisect.insort_left(block, new_row)
997
dead_patterns = set([('a', 'r'), ('a', 'a'), ('r', 'r'), ('r', 'a')])
998
def iter_entries_removable():
999
for block in self._dirblocks:
1000
deleted_positions = []
1001
for pos, entry in enumerate(block[1]):
1003
if (entry[1][0][0], entry[1][1][0]) in dead_patterns:
1004
deleted_positions.append(pos)
1005
if deleted_positions:
1006
if len(deleted_positions) == len(block[1]):
1009
for pos in reversed(deleted_positions):
1011
# if the first parent is a ghost:
1012
if parents[0] in self.get_ghosts():
1013
empty_parent = [DirState.NULL_PARENT_DETAILS]
1014
for entry in iter_entries_removable():
1015
entry[1][1:] = empty_parent
1017
for entry in iter_entries_removable():
1021
self._parents = [parents[0]]
352
1022
self._dirblock_state = DirState.IN_MEMORY_MODIFIED
1023
self._header_state = DirState.IN_MEMORY_MODIFIED
354
1025
def _empty_parent_info(self):
355
1026
return [DirState.NULL_PARENT_DETAILS] * (len(self._parents) -
356
1027
len(self._ghosts))
358
1029
def _ensure_block(self, parent_block_index, parent_row_index, dirname):
359
"""Enssure a block for dirname exists.
1030
"""Ensure a block for dirname exists.
361
1032
This function exists to let callers which know that there is a
362
1033
directory dirname ensure that the block for it exists. This block can
363
1034
fail to exist because of demand loading, or because a directory had no
375
1046
:param dirname: The utf8 dirname to ensure there is a block for.
376
1047
:return: The index for the block.
1049
if dirname == '' and parent_row_index == 0 and parent_block_index == 0:
1050
# This is the signature of the root row, and the
1051
# contents-of-root row is always index 1
378
1053
# the basename of the directory must be the end of its full name.
379
1054
if not (parent_block_index == -1 and
380
1055
parent_block_index == -1 and dirname == ''):
381
assert dirname.endswith(
382
self._dirblocks[parent_block_index][1][parent_row_index][0][1])
383
## In future, when doing partial parsing, this should load and
384
# populate the entire block.
385
index = bisect.bisect_left(self._dirblocks, (dirname, []))
386
if (index == len(self._dirblocks) or
387
self._dirblocks[index][0] != dirname):
388
self._dirblocks.insert(index, (dirname, []))
1056
if not dirname.endswith(
1057
self._dirblocks[parent_block_index][1][parent_row_index][0][1]):
1058
raise AssertionError("bad dirname %r" % dirname)
1059
block_index, present = self._find_block_index_from_key((dirname, '', ''))
1061
## In future, when doing partial parsing, this should load and
1062
# populate the entire block.
1063
self._dirblocks.insert(block_index, (dirname, []))
391
1066
def _entries_to_current_state(self, new_entries):
392
"""Load new_entries into self._root_entries and self.dirblocks.
1067
"""Load new_entries into self.dirblocks.
394
1069
Process new_entries into the current state object, making them the active
1070
state. The entries are grouped together by directory to form dirblocks.
397
1072
:param new_entries: A sorted list of entries. This function does not sort
398
1073
to prevent unneeded overhead when callers have a sorted list already.
399
1074
:return: Nothing.
401
assert new_entries[0][0][0:2] == ('', ''), \
402
"Missing root row %r" % new_entries[0][0]
403
self._root_entries = []
404
self._dirblocks = [('', [])]
405
current_block = self._root_entries
1076
if new_entries[0][0][0:2] != ('', ''):
1077
raise AssertionError(
1078
"Missing root row %r" % (new_entries[0][0],))
1079
# The two blocks here are deliberate: the root block and the
1080
# contents-of-root block.
1081
self._dirblocks = [('', []), ('', [])]
1082
current_block = self._dirblocks[0][1]
406
1083
current_dirname = ''
407
1084
root_key = ('', '')
1085
append_entry = current_block.append
408
1086
for entry in new_entries:
409
1087
if entry[0][0] != current_dirname:
1088
# new block - different dirname
411
1089
current_block = []
412
self._dirblocks.append((entry[0][0], current_block))
413
elif entry[0][0:2] != root_key:
414
# this is not a root entry for a tree
415
current_block = self._dirblocks[-1][1]
1090
current_dirname = entry[0][0]
1091
self._dirblocks.append((current_dirname, current_block))
1092
append_entry = current_block.append
416
1093
# append the entry to the current block
417
current_block.append(entry)
1095
self._split_root_dirblock_into_contents()
1097
def _split_root_dirblock_into_contents(self):
1098
"""Split the root dirblocks into root and contents-of-root.
1100
After parsing by path, we end up with root entries and contents-of-root
1101
entries in the same block. This loop splits them out again.
1103
# The above loop leaves the "root block" entries mixed with the
1104
# "contents-of-root block". But we don't want an if check on
1105
# all entries, so instead we just fix it up here.
1106
if self._dirblocks[1] != ('', []):
1107
raise ValueError("bad dirblock start %r" % (self._dirblocks[1],))
1109
contents_of_root_block = []
1110
for entry in self._dirblocks[0][1]:
1111
if not entry[0][1]: # This is a root entry
1112
root_block.append(entry)
1114
contents_of_root_block.append(entry)
1115
self._dirblocks[0] = ('', root_block)
1116
self._dirblocks[1] = ('', contents_of_root_block)
1118
def _entries_for_path(self, path):
1119
"""Return a list with all the entries that match path for all ids."""
1120
dirname, basename = os.path.split(path)
1121
key = (dirname, basename, '')
1122
block_index, present = self._find_block_index_from_key(key)
1124
# the block which should contain path is absent.
1127
block = self._dirblocks[block_index][1]
1128
entry_index, _ = self._find_entry_index(key, block)
1129
# we may need to look at multiple entries at this path: walk while the specific_files match.
1130
while (entry_index < len(block) and
1131
block[entry_index][0][0:2] == key[0:2]):
1132
result.append(block[entry_index])
419
1136
def _entry_to_line(self, entry):
420
1137
"""Serialize entry to a NULL delimited line ready for _get_output_lines.
422
1139
:param entry: An entry_tuple as defined in the module docstring.
424
1141
entire_entry = list(entry[0])
425
1142
for tree_number, tree_data in enumerate(entry[1]):
426
# (kind, fingerprint, size, executable, tree_specific_string)
1143
# (minikind, fingerprint, size, executable, tree_specific_string)
427
1144
entire_entry.extend(tree_data)
428
1145
# 3 for the key, 5 for the fields per tree.
429
1146
tree_offset = 3 + tree_number * 5
431
entire_entry[tree_offset + 0] = DirState._kind_to_minikind[tree_data[0]]
1148
entire_entry[tree_offset + 0] = tree_data[0]
433
1150
entire_entry[tree_offset + 2] = str(tree_data[2])
435
1152
entire_entry[tree_offset + 3] = DirState._to_yesno[tree_data[3]]
436
1153
return '\0'.join(entire_entry)
1155
def _fields_per_entry(self):
1156
"""How many null separated fields should be in each entry row.
1158
Each line now has an extra '\n' field which is not used
1159
so we just skip over it
1161
3 fields for the key
1162
+ number of fields per tree_data (5) * tree count
1165
tree_count = 1 + self._num_present_parents()
1166
return 3 + 5 * tree_count + 1
438
1168
def _find_block(self, key, add_if_missing=False):
439
1169
"""Return the block that key should be present in.
441
1171
:param key: A dirstate entry key.
442
1172
:return: The block tuple.
444
if key[0:2] == ('', ''):
445
return self._root_entries
447
block_index, present = self._find_block_index_from_key(key)
450
self._dirblocks.insert(block_index, (key[0], []))
452
# some parent path has not been added - its an error to add this
1174
block_index, present = self._find_block_index_from_key(key)
1176
if not add_if_missing:
1177
# check to see if key is versioned itself - we might want to
1178
# add it anyway, because dirs with no entries dont get a
1179
# dirblock at parse time.
1180
# This is an uncommon branch to take: most dirs have children,
1181
# and most code works with versioned paths.
1182
parent_base, parent_name = osutils.split(key[0])
1183
if not self._get_block_entry_index(parent_base, parent_name, 0)[3]:
1184
# some parent path has not been added - its an error to add
454
1186
raise errors.NotVersionedError(key[0:2], str(self))
455
return self._dirblocks[block_index]
1187
self._dirblocks.insert(block_index, (key[0], []))
1188
return self._dirblocks[block_index]
457
1190
def _find_block_index_from_key(self, key):
458
1191
"""Find the dirblock index for a key.
460
1193
:return: The block index, True if the block for the key is present.
462
block_index = bisect.bisect_left(self._dirblocks, (key[0], []))
1195
if key[0:2] == ('', ''):
1198
if (self._last_block_index is not None and
1199
self._dirblocks[self._last_block_index][0] == key[0]):
1200
return self._last_block_index, True
1203
block_index = bisect_dirblock(self._dirblocks, key[0], 1,
1204
cache=self._split_path_cache)
1205
# _right returns one-past-where-key is so we have to subtract
1206
# one to use it. we use _right here because there are two
1207
# '' blocks - the root, and the contents of root
1208
# we always have a minimum of 2 in self._dirblocks: root and
1209
# root-contents, and for '', we get 2 back, so this is
1210
# simple and correct:
463
1211
present = (block_index < len(self._dirblocks) and
464
1212
self._dirblocks[block_index][0] == key[0])
1213
self._last_block_index = block_index
1214
# Reset the entry index cache to the beginning of the block.
1215
self._last_entry_index = -1
465
1216
return block_index, present
467
def _find_dirblock_index(self, dirname):
468
"""Find the dirblock index for dirname.
470
:return: -1 if the dirname is not present, or the index in
471
self._dirblocks for it otherwise.
473
block_index = bisect.bisect_left(self._dirblocks, (dirname, []))
474
if (block_index == len(self._dirblocks) or
475
self._dirblocks[block_index][0] != dirname):
479
1218
def _find_entry_index(self, key, block):
480
1219
"""Find the entry index for a key in a block.
482
1221
:return: The entry index, True if the entry for the key is present.
1223
len_block = len(block)
1225
if self._last_entry_index is not None:
1227
entry_index = self._last_entry_index + 1
1228
# A hit is when the key is after the last slot, and before or
1229
# equal to the next slot.
1230
if ((entry_index > 0 and block[entry_index - 1][0] < key) and
1231
key <= block[entry_index][0]):
1232
self._last_entry_index = entry_index
1233
present = (block[entry_index][0] == key)
1234
return entry_index, present
484
1237
entry_index = bisect.bisect_left(block, (key, []))
485
present = (entry_index < len(block) and
1238
present = (entry_index < len_block and
486
1239
block[entry_index][0] == key)
1240
self._last_entry_index = entry_index
487
1241
return entry_index, present
490
def from_tree(tree, dir_state_filename):
1244
def from_tree(tree, dir_state_filename, sha1_provider=None):
491
1245
"""Create a dirstate from a bzr Tree.
493
1247
:param tree: The tree which should provide parent information and
497
# XXX: aka the big ugly.: To fix this, turn it into:
498
# init; set_path_id(root); set_parents(tree.get_parnets); write_inventory(tree.inventory)
500
result._state_file = open(dir_state_filename, 'wb+')
502
_encode = base64.encodestring
504
parent_ids = tree.get_parent_ids()
505
num_parents = len(parent_ids)
507
raise ValueError('Cannot handle more than 3 parents')
510
for parent_id in parent_ids:
511
parent_trees.append(tree.branch.repository.revision_tree(parent_id))
512
parent_trees[-1].lock_read()
513
all_trees = [tree] + parent_trees
514
num_trees = len(all_trees)
516
# FIXME: is this utf8 safe?
518
to_minikind = DirState._kind_to_minikind
519
to_yesno = DirState._to_yesno
521
st = os.lstat(tree.basedir)
524
for tree_index, tree in enumerate(all_trees):
525
for path, tree_entry in tree.iter_entries_by_dir():
526
dirname, basename = os.path.split(path.encode('utf8'))
527
file_id = tree_entry.file_id.encode('utf8')
528
kind = tree_entry.kind
529
if kind == 'directory':
1249
:param sha1_provider: an object meeting the SHA1Provider interface.
1250
If None, a DefaultSHA1Provider is used.
1251
:return: a DirState object which is currently locked for writing.
1252
(it was locked by DirState.initialize)
1254
result = DirState.initialize(dir_state_filename,
1255
sha1_provider=sha1_provider)
1259
parent_ids = tree.get_parent_ids()
1260
num_parents = len(parent_ids)
1262
for parent_id in parent_ids:
1263
parent_tree = tree.branch.repository.revision_tree(parent_id)
1264
parent_trees.append((parent_id, parent_tree))
1265
parent_tree.lock_read()
1266
result.set_parent_trees(parent_trees, [])
1267
result.set_state_from_inventory(tree.inventory)
1269
for revid, parent_tree in parent_trees:
1270
parent_tree.unlock()
1273
# The caller won't have a chance to unlock this, so make sure we
1279
def update_by_delta(self, delta):
1280
"""Apply an inventory delta to the dirstate for tree 0
1282
This is the workhorse for apply_inventory_delta in dirstate based
1285
:param delta: An inventory delta. See Inventory.apply_delta for
1288
self._read_dirblocks_if_needed()
1289
encode = cache_utf8.encode
1292
# Accumulate parent references (path_utf8, id), to check for parentless
1293
# items or items placed under files/links/tree-references. We get
1294
# references from every item in the delta that is not a deletion and
1295
# is not itself the root.
1297
# Added ids must not be in the dirstate already. This set holds those
1300
# This loop transforms the delta to single atomic operations that can
1301
# be executed and validated.
1302
for old_path, new_path, file_id, inv_entry in sorted(
1303
inventory._check_delta_unique_old_paths(
1304
inventory._check_delta_unique_new_paths(
1305
inventory._check_delta_ids_match_entry(
1306
inventory._check_delta_ids_are_valid(
1307
inventory._check_delta_new_path_entry_both_or_None(delta))))),
1309
if (file_id in insertions) or (file_id in removals):
1310
raise errors.InconsistentDelta(old_path or new_path, file_id,
1312
if old_path is not None:
1313
old_path = old_path.encode('utf-8')
1314
removals[file_id] = old_path
1316
new_ids.add(file_id)
1317
if new_path is not None:
1318
if inv_entry is None:
1319
raise errors.InconsistentDelta(new_path, file_id,
1320
"new_path with no entry")
1321
new_path = new_path.encode('utf-8')
1322
dirname_utf8, basename = osutils.split(new_path)
1324
parents.add((dirname_utf8, inv_entry.parent_id))
1325
key = (dirname_utf8, basename, file_id)
1326
minikind = DirState._kind_to_minikind[inv_entry.kind]
1328
fingerprint = inv_entry.reference_revision or ''
530
1330
fingerprint = ''
533
elif kind == 'symlink':
534
fingerprint = tree.symlink_target(path)
538
fingerprint = tree.get_file_sha1(tree_entry.file_id, path)
539
size = tree_entry.text_size
540
executable = tree.is_executable(tree_entry.file_id, path)
544
key = (dirname, basename, file_id)
545
if (dirname, basename) == ('', ''):
549
block_index = bisect.bisect_left(dirblocks, (dirname, []))
550
if block_index == len(dirblocks) or dirblocks[block_index][0] != dirname:
552
dirblocks.insert(block_index, (dirname, []))
553
block = dirblocks[block_index][1]
554
# find the data for this path within block:
555
entry_index = bisect.bisect_left(block, (key,))
556
if entry_index == len(block) or block[entry_index][0] != key:
557
# new key in this block, add blank data
558
block.insert(entry_index, (key, [None] * num_trees))
559
# get the right form of data for this trees type
562
st = os.lstat(tree.abspath(path))
563
tree_data = pack_stat(st)
567
tree_data = tree_entry.revision.encode('utf8')
568
block[entry_index][1][tree_index] = (
575
result._set_data(parent_ids, root_entries, dirblocks)
577
for tree in all_trees:
1331
insertions[file_id] = (key, minikind, inv_entry.executable,
1332
fingerprint, new_path)
1333
# Transform moves into delete+add pairs
1334
if None not in (old_path, new_path):
1335
for child in self._iter_child_entries(0, old_path):
1336
if child[0][2] in insertions or child[0][2] in removals:
1338
child_dirname = child[0][0]
1339
child_basename = child[0][1]
1340
minikind = child[1][0][0]
1341
fingerprint = child[1][0][4]
1342
executable = child[1][0][3]
1343
old_child_path = osutils.pathjoin(child_dirname,
1345
removals[child[0][2]] = old_child_path
1346
child_suffix = child_dirname[len(old_path):]
1347
new_child_dirname = (new_path + child_suffix)
1348
key = (new_child_dirname, child_basename, child[0][2])
1349
new_child_path = osutils.pathjoin(new_child_dirname,
1351
insertions[child[0][2]] = (key, minikind, executable,
1352
fingerprint, new_child_path)
1353
self._check_delta_ids_absent(new_ids, delta, 0)
1355
self._apply_removals(removals.iteritems())
1356
self._apply_insertions(insertions.values())
1358
self._after_delta_check_parents(parents, 0)
1359
except errors.BzrError, e:
1360
self._changes_aborted = True
1361
if 'integrity error' not in str(e):
1363
# _get_entry raises BzrError when a request is inconsistent; we
1364
# want such errors to be shown as InconsistentDelta - and that
1365
# fits the behaviour we trigger.
1366
raise errors.InconsistentDeltaDelta(delta, "error from _get_entry.")
1368
def _apply_removals(self, removals):
1369
for file_id, path in sorted(removals, reverse=True,
1370
key=operator.itemgetter(1)):
1371
dirname, basename = osutils.split(path)
1372
block_i, entry_i, d_present, f_present = \
1373
self._get_block_entry_index(dirname, basename, 0)
1375
entry = self._dirblocks[block_i][1][entry_i]
1377
self._changes_aborted = True
1378
raise errors.InconsistentDelta(path, file_id,
1379
"Wrong path for old path.")
1380
if not f_present or entry[1][0][0] in 'ar':
1381
self._changes_aborted = True
1382
raise errors.InconsistentDelta(path, file_id,
1383
"Wrong path for old path.")
1384
if file_id != entry[0][2]:
1385
self._changes_aborted = True
1386
raise errors.InconsistentDelta(path, file_id,
1387
"Attempt to remove path has wrong id - found %r."
1389
self._make_absent(entry)
1390
# See if we have a malformed delta: deleting a directory must not
1391
# leave crud behind. This increases the number of bisects needed
1392
# substantially, but deletion or renames of large numbers of paths
1393
# is rare enough it shouldn't be an issue (famous last words?) RBC
1395
block_i, entry_i, d_present, f_present = \
1396
self._get_block_entry_index(path, '', 0)
1398
# The dir block is still present in the dirstate; this could
1399
# be due to it being in a parent tree, or a corrupt delta.
1400
for child_entry in self._dirblocks[block_i][1]:
1401
if child_entry[1][0][0] not in ('r', 'a'):
1402
self._changes_aborted = True
1403
raise errors.InconsistentDelta(path, entry[0][2],
1404
"The file id was deleted but its children were "
1407
def _apply_insertions(self, adds):
1409
for key, minikind, executable, fingerprint, path_utf8 in sorted(adds):
1410
self.update_minimal(key, minikind, executable, fingerprint,
1411
path_utf8=path_utf8)
1412
except errors.NotVersionedError:
1413
self._changes_aborted = True
1414
raise errors.InconsistentDelta(path_utf8.decode('utf8'), key[2],
1417
def update_basis_by_delta(self, delta, new_revid):
1418
"""Update the parents of this tree after a commit.
1420
This gives the tree one parent, with revision id new_revid. The
1421
inventory delta is applied to the current basis tree to generate the
1422
inventory for the parent new_revid, and all other parent trees are
1425
Note that an exception during the operation of this method will leave
1426
the dirstate in a corrupt state where it should not be saved.
1428
Finally, we expect all changes to be synchronising the basis tree with
1431
:param new_revid: The new revision id for the trees parent.
1432
:param delta: An inventory delta (see apply_inventory_delta) describing
1433
the changes from the current left most parent revision to new_revid.
1435
self._read_dirblocks_if_needed()
1436
self._discard_merge_parents()
1437
if self._ghosts != []:
1438
raise NotImplementedError(self.update_basis_by_delta)
1439
if len(self._parents) == 0:
1440
# setup a blank tree, the most simple way.
1441
empty_parent = DirState.NULL_PARENT_DETAILS
1442
for entry in self._iter_entries():
1443
entry[1].append(empty_parent)
1444
self._parents.append(new_revid)
1446
self._parents[0] = new_revid
1448
delta = sorted(delta, reverse=True)
1452
# The paths this function accepts are unicode and must be encoded as we
1454
encode = cache_utf8.encode
1455
inv_to_entry = self._inv_entry_to_details
1456
# delta is now (deletes, changes), (adds) in reverse lexographical
1458
# deletes in reverse lexographic order are safe to process in situ.
1459
# renames are not, as a rename from any path could go to a path
1460
# lexographically lower, so we transform renames into delete, add pairs,
1461
# expanding them recursively as needed.
1462
# At the same time, to reduce interface friction we convert the input
1463
# inventory entries to dirstate.
1464
root_only = ('', '')
1465
# Accumulate parent references (path_utf8, id), to check for parentless
1466
# items or items placed under files/links/tree-references. We get
1467
# references from every item in the delta that is not a deletion and
1468
# is not itself the root.
1470
# Added ids must not be in the dirstate already. This set holds those
1473
for old_path, new_path, file_id, inv_entry in delta:
1474
if inv_entry is not None and file_id != inv_entry.file_id:
1475
raise errors.InconsistentDelta(new_path, file_id,
1476
"mismatched entry file_id %r" % inv_entry)
1477
if new_path is not None:
1478
if inv_entry is None:
1479
raise errors.InconsistentDelta(new_path, file_id,
1480
"new_path with no entry")
1481
new_path_utf8 = encode(new_path)
1482
# note the parent for validation
1483
dirname_utf8, basename_utf8 = osutils.split(new_path_utf8)
1485
parents.add((dirname_utf8, inv_entry.parent_id))
1486
if old_path is None:
1487
adds.append((None, encode(new_path), file_id,
1488
inv_to_entry(inv_entry), True))
1489
new_ids.add(file_id)
1490
elif new_path is None:
1491
deletes.append((encode(old_path), None, file_id, None, True))
1492
elif (old_path, new_path) != root_only:
1494
# Because renames must preserve their children we must have
1495
# processed all relocations and removes before hand. The sort
1496
# order ensures we've examined the child paths, but we also
1497
# have to execute the removals, or the split to an add/delete
1498
# pair will result in the deleted item being reinserted, or
1499
# renamed items being reinserted twice - and possibly at the
1500
# wrong place. Splitting into a delete/add pair also simplifies
1501
# the handling of entries with ('f', ...), ('r' ...) because
1502
# the target of the 'r' is old_path here, and we add that to
1503
# deletes, meaning that the add handler does not need to check
1504
# for 'r' items on every pass.
1505
self._update_basis_apply_deletes(deletes)
1507
# Split into an add/delete pair recursively.
1508
adds.append((None, new_path_utf8, file_id,
1509
inv_to_entry(inv_entry), False))
1510
# Expunge deletes that we've seen so that deleted/renamed
1511
# children of a rename directory are handled correctly.
1512
new_deletes = reversed(list(self._iter_child_entries(1,
1514
# Remove the current contents of the tree at orig_path, and
1515
# reinsert at the correct new path.
1516
for entry in new_deletes:
1518
source_path = entry[0][0] + '/' + entry[0][1]
1520
source_path = entry[0][1]
1522
target_path = new_path_utf8 + source_path[len(old_path):]
1525
raise AssertionError("cannot rename directory to"
1527
target_path = source_path[len(old_path) + 1:]
1528
adds.append((None, target_path, entry[0][2], entry[1][1], False))
1530
(source_path, target_path, entry[0][2], None, False))
1532
(encode(old_path), new_path, file_id, None, False))
1534
# changes to just the root should not require remove/insertion
1536
changes.append((encode(old_path), encode(new_path), file_id,
1537
inv_to_entry(inv_entry)))
1538
self._check_delta_ids_absent(new_ids, delta, 1)
1540
# Finish expunging deletes/first half of renames.
1541
self._update_basis_apply_deletes(deletes)
1542
# Reinstate second half of renames and new paths.
1543
self._update_basis_apply_adds(adds)
1544
# Apply in-situ changes.
1545
self._update_basis_apply_changes(changes)
1547
self._after_delta_check_parents(parents, 1)
1548
except errors.BzrError, e:
1549
self._changes_aborted = True
1550
if 'integrity error' not in str(e):
1552
# _get_entry raises BzrError when a request is inconsistent; we
1553
# want such errors to be shown as InconsistentDelta - and that
1554
# fits the behaviour we trigger. Partof this is driven by dirstate
1555
# only supporting deltas that turn the basis into a closer fit to
1557
raise errors.InconsistentDeltaDelta(delta, "error from _get_entry.")
1559
self._dirblock_state = DirState.IN_MEMORY_MODIFIED
1560
self._header_state = DirState.IN_MEMORY_MODIFIED
1561
self._id_index = None
1564
def _check_delta_ids_absent(self, new_ids, delta, tree_index):
1565
"""Check that none of the file_ids in new_ids are present in a tree."""
1568
id_index = self._get_id_index()
1569
for file_id in new_ids:
1570
for key in id_index.get(file_id, ()):
1571
block_i, entry_i, d_present, f_present = \
1572
self._get_block_entry_index(key[0], key[1], tree_index)
1574
# In a different tree
1576
entry = self._dirblocks[block_i][1][entry_i]
1577
if entry[0][2] != file_id:
1578
# Different file_id, so not what we want.
1580
# NB: No changes made before this helper is called, so no need
1581
# to set the _changes_aborted flag.
1582
raise errors.InconsistentDelta(
1583
("%s/%s" % key[0:2]).decode('utf8'), file_id,
1584
"This file_id is new in the delta but already present in "
1587
def _update_basis_apply_adds(self, adds):
1588
"""Apply a sequence of adds to tree 1 during update_basis_by_delta.
1590
They may be adds, or renames that have been split into add/delete
1593
:param adds: A sequence of adds. Each add is a tuple:
1594
(None, new_path_utf8, file_id, (entry_details), real_add). real_add
1595
is False when the add is the second half of a remove-and-reinsert
1596
pair created to handle renames and deletes.
1598
# Adds are accumulated partly from renames, so can be in any input
1601
# adds is now in lexographic order, which places all parents before
1602
# their children, so we can process it linearly.
1604
for old_path, new_path, file_id, new_details, real_add in adds:
1605
# the entry for this file_id must be in tree 0.
1606
entry = self._get_entry(0, file_id, new_path)
1607
if entry[0] is None or entry[0][2] != file_id:
1608
self._changes_aborted = True
1609
raise errors.InconsistentDelta(new_path, file_id,
1610
'working tree does not contain new entry')
1611
if real_add and entry[1][1][0] not in absent:
1612
self._changes_aborted = True
1613
raise errors.InconsistentDelta(new_path, file_id,
1614
'The entry was considered to be a genuinely new record,'
1615
' but there was already an old record for it.')
1616
# We don't need to update the target of an 'r' because the handling
1617
# of renames turns all 'r' situations into a delete at the original
1619
entry[1][1] = new_details
1621
def _update_basis_apply_changes(self, changes):
1622
"""Apply a sequence of changes to tree 1 during update_basis_by_delta.
1624
:param adds: A sequence of changes. Each change is a tuple:
1625
(path_utf8, path_utf8, file_id, (entry_details))
1628
for old_path, new_path, file_id, new_details in changes:
1629
# the entry for this file_id must be in tree 0.
1630
entry = self._get_entry(0, file_id, new_path)
1631
if entry[0] is None or entry[0][2] != file_id:
1632
self._changes_aborted = True
1633
raise errors.InconsistentDelta(new_path, file_id,
1634
'working tree does not contain new entry')
1635
if (entry[1][0][0] in absent or
1636
entry[1][1][0] in absent):
1637
self._changes_aborted = True
1638
raise errors.InconsistentDelta(new_path, file_id,
1639
'changed considered absent')
1640
entry[1][1] = new_details
1642
def _update_basis_apply_deletes(self, deletes):
1643
"""Apply a sequence of deletes to tree 1 during update_basis_by_delta.
1645
They may be deletes, or renames that have been split into add/delete
1648
:param deletes: A sequence of deletes. Each delete is a tuple:
1649
(old_path_utf8, new_path_utf8, file_id, None, real_delete).
1650
real_delete is True when the desired outcome is an actual deletion
1651
rather than the rename handling logic temporarily deleting a path
1652
during the replacement of a parent.
1654
null = DirState.NULL_PARENT_DETAILS
1655
for old_path, new_path, file_id, _, real_delete in deletes:
1656
if real_delete != (new_path is None):
1657
self._changes_aborted = True
1658
raise AssertionError("bad delete delta")
1659
# the entry for this file_id must be in tree 1.
1660
dirname, basename = osutils.split(old_path)
1661
block_index, entry_index, dir_present, file_present = \
1662
self._get_block_entry_index(dirname, basename, 1)
1663
if not file_present:
1664
self._changes_aborted = True
1665
raise errors.InconsistentDelta(old_path, file_id,
1666
'basis tree does not contain removed entry')
1667
entry = self._dirblocks[block_index][1][entry_index]
1668
if entry[0][2] != file_id:
1669
self._changes_aborted = True
1670
raise errors.InconsistentDelta(old_path, file_id,
1671
'mismatched file_id in tree 1')
1673
if entry[1][0][0] != 'a':
1674
self._changes_aborted = True
1675
raise errors.InconsistentDelta(old_path, file_id,
1676
'This was marked as a real delete, but the WT state'
1677
' claims that it still exists and is versioned.')
1678
del self._dirblocks[block_index][1][entry_index]
1680
if entry[1][0][0] == 'a':
1681
self._changes_aborted = True
1682
raise errors.InconsistentDelta(old_path, file_id,
1683
'The entry was considered a rename, but the source path'
1684
' is marked as absent.')
1685
# For whatever reason, we were asked to rename an entry
1686
# that was originally marked as deleted. This could be
1687
# because we are renaming the parent directory, and the WT
1688
# current state has the file marked as deleted.
1689
elif entry[1][0][0] == 'r':
1690
# implement the rename
1691
del self._dirblocks[block_index][1][entry_index]
1693
# it is being resurrected here, so blank it out temporarily.
1694
self._dirblocks[block_index][1][entry_index][1][1] = null
1696
def _after_delta_check_parents(self, parents, index):
1697
"""Check that parents required by the delta are all intact.
1699
:param parents: An iterable of (path_utf8, file_id) tuples which are
1700
required to be present in tree 'index' at path_utf8 with id file_id
1702
:param index: The column in the dirstate to check for parents in.
1704
for dirname_utf8, file_id in parents:
1705
# Get the entry - the ensures that file_id, dirname_utf8 exists and
1706
# has the right file id.
1707
entry = self._get_entry(index, file_id, dirname_utf8)
1708
if entry[1] is None:
1709
self._changes_aborted = True
1710
raise errors.InconsistentDelta(dirname_utf8.decode('utf8'),
1711
file_id, "This parent is not present.")
1712
# Parents of things must be directories
1713
if entry[1][index][0] != 'd':
1714
self._changes_aborted = True
1715
raise errors.InconsistentDelta(dirname_utf8.decode('utf8'),
1716
file_id, "This parent is not a directory.")
1718
def _observed_sha1(self, entry, sha1, stat_value,
1719
_stat_to_minikind=_stat_to_minikind, _pack_stat=pack_stat):
1720
"""Note the sha1 of a file.
1722
:param entry: The entry the sha1 is for.
1723
:param sha1: The observed sha1.
1724
:param stat_value: The os.lstat for the file.
1727
minikind = _stat_to_minikind[stat_value.st_mode & 0170000]
1731
packed_stat = _pack_stat(stat_value)
1733
if self._cutoff_time is None:
1734
self._sha_cutoff_time()
1735
if (stat_value.st_mtime < self._cutoff_time
1736
and stat_value.st_ctime < self._cutoff_time):
1737
entry[1][0] = ('f', sha1, entry[1][0][2], entry[1][0][3],
1739
self._dirblock_state = DirState.IN_MEMORY_MODIFIED
1741
def _sha_cutoff_time(self):
1742
"""Return cutoff time.
1744
Files modified more recently than this time are at risk of being
1745
undetectably modified and so can't be cached.
1747
# Cache the cutoff time as long as we hold a lock.
1748
# time.time() isn't super expensive (approx 3.38us), but
1749
# when you call it 50,000 times it adds up.
1750
# For comparison, os.lstat() costs 7.2us if it is hot.
1751
self._cutoff_time = int(time.time()) - 3
1752
return self._cutoff_time
1754
def _lstat(self, abspath, entry):
1755
"""Return the os.lstat value for this path."""
1756
return os.lstat(abspath)
1758
def _sha1_file_and_mutter(self, abspath):
1759
# when -Dhashcache is turned on, this is monkey-patched in to log
1761
trace.mutter("dirstate sha1 " + abspath)
1762
return self._sha1_provider.sha1(abspath)
1764
def _is_executable(self, mode, old_executable):
1765
"""Is this file executable?"""
1766
return bool(S_IEXEC & mode)
1768
def _is_executable_win32(self, mode, old_executable):
1769
"""On win32 the executable bit is stored in the dirstate."""
1770
return old_executable
1772
if sys.platform == 'win32':
1773
_is_executable = _is_executable_win32
1775
def _read_link(self, abspath, old_link):
1776
"""Read the target of a symlink"""
1777
# TODO: jam 200700301 On Win32, this could just return the value
1778
# already in memory. However, this really needs to be done at a
1779
# higher level, because there either won't be anything on disk,
1780
# or the thing on disk will be a file.
1781
fs_encoding = osutils._fs_enc
1782
if isinstance(abspath, unicode):
1783
# abspath is defined as the path to pass to lstat. readlink is
1784
# buggy in python < 2.6 (it doesn't encode unicode path into FS
1785
# encoding), so we need to encode ourselves knowing that unicode
1786
# paths are produced by UnicodeDirReader on purpose.
1787
abspath = abspath.encode(fs_encoding)
1788
target = os.readlink(abspath)
1789
if fs_encoding not in ('UTF-8', 'US-ASCII', 'ANSI_X3.4-1968'):
1790
# Change encoding if needed
1791
target = target.decode(fs_encoding).encode('UTF-8')
581
1794
def get_ghosts(self):
582
1795
"""Return a list of the parent tree revision ids that are ghosts."""
630
1924
rather it indicates that there are at least some files in some
631
1925
tree present there.
633
# looking up the root is not supported, because the root entries exist
634
# outside the used coordinate system
635
assert not (dirname == '' and basename == ''), 'blackhole lookup error'
636
1927
self._read_dirblocks_if_needed()
637
block_index = bisect.bisect_left(self._dirblocks, (dirname, []))
638
if (block_index == len(self._dirblocks) or
639
self._dirblocks[block_index][0] != dirname):
1928
key = dirname, basename, ''
1929
block_index, present = self._find_block_index_from_key(key)
640
1931
# no such directory - return the dir index and 0 for the row.
641
1932
return block_index, 0, False, False
642
1933
block = self._dirblocks[block_index][1] # access the entries only
643
search = ((dirname, basename),)
644
row_index = bisect.bisect_left(block, search)
645
# linear search through present entries at this path to find the one
1934
entry_index, present = self._find_entry_index(key, block)
1935
# linear search through entries at this path to find the one
647
while row_index < len(block) and block[row_index][0][1] == basename:
648
if block[row_index][1][tree_index] not in ('absent', 'relocated'):
649
return block_index, row_index, True, True
651
return block_index, row_index, True, False
1937
while entry_index < len(block) and block[entry_index][0][1] == basename:
1938
if block[entry_index][1][tree_index][0] not in 'ar':
1939
# neither absent or relocated
1940
return block_index, entry_index, True, True
1942
return block_index, entry_index, True, False
653
def _get_entry(self, tree_index, fileid_utf8=None, path_utf8=None):
654
"""Get the dirstate entry for path in tree tree_index
1944
def _get_entry(self, tree_index, fileid_utf8=None, path_utf8=None, include_deleted=False):
1945
"""Get the dirstate entry for path in tree tree_index.
656
1947
If either file_id or path is supplied, it is used as the key to lookup.
657
1948
If both are supplied, the fastest lookup is used, and an error is
658
1949
raised if they do not both point at the same row.
660
1951
:param tree_index: The index of the tree we wish to locate this path
661
1952
in. If the path is present in that tree, the entry containing its
662
1953
details is returned, otherwise (None, None) is returned
1954
0 is the working tree, higher indexes are successive parent
663
1956
:param fileid_utf8: A utf8 file_id to look up.
664
1957
:param path_utf8: An utf8 path to be looked up.
1958
:param include_deleted: If True, and performing a lookup via
1959
fileid_utf8 rather than path_utf8, return an entry for deleted
665
1961
:return: The dirstate entry tuple for path, or (None, None)
667
if path_utf8 is not None:
668
assert path_utf8.__class__ == str, 'path_utf8 is not a str: %s %s' % (type(path_utf8), path_utf8)
669
1963
self._read_dirblocks_if_needed()
670
1964
if path_utf8 is not None:
1965
if type(path_utf8) is not str:
1966
raise errors.BzrError('path_utf8 is not a str: %s %r'
1967
% (type(path_utf8), path_utf8))
671
1968
# path lookups are faster
673
for entry in self._root_entries:
674
if entry[1][tree_index] not in ('absent', 'relocated'):
676
raise Exception, 'rootless trees not supported yet'
677
dirname, basename = os.path.split(path_utf8)
1969
dirname, basename = osutils.split(path_utf8)
678
1970
block_index, entry_index, dir_present, file_present = \
679
1971
self._get_block_entry_index(dirname, basename, tree_index)
680
1972
if not file_present:
681
1973
return None, None
682
1974
entry = self._dirblocks[block_index][1][entry_index]
683
assert entry[0][2] and entry[1][tree_index][0] not in ('absent', 'relocated'), 'unversioned entry?!?!'
1975
if not (entry[0][2] and entry[1][tree_index][0] not in ('a', 'r')):
1976
raise AssertionError('unversioned entry?')
685
1978
if entry[0][2] != fileid_utf8:
686
raise BzrError('integrity error ? : mismatching tree_index, file_id and path')
1979
self._changes_aborted = True
1980
raise errors.BzrError('integrity error ? : mismatching'
1981
' tree_index, file_id and path')
689
for entry in self._iter_entries():
690
if entry[0][2] == fileid_utf8:
691
if entry[1][tree_index][0] == 'relocated':
692
# look up the real location directly by path
693
return self._get_entry(tree_index,
694
fileid_utf8=fileid_utf8,
695
path_utf8=entry[1][tree_index][0])
696
if entry[1][tree_index][0] == 'absent':
697
# not in the tree at all.
1984
possible_keys = self._get_id_index().get(fileid_utf8, ())
1985
if not possible_keys:
1987
for key in possible_keys:
1988
block_index, present = \
1989
self._find_block_index_from_key(key)
1990
# strange, probably indicates an out of date
1991
# id index - for now, allow this.
1994
# WARNING: DO not change this code to use _get_block_entry_index
1995
# as that function is not suitable: it does not use the key
1996
# to lookup, and thus the wrong coordinates are returned.
1997
block = self._dirblocks[block_index][1]
1998
entry_index, present = self._find_entry_index(key, block)
2000
entry = self._dirblocks[block_index][1][entry_index]
2001
# TODO: We might want to assert that entry[0][2] ==
2003
if entry[1][tree_index][0] in 'fdlt':
2004
# this is the result we are looking for: the
2005
# real home of this file_id in this tree.
2007
if entry[1][tree_index][0] == 'a':
2008
# there is no home for this entry in this tree
698
2011
return None, None
2012
if entry[1][tree_index][0] != 'r':
2013
raise AssertionError(
2014
"entry %r has invalid minikind %r for tree %r" \
2016
entry[1][tree_index][0],
2018
real_path = entry[1][tree_index][1]
2019
return self._get_entry(tree_index, fileid_utf8=fileid_utf8,
2020
path_utf8=real_path)
700
2021
return None, None
703
def initialize(path):
2024
def initialize(cls, path, sha1_provider=None):
704
2025
"""Create a new dirstate on path.
706
2027
The new dirstate will be an empty tree - that is it has no parents,
707
2028
and only a root node - which has id ROOT_ID.
709
2030
:param path: The name of the file for the dirstate.
710
:return: A DirState object.
2031
:param sha1_provider: an object meeting the SHA1Provider interface.
2032
If None, a DefaultSHA1Provider is used.
2033
:return: A write-locked DirState object.
712
2035
# This constructs a new DirState object on a path, sets the _state_file
713
2036
# to a new empty file for that path. It then calls _set_data() with our
714
2037
# stock empty dirstate information - a root with ROOT_ID, no children,
715
2038
# and no parents. Finally it calls save() to ensure that this data will
718
result._state_file = open(path, 'wb+')
2040
if sha1_provider is None:
2041
sha1_provider = DefaultSHA1Provider()
2042
result = cls(path, sha1_provider)
2043
# root dir and root dir contents with no children.
2044
empty_tree_dirblocks = [('', []), ('', [])]
719
2045
# a new root directory, with a NULLSTAT.
720
root_entries = [(('', '', bzrlib.inventory.ROOT_ID), [
721
('directory', '', 0, False, DirState.NULLSTAT),
724
empty_tree_dirblocks = [('', [])] # root dir contents - no entries.
725
result._set_data([], root_entries, empty_tree_dirblocks)
2046
empty_tree_dirblocks[0][1].append(
2047
(('', '', inventory.ROOT_ID), [
2048
('d', '', 0, False, DirState.NULLSTAT),
2052
result._set_data([], empty_tree_dirblocks)
729
result._state_file.close()
733
def _inv_entry_to_details(self, inv_entry):
2060
def _inv_entry_to_details(inv_entry):
734
2061
"""Convert an inventory entry (from a revision tree) to state details.
736
2063
:param inv_entry: An inventory entry whose sha1 and link targets can be
903
2242
After reading in, the file should be positioned at the null
904
2243
just before the start of the first record in the file.
906
:return: (expected adler checksum, number of entries, parent list)
2245
:return: (expected crc checksum, number of entries, parent list)
908
2247
self._read_prelude()
909
2248
parent_line = self._state_file.readline()
910
2249
info = parent_line.split('\0')
911
2250
num_parents = int(info[0])
912
assert num_parents == len(info)-2, 'incorrect parent info line'
913
2251
self._parents = info[1:-1]
915
2252
ghost_line = self._state_file.readline()
916
2253
info = ghost_line.split('\0')
917
2254
num_ghosts = int(info[1])
918
assert num_ghosts == len(info)-3, 'incorrect ghost info line'
919
2255
self._ghosts = info[2:-1]
920
2256
self._header_state = DirState.IN_MEMORY_UNMODIFIED
2257
self._end_of_header = self._state_file.tell()
922
2259
def _read_header_if_needed(self):
923
2260
"""Read the header of the dirstate file if needed."""
2261
# inline this as it will be called a lot
2262
if not self._lock_token:
2263
raise errors.ObjectNotLocked(self)
924
2264
if self._header_state == DirState.NOT_IN_MEMORY:
925
2265
self._read_header()
927
2267
def _read_prelude(self):
928
"""Read in the prelude header of the dirstate file
2268
"""Read in the prelude header of the dirstate file.
930
This only reads in the stuff that is not connected to the adler
2270
This only reads in the stuff that is not connected to the crc
931
2271
checksum. The position will be correct to read in the rest of
932
2272
the file and check the checksum after this point.
933
2273
The next entry in the file should be the number of parents,
934
2274
and their ids. Followed by a newline.
936
2276
header = self._state_file.readline()
937
assert header == '#bazaar dirstate flat format 2\n', \
938
'invalid header line: %r' % (header,)
939
adler_line = self._state_file.readline()
940
assert adler_line.startswith('adler32: '), 'missing adler32 checksum'
941
self.adler_expected = int(adler_line[len('adler32: '):-1])
2277
if header != DirState.HEADER_FORMAT_3:
2278
raise errors.BzrError(
2279
'invalid header line: %r' % (header,))
2280
crc_line = self._state_file.readline()
2281
if not crc_line.startswith('crc32: '):
2282
raise errors.BzrError('missing crc32 checksum: %r' % crc_line)
2283
self.crc_expected = int(crc_line[len('crc32: '):-1])
942
2284
num_entries_line = self._state_file.readline()
943
assert num_entries_line.startswith('num_entries: '), 'missing num_entries line'
2285
if not num_entries_line.startswith('num_entries: '):
2286
raise errors.BzrError('missing num_entries line')
944
2287
self._num_entries = int(num_entries_line[len('num_entries: '):-1])
2289
def sha1_from_stat(self, path, stat_result, _pack_stat=pack_stat):
2290
"""Find a sha1 given a stat lookup."""
2291
return self._get_packed_stat_index().get(_pack_stat(stat_result), None)
2293
def _get_packed_stat_index(self):
2294
"""Get a packed_stat index of self._dirblocks."""
2295
if self._packed_stat_index is None:
2297
for key, tree_details in self._iter_entries():
2298
if tree_details[0][0] == 'f':
2299
index[tree_details[0][4]] = tree_details[0][1]
2300
self._packed_stat_index = index
2301
return self._packed_stat_index
947
2304
"""Save any pending changes created during this session.
949
2306
We reuse the existing file, because that prevents race conditions with
950
file creation, and we expect to be using oslocks on it in the near
951
future to prevent concurrent modification and reads - because dirstates
952
incremental data aggretation is not compatible with reading a modified
953
file, and replacing a file in use by another process is impossible on
2307
file creation, and use oslocks on it to prevent concurrent modification
2308
and reads - because dirstate's incremental data aggregation is not
2309
compatible with reading a modified file, and replacing a file in use by
2310
another process is impossible on Windows.
956
2312
A dirstate in read only mode should be smart enough though to validate
957
2313
that the file has not changed, and otherwise discard its cache and
958
2314
start over, to allow for fine grained read lock duration, so 'status'
959
2315
wont block 'commit' - for example.
2317
if self._changes_aborted:
2318
# Should this be a warning? For now, I'm expecting that places that
2319
# mark it inconsistent will warn, making a warning here redundant.
2320
trace.mutter('Not saving DirState because '
2321
'_changes_aborted is set.')
961
2323
if (self._header_state == DirState.IN_MEMORY_MODIFIED or
962
2324
self._dirblock_state == DirState.IN_MEMORY_MODIFIED):
963
self._state_file.seek(0)
964
self._state_file.writelines(self.get_lines())
965
self._state_file.truncate()
966
self._state_file.flush()
967
self._header_state = DirState.IN_MEMORY_UNMODIFIED
968
self._dirblock_state = DirState.IN_MEMORY_UNMODIFIED
970
def _set_data(self, parent_ids, root_entries, dirblocks):
2326
grabbed_write_lock = False
2327
if self._lock_state != 'w':
2328
grabbed_write_lock, new_lock = self._lock_token.temporary_write_lock()
2329
# Switch over to the new lock, as the old one may be closed.
2330
# TODO: jam 20070315 We should validate the disk file has
2331
# not changed contents. Since temporary_write_lock may
2332
# not be an atomic operation.
2333
self._lock_token = new_lock
2334
self._state_file = new_lock.f
2335
if not grabbed_write_lock:
2336
# We couldn't grab a write lock, so we switch back to a read one
2339
self._state_file.seek(0)
2340
self._state_file.writelines(self.get_lines())
2341
self._state_file.truncate()
2342
self._state_file.flush()
2343
self._header_state = DirState.IN_MEMORY_UNMODIFIED
2344
self._dirblock_state = DirState.IN_MEMORY_UNMODIFIED
2346
if grabbed_write_lock:
2347
self._lock_token = self._lock_token.restore_read_lock()
2348
self._state_file = self._lock_token.f
2349
# TODO: jam 20070315 We should validate the disk file has
2350
# not changed contents. Since restore_read_lock may
2351
# not be an atomic operation.
2353
def _set_data(self, parent_ids, dirblocks):
971
2354
"""Set the full dirstate data in memory.
973
2356
This is an internal function used to completely replace the objects
974
2357
in memory state. It puts the dirstate into state 'full-dirty'.
976
2359
:param parent_ids: A list of parent tree revision ids.
977
:param root_entrie: The root entries: A list of entries, one per fileid found
979
2360
:param dirblocks: A list containing one tuple for each directory in the
980
tree. Each tuple contains the directory path and a list of entries
2361
tree. Each tuple contains the directory path and a list of entries
981
2362
found in that directory.
983
2364
# our memory copy is now authoritative.
984
2365
self._dirblocks = dirblocks
985
self._root_entries = root_entries
986
2366
self._header_state = DirState.IN_MEMORY_MODIFIED
987
2367
self._dirblock_state = DirState.IN_MEMORY_MODIFIED
988
2368
self._parents = list(parent_ids)
2369
self._id_index = None
2370
self._packed_stat_index = None
990
2372
def set_path_id(self, path, new_id):
991
2373
"""Change the id of path to new_id in the current working tree.
993
2375
:param path: The path inside the tree to set - '' is the root, 'foo'
994
2376
is the path foo in the root.
995
:param new_id: The new id to assign to the path. If unicode, it will
996
be encoded to utf8. In future this will be deprecated: avoid using
997
unicode ids if possible.
2377
:param new_id: The new id to assign to the path. This must be a utf8
2378
file id (not unicode, and not None).
999
# TODO: start warning here.
1000
if new_id.__class__ == unicode:
1001
new_id = new_id.encode('utf8')
1002
2380
self._read_dirblocks_if_needed()
1004
import pdb;pdb.set_trace()
2382
# TODO: logic not written
1006
2383
raise NotImplementedError(self.set_path_id)
1007
2384
# TODO: check new id is unique
1008
entry = self._get_entry(0, path_utf8='')
1009
# TODO: version of _get_block_entry_index that works with the root so
1010
# we dont look up this twice.
1011
index = self._root_entries.index(entry)
1012
if new_id == entry[0][2]:
2385
entry = self._get_entry(0, path_utf8=path)
2386
if entry[0][2] == new_id:
2387
# Nothing to change.
1015
if len(entry[1]) > 1:
1016
# TODO: split the record.
1017
raise NotImplementedError(self.set_path_id)
1018
root_info, root_parents = self._root_entrie
1019
if len(root_parents):
1020
self.add_deleted(root_info[3], root_parents)
1021
# replace the entry:
1022
self._root_entries[index] = (('', '', new_id), entry[1])
2389
# mark the old path absent, and insert a new root path
2390
self._make_absent(entry)
2391
self.update_minimal(('', '', new_id), 'd',
2392
path_utf8='', packed_stat=entry[1][0][4])
1023
2393
self._dirblock_state = DirState.IN_MEMORY_MODIFIED
1025
2395
def set_parent_trees(self, trees, ghosts):
1026
2396
"""Set the parent trees for the dirstate.
1028
2398
:param trees: A list of revision_id, tree tuples. tree must be provided
1029
even if the revision_id refers to a ghost: supply an empty tree in
2399
even if the revision_id refers to a ghost: supply an empty tree in
1031
2401
:param ghosts: A list of the revision_ids that are ghosts at the time
1034
# TODO: generate a list of parent indexes to preserve to save
2404
# TODO: generate a list of parent indexes to preserve to save
1035
2405
# processing specific parent trees. In the common case one tree will
1036
2406
# be preserved - the left most parent.
1037
2407
# TODO: if the parent tree is a dirstate, we might want to walk them
1038
2408
# all by path in parallel for 'optimal' common-case performance.
1039
2409
# generate new root row.
1040
2410
self._read_dirblocks_if_needed()
1041
old_roots = self._root_entries
1042
root_info = self._root_entries[0]
1043
new_parent_count = len(trees)
1044
2411
# TODO future sketch: Examine the existing parents to generate a change
1045
2412
# map and then walk the new parent trees only, mapping them into the
1046
2413
# dirstate. Walk the dirstate at the same time to remove unreferenced
1049
# sketch: loop over all entries in the dirstate, cherry picking
2416
# sketch: loop over all entries in the dirstate, cherry picking
1050
2417
# entries from the parent trees, if they are not ghost trees.
1051
2418
# after we finish walking the dirstate, all entries not in the dirstate
1052
2419
# are deletes, so we want to append them to the end as per the design
1198
2590
while current_new or current_old:
1199
2591
# skip entries in old that are not really there
1200
if current_old and current_old[1][0][0] in ('relocated', 'absent'):
2592
if current_old and current_old[1][0][0] in 'ar':
2593
# relocated or absent
1201
2594
current_old = advance(old_iterator)
1203
2596
if current_new:
1204
2597
# convert new into dirblock style
1205
2598
new_path_utf8 = current_new[0].encode('utf8')
1206
new_dirname, new_basename = os.path.split(new_path_utf8)
1207
new_id = current_new[1].file_id.encode('utf8')
2599
new_dirname, new_basename = osutils.split(new_path_utf8)
2600
new_id = current_new[1].file_id
1208
2601
new_entry_key = (new_dirname, new_basename, new_id)
2602
current_new_minikind = \
2603
DirState._kind_to_minikind[current_new[1].kind]
2604
if current_new_minikind == 't':
2605
fingerprint = current_new[1].reference_revision or ''
2607
# We normally only insert or remove records, or update
2608
# them when it has significantly changed. Then we want to
2609
# erase its fingerprint. Unaffected records should
2610
# normally not be updated at all.
1210
2613
# for safety disable variables
1211
new_path_utf8 = new_dirname = new_basename = new_id = new_entry_key = None
2614
new_path_utf8 = new_dirname = new_basename = new_id = \
2615
new_entry_key = None
1212
2616
# 5 cases, we dont have a value that is strictly greater than everything, so
1213
2617
# we make both end conditions explicit
1214
2618
if not current_old:
1215
2619
# old is finished: insert current_new into the state.
1216
self.update_minimal(new_entry_key, current_new[1].kind,
1217
num_present_parents, executable=current_new[1].executable,
1218
id_index=id_index, path_utf8=new_path_utf8)
2621
trace.mutter("Appending from new '%s'.",
2622
new_path_utf8.decode('utf8'))
2623
self.update_minimal(new_entry_key, current_new_minikind,
2624
executable=current_new[1].executable,
2625
path_utf8=new_path_utf8, fingerprint=fingerprint,
1219
2627
current_new = advance(new_iterator)
1220
2628
elif not current_new:
1221
2629
# new is finished
1222
self._make_absent(num_present_parents, current_old, id_index)
2631
trace.mutter("Truncating from old '%s/%s'.",
2632
current_old[0][0].decode('utf8'),
2633
current_old[0][1].decode('utf8'))
2634
self._make_absent(current_old)
1223
2635
current_old = advance(old_iterator)
1224
2636
elif new_entry_key == current_old[0]:
1225
2637
# same - common case
2638
# We're looking at the same path and id in both the dirstate
2639
# and inventory, so just need to update the fields in the
2640
# dirstate from the one in the inventory.
1226
2641
# TODO: update the record if anything significant has changed.
1227
2642
# the minimal required trigger is if the execute bit or cached
1228
2643
# kind has changed.
1229
2644
if (current_old[1][0][3] != current_new[1].executable or
1230
current_old[1][0][0] != current_new[1].kind):
1231
self.update_minimal(current_old[0], current_new[1].kind,
1232
num_present_parents,
2645
current_old[1][0][0] != current_new_minikind):
2647
trace.mutter("Updating in-place change '%s'.",
2648
new_path_utf8.decode('utf8'))
2649
self.update_minimal(current_old[0], current_new_minikind,
1233
2650
executable=current_new[1].executable,
1234
id_index=id_index, path_utf8=new_path_utf8)
2651
path_utf8=new_path_utf8, fingerprint=fingerprint,
1235
2653
# both sides are dealt with, move on
1236
2654
current_old = advance(old_iterator)
1237
2655
current_new = advance(new_iterator)
1238
elif new_entry_key < current_old[0]:
2656
elif (cmp_by_dirs(new_dirname, current_old[0][0]) < 0
2657
or (new_dirname == current_old[0][0]
2658
and new_entry_key[1:] < current_old[0][1:])):
1239
2659
# new comes before:
1240
2660
# add a entry for this and advance new
1241
self.update_minimal(new_entry_key, current_new[1].kind,
1242
num_present_parents, executable=current_new[1].executable,
1243
id_index=id_index, path_utf8=new_path_utf8)
2662
trace.mutter("Inserting from new '%s'.",
2663
new_path_utf8.decode('utf8'))
2664
self.update_minimal(new_entry_key, current_new_minikind,
2665
executable=current_new[1].executable,
2666
path_utf8=new_path_utf8, fingerprint=fingerprint,
1244
2668
current_new = advance(new_iterator)
1247
self._make_absent(num_present_parents, current_old, id_index)
2670
# we've advanced past the place where the old key would be,
2671
# without seeing it in the new list. so it must be gone.
2673
trace.mutter("Deleting from old '%s/%s'.",
2674
current_old[0][0].decode('utf8'),
2675
current_old[0][1].decode('utf8'))
2676
self._make_absent(current_old)
1248
2677
current_old = advance(old_iterator)
1249
2678
self._dirblock_state = DirState.IN_MEMORY_MODIFIED
1251
def _make_absent(self, num_present_parents, current_old, id_index):
1252
# remove old from the state, advance old
1253
# to remove old, we have two conditions:
1254
# either its the last reference to this path that we are
1255
# removing, or its not. If its the last reference, we remove
1256
# the entire row and remove the path from the id mapping. If
1257
# its not the last reference, we just set it to absent.
1258
last_reference = True
1259
for lookup_index in xrange(1, num_present_parents + 1):
1260
if current_old[1][lookup_index] not in ('absent', 'relocated'):
1261
last_reference = False
1263
if not last_reference:
1264
# common case, theres a parent at this path
1265
current_old[1][0] = DirState.NULL_PARENT_DETAILS
1267
# there are no more references at this path
1268
id_index[current_old[0][2]].remove(current_old[0])
1269
# are there others (which will need to be changed
1270
# from relocated to absent for index 0)?
1271
for update_key in id_index[current_old[0][2]]:
1272
# update the entry for 0 to say absent: there is a parent at
1273
# that path, but nothing in this tree for that file id anymore.
1274
update_block_index, present = \
1275
self._find_block_index_from_key(update_key)
1277
update_entry_index, present = \
1278
self._find_entry_index(update_key, self._dirblocks[update_block_index][1])
1280
update_tree_details = self._dirblocks[update_block_index][1][update_entry_index][1]
1281
# it must currently be relocated
1282
assert update_tree_details[0][0] == 'relocated'
1283
update_tree_details[0] = DirState.NULL_PARENT_DETAILS
2679
self._id_index = None
2680
self._packed_stat_index = None
2682
trace.mutter("set_state_from_inventory complete.")
2684
def _make_absent(self, current_old):
2685
"""Mark current_old - an entry - as absent for tree 0.
2687
:return: True if this was the last details entry for the entry key:
2688
that is, if the underlying block has had the entry removed, thus
2689
shrinking in length.
2691
# build up paths that this id will be left at after the change is made,
2692
# so we can update their cross references in tree 0
2693
all_remaining_keys = set()
2694
# Dont check the working tree, because it's going.
2695
for details in current_old[1][1:]:
2696
if details[0] not in 'ar': # absent, relocated
2697
all_remaining_keys.add(current_old[0])
2698
elif details[0] == 'r': # relocated
2699
# record the key for the real path.
2700
all_remaining_keys.add(tuple(osutils.split(details[1])) + (current_old[0][2],))
2701
# absent rows are not present at any path.
2702
last_reference = current_old[0] not in all_remaining_keys
2704
# the current row consists entire of the current item (being marked
2705
# absent), and relocated or absent entries for the other trees:
2706
# Remove it, its meaningless.
1284
2707
block = self._find_block(current_old[0])
1285
2708
entry_index, present = self._find_entry_index(current_old[0], block[1])
2710
raise AssertionError('could not find entry for %s' % (current_old,))
1287
2711
block[1].pop(entry_index)
1289
def update_minimal(self, key, kind, num_present_parents, executable=False,
1290
fingerprint='', packed_stat=None, size=0, id_index=None,
1292
"""Update an entry to the state in tree 0."""
1293
if key[0:2] == ('', ''):
1294
block = self._root_entries
1296
block = self._find_block(key)[1]
2712
# if we have an id_index in use, remove this key from it for this id.
2713
if self._id_index is not None:
2714
self._remove_from_id_index(self._id_index, current_old[0])
2715
# update all remaining keys for this id to record it as absent. The
2716
# existing details may either be the record we are marking as deleted
2717
# (if there were other trees with the id present at this path), or may
2719
for update_key in all_remaining_keys:
2720
update_block_index, present = \
2721
self._find_block_index_from_key(update_key)
2723
raise AssertionError('could not find block for %s' % (update_key,))
2724
update_entry_index, present = \
2725
self._find_entry_index(update_key, self._dirblocks[update_block_index][1])
2727
raise AssertionError('could not find entry for %s' % (update_key,))
2728
update_tree_details = self._dirblocks[update_block_index][1][update_entry_index][1]
2729
# it must not be absent at the moment
2730
if update_tree_details[0][0] == 'a': # absent
2731
raise AssertionError('bad row %r' % (update_tree_details,))
2732
update_tree_details[0] = DirState.NULL_PARENT_DETAILS
2733
self._dirblock_state = DirState.IN_MEMORY_MODIFIED
2734
return last_reference
2736
def update_minimal(self, key, minikind, executable=False, fingerprint='',
2737
packed_stat=None, size=0, path_utf8=None, fullscan=False):
2738
"""Update an entry to the state in tree 0.
2740
This will either create a new entry at 'key' or update an existing one.
2741
It also makes sure that any other records which might mention this are
2744
:param key: (dir, name, file_id) for the new entry
2745
:param minikind: The type for the entry ('f' == 'file', 'd' ==
2747
:param executable: Should the executable bit be set?
2748
:param fingerprint: Simple fingerprint for new entry: canonical-form
2749
sha1 for files, referenced revision id for subtrees, etc.
2750
:param packed_stat: Packed stat value for new entry.
2751
:param size: Size information for new entry
2752
:param path_utf8: key[0] + '/' + key[1], just passed in to avoid doing
2754
:param fullscan: If True then a complete scan of the dirstate is being
2755
done and checking for duplicate rows should not be done. This
2756
should only be set by set_state_from_inventory and similar methods.
2758
If packed_stat and fingerprint are not given, they're invalidated in
2761
block = self._find_block(key)[1]
1297
2762
if packed_stat is None:
1298
2763
packed_stat = DirState.NULLSTAT
2764
# XXX: Some callers pass '' as the packed_stat, and it seems to be
2765
# sometimes present in the dirstate - this seems oddly inconsistent.
1299
2767
entry_index, present = self._find_entry_index(key, block)
1300
new_details = (kind, fingerprint, size, executable, packed_stat)
1301
assert id_index, 'need an id index to do updates for now !'
2768
new_details = (minikind, fingerprint, size, executable, packed_stat)
2769
id_index = self._get_id_index()
1302
2770
if not present:
2771
# New record. Check there isn't a entry at this path already.
2773
low_index, _ = self._find_entry_index(key[0:2] + ('',), block)
2774
while low_index < len(block):
2775
entry = block[low_index]
2776
if entry[0][0:2] == key[0:2]:
2777
if entry[1][0][0] not in 'ar':
2778
# This entry has the same path (but a different id) as
2779
# the new entry we're adding, and is present in ths
2781
raise errors.InconsistentDelta(
2782
("%s/%s" % key[0:2]).decode('utf8'), key[2],
2783
"Attempt to add item at path already occupied by "
2784
"id %r" % entry[0][2])
1303
2788
# new entry, synthesis cross reference here,
1304
existing_keys = id_index.setdefault(key[2], set())
2789
existing_keys = id_index.get(key[2], ())
1305
2790
if not existing_keys:
1306
2791
# not currently in the state, simplest case
1307
2792
new_entry = key, [new_details] + self._empty_parent_info()
1368
2891
# This is the vertical axis in the matrix, all pointing
1369
2892
# to the real path.
1370
2893
block_index, present = self._find_block_index_from_key(entry_key)
2895
raise AssertionError('not present: %r', entry_key)
1372
2896
entry_index, present = self._find_entry_index(entry_key, self._dirblocks[block_index][1])
2898
raise AssertionError('not present: %r', entry_key)
1374
2899
self._dirblocks[block_index][1][entry_index][1][0] = \
1375
('relocated', path_utf8, 0, False, '')
2900
('r', path_utf8, 0, False, '')
2901
# add a containing dirblock if needed.
2902
if new_details[0] == 'd':
2903
subdir_key = (osutils.pathjoin(*key[0:2]), '', '')
2904
block_index, present = self._find_block_index_from_key(subdir_key)
2906
self._dirblocks.insert(block_index, (subdir_key[0], []))
1377
2908
self._dirblock_state = DirState.IN_MEMORY_MODIFIED
1381
def pack_stat(st, _encode=base64.encodestring, _pack=struct.pack):
1382
"""Convert stat values into a packed representation."""
1383
# jam 20060614 it isn't really worth removing more entries if we
1384
# are going to leave it in packed form.
1385
# With only st_mtime and st_mode filesize is 5.5M and read time is 275ms
1386
# With all entries filesize is 5.9M and read time is mabye 280ms
1387
# well within the noise margin
1389
# base64.encode always adds a final newline, so strip it off
1390
return _encode(_pack('>llllll'
1391
, st.st_size, st.st_mtime, st.st_ctime
1392
, st.st_dev, st.st_ino, st.st_mode))[:-1]
2910
def _maybe_remove_row(self, block, index, id_index):
2911
"""Remove index if it is absent or relocated across the row.
2913
id_index is updated accordingly.
2914
:return: True if we removed the row, False otherwise
2916
present_in_row = False
2917
entry = block[index]
2918
for column in entry[1]:
2919
if column[0] not in 'ar':
2920
present_in_row = True
2922
if not present_in_row:
2924
self._remove_from_id_index(id_index, entry[0])
2928
def _validate(self):
2929
"""Check that invariants on the dirblock are correct.
2931
This can be useful in debugging; it shouldn't be necessary in
2934
This must be called with a lock held.
2936
# NOTE: This must always raise AssertionError not just assert,
2937
# otherwise it may not behave properly under python -O
2939
# TODO: All entries must have some content that's not 'a' or 'r',
2940
# otherwise it could just be removed.
2942
# TODO: All relocations must point directly to a real entry.
2944
# TODO: No repeated keys.
2947
from pprint import pformat
2948
self._read_dirblocks_if_needed()
2949
if len(self._dirblocks) > 0:
2950
if not self._dirblocks[0][0] == '':
2951
raise AssertionError(
2952
"dirblocks don't start with root block:\n" + \
2953
pformat(self._dirblocks))
2954
if len(self._dirblocks) > 1:
2955
if not self._dirblocks[1][0] == '':
2956
raise AssertionError(
2957
"dirblocks missing root directory:\n" + \
2958
pformat(self._dirblocks))
2959
# the dirblocks are sorted by their path components, name, and dir id
2960
dir_names = [d[0].split('/')
2961
for d in self._dirblocks[1:]]
2962
if dir_names != sorted(dir_names):
2963
raise AssertionError(
2964
"dir names are not in sorted order:\n" + \
2965
pformat(self._dirblocks) + \
2968
for dirblock in self._dirblocks:
2969
# within each dirblock, the entries are sorted by filename and
2971
for entry in dirblock[1]:
2972
if dirblock[0] != entry[0][0]:
2973
raise AssertionError(
2975
"doesn't match directory name in\n%r" %
2976
(entry, pformat(dirblock)))
2977
if dirblock[1] != sorted(dirblock[1]):
2978
raise AssertionError(
2979
"dirblock for %r is not sorted:\n%s" % \
2980
(dirblock[0], pformat(dirblock)))
2982
def check_valid_parent():
2983
"""Check that the current entry has a valid parent.
2985
This makes sure that the parent has a record,
2986
and that the parent isn't marked as "absent" in the
2987
current tree. (It is invalid to have a non-absent file in an absent
2990
if entry[0][0:2] == ('', ''):
2991
# There should be no parent for the root row
2993
parent_entry = self._get_entry(tree_index, path_utf8=entry[0][0])
2994
if parent_entry == (None, None):
2995
raise AssertionError(
2996
"no parent entry for: %s in tree %s"
2997
% (this_path, tree_index))
2998
if parent_entry[1][tree_index][0] != 'd':
2999
raise AssertionError(
3000
"Parent entry for %s is not marked as a valid"
3001
" directory. %s" % (this_path, parent_entry,))
3003
# For each file id, for each tree: either
3004
# the file id is not present at all; all rows with that id in the
3005
# key have it marked as 'absent'
3006
# OR the file id is present under exactly one name; any other entries
3007
# that mention that id point to the correct name.
3009
# We check this with a dict per tree pointing either to the present
3010
# name, or None if absent.
3011
tree_count = self._num_present_parents() + 1
3012
id_path_maps = [dict() for i in range(tree_count)]
3013
# Make sure that all renamed entries point to the correct location.
3014
for entry in self._iter_entries():
3015
file_id = entry[0][2]
3016
this_path = osutils.pathjoin(entry[0][0], entry[0][1])
3017
if len(entry[1]) != tree_count:
3018
raise AssertionError(
3019
"wrong number of entry details for row\n%s" \
3020
",\nexpected %d" % \
3021
(pformat(entry), tree_count))
3022
absent_positions = 0
3023
for tree_index, tree_state in enumerate(entry[1]):
3024
this_tree_map = id_path_maps[tree_index]
3025
minikind = tree_state[0]
3026
if minikind in 'ar':
3027
absent_positions += 1
3028
# have we seen this id before in this column?
3029
if file_id in this_tree_map:
3030
previous_path, previous_loc = this_tree_map[file_id]
3031
# any later mention of this file must be consistent with
3032
# what was said before
3034
if previous_path is not None:
3035
raise AssertionError(
3036
"file %s is absent in row %r but also present " \
3038
(file_id, entry, previous_path))
3039
elif minikind == 'r':
3040
target_location = tree_state[1]
3041
if previous_path != target_location:
3042
raise AssertionError(
3043
"file %s relocation in row %r but also at %r" \
3044
% (file_id, entry, previous_path))
3046
# a file, directory, etc - may have been previously
3047
# pointed to by a relocation, which must point here
3048
if previous_path != this_path:
3049
raise AssertionError(
3050
"entry %r inconsistent with previous path %r "
3052
(entry, previous_path, previous_loc))
3053
check_valid_parent()
3056
# absent; should not occur anywhere else
3057
this_tree_map[file_id] = None, this_path
3058
elif minikind == 'r':
3059
# relocation, must occur at expected location
3060
this_tree_map[file_id] = tree_state[1], this_path
3062
this_tree_map[file_id] = this_path, this_path
3063
check_valid_parent()
3064
if absent_positions == tree_count:
3065
raise AssertionError(
3066
"entry %r has no data for any tree." % (entry,))
3067
if self._id_index is not None:
3068
for file_id, entry_keys in self._id_index.iteritems():
3069
for entry_key in entry_keys:
3070
if entry_key[2] != file_id:
3071
raise AssertionError(
3072
'file_id %r did not match entry key %s'
3073
% (file_id, entry_key))
3074
if len(entry_keys) != len(set(entry_keys)):
3075
raise AssertionError(
3076
'id_index contained non-unique data for %s'
3079
def _wipe_state(self):
3080
"""Forget all state information about the dirstate."""
3081
self._header_state = DirState.NOT_IN_MEMORY
3082
self._dirblock_state = DirState.NOT_IN_MEMORY
3083
self._changes_aborted = False
3086
self._dirblocks = []
3087
self._id_index = None
3088
self._packed_stat_index = None
3089
self._end_of_header = None
3090
self._cutoff_time = None
3091
self._split_path_cache = {}
3093
def lock_read(self):
3094
"""Acquire a read lock on the dirstate."""
3095
if self._lock_token is not None:
3096
raise errors.LockContention(self._lock_token)
3097
# TODO: jam 20070301 Rather than wiping completely, if the blocks are
3098
# already in memory, we could read just the header and check for
3099
# any modification. If not modified, we can just leave things
3101
self._lock_token = lock.ReadLock(self._filename)
3102
self._lock_state = 'r'
3103
self._state_file = self._lock_token.f
3106
def lock_write(self):
3107
"""Acquire a write lock on the dirstate."""
3108
if self._lock_token is not None:
3109
raise errors.LockContention(self._lock_token)
3110
# TODO: jam 20070301 Rather than wiping completely, if the blocks are
3111
# already in memory, we could read just the header and check for
3112
# any modification. If not modified, we can just leave things
3114
self._lock_token = lock.WriteLock(self._filename)
3115
self._lock_state = 'w'
3116
self._state_file = self._lock_token.f
3120
"""Drop any locks held on the dirstate."""
3121
if self._lock_token is None:
3122
raise errors.LockNotHeld(self)
3123
# TODO: jam 20070301 Rather than wiping completely, if the blocks are
3124
# already in memory, we could read just the header and check for
3125
# any modification. If not modified, we can just leave things
3127
self._state_file = None
3128
self._lock_state = None
3129
self._lock_token.unlock()
3130
self._lock_token = None
3131
self._split_path_cache = {}
3133
def _requires_lock(self):
3134
"""Check that a lock is currently held by someone on the dirstate."""
3135
if not self._lock_token:
3136
raise errors.ObjectNotLocked(self)
3139
def py_update_entry(state, entry, abspath, stat_value,
3140
_stat_to_minikind=DirState._stat_to_minikind,
3141
_pack_stat=pack_stat):
3142
"""Update the entry based on what is actually on disk.
3144
This function only calculates the sha if it needs to - if the entry is
3145
uncachable, or clearly different to the first parent's entry, no sha
3146
is calculated, and None is returned.
3148
:param state: The dirstate this entry is in.
3149
:param entry: This is the dirblock entry for the file in question.
3150
:param abspath: The path on disk for this file.
3151
:param stat_value: The stat value done on the path.
3152
:return: None, or The sha1 hexdigest of the file (40 bytes) or link
3153
target of a symlink.
3156
minikind = _stat_to_minikind[stat_value.st_mode & 0170000]
3160
packed_stat = _pack_stat(stat_value)
3161
(saved_minikind, saved_link_or_sha1, saved_file_size,
3162
saved_executable, saved_packed_stat) = entry[1][0]
3164
if minikind == 'd' and saved_minikind == 't':
3166
if (minikind == saved_minikind
3167
and packed_stat == saved_packed_stat):
3168
# The stat hasn't changed since we saved, so we can re-use the
3173
# size should also be in packed_stat
3174
if saved_file_size == stat_value.st_size:
3175
return saved_link_or_sha1
3177
# If we have gotten this far, that means that we need to actually
3178
# process this entry.
3181
executable = state._is_executable(stat_value.st_mode,
3183
if state._cutoff_time is None:
3184
state._sha_cutoff_time()
3185
if (stat_value.st_mtime < state._cutoff_time
3186
and stat_value.st_ctime < state._cutoff_time
3187
and len(entry[1]) > 1
3188
and entry[1][1][0] != 'a'):
3189
# Could check for size changes for further optimised
3190
# avoidance of sha1's. However the most prominent case of
3191
# over-shaing is during initial add, which this catches.
3192
# Besides, if content filtering happens, size and sha
3193
# are calculated at the same time, so checking just the size
3194
# gains nothing w.r.t. performance.
3195
link_or_sha1 = state._sha1_file(abspath)
3196
entry[1][0] = ('f', link_or_sha1, stat_value.st_size,
3197
executable, packed_stat)
3199
entry[1][0] = ('f', '', stat_value.st_size,
3200
executable, DirState.NULLSTAT)
3201
elif minikind == 'd':
3203
entry[1][0] = ('d', '', 0, False, packed_stat)
3204
if saved_minikind != 'd':
3205
# This changed from something into a directory. Make sure we
3206
# have a directory block for it. This doesn't happen very
3207
# often, so this doesn't have to be super fast.
3208
block_index, entry_index, dir_present, file_present = \
3209
state._get_block_entry_index(entry[0][0], entry[0][1], 0)
3210
state._ensure_block(block_index, entry_index,
3211
osutils.pathjoin(entry[0][0], entry[0][1]))
3212
elif minikind == 'l':
3213
link_or_sha1 = state._read_link(abspath, saved_link_or_sha1)
3214
if state._cutoff_time is None:
3215
state._sha_cutoff_time()
3216
if (stat_value.st_mtime < state._cutoff_time
3217
and stat_value.st_ctime < state._cutoff_time):
3218
entry[1][0] = ('l', link_or_sha1, stat_value.st_size,
3221
entry[1][0] = ('l', '', stat_value.st_size,
3222
False, DirState.NULLSTAT)
3223
state._dirblock_state = DirState.IN_MEMORY_MODIFIED
3227
class ProcessEntryPython(object):
3229
__slots__ = ["old_dirname_to_file_id", "new_dirname_to_file_id",
3230
"last_source_parent", "last_target_parent", "include_unchanged",
3231
"partial", "use_filesystem_for_exec", "utf8_decode",
3232
"searched_specific_files", "search_specific_files",
3233
"searched_exact_paths", "search_specific_file_parents", "seen_ids",
3234
"state", "source_index", "target_index", "want_unversioned", "tree"]
3236
def __init__(self, include_unchanged, use_filesystem_for_exec,
3237
search_specific_files, state, source_index, target_index,
3238
want_unversioned, tree):
3239
self.old_dirname_to_file_id = {}
3240
self.new_dirname_to_file_id = {}
3241
# Are we doing a partial iter_changes?
3242
self.partial = search_specific_files != set([''])
3243
# Using a list so that we can access the values and change them in
3244
# nested scope. Each one is [path, file_id, entry]
3245
self.last_source_parent = [None, None]
3246
self.last_target_parent = [None, None]
3247
self.include_unchanged = include_unchanged
3248
self.use_filesystem_for_exec = use_filesystem_for_exec
3249
self.utf8_decode = cache_utf8._utf8_decode
3250
# for all search_indexs in each path at or under each element of
3251
# search_specific_files, if the detail is relocated: add the id, and
3252
# add the relocated path as one to search if its not searched already.
3253
# If the detail is not relocated, add the id.
3254
self.searched_specific_files = set()
3255
# When we search exact paths without expanding downwards, we record
3257
self.searched_exact_paths = set()
3258
self.search_specific_files = search_specific_files
3259
# The parents up to the root of the paths we are searching.
3260
# After all normal paths are returned, these specific items are returned.
3261
self.search_specific_file_parents = set()
3262
# The ids we've sent out in the delta.
3263
self.seen_ids = set()
3265
self.source_index = source_index
3266
self.target_index = target_index
3267
if target_index != 0:
3268
# A lot of code in here depends on target_index == 0
3269
raise errors.BzrError('unsupported target index')
3270
self.want_unversioned = want_unversioned
3273
def _process_entry(self, entry, path_info, pathjoin=osutils.pathjoin):
3274
"""Compare an entry and real disk to generate delta information.
3276
:param path_info: top_relpath, basename, kind, lstat, abspath for
3277
the path of entry. If None, then the path is considered absent in
3278
the target (Perhaps we should pass in a concrete entry for this ?)
3279
Basename is returned as a utf8 string because we expect this
3280
tuple will be ignored, and don't want to take the time to
3282
:return: (iter_changes_result, changed). If the entry has not been
3283
handled then changed is None. Otherwise it is False if no content
3284
or metadata changes have occurred, and True if any content or
3285
metadata change has occurred. If self.include_unchanged is True then
3286
if changed is not None, iter_changes_result will always be a result
3287
tuple. Otherwise, iter_changes_result is None unless changed is
3290
if self.source_index is None:
3291
source_details = DirState.NULL_PARENT_DETAILS
3293
source_details = entry[1][self.source_index]
3294
target_details = entry[1][self.target_index]
3295
target_minikind = target_details[0]
3296
if path_info is not None and target_minikind in 'fdlt':
3297
if not (self.target_index == 0):
3298
raise AssertionError()
3299
link_or_sha1 = update_entry(self.state, entry,
3300
abspath=path_info[4], stat_value=path_info[3])
3301
# The entry may have been modified by update_entry
3302
target_details = entry[1][self.target_index]
3303
target_minikind = target_details[0]
3306
file_id = entry[0][2]
3307
source_minikind = source_details[0]
3308
if source_minikind in 'fdltr' and target_minikind in 'fdlt':
3309
# claimed content in both: diff
3310
# r | fdlt | | add source to search, add id path move and perform
3311
# | | | diff check on source-target
3312
# r | fdlt | a | dangling file that was present in the basis.
3314
if source_minikind in 'r':
3315
# add the source to the search path to find any children it
3316
# has. TODO ? : only add if it is a container ?
3317
if not osutils.is_inside_any(self.searched_specific_files,
3319
self.search_specific_files.add(source_details[1])
3320
# generate the old path; this is needed for stating later
3322
old_path = source_details[1]
3323
old_dirname, old_basename = os.path.split(old_path)
3324
path = pathjoin(entry[0][0], entry[0][1])
3325
old_entry = self.state._get_entry(self.source_index,
3327
# update the source details variable to be the real
3329
if old_entry == (None, None):
3330
raise errors.CorruptDirstate(self.state._filename,
3331
"entry '%s/%s' is considered renamed from %r"
3332
" but source does not exist\n"
3333
"entry: %s" % (entry[0][0], entry[0][1], old_path, entry))
3334
source_details = old_entry[1][self.source_index]
3335
source_minikind = source_details[0]
3337
old_dirname = entry[0][0]
3338
old_basename = entry[0][1]
3339
old_path = path = None
3340
if path_info is None:
3341
# the file is missing on disk, show as removed.
3342
content_change = True
3346
# source and target are both versioned and disk file is present.
3347
target_kind = path_info[2]
3348
if target_kind == 'directory':
3350
old_path = path = pathjoin(old_dirname, old_basename)
3351
self.new_dirname_to_file_id[path] = file_id
3352
if source_minikind != 'd':
3353
content_change = True
3355
# directories have no fingerprint
3356
content_change = False
3358
elif target_kind == 'file':
3359
if source_minikind != 'f':
3360
content_change = True
3362
# Check the sha. We can't just rely on the size as
3363
# content filtering may mean differ sizes actually
3364
# map to the same content
3365
if link_or_sha1 is None:
3367
statvalue, link_or_sha1 = \
3368
self.state._sha1_provider.stat_and_sha1(
3370
self.state._observed_sha1(entry, link_or_sha1,
3372
content_change = (link_or_sha1 != source_details[1])
3373
# Target details is updated at update_entry time
3374
if self.use_filesystem_for_exec:
3375
# We don't need S_ISREG here, because we are sure
3376
# we are dealing with a file.
3377
target_exec = bool(stat.S_IEXEC & path_info[3].st_mode)
3379
target_exec = target_details[3]
3380
elif target_kind == 'symlink':
3381
if source_minikind != 'l':
3382
content_change = True
3384
content_change = (link_or_sha1 != source_details[1])
3386
elif target_kind == 'tree-reference':
3387
if source_minikind != 't':
3388
content_change = True
3390
content_change = False
3394
path = pathjoin(old_dirname, old_basename)
3395
raise errors.BadFileKindError(path, path_info[2])
3396
if source_minikind == 'd':
3398
old_path = path = pathjoin(old_dirname, old_basename)
3399
self.old_dirname_to_file_id[old_path] = file_id
3400
# parent id is the entry for the path in the target tree
3401
if old_basename and old_dirname == self.last_source_parent[0]:
3402
source_parent_id = self.last_source_parent[1]
3405
source_parent_id = self.old_dirname_to_file_id[old_dirname]
3407
source_parent_entry = self.state._get_entry(self.source_index,
3408
path_utf8=old_dirname)
3409
source_parent_id = source_parent_entry[0][2]
3410
if source_parent_id == entry[0][2]:
3411
# This is the root, so the parent is None
3412
source_parent_id = None
3414
self.last_source_parent[0] = old_dirname
3415
self.last_source_parent[1] = source_parent_id
3416
new_dirname = entry[0][0]
3417
if entry[0][1] and new_dirname == self.last_target_parent[0]:
3418
target_parent_id = self.last_target_parent[1]
3421
target_parent_id = self.new_dirname_to_file_id[new_dirname]
3423
# TODO: We don't always need to do the lookup, because the
3424
# parent entry will be the same as the source entry.
3425
target_parent_entry = self.state._get_entry(self.target_index,
3426
path_utf8=new_dirname)
3427
if target_parent_entry == (None, None):
3428
raise AssertionError(
3429
"Could not find target parent in wt: %s\nparent of: %s"
3430
% (new_dirname, entry))
3431
target_parent_id = target_parent_entry[0][2]
3432
if target_parent_id == entry[0][2]:
3433
# This is the root, so the parent is None
3434
target_parent_id = None
3436
self.last_target_parent[0] = new_dirname
3437
self.last_target_parent[1] = target_parent_id
3439
source_exec = source_details[3]
3440
changed = (content_change
3441
or source_parent_id != target_parent_id
3442
or old_basename != entry[0][1]
3443
or source_exec != target_exec
3445
if not changed and not self.include_unchanged:
3448
if old_path is None:
3449
old_path = path = pathjoin(old_dirname, old_basename)
3450
old_path_u = self.utf8_decode(old_path)[0]
3453
old_path_u = self.utf8_decode(old_path)[0]
3454
if old_path == path:
3457
path_u = self.utf8_decode(path)[0]
3458
source_kind = DirState._minikind_to_kind[source_minikind]
3459
return (entry[0][2],
3460
(old_path_u, path_u),
3463
(source_parent_id, target_parent_id),
3464
(self.utf8_decode(old_basename)[0], self.utf8_decode(entry[0][1])[0]),
3465
(source_kind, target_kind),
3466
(source_exec, target_exec)), changed
3467
elif source_minikind in 'a' and target_minikind in 'fdlt':
3468
# looks like a new file
3469
path = pathjoin(entry[0][0], entry[0][1])
3470
# parent id is the entry for the path in the target tree
3471
# TODO: these are the same for an entire directory: cache em.
3472
parent_id = self.state._get_entry(self.target_index,
3473
path_utf8=entry[0][0])[0][2]
3474
if parent_id == entry[0][2]:
3476
if path_info is not None:
3478
if self.use_filesystem_for_exec:
3479
# We need S_ISREG here, because we aren't sure if this
3482
stat.S_ISREG(path_info[3].st_mode)
3483
and stat.S_IEXEC & path_info[3].st_mode)
3485
target_exec = target_details[3]
3486
return (entry[0][2],
3487
(None, self.utf8_decode(path)[0]),
3491
(None, self.utf8_decode(entry[0][1])[0]),
3492
(None, path_info[2]),
3493
(None, target_exec)), True
3495
# Its a missing file, report it as such.
3496
return (entry[0][2],
3497
(None, self.utf8_decode(path)[0]),
3501
(None, self.utf8_decode(entry[0][1])[0]),
3503
(None, False)), True
3504
elif source_minikind in 'fdlt' and target_minikind in 'a':
3505
# unversioned, possibly, or possibly not deleted: we dont care.
3506
# if its still on disk, *and* theres no other entry at this
3507
# path [we dont know this in this routine at the moment -
3508
# perhaps we should change this - then it would be an unknown.
3509
old_path = pathjoin(entry[0][0], entry[0][1])
3510
# parent id is the entry for the path in the target tree
3511
parent_id = self.state._get_entry(self.source_index, path_utf8=entry[0][0])[0][2]
3512
if parent_id == entry[0][2]:
3514
return (entry[0][2],
3515
(self.utf8_decode(old_path)[0], None),
3519
(self.utf8_decode(entry[0][1])[0], None),
3520
(DirState._minikind_to_kind[source_minikind], None),
3521
(source_details[3], None)), True
3522
elif source_minikind in 'fdlt' and target_minikind in 'r':
3523
# a rename; could be a true rename, or a rename inherited from
3524
# a renamed parent. TODO: handle this efficiently. Its not
3525
# common case to rename dirs though, so a correct but slow
3526
# implementation will do.
3527
if not osutils.is_inside_any(self.searched_specific_files, target_details[1]):
3528
self.search_specific_files.add(target_details[1])
3529
elif source_minikind in 'ra' and target_minikind in 'ra':
3530
# neither of the selected trees contain this file,
3531
# so skip over it. This is not currently directly tested, but
3532
# is indirectly via test_too_much.TestCommands.test_conflicts.
3535
raise AssertionError("don't know how to compare "
3536
"source_minikind=%r, target_minikind=%r"
3537
% (source_minikind, target_minikind))
3538
## import pdb;pdb.set_trace()
3544
def _gather_result_for_consistency(self, result):
3545
"""Check a result we will yield to make sure we are consistent later.
3547
This gathers result's parents into a set to output later.
3549
:param result: A result tuple.
3551
if not self.partial or not result[0]:
3553
self.seen_ids.add(result[0])
3554
new_path = result[1][1]
3556
# Not the root and not a delete: queue up the parents of the path.
3557
self.search_specific_file_parents.update(
3558
osutils.parent_directories(new_path.encode('utf8')))
3559
# Add the root directory which parent_directories does not
3561
self.search_specific_file_parents.add('')
3563
def iter_changes(self):
3564
"""Iterate over the changes."""
3565
utf8_decode = cache_utf8._utf8_decode
3566
_cmp_by_dirs = cmp_by_dirs
3567
_process_entry = self._process_entry
3568
search_specific_files = self.search_specific_files
3569
searched_specific_files = self.searched_specific_files
3570
splitpath = osutils.splitpath
3572
# compare source_index and target_index at or under each element of search_specific_files.
3573
# follow the following comparison table. Note that we only want to do diff operations when
3574
# the target is fdl because thats when the walkdirs logic will have exposed the pathinfo
3578
# Source | Target | disk | action
3579
# r | fdlt | | add source to search, add id path move and perform
3580
# | | | diff check on source-target
3581
# r | fdlt | a | dangling file that was present in the basis.
3583
# r | a | | add source to search
3585
# r | r | | this path is present in a non-examined tree, skip.
3586
# r | r | a | this path is present in a non-examined tree, skip.
3587
# a | fdlt | | add new id
3588
# a | fdlt | a | dangling locally added file, skip
3589
# a | a | | not present in either tree, skip
3590
# a | a | a | not present in any tree, skip
3591
# a | r | | not present in either tree at this path, skip as it
3592
# | | | may not be selected by the users list of paths.
3593
# a | r | a | not present in either tree at this path, skip as it
3594
# | | | may not be selected by the users list of paths.
3595
# fdlt | fdlt | | content in both: diff them
3596
# fdlt | fdlt | a | deleted locally, but not unversioned - show as deleted ?
3597
# fdlt | a | | unversioned: output deleted id for now
3598
# fdlt | a | a | unversioned and deleted: output deleted id
3599
# fdlt | r | | relocated in this tree, so add target to search.
3600
# | | | Dont diff, we will see an r,fd; pair when we reach
3601
# | | | this id at the other path.
3602
# fdlt | r | a | relocated in this tree, so add target to search.
3603
# | | | Dont diff, we will see an r,fd; pair when we reach
3604
# | | | this id at the other path.
3606
# TODO: jam 20070516 - Avoid the _get_entry lookup overhead by
3607
# keeping a cache of directories that we have seen.
3609
while search_specific_files:
3610
# TODO: the pending list should be lexically sorted? the
3611
# interface doesn't require it.
3612
current_root = search_specific_files.pop()
3613
current_root_unicode = current_root.decode('utf8')
3614
searched_specific_files.add(current_root)
3615
# process the entries for this containing directory: the rest will be
3616
# found by their parents recursively.
3617
root_entries = self.state._entries_for_path(current_root)
3618
root_abspath = self.tree.abspath(current_root_unicode)
3620
root_stat = os.lstat(root_abspath)
3622
if e.errno == errno.ENOENT:
3623
# the path does not exist: let _process_entry know that.
3624
root_dir_info = None
3626
# some other random error: hand it up.
3629
root_dir_info = ('', current_root,
3630
osutils.file_kind_from_stat_mode(root_stat.st_mode), root_stat,
3632
if root_dir_info[2] == 'directory':
3633
if self.tree._directory_is_tree_reference(
3634
current_root.decode('utf8')):
3635
root_dir_info = root_dir_info[:2] + \
3636
('tree-reference',) + root_dir_info[3:]
3638
if not root_entries and not root_dir_info:
3639
# this specified path is not present at all, skip it.
3641
path_handled = False
3642
for entry in root_entries:
3643
result, changed = _process_entry(entry, root_dir_info)
3644
if changed is not None:
3647
self._gather_result_for_consistency(result)
3648
if changed or self.include_unchanged:
3650
if self.want_unversioned and not path_handled and root_dir_info:
3651
new_executable = bool(
3652
stat.S_ISREG(root_dir_info[3].st_mode)
3653
and stat.S_IEXEC & root_dir_info[3].st_mode)
3655
(None, current_root_unicode),
3659
(None, splitpath(current_root_unicode)[-1]),
3660
(None, root_dir_info[2]),
3661
(None, new_executable)
3663
initial_key = (current_root, '', '')
3664
block_index, _ = self.state._find_block_index_from_key(initial_key)
3665
if block_index == 0:
3666
# we have processed the total root already, but because the
3667
# initial key matched it we should skip it here.
3669
if root_dir_info and root_dir_info[2] == 'tree-reference':
3670
current_dir_info = None
3672
dir_iterator = osutils._walkdirs_utf8(root_abspath, prefix=current_root)
3674
current_dir_info = dir_iterator.next()
3676
# on win32, python2.4 has e.errno == ERROR_DIRECTORY, but
3677
# python 2.5 has e.errno == EINVAL,
3678
# and e.winerror == ERROR_DIRECTORY
3679
e_winerror = getattr(e, 'winerror', None)
3680
win_errors = (ERROR_DIRECTORY, ERROR_PATH_NOT_FOUND)
3681
# there may be directories in the inventory even though
3682
# this path is not a file on disk: so mark it as end of
3684
if e.errno in (errno.ENOENT, errno.ENOTDIR, errno.EINVAL):
3685
current_dir_info = None
3686
elif (sys.platform == 'win32'
3687
and (e.errno in win_errors
3688
or e_winerror in win_errors)):
3689
current_dir_info = None
3693
if current_dir_info[0][0] == '':
3694
# remove .bzr from iteration
3695
bzr_index = bisect.bisect_left(current_dir_info[1], ('.bzr',))
3696
if current_dir_info[1][bzr_index][0] != '.bzr':
3697
raise AssertionError()
3698
del current_dir_info[1][bzr_index]
3699
# walk until both the directory listing and the versioned metadata
3701
if (block_index < len(self.state._dirblocks) and
3702
osutils.is_inside(current_root, self.state._dirblocks[block_index][0])):
3703
current_block = self.state._dirblocks[block_index]
3705
current_block = None
3706
while (current_dir_info is not None or
3707
current_block is not None):
3708
if (current_dir_info and current_block
3709
and current_dir_info[0][0] != current_block[0]):
3710
if _cmp_by_dirs(current_dir_info[0][0], current_block[0]) < 0:
3711
# filesystem data refers to paths not covered by the dirblock.
3712
# this has two possibilities:
3713
# A) it is versioned but empty, so there is no block for it
3714
# B) it is not versioned.
3716
# if (A) then we need to recurse into it to check for
3717
# new unknown files or directories.
3718
# if (B) then we should ignore it, because we don't
3719
# recurse into unknown directories.
3721
while path_index < len(current_dir_info[1]):
3722
current_path_info = current_dir_info[1][path_index]
3723
if self.want_unversioned:
3724
if current_path_info[2] == 'directory':
3725
if self.tree._directory_is_tree_reference(
3726
current_path_info[0].decode('utf8')):
3727
current_path_info = current_path_info[:2] + \
3728
('tree-reference',) + current_path_info[3:]
3729
new_executable = bool(
3730
stat.S_ISREG(current_path_info[3].st_mode)
3731
and stat.S_IEXEC & current_path_info[3].st_mode)
3733
(None, utf8_decode(current_path_info[0])[0]),
3737
(None, utf8_decode(current_path_info[1])[0]),
3738
(None, current_path_info[2]),
3739
(None, new_executable))
3740
# dont descend into this unversioned path if it is
3742
if current_path_info[2] in ('directory',
3744
del current_dir_info[1][path_index]
3748
# This dir info has been handled, go to the next
3750
current_dir_info = dir_iterator.next()
3751
except StopIteration:
3752
current_dir_info = None
3754
# We have a dirblock entry for this location, but there
3755
# is no filesystem path for this. This is most likely
3756
# because a directory was removed from the disk.
3757
# We don't have to report the missing directory,
3758
# because that should have already been handled, but we
3759
# need to handle all of the files that are contained
3761
for current_entry in current_block[1]:
3762
# entry referring to file not present on disk.
3763
# advance the entry only, after processing.
3764
result, changed = _process_entry(current_entry, None)
3765
if changed is not None:
3767
self._gather_result_for_consistency(result)
3768
if changed or self.include_unchanged:
3771
if (block_index < len(self.state._dirblocks) and
3772
osutils.is_inside(current_root,
3773
self.state._dirblocks[block_index][0])):
3774
current_block = self.state._dirblocks[block_index]
3776
current_block = None
3779
if current_block and entry_index < len(current_block[1]):
3780
current_entry = current_block[1][entry_index]
3782
current_entry = None
3783
advance_entry = True
3785
if current_dir_info and path_index < len(current_dir_info[1]):
3786
current_path_info = current_dir_info[1][path_index]
3787
if current_path_info[2] == 'directory':
3788
if self.tree._directory_is_tree_reference(
3789
current_path_info[0].decode('utf8')):
3790
current_path_info = current_path_info[:2] + \
3791
('tree-reference',) + current_path_info[3:]
3793
current_path_info = None
3795
path_handled = False
3796
while (current_entry is not None or
3797
current_path_info is not None):
3798
if current_entry is None:
3799
# the check for path_handled when the path is advanced
3800
# will yield this path if needed.
3802
elif current_path_info is None:
3803
# no path is fine: the per entry code will handle it.
3804
result, changed = _process_entry(current_entry, current_path_info)
3805
if changed is not None:
3807
self._gather_result_for_consistency(result)
3808
if changed or self.include_unchanged:
3810
elif (current_entry[0][1] != current_path_info[1]
3811
or current_entry[1][self.target_index][0] in 'ar'):
3812
# The current path on disk doesn't match the dirblock
3813
# record. Either the dirblock is marked as absent, or
3814
# the file on disk is not present at all in the
3815
# dirblock. Either way, report about the dirblock
3816
# entry, and let other code handle the filesystem one.
3818
# Compare the basename for these files to determine
3820
if current_path_info[1] < current_entry[0][1]:
3821
# extra file on disk: pass for now, but only
3822
# increment the path, not the entry
3823
advance_entry = False
3825
# entry referring to file not present on disk.
3826
# advance the entry only, after processing.
3827
result, changed = _process_entry(current_entry, None)
3828
if changed is not None:
3830
self._gather_result_for_consistency(result)
3831
if changed or self.include_unchanged:
3833
advance_path = False
3835
result, changed = _process_entry(current_entry, current_path_info)
3836
if changed is not None:
3839
self._gather_result_for_consistency(result)
3840
if changed or self.include_unchanged:
3842
if advance_entry and current_entry is not None:
3844
if entry_index < len(current_block[1]):
3845
current_entry = current_block[1][entry_index]
3847
current_entry = None
3849
advance_entry = True # reset the advance flaga
3850
if advance_path and current_path_info is not None:
3851
if not path_handled:
3852
# unversioned in all regards
3853
if self.want_unversioned:
3854
new_executable = bool(
3855
stat.S_ISREG(current_path_info[3].st_mode)
3856
and stat.S_IEXEC & current_path_info[3].st_mode)
3858
relpath_unicode = utf8_decode(current_path_info[0])[0]
3859
except UnicodeDecodeError:
3860
raise errors.BadFilenameEncoding(
3861
current_path_info[0], osutils._fs_enc)
3863
(None, relpath_unicode),
3867
(None, utf8_decode(current_path_info[1])[0]),
3868
(None, current_path_info[2]),
3869
(None, new_executable))
3870
# dont descend into this unversioned path if it is
3872
if current_path_info[2] in ('directory'):
3873
del current_dir_info[1][path_index]
3875
# dont descend the disk iterator into any tree
3877
if current_path_info[2] == 'tree-reference':
3878
del current_dir_info[1][path_index]
3881
if path_index < len(current_dir_info[1]):
3882
current_path_info = current_dir_info[1][path_index]
3883
if current_path_info[2] == 'directory':
3884
if self.tree._directory_is_tree_reference(
3885
current_path_info[0].decode('utf8')):
3886
current_path_info = current_path_info[:2] + \
3887
('tree-reference',) + current_path_info[3:]
3889
current_path_info = None
3890
path_handled = False
3892
advance_path = True # reset the advance flagg.
3893
if current_block is not None:
3895
if (block_index < len(self.state._dirblocks) and
3896
osutils.is_inside(current_root, self.state._dirblocks[block_index][0])):
3897
current_block = self.state._dirblocks[block_index]
3899
current_block = None
3900
if current_dir_info is not None:
3902
current_dir_info = dir_iterator.next()
3903
except StopIteration:
3904
current_dir_info = None
3905
for result in self._iter_specific_file_parents():
3908
def _iter_specific_file_parents(self):
3909
"""Iter over the specific file parents."""
3910
while self.search_specific_file_parents:
3911
# Process the parent directories for the paths we were iterating.
3912
# Even in extremely large trees this should be modest, so currently
3913
# no attempt is made to optimise.
3914
path_utf8 = self.search_specific_file_parents.pop()
3915
if osutils.is_inside_any(self.searched_specific_files, path_utf8):
3916
# We've examined this path.
3918
if path_utf8 in self.searched_exact_paths:
3919
# We've examined this path.
3921
path_entries = self.state._entries_for_path(path_utf8)
3922
# We need either one or two entries. If the path in
3923
# self.target_index has moved (so the entry in source_index is in
3924
# 'ar') then we need to also look for the entry for this path in
3925
# self.source_index, to output the appropriate delete-or-rename.
3926
selected_entries = []
3928
for candidate_entry in path_entries:
3929
# Find entries present in target at this path:
3930
if candidate_entry[1][self.target_index][0] not in 'ar':
3932
selected_entries.append(candidate_entry)
3933
# Find entries present in source at this path:
3934
elif (self.source_index is not None and
3935
candidate_entry[1][self.source_index][0] not in 'ar'):
3937
if candidate_entry[1][self.target_index][0] == 'a':
3938
# Deleted, emit it here.
3939
selected_entries.append(candidate_entry)
3941
# renamed, emit it when we process the directory it
3943
self.search_specific_file_parents.add(
3944
candidate_entry[1][self.target_index][1])
3946
raise AssertionError(
3947
"Missing entry for specific path parent %r, %r" % (
3948
path_utf8, path_entries))
3949
path_info = self._path_info(path_utf8, path_utf8.decode('utf8'))
3950
for entry in selected_entries:
3951
if entry[0][2] in self.seen_ids:
3953
result, changed = self._process_entry(entry, path_info)
3955
raise AssertionError(
3956
"Got entry<->path mismatch for specific path "
3957
"%r entry %r path_info %r " % (
3958
path_utf8, entry, path_info))
3959
# Only include changes - we're outside the users requested
3962
self._gather_result_for_consistency(result)
3963
if (result[6][0] == 'directory' and
3964
result[6][1] != 'directory'):
3965
# This stopped being a directory, the old children have
3967
if entry[1][self.source_index][0] == 'r':
3968
# renamed, take the source path
3969
entry_path_utf8 = entry[1][self.source_index][1]
3971
entry_path_utf8 = path_utf8
3972
initial_key = (entry_path_utf8, '', '')
3973
block_index, _ = self.state._find_block_index_from_key(
3975
if block_index == 0:
3976
# The children of the root are in block index 1.
3978
current_block = None
3979
if block_index < len(self.state._dirblocks):
3980
current_block = self.state._dirblocks[block_index]
3981
if not osutils.is_inside(
3982
entry_path_utf8, current_block[0]):
3983
# No entries for this directory at all.
3984
current_block = None
3985
if current_block is not None:
3986
for entry in current_block[1]:
3987
if entry[1][self.source_index][0] in 'ar':
3988
# Not in the source tree, so doesn't have to be
3991
# Path of the entry itself.
3993
self.search_specific_file_parents.add(
3994
osutils.pathjoin(*entry[0][:2]))
3995
if changed or self.include_unchanged:
3997
self.searched_exact_paths.add(path_utf8)
3999
def _path_info(self, utf8_path, unicode_path):
4000
"""Generate path_info for unicode_path.
4002
:return: None if unicode_path does not exist, or a path_info tuple.
4004
abspath = self.tree.abspath(unicode_path)
4006
stat = os.lstat(abspath)
4008
if e.errno == errno.ENOENT:
4009
# the path does not exist.
4013
utf8_basename = utf8_path.rsplit('/', 1)[-1]
4014
dir_info = (utf8_path, utf8_basename,
4015
osutils.file_kind_from_stat_mode(stat.st_mode), stat,
4017
if dir_info[2] == 'directory':
4018
if self.tree._directory_is_tree_reference(
4020
self.root_dir_info = self.root_dir_info[:2] + \
4021
('tree-reference',) + self.root_dir_info[3:]
4025
# Try to load the compiled form if possible
4027
from bzrlib._dirstate_helpers_pyx import (
4033
ProcessEntryC as _process_entry,
4034
update_entry as update_entry,
4036
except ImportError, e:
4037
osutils.failed_to_load_extension(e)
4038
from bzrlib._dirstate_helpers_py import (
4045
# FIXME: It would be nice to be able to track moved lines so that the
4046
# corresponding python code can be moved to the _dirstate_helpers_py
4047
# module. I don't want to break the history for this important piece of
4048
# code so I left the code here -- vila 20090622
4049
update_entry = py_update_entry
4050
_process_entry = ProcessEntryPython