1
# Copyright (C) 2006, 2007 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17
"""DirState objects record the state of a directory and its bzr metadata.
19
Pseudo EBNF grammar for the state file. Fields are separated by NULLs, and
20
lines by NL. The field delimiters are ommitted in the grammar, line delimiters
21
are not - this is done for clarity of reading. All string data is in utf8.
23
MINIKIND = "f" | "d" | "l" | "a" | "r";
26
WHOLE_NUMBER = {digit}, digit;
28
REVISION_ID = a non-empty utf8 string;
30
dirstate format = header line, full checksum, row count, parent details,
31
ghost_details, entries;
32
header line = "#bazaar dirstate flat format 2", NL;
33
full checksum = "adler32: ", ["-"], WHOLE_NUMBER, NL;
34
row count = "num_entries: ", digit, NL;
35
parent_details = WHOLE NUMBER, {REVISION_ID}* NL;
36
ghost_details = WHOLE NUMBER, {REVISION_ID}*, NL;
38
entry = entry_key, current_entry_details, {parent_entry_details};
39
entry_key = dirname, basename, fileid;
40
current_entry_details = common_entry_details, working_entry_details;
41
parent_entry_details = common_entry_details, history_entry_details;
42
common_entry_details = MINIKIND, fingerprint, size, executable
43
working_entry_details = packed_stat
44
history_entry_details = REVISION_ID;
47
fingerprint = a nonempty utf8 sequence with meaning defined by minikind.
49
Given this definition, the following is useful to know:
50
entry (aka row) - all the data for a given key.
51
entry[0]: The key (dirname, basename, fileid)
55
entry[1]: The tree(s) data for this path and id combination.
56
entry[1][0]: The current tree
57
entry[1][1]: The second tree
59
For an entry for a tree, we have (using tree 0 - current tree) to demonstrate:
60
entry[1][0][0]: minikind
61
entry[1][0][1]: fingerprint
63
entry[1][0][3]: executable
64
entry[1][0][4]: packed_stat
66
entry[1][1][4]: revision_id
68
There may be multiple rows at the root, one per id present in the root, so the
69
in memory root row is now:
70
self._dirblocks[0] -> ('', [entry ...]),
71
and the entries in there are
74
entries[0][2]: file_id
75
entries[1][0]: The tree data for the current tree for this fileid at /
79
'r' is a relocated entry: This path is not present in this tree with this id,
80
but the id can be found at another location. The fingerprint is used to
81
point to the target location.
82
'a' is an absent entry: In that tree the id is not present at this path.
83
'd' is a directory entry: This path in this tree is a directory with the
84
current file id. There is no fingerprint for directories.
85
'f' is a file entry: As for directory, but its a file. The fingerprint is a
87
'l' is a symlink entry: As for directory, but a symlink. The fingerprint is the
91
--- Format 1 had the following different definition: ---
92
rows = dirname, NULL, basename, NULL, MINIKIND, NULL, fileid_utf8, NULL,
93
WHOLE NUMBER (* size *), NULL, packed stat, NULL, sha1|symlink target,
95
PARENT ROW = NULL, revision_utf8, NULL, MINIKIND, NULL, dirname, NULL,
96
basename, NULL, WHOLE NUMBER (* size *), NULL, "y" | "n", NULL,
99
PARENT ROW's are emitted for every parent that is not in the ghosts details
100
line. That is, if the parents are foo, bar, baz, and the ghosts are bar, then
101
each row will have a PARENT ROW for foo and baz, but not for bar.
104
In any tree, a kind of 'moved' indicates that the fingerprint field
105
(which we treat as opaque data specific to the 'kind' anyway) has the
106
details for the id of this row in that tree.
108
I'm strongly tempted to add a id->path index as well, but I think that
109
where we need id->path mapping; we also usually read the whole file, so
110
I'm going to skip that for the moment, as we have the ability to locate
111
via bisect any path in any tree, and if we lookup things by path, we can
112
accumulate a id->path mapping as we go, which will tend to match what we
115
I plan to implement this asap, so please speak up now to alter/tweak the
116
design - and once we stabilise on this, I'll update the wiki page for
119
The rationale for all this is that we want fast operations for the
120
common case (diff/status/commit/merge on all files) and extremely fast
121
operations for the less common but still occurs a lot status/diff/commit
122
on specific files). Operations on specific files involve a scan for all
123
the children of a path, *in every involved tree*, which the current
124
format did not accommodate.
128
1) Fast end to end use for bzr's top 5 uses cases. (commmit/diff/status/merge/???)
129
2) fall back current object model as needed.
130
3) scale usably to the largest trees known today - say 50K entries. (mozilla
131
is an example of this)
135
Eventually reuse dirstate objects across locks IFF the dirstate file has not
136
been modified, but will require that we flush/ignore cached stat-hit data
137
because we wont want to restat all files on disk just because a lock was
138
acquired, yet we cannot trust the data after the previous lock was released.
140
Memory representation:
141
vector of all directories, and vector of the childen ?
143
root_entrie = (direntry for root, [parent_direntries_for_root]),
145
('', ['data for achild', 'data for bchild', 'data for cchild'])
146
('dir', ['achild', 'cchild', 'echild'])
148
- single bisect to find N subtrees from a path spec
149
- in-order for serialisation - this is 'dirblock' grouping.
150
- insertion of a file '/a' affects only the '/' child-vector, that is, to
151
insert 10K elements from scratch does not generates O(N^2) memoves of a
152
single vector, rather each individual, which tends to be limited to a
153
manageable number. Will scale badly on trees with 10K entries in a
154
single directory. compare with Inventory.InventoryDirectory which has
155
a dictionary for the children. No bisect capability, can only probe for
156
exact matches, or grab all elements and sorta.
157
- Whats the risk of error here? Once we have the base format being processed
158
we should have a net win regardless of optimality. So we are going to
159
go with what seems reasonably.
162
maybe we should do a test profile of these core structure - 10K simulated searches/lookups/etc?
164
Objects for each row?
165
The lifetime of Dirstate objects is current per lock, but see above for
166
possible extensions. The lifetime of a row from a dirstate is expected to be
167
very short in the optimistic case: which we are optimising for. For instance,
168
subtree status will determine from analysis of the disk data what rows need to
169
be examined at all, and will be able to determine from a single row whether
170
that file has altered or not, so we are aiming to process tens of thousands of
171
entries each second within the dirstate context, before exposing anything to
172
the larger codebase. This suggests we want the time for a single file
173
comparison to be < 0.1 milliseconds. That would give us 10000 paths per second
174
processed, and to scale to 100 thousand we'll another order of magnitude to do
175
that. Now, as the lifetime for all unchanged entries is the time to parse, stat
176
the file on disk, and then immediately discard, the overhead of object creation
177
becomes a significant cost.
179
Figures: Creating a tuple from from 3 elements was profiled at 0.0625
180
microseconds, whereas creating a object which is subclassed from tuple was
181
0.500 microseconds, and creating an object with 3 elements and slots was 3
182
microseconds long. 0.1 milliseconds is 100 microseconds, and ideally we'll get
183
down to 10 microseconds for the total processing - having 33% of that be object
184
creation is a huge overhead. There is a potential cost in using tuples within
185
each row which is that the conditional code to do comparisons may be slower
186
than method invocation, but method invocation is known to be slow due to stack
187
frame creation, so avoiding methods in these tight inner loops in unfortunately
188
desirable. We can consider a pyrex version of this with objects in future if
200
from stat import S_IEXEC
212
from bzrlib.osutils import (
220
class _Bisector(object):
221
"""This just keeps track of information as we are bisecting."""
224
class DirState(object):
225
"""Record directory and metadata state for fast access.
227
A dirstate is a specialised data structure for managing local working
228
tree state information. Its not yet well defined whether it is platform
229
specific, and if it is how we detect/parameterise that.
232
_kind_to_minikind = {'absent':'a', 'file':'f', 'directory':'d', 'relocated':'r', 'symlink':'l'}
233
_minikind_to_kind = {'a':'absent', 'f':'file', 'd':'directory', 'l':'symlink', 'r':'relocated'}
234
_to_yesno = {True:'y', False: 'n'} # TODO profile the performance gain
235
# of using int conversion rather than a dict here. AND BLAME ANDREW IF
238
# TODO: jam 20070221 Make sure we handle when there are duplicated records
239
# (like when we remove + add the same path, or we have a rename)
240
# TODO: jam 20070221 Figure out what to do if we have a record that exceeds
241
# the BISECT_PAGE_SIZE. For now, we just have to make it large enough
242
# that we are sure a single record will always fit.
243
BISECT_PAGE_SIZE = 4096
246
IN_MEMORY_UNMODIFIED = 1
247
IN_MEMORY_MODIFIED = 2
249
# A pack_stat (the x's) that is just noise and will never match the output
252
NULL_PARENT_DETAILS = ('a', '', 0, False, '')
254
HEADER_FORMAT_2 = '#bazaar dirstate flat format 2\n'
255
HEADER_FORMAT_3 = '#bazaar dirstate flat format 3\n'
257
def __init__(self, path):
258
"""Create a DirState object.
262
:attr _root_entrie: The root row of the directory/file information,
263
- contains the path to / - '', ''
264
- kind of 'directory',
265
- the file id of the root in utf8
268
- and no sha information.
269
:param path: The path at which the dirstate file on disk should live.
271
# _header_state and _dirblock_state represent the current state
272
# of the dirstate metadata and the per-row data respectiely.
273
# NOT_IN_MEMORY indicates that no data is in memory
274
# IN_MEMORY_UNMODIFIED indicates that what we have in memory
275
# is the same as is on disk
276
# IN_MEMORY_MODIFIED indicates that we have a modified version
277
# of what is on disk.
278
# In future we will add more granularity, for instance _dirblock_state
279
# will probably support partially-in-memory as a separate variable,
280
# allowing for partially-in-memory unmodified and partially-in-memory
282
self._header_state = DirState.NOT_IN_MEMORY
283
self._dirblock_state = DirState.NOT_IN_MEMORY
287
self._state_file = None
288
self._filename = path
289
self._lock_token = None
290
self._lock_state = None
291
self._id_index = None
292
self._end_of_header = None
293
self._split_path_cache = {}
294
self._bisect_page_size = DirState.BISECT_PAGE_SIZE
296
def add(self, path, file_id, kind, stat, link_or_sha1):
297
"""Add a path to be tracked.
299
:param path: The path within the dirstate - '' is the root, 'foo' is the
300
path foo within the root, 'foo/bar' is the path bar within foo
302
:param file_id: The file id of the path being added.
303
:param kind: The kind of the path.
304
:param stat: The output of os.lstat for the path.
305
:param link_or_sha1: The sha value of the file, or the target of a
306
symlink. '' for directories.
309
# find the block its in.
310
# find the location in the block.
311
# check its not there
313
#------- copied from inventory.make_entry
314
# --- normalized_filename wants a unicode basename only, so get one.
315
dirname, basename = osutils.split(path)
316
# we dont import normalized_filename directly because we want to be
317
# able to change the implementation at runtime for tests.
318
norm_name, can_access = osutils.normalized_filename(basename)
319
if norm_name != basename:
323
raise errors.InvalidNormalization(path)
324
# now that we've normalised, we need the correct utf8 path and
325
# dirname and basename elements. This single encode and split should be
326
# faster than three separate encodes.
327
utf8path = (dirname + '/' + basename).strip('/').encode('utf8')
328
dirname, basename = osutils.split(utf8path)
329
assert file_id.__class__ == str, \
330
"must be a utf8 file_id not %s" % (type(file_id))
331
# Make sure the file_id does not exist in this tree
332
file_id_entry = self._get_entry(0, fileid_utf8=file_id)
333
if file_id_entry != (None, None):
334
path = osutils.pathjoin(file_id_entry[0][0], file_id_entry[0][1])
335
kind = DirState._minikind_to_kind[file_id_entry[1][0][0]]
336
info = '%s:%s' % (kind, path)
337
raise errors.DuplicateFileId(file_id, info)
338
first_key = (dirname, basename, '')
339
block_index, present = self._find_block_index_from_key(first_key)
341
# check the path is not in the tree
342
block = self._dirblocks[block_index][1]
343
entry_index, _ = self._find_entry_index(first_key, block)
344
while (entry_index < len(block) and
345
block[entry_index][0][0:2] == first_key[0:2]):
346
if block[entry_index][1][0][0] not in 'ar':
347
# this path is in the dirstate in the current tree.
348
raise Exception, "adding already added path!"
351
# The block where we want to put the file is not present. But it
352
# might be because the directory was empty, or not loaded yet. Look
353
# for a parent entry, if not found, raise NotVersionedError
354
parent_dir, parent_base = osutils.split(dirname)
355
parent_block_idx, parent_entry_idx, _, parent_present = \
356
self._get_block_entry_index(parent_dir, parent_base, 0)
357
if not parent_present:
358
raise errors.NotVersionedError(path, str(self))
359
self._ensure_block(parent_block_idx, parent_entry_idx, dirname)
360
block = self._dirblocks[block_index][1]
361
entry_key = (dirname, basename, file_id)
364
packed_stat = DirState.NULLSTAT
367
packed_stat = pack_stat(stat)
368
parent_info = self._empty_parent_info()
369
minikind = DirState._kind_to_minikind[kind]
371
entry_data = entry_key, [
372
(minikind, link_or_sha1, size, False, packed_stat),
374
elif kind == 'directory':
375
entry_data = entry_key, [
376
(minikind, '', 0, False, packed_stat),
378
elif kind == 'symlink':
379
entry_data = entry_key, [
380
(minikind, link_or_sha1, size, False, packed_stat),
383
raise errors.BzrError('unknown kind %r' % kind)
384
entry_index, present = self._find_entry_index(entry_key, block)
385
assert not present, "basename %r already added" % basename
386
block.insert(entry_index, entry_data)
388
if kind == 'directory':
389
# insert a new dirblock
390
self._ensure_block(block_index, entry_index, utf8path)
391
self._dirblock_state = DirState.IN_MEMORY_MODIFIED
393
self._id_index.setdefault(entry_key[2], set()).add(entry_key)
395
def _bisect(self, dir_name_list):
396
"""Bisect through the disk structure for specific rows.
398
:param dir_name_list: A list of (dir, name) pairs.
399
:return: A dict mapping (dir, name) => entry for found entries. Missing
400
entries will not be in the map.
402
self._requires_lock()
403
# We need the file pointer to be right after the initial header block
404
self._read_header_if_needed()
405
# If _dirblock_state was in memory, we should just return info from
406
# there, this function is only meant to handle when we want to read
408
assert self._dirblock_state == DirState.NOT_IN_MEMORY
410
# The disk representation is generally info + '\0\n\0' at the end. But
411
# for bisecting, it is easier to treat this as '\0' + info + '\0\n'
412
# Because it means we can sync on the '\n'
413
state_file = self._state_file
414
file_size = os.fstat(state_file.fileno()).st_size
415
# We end up with 2 extra fields, we should have a trailing '\n' to
416
# ensure that we read the whole record, and we should have a precursur
417
# '' which ensures that we start after the previous '\n'
418
entry_field_count = self._fields_per_entry() + 1
420
low = self._end_of_header
421
high = file_size - 1 # Ignore the final '\0'
422
# Map from (dir, name) => entry
425
# Avoid infinite seeking
426
max_count = 30*len(dir_name_list)
428
# pending is a list of places to look.
429
# each entry is a tuple of low, high, dir_names
430
# low -> the first byte offset to read (inclusive)
431
# high -> the last byte offset (inclusive)
432
# dir_names -> The list of (dir, name) pairs that should be found in
433
# the [low, high] range
434
pending = [(low, high, dir_name_list)]
436
page_size = self._bisect_page_size
438
fields_to_entry = self._get_fields_to_entry()
441
low, high, cur_files = pending.pop()
443
if not cur_files or low >= high:
448
if count > max_count:
449
raise errors.BzrError('Too many seeks, most likely a bug.')
451
mid = max(low, (low+high-page_size)/2)
454
# limit the read size, so we don't end up reading data that we have
456
read_size = min(page_size, (high-mid)+1)
457
block = state_file.read(read_size)
460
entries = block.split('\n')
463
# We didn't find a '\n', so we cannot have found any records.
464
# So put this range back and try again. But we know we have to
465
# increase the page size, because a single read did not contain
466
# a record break (so records must be larger than page_size)
468
pending.append((low, high, cur_files))
471
# Check the first and last entries, in case they are partial, or if
472
# we don't care about the rest of this page
474
first_fields = entries[0].split('\0')
475
if len(first_fields) < entry_field_count:
476
# We didn't get the complete first entry
477
# so move start, and grab the next, which
478
# should be a full entry
479
start += len(entries[0])+1
480
first_fields = entries[1].split('\0')
483
if len(first_fields) <= 2:
484
# We didn't even get a filename here... what do we do?
485
# Try a large page size and repeat this query
487
pending.append((low, high, cur_files))
490
# Find what entries we are looking for, which occur before and
491
# after this first record.
493
first_dir_name = (first_fields[1], first_fields[2])
494
first_loc = bisect.bisect_left(cur_files, first_dir_name)
496
# These exist before the current location
497
pre = cur_files[:first_loc]
498
# These occur after the current location, which may be in the
499
# data we read, or might be after the last entry
500
post = cur_files[first_loc:]
502
if post and len(first_fields) >= entry_field_count:
503
# We have files after the first entry
505
# Parse the last entry
506
last_entry_num = len(entries)-1
507
last_fields = entries[last_entry_num].split('\0')
508
if len(last_fields) < entry_field_count:
509
# The very last hunk was not complete,
510
# read the previous hunk
511
after = mid + len(block) - len(entries[-1])
513
last_fields = entries[last_entry_num].split('\0')
515
after = mid + len(block)
517
last_dir_name = (last_fields[1], last_fields[2])
518
last_loc = bisect.bisect_right(post, last_dir_name)
520
middle_files = post[:last_loc]
521
post = post[last_loc:]
524
# We have files that should occur in this block
525
# (>= first, <= last)
526
# Either we will find them here, or we can mark them as
529
if middle_files[0] == first_dir_name:
530
# We might need to go before this location
531
pre.append(first_dir_name)
532
if middle_files[-1] == last_dir_name:
533
post.insert(0, last_dir_name)
535
# Find out what paths we have
536
paths = {first_dir_name:[first_fields]}
537
# last_dir_name might == first_dir_name so we need to be
538
# careful if we should append rather than overwrite
539
if last_entry_num != first_entry_num:
540
paths.setdefault(last_dir_name, []).append(last_fields)
541
for num in xrange(first_entry_num+1, last_entry_num):
542
# TODO: jam 20070223 We are already splitting here, so
543
# shouldn't we just split the whole thing rather
544
# than doing the split again in add_one_record?
545
fields = entries[num].split('\0')
546
dir_name = (fields[1], fields[2])
547
paths.setdefault(dir_name, []).append(fields)
549
for dir_name in middle_files:
550
for fields in paths.get(dir_name, []):
551
# offset by 1 because of the opening '\0'
552
# consider changing fields_to_entry to avoid the
554
entry = fields_to_entry(fields[1:])
555
found.setdefault(dir_name, []).append(entry)
557
# Now we have split up everything into pre, middle, and post, and
558
# we have handled everything that fell in 'middle'.
559
# We add 'post' first, so that we prefer to seek towards the
560
# beginning, so that we will tend to go as early as we need, and
561
# then only seek forward after that.
563
pending.append((after, high, post))
565
pending.append((low, start-1, pre))
567
# Consider that we may want to return the directory entries in sorted
568
# order. For now, we just return them in whatever order we found them,
569
# and leave it up to the caller if they care if it is ordered or not.
572
def _bisect_dirblocks(self, dir_list):
573
"""Bisect through the disk structure to find entries in given dirs.
575
_bisect_dirblocks is meant to find the contents of directories, which
576
differs from _bisect, which only finds individual entries.
578
:param dir_list: An sorted list of directory names ['', 'dir', 'foo'].
579
:return: A map from dir => entries_for_dir
581
# TODO: jam 20070223 A lot of the bisecting logic could be shared
582
# between this and _bisect. It would require parameterizing the
583
# inner loop with a function, though. We should evaluate the
584
# performance difference.
585
self._requires_lock()
586
# We need the file pointer to be right after the initial header block
587
self._read_header_if_needed()
588
# If _dirblock_state was in memory, we should just return info from
589
# there, this function is only meant to handle when we want to read
591
assert self._dirblock_state == DirState.NOT_IN_MEMORY
593
# The disk representation is generally info + '\0\n\0' at the end. But
594
# for bisecting, it is easier to treat this as '\0' + info + '\0\n'
595
# Because it means we can sync on the '\n'
596
state_file = self._state_file
597
file_size = os.fstat(state_file.fileno()).st_size
598
# We end up with 2 extra fields, we should have a trailing '\n' to
599
# ensure that we read the whole record, and we should have a precursur
600
# '' which ensures that we start after the previous '\n'
601
entry_field_count = self._fields_per_entry() + 1
603
low = self._end_of_header
604
high = file_size - 1 # Ignore the final '\0'
605
# Map from dir => entry
608
# Avoid infinite seeking
609
max_count = 30*len(dir_list)
611
# pending is a list of places to look.
612
# each entry is a tuple of low, high, dir_names
613
# low -> the first byte offset to read (inclusive)
614
# high -> the last byte offset (inclusive)
615
# dirs -> The list of directories that should be found in
616
# the [low, high] range
617
pending = [(low, high, dir_list)]
619
page_size = self._bisect_page_size
621
fields_to_entry = self._get_fields_to_entry()
624
low, high, cur_dirs = pending.pop()
626
if not cur_dirs or low >= high:
631
if count > max_count:
632
raise errors.BzrError('Too many seeks, most likely a bug.')
634
mid = max(low, (low+high-page_size)/2)
637
# limit the read size, so we don't end up reading data that we have
639
read_size = min(page_size, (high-mid)+1)
640
block = state_file.read(read_size)
643
entries = block.split('\n')
646
# We didn't find a '\n', so we cannot have found any records.
647
# So put this range back and try again. But we know we have to
648
# increase the page size, because a single read did not contain
649
# a record break (so records must be larger than page_size)
651
pending.append((low, high, cur_dirs))
654
# Check the first and last entries, in case they are partial, or if
655
# we don't care about the rest of this page
657
first_fields = entries[0].split('\0')
658
if len(first_fields) < entry_field_count:
659
# We didn't get the complete first entry
660
# so move start, and grab the next, which
661
# should be a full entry
662
start += len(entries[0])+1
663
first_fields = entries[1].split('\0')
666
if len(first_fields) <= 1:
667
# We didn't even get a dirname here... what do we do?
668
# Try a large page size and repeat this query
670
pending.append((low, high, cur_dirs))
673
# Find what entries we are looking for, which occur before and
674
# after this first record.
676
first_dir = first_fields[1]
677
first_loc = bisect.bisect_left(cur_dirs, first_dir)
679
# These exist before the current location
680
pre = cur_dirs[:first_loc]
681
# These occur after the current location, which may be in the
682
# data we read, or might be after the last entry
683
post = cur_dirs[first_loc:]
685
if post and len(first_fields) >= entry_field_count:
686
# We have records to look at after the first entry
688
# Parse the last entry
689
last_entry_num = len(entries)-1
690
last_fields = entries[last_entry_num].split('\0')
691
if len(last_fields) < entry_field_count:
692
# The very last hunk was not complete,
693
# read the previous hunk
694
after = mid + len(block) - len(entries[-1])
696
last_fields = entries[last_entry_num].split('\0')
698
after = mid + len(block)
700
last_dir = last_fields[1]
701
last_loc = bisect.bisect_right(post, last_dir)
703
middle_files = post[:last_loc]
704
post = post[last_loc:]
707
# We have files that should occur in this block
708
# (>= first, <= last)
709
# Either we will find them here, or we can mark them as
712
if middle_files[0] == first_dir:
713
# We might need to go before this location
714
pre.append(first_dir)
715
if middle_files[-1] == last_dir:
716
post.insert(0, last_dir)
718
# Find out what paths we have
719
paths = {first_dir:[first_fields]}
720
# last_dir might == first_dir so we need to be
721
# careful if we should append rather than overwrite
722
if last_entry_num != first_entry_num:
723
paths.setdefault(last_dir, []).append(last_fields)
724
for num in xrange(first_entry_num+1, last_entry_num):
725
# TODO: jam 20070223 We are already splitting here, so
726
# shouldn't we just split the whole thing rather
727
# than doing the split again in add_one_record?
728
fields = entries[num].split('\0')
729
paths.setdefault(fields[1], []).append(fields)
731
for cur_dir in middle_files:
732
for fields in paths.get(cur_dir, []):
733
# offset by 1 because of the opening '\0'
734
# consider changing fields_to_entry to avoid the
736
entry = fields_to_entry(fields[1:])
737
found.setdefault(cur_dir, []).append(entry)
739
# Now we have split up everything into pre, middle, and post, and
740
# we have handled everything that fell in 'middle'.
741
# We add 'post' first, so that we prefer to seek towards the
742
# beginning, so that we will tend to go as early as we need, and
743
# then only seek forward after that.
745
pending.append((after, high, post))
747
pending.append((low, start-1, pre))
751
def _bisect_recursive(self, dir_name_list):
752
"""Bisect for entries for all paths and their children.
754
This will use bisect to find all records for the supplied paths. It
755
will then continue to bisect for any records which are marked as
756
directories. (and renames?)
758
:param paths: A sorted list of (dir, name) pairs
759
eg: [('', 'a'), ('', 'f'), ('a/b', 'c')]
760
:return: A dictionary mapping (dir, name, file_id) => [tree_info]
762
# Map from (dir, name, file_id) => [tree_info]
765
found_dir_names = set()
767
# Directories that have been read
768
processed_dirs = set()
769
# Get the ball rolling with the first bisect for all entries.
770
newly_found = self._bisect(dir_name_list)
773
# Directories that need to be read
775
paths_to_search = set()
776
for entry_list in newly_found.itervalues():
777
for dir_name_id, trees_info in entry_list:
778
found[dir_name_id] = trees_info
779
found_dir_names.add(dir_name_id[:2])
781
for tree_info in trees_info:
782
minikind = tree_info[0]
785
# We already processed this one as a directory,
786
# we don't need to do the extra work again.
788
subdir, name, file_id = dir_name_id
789
path = osutils.pathjoin(subdir, name)
791
if path not in processed_dirs:
792
pending_dirs.add(path)
793
elif minikind == 'r':
794
# Rename, we need to directly search the target
795
# which is contained in the fingerprint column
796
dir_name = osutils.split(tree_info[1])
797
if dir_name[0] in pending_dirs:
798
# This entry will be found in the dir search
800
# TODO: We need to check if this entry has
801
# already been found. Otherwise we might be
802
# hitting infinite recursion.
803
if dir_name not in found_dir_names:
804
paths_to_search.add(dir_name)
805
# Now we have a list of paths to look for directly, and
806
# directory blocks that need to be read.
807
# newly_found is mixing the keys between (dir, name) and path
808
# entries, but that is okay, because we only really care about the
810
newly_found = self._bisect(sorted(paths_to_search))
811
newly_found.update(self._bisect_dirblocks(sorted(pending_dirs)))
812
processed_dirs.update(pending_dirs)
815
def _empty_parent_info(self):
816
return [DirState.NULL_PARENT_DETAILS] * (len(self._parents) -
819
def _ensure_block(self, parent_block_index, parent_row_index, dirname):
820
"""Ensure a block for dirname exists.
822
This function exists to let callers which know that there is a
823
directory dirname ensure that the block for it exists. This block can
824
fail to exist because of demand loading, or because a directory had no
825
children. In either case it is not an error. It is however an error to
826
call this if there is no parent entry for the directory, and thus the
827
function requires the coordinates of such an entry to be provided.
829
The root row is special cased and can be indicated with a parent block
832
:param parent_block_index: The index of the block in which dirname's row
834
:param parent_row_index: The index in the parent block where the row
836
:param dirname: The utf8 dirname to ensure there is a block for.
837
:return: The index for the block.
839
if dirname == '' and parent_row_index == 0 and parent_block_index == 0:
840
# This is the signature of the root row, and the
841
# contents-of-root row is always index 1
843
# the basename of the directory must be the end of its full name.
844
if not (parent_block_index == -1 and
845
parent_block_index == -1 and dirname == ''):
846
assert dirname.endswith(
847
self._dirblocks[parent_block_index][1][parent_row_index][0][1])
848
block_index, present = self._find_block_index_from_key((dirname, '', ''))
850
## In future, when doing partial parsing, this should load and
851
# populate the entire block.
852
self._dirblocks.insert(block_index, (dirname, []))
855
def _entries_to_current_state(self, new_entries):
856
"""Load new_entries into self.dirblocks.
858
Process new_entries into the current state object, making them the active
861
:param new_entries: A sorted list of entries. This function does not sort
862
to prevent unneeded overhead when callers have a sorted list already.
865
assert new_entries[0][0][0:2] == ('', ''), \
866
"Missing root row %r" % (new_entries[0][0],)
867
# The two blocks here are deliberate: the root block and the
868
# contents-of-root block.
869
self._dirblocks = [('', []), ('', [])]
870
current_block = self._dirblocks[0][1]
873
append_entry = current_block.append
874
for entry in new_entries:
875
if entry[0][0] != current_dirname:
876
# new block - different dirname
878
current_dirname = entry[0][0]
879
self._dirblocks.append((current_dirname, current_block))
880
append_entry = current_block.append
881
# append the entry to the current block
883
self._split_root_dirblock_into_contents()
885
def _split_root_dirblock_into_contents(self):
886
"""Split the root dirblocks into root and contents-of-root.
888
After parsing by path, we end up with root entries and contents-of-root
889
entries in the same block. This loop splits them out again.
891
# The above loop leaves the "root block" entries mixed with the
892
# "contents-of-root block". But we don't want an if check on
893
# all entries, so instead we just fix it up here.
894
assert self._dirblocks[1] == ('', [])
896
contents_of_root_block = []
897
for entry in self._dirblocks[0][1]:
898
if not entry[0][1]: # This is a root entry
899
root_block.append(entry)
901
contents_of_root_block.append(entry)
902
self._dirblocks[0] = ('', root_block)
903
self._dirblocks[1] = ('', contents_of_root_block)
905
def _entry_to_line(self, entry):
906
"""Serialize entry to a NULL delimited line ready for _get_output_lines.
908
:param entry: An entry_tuple as defined in the module docstring.
910
entire_entry = list(entry[0])
911
for tree_number, tree_data in enumerate(entry[1]):
912
# (minikind, fingerprint, size, executable, tree_specific_string)
913
entire_entry.extend(tree_data)
914
# 3 for the key, 5 for the fields per tree.
915
tree_offset = 3 + tree_number * 5
917
entire_entry[tree_offset + 0] = tree_data[0]
919
entire_entry[tree_offset + 2] = str(tree_data[2])
921
entire_entry[tree_offset + 3] = DirState._to_yesno[tree_data[3]]
922
return '\0'.join(entire_entry)
924
def _fields_per_entry(self):
925
"""How many null separated fields should be in each entry row.
927
Each line now has an extra '\n' field which is not used
928
so we just skip over it
931
+ number of fields per tree_data (5) * tree count
934
tree_count = 1 + self._num_present_parents()
935
return 3 + 5 * tree_count + 1
937
def _find_block(self, key, add_if_missing=False):
938
"""Return the block that key should be present in.
940
:param key: A dirstate entry key.
941
:return: The block tuple.
943
block_index, present = self._find_block_index_from_key(key)
945
if not add_if_missing:
946
# check to see if key is versioned itself - we might want to
947
# add it anyway, because dirs with no entries dont get a
948
# dirblock at parse time.
949
# This is an uncommon branch to take: most dirs have children,
950
# and most code works with versioned paths.
951
parent_base, parent_name = osutils.split(key[0])
952
if not self._get_block_entry_index(parent_base, parent_name, 0)[3]:
953
# some parent path has not been added - its an error to add
955
raise errors.NotVersionedError(key[0:2], str(self))
956
self._dirblocks.insert(block_index, (key[0], []))
957
return self._dirblocks[block_index]
959
def _find_block_index_from_key(self, key):
960
"""Find the dirblock index for a key.
962
:return: The block index, True if the block for the key is present.
964
if key[0:2] == ('', ''):
966
block_index = bisect_dirblock(self._dirblocks, key[0], 1,
967
cache=self._split_path_cache)
968
# _right returns one-past-where-key is so we have to subtract
969
# one to use it. we use _right here because there are two
970
# '' blocks - the root, and the contents of root
971
# we always have a minimum of 2 in self._dirblocks: root and
972
# root-contents, and for '', we get 2 back, so this is
973
# simple and correct:
974
present = (block_index < len(self._dirblocks) and
975
self._dirblocks[block_index][0] == key[0])
976
return block_index, present
978
def _find_entry_index(self, key, block):
979
"""Find the entry index for a key in a block.
981
:return: The entry index, True if the entry for the key is present.
983
entry_index = bisect.bisect_left(block, (key, []))
984
present = (entry_index < len(block) and
985
block[entry_index][0] == key)
986
return entry_index, present
989
def from_tree(tree, dir_state_filename):
990
"""Create a dirstate from a bzr Tree.
992
:param tree: The tree which should provide parent information and
994
:return: a DirState object which is currently locked for writing.
995
(it was locked by DirState.initialize)
997
result = DirState.initialize(dir_state_filename)
1001
parent_ids = tree.get_parent_ids()
1002
num_parents = len(parent_ids)
1004
for parent_id in parent_ids:
1005
parent_tree = tree.branch.repository.revision_tree(parent_id)
1006
parent_trees.append((parent_id, parent_tree))
1007
parent_tree.lock_read()
1008
result.set_parent_trees(parent_trees, [])
1009
result.set_state_from_inventory(tree.inventory)
1011
for revid, parent_tree in parent_trees:
1012
parent_tree.unlock()
1015
# The caller won't have a chance to unlock this, so make sure we
1021
def update_entry(self, entry, abspath, stat_value=None):
1022
"""Update the entry based on what is actually on disk.
1024
:param entry: This is the dirblock entry for the file in question.
1025
:param abspath: The path on disk for this file.
1026
:param stat_value: (optional) if we already have done a stat on the
1028
:return: The sha1 hexdigest of the file (40 bytes) or link target of a
1031
# This code assumes that the entry passed in is directly held in one of
1032
# the internal _dirblocks. So the dirblock state must have already been
1034
assert self._dirblock_state != DirState.NOT_IN_MEMORY
1035
if stat_value is None:
1037
# We could inline os.lstat but the common case is that
1038
# stat_value will be passed in, not read here.
1039
stat_value = self._lstat(abspath, entry)
1040
except (OSError, IOError), e:
1041
if e.errno in (errno.ENOENT, errno.EACCES,
1043
# The entry is missing, consider it gone
1047
kind = osutils.file_kind_from_stat_mode(stat_value.st_mode)
1049
minikind = DirState._kind_to_minikind[kind]
1050
except KeyError: # Unknown kind
1052
packed_stat = pack_stat(stat_value)
1053
(saved_minikind, saved_link_or_sha1, saved_file_size,
1054
saved_executable, saved_packed_stat) = entry[1][0]
1056
if (minikind == saved_minikind
1057
and packed_stat == saved_packed_stat
1058
# size should also be in packed_stat
1059
and saved_file_size == stat_value.st_size):
1060
# The stat hasn't changed since we saved, so we can potentially
1061
# re-use the saved sha hash.
1065
cutoff = self._sha_cutoff_time()
1066
if (stat_value.st_mtime < cutoff
1067
and stat_value.st_ctime < cutoff):
1068
# Return the existing fingerprint
1069
return saved_link_or_sha1
1071
# If we have gotten this far, that means that we need to actually
1072
# process this entry.
1075
link_or_sha1 = self._sha1_file(abspath, entry)
1076
executable = self._is_executable(stat_value.st_mode,
1078
entry[1][0] = ('f', link_or_sha1, stat_value.st_size,
1079
executable, packed_stat)
1080
elif minikind == 'd':
1082
entry[1][0] = ('d', '', 0, False, packed_stat)
1083
if saved_minikind != 'd':
1084
# This changed from something into a directory. Make sure we
1085
# have a directory block for it. This doesn't happen very
1086
# often, so this doesn't have to be super fast.
1087
block_index, entry_index, dir_present, file_present = \
1088
self._get_block_entry_index(entry[0][0], entry[0][1], 0)
1089
self._ensure_block(block_index, entry_index,
1090
osutils.pathjoin(entry[0][0], entry[0][1]))
1091
elif minikind == 'l':
1092
link_or_sha1 = self._read_link(abspath, saved_link_or_sha1)
1093
entry[1][0] = ('l', link_or_sha1, stat_value.st_size,
1095
self._dirblock_state = DirState.IN_MEMORY_MODIFIED
1098
def _sha_cutoff_time(self):
1099
"""Return cutoff time.
1101
Files modified more recently than this time are at risk of being
1102
undetectably modified and so can't be cached.
1104
# TODO: jam 20070301 Cache the cutoff time as long as we hold a lock.
1105
# time.time() isn't super expensive (approx 3.38us), but
1106
# when you call it 50,000 times it adds up.
1107
# For comparison, os.lstat() costs 7.2us if it is hot.
1108
return int(time.time()) - 3
1110
def _lstat(self, abspath, entry):
1111
"""Return the os.lstat value for this path."""
1112
return os.lstat(abspath)
1114
def _sha1_file(self, abspath, entry):
1115
"""Calculate the SHA1 of a file by reading the full text"""
1116
f = file(abspath, 'rb', buffering=65000)
1118
return osutils.sha_file(f)
1122
def _is_executable(self, mode, old_executable):
1123
"""Is this file executable?"""
1124
# TODO: jam 20070301 Win32 should just return the original value
1125
return bool(S_IEXEC & mode)
1127
def _read_link(self, abspath, old_link):
1128
"""Read the target of a symlink"""
1129
# TODO: jam 200700301 On Win32, this could just return the value
1130
# already in memory.
1131
return os.readlink(abspath)
1133
def get_ghosts(self):
1134
"""Return a list of the parent tree revision ids that are ghosts."""
1135
self._read_header_if_needed()
1138
def get_lines(self):
1139
"""Serialise the entire dirstate to a sequence of lines."""
1140
if (self._header_state == DirState.IN_MEMORY_UNMODIFIED and
1141
self._dirblock_state == DirState.IN_MEMORY_UNMODIFIED):
1142
# read whats on disk.
1143
self._state_file.seek(0)
1144
return self._state_file.readlines()
1146
lines.append(self._get_parents_line(self.get_parent_ids()))
1147
lines.append(self._get_ghosts_line(self._ghosts))
1148
# append the root line which is special cased
1149
lines.extend(map(self._entry_to_line, self._iter_entries()))
1150
return self._get_output_lines(lines)
1152
def _get_ghosts_line(self, ghost_ids):
1153
"""Create a line for the state file for ghost information."""
1154
return '\0'.join([str(len(ghost_ids))] + ghost_ids)
1156
def _get_parents_line(self, parent_ids):
1157
"""Create a line for the state file for parents information."""
1158
return '\0'.join([str(len(parent_ids))] + parent_ids)
1160
def _get_fields_to_entry(self):
1161
"""Get a function which converts entry fields into a entry record.
1163
This handles size and executable, as well as parent records.
1165
:return: A function which takes a list of fields, and returns an
1166
appropriate record for storing in memory.
1168
# This is intentionally unrolled for performance
1169
num_present_parents = self._num_present_parents()
1170
if num_present_parents == 0:
1171
def fields_to_entry_0_parents(fields, _int=int):
1172
path_name_file_id_key = (fields[0], fields[1], fields[2])
1173
return (path_name_file_id_key, [
1175
fields[3], # minikind
1176
fields[4], # fingerprint
1177
_int(fields[5]), # size
1178
fields[6] == 'y', # executable
1179
fields[7], # packed_stat or revision_id
1181
return fields_to_entry_0_parents
1182
elif num_present_parents == 1:
1183
def fields_to_entry_1_parent(fields, _int=int):
1184
path_name_file_id_key = (fields[0], fields[1], fields[2])
1185
return (path_name_file_id_key, [
1187
fields[3], # minikind
1188
fields[4], # fingerprint
1189
_int(fields[5]), # size
1190
fields[6] == 'y', # executable
1191
fields[7], # packed_stat or revision_id
1194
fields[8], # minikind
1195
fields[9], # fingerprint
1196
_int(fields[10]), # size
1197
fields[11] == 'y', # executable
1198
fields[12], # packed_stat or revision_id
1201
return fields_to_entry_1_parent
1202
elif num_present_parents == 2:
1203
def fields_to_entry_2_parents(fields, _int=int):
1204
path_name_file_id_key = (fields[0], fields[1], fields[2])
1205
return (path_name_file_id_key, [
1207
fields[3], # minikind
1208
fields[4], # fingerprint
1209
_int(fields[5]), # size
1210
fields[6] == 'y', # executable
1211
fields[7], # packed_stat or revision_id
1214
fields[8], # minikind
1215
fields[9], # fingerprint
1216
_int(fields[10]), # size
1217
fields[11] == 'y', # executable
1218
fields[12], # packed_stat or revision_id
1221
fields[13], # minikind
1222
fields[14], # fingerprint
1223
_int(fields[15]), # size
1224
fields[16] == 'y', # executable
1225
fields[17], # packed_stat or revision_id
1228
return fields_to_entry_2_parents
1230
def fields_to_entry_n_parents(fields, _int=int):
1231
path_name_file_id_key = (fields[0], fields[1], fields[2])
1232
trees = [(fields[cur], # minikind
1233
fields[cur+1], # fingerprint
1234
_int(fields[cur+2]), # size
1235
fields[cur+3] == 'y', # executable
1236
fields[cur+4], # stat or revision_id
1237
) for cur in xrange(3, len(fields)-1, 5)]
1238
return path_name_file_id_key, trees
1239
return fields_to_entry_n_parents
1241
def get_parent_ids(self):
1242
"""Return a list of the parent tree ids for the directory state."""
1243
self._read_header_if_needed()
1244
return list(self._parents)
1246
def _get_block_entry_index(self, dirname, basename, tree_index):
1247
"""Get the coordinates for a path in the state structure.
1249
:param dirname: The utf8 dirname to lookup.
1250
:param basename: The utf8 basename to lookup.
1251
:param tree_index: The index of the tree for which this lookup should
1253
:return: A tuple describing where the path is located, or should be
1254
inserted. The tuple contains four fields: the block index, the row
1255
index, anda two booleans are True when the directory is present, and
1256
when the entire path is present. There is no guarantee that either
1257
coordinate is currently reachable unless the found field for it is
1258
True. For instance, a directory not present in the searched tree
1259
may be returned with a value one greater than the current highest
1260
block offset. The directory present field will always be True when
1261
the path present field is True. The directory present field does
1262
NOT indicate that the directory is present in the searched tree,
1263
rather it indicates that there are at least some files in some
1266
self._read_dirblocks_if_needed()
1267
key = dirname, basename, ''
1268
block_index, present = self._find_block_index_from_key(key)
1270
# no such directory - return the dir index and 0 for the row.
1271
return block_index, 0, False, False
1272
block = self._dirblocks[block_index][1] # access the entries only
1273
entry_index, present = self._find_entry_index(key, block)
1274
# linear search through present entries at this path to find the one
1276
while entry_index < len(block) and block[entry_index][0][1] == basename:
1277
if block[entry_index][1][tree_index][0] not in \
1278
('a', 'r'): # absent, relocated
1279
return block_index, entry_index, True, True
1281
return block_index, entry_index, True, False
1283
def _get_entry(self, tree_index, fileid_utf8=None, path_utf8=None):
1284
"""Get the dirstate entry for path in tree tree_index
1286
If either file_id or path is supplied, it is used as the key to lookup.
1287
If both are supplied, the fastest lookup is used, and an error is
1288
raised if they do not both point at the same row.
1290
:param tree_index: The index of the tree we wish to locate this path
1291
in. If the path is present in that tree, the entry containing its
1292
details is returned, otherwise (None, None) is returned
1293
:param fileid_utf8: A utf8 file_id to look up.
1294
:param path_utf8: An utf8 path to be looked up.
1295
:return: The dirstate entry tuple for path, or (None, None)
1297
self._read_dirblocks_if_needed()
1298
if path_utf8 is not None:
1299
assert path_utf8.__class__ == str, 'path_utf8 is not a str: %s %s' % (type(path_utf8), path_utf8)
1300
# path lookups are faster
1301
dirname, basename = osutils.split(path_utf8)
1302
block_index, entry_index, dir_present, file_present = \
1303
self._get_block_entry_index(dirname, basename, tree_index)
1304
if not file_present:
1306
entry = self._dirblocks[block_index][1][entry_index]
1307
assert entry[0][2] and entry[1][tree_index][0] not in ('a', 'r'), 'unversioned entry?!?!'
1309
if entry[0][2] != fileid_utf8:
1310
raise errors.BzrError('integrity error ? : mismatching'
1311
' tree_index, file_id and path')
1314
assert fileid_utf8 is not None
1315
possible_keys = self._get_id_index().get(fileid_utf8, None)
1316
if not possible_keys:
1318
for key in possible_keys:
1319
block_index, present = \
1320
self._find_block_index_from_key(key)
1321
# strange, probably indicates an out of date
1322
# id index - for now, allow this.
1325
# WARNING: DO not change this code to use _get_block_entry_index
1326
# as that function is not suitable: it does not use the key
1327
# to lookup, and thus the wront coordinates are returned.
1328
block = self._dirblocks[block_index][1]
1329
entry_index, present = self._find_entry_index(key, block)
1331
entry = self._dirblocks[block_index][1][entry_index]
1332
if entry[1][tree_index][0] in 'fdl':
1333
# this is the result we are looking for: the
1334
# real home of this file_id in this tree.
1336
if entry[1][tree_index][0] == 'a':
1337
# there is no home for this entry in this tree
1339
assert entry[1][tree_index][0] == 'r'
1340
real_path = entry[1][tree_index][1]
1341
return self._get_entry(tree_index, fileid_utf8=fileid_utf8,
1342
path_utf8=real_path)
1346
def initialize(cls, path):
1347
"""Create a new dirstate on path.
1349
The new dirstate will be an empty tree - that is it has no parents,
1350
and only a root node - which has id ROOT_ID.
1352
The object will be write locked when returned to the caller,
1353
unless there was an exception in the writing, in which case it
1356
:param path: The name of the file for the dirstate.
1357
:return: A DirState object.
1359
# This constructs a new DirState object on a path, sets the _state_file
1360
# to a new empty file for that path. It then calls _set_data() with our
1361
# stock empty dirstate information - a root with ROOT_ID, no children,
1362
# and no parents. Finally it calls save() to ensure that this data will
1365
# root dir and root dir contents with no children.
1366
empty_tree_dirblocks = [('', []), ('', [])]
1367
# a new root directory, with a NULLSTAT.
1368
empty_tree_dirblocks[0][1].append(
1369
(('', '', inventory.ROOT_ID), [
1370
('d', '', 0, False, DirState.NULLSTAT),
1374
result._set_data([], empty_tree_dirblocks)
1381
def _inv_entry_to_details(self, inv_entry):
1382
"""Convert an inventory entry (from a revision tree) to state details.
1384
:param inv_entry: An inventory entry whose sha1 and link targets can be
1385
relied upon, and which has a revision set.
1386
:return: A details tuple - the details for a single tree at a path +
1389
kind = inv_entry.kind
1390
minikind = DirState._kind_to_minikind[kind]
1391
tree_data = inv_entry.revision
1392
assert len(tree_data) > 0, 'empty revision for the inv_entry.'
1393
if kind == 'directory':
1397
elif kind == 'symlink':
1398
fingerprint = inv_entry.symlink_target or ''
1401
elif kind == 'file':
1402
fingerprint = inv_entry.text_sha1 or ''
1403
size = inv_entry.text_size or 0
1404
executable = inv_entry.executable
1407
return (minikind, fingerprint, size, executable, tree_data)
1409
def _iter_entries(self):
1410
"""Iterate over all the entries in the dirstate.
1412
Each yelt item is an entry in the standard format described in the
1413
docstring of bzrlib.dirstate.
1415
self._read_dirblocks_if_needed()
1416
for directory in self._dirblocks:
1417
for entry in directory[1]:
1420
def _get_id_index(self):
1421
"""Get an id index of self._dirblocks."""
1422
if self._id_index is None:
1424
for key, tree_details in self._iter_entries():
1425
id_index.setdefault(key[2], set()).add(key)
1426
self._id_index = id_index
1427
return self._id_index
1429
def _get_output_lines(self, lines):
1430
"""format lines for final output.
1432
:param lines: A sequece of lines containing the parents list and the
1435
output_lines = [DirState.HEADER_FORMAT_3]
1436
lines.append('') # a final newline
1437
inventory_text = '\0\n\0'.join(lines)
1438
output_lines.append('adler32: %s\n' % (zlib.adler32(inventory_text),))
1439
# -3, 1 for num parents, 1 for ghosts, 1 for final newline
1440
num_entries = len(lines)-3
1441
output_lines.append('num_entries: %s\n' % (num_entries,))
1442
output_lines.append(inventory_text)
1445
def _make_deleted_row(self, fileid_utf8, parents):
1446
"""Return a deleted for for fileid_utf8."""
1447
return ('/', 'RECYCLED.BIN', 'file', fileid_utf8, 0, DirState.NULLSTAT,
1450
def _num_present_parents(self):
1451
"""The number of parent entries in each record row."""
1452
return len(self._parents) - len(self._ghosts)
1456
"""Construct a DirState on the file at path path.
1458
:return: An unlocked DirState object, associated with the given path.
1460
result = DirState(path)
1463
def _read_dirblocks_if_needed(self):
1464
"""Read in all the dirblocks from the file if they are not in memory.
1466
This populates self._dirblocks, and sets self._dirblock_state to
1467
IN_MEMORY_UNMODIFIED. It is not currently ready for incremental block
1470
self._read_header_if_needed()
1471
if self._dirblock_state == DirState.NOT_IN_MEMORY:
1472
# move the _state_file pointer to after the header (in case bisect
1473
# has been called in the mean time)
1474
self._state_file.seek(self._end_of_header)
1475
text = self._state_file.read()
1476
# TODO: check the adler checksums. adler_measured = zlib.adler32(text)
1478
fields = text.split('\0')
1479
# Remove the last blank entry
1480
trailing = fields.pop()
1481
assert trailing == ''
1482
# consider turning fields into a tuple.
1484
# skip the first field which is the trailing null from the header.
1486
# Each line now has an extra '\n' field which is not used
1487
# so we just skip over it
1489
# 3 fields for the key
1490
# + number of fields per tree_data (5) * tree count
1492
num_present_parents = self._num_present_parents()
1493
tree_count = 1 + num_present_parents
1494
entry_size = self._fields_per_entry()
1495
expected_field_count = entry_size * self._num_entries
1496
if len(fields) - cur > expected_field_count:
1497
fields = fields[:expected_field_count + cur]
1498
trace.mutter('Unexpectedly long dirstate field count!')
1499
print "XXX: incorrectly truncated dirstate file bug triggered."
1500
field_count = len(fields)
1501
# this checks our adjustment, and also catches file too short.
1502
assert field_count - cur == expected_field_count, \
1503
'field count incorrect %s != %s, entry_size=%s, '\
1504
'num_entries=%s fields=%r' % (
1505
field_count - cur, expected_field_count, entry_size,
1506
self._num_entries, fields)
1508
if num_present_parents == 1:
1509
# Bind external functions to local names
1511
# We access all fields in order, so we can just iterate over
1512
# them. Grab an straight iterator over the fields. (We use an
1513
# iterator because we don't want to do a lot of additions, nor
1514
# do we want to do a lot of slicing)
1515
next = iter(fields).next
1516
# Move the iterator to the current position
1517
for x in xrange(cur):
1519
# The two blocks here are deliberate: the root block and the
1520
# contents-of-root block.
1521
self._dirblocks = [('', []), ('', [])]
1522
current_block = self._dirblocks[0][1]
1523
current_dirname = ''
1524
append_entry = current_block.append
1525
for count in xrange(self._num_entries):
1529
if dirname != current_dirname:
1530
# new block - different dirname
1532
current_dirname = dirname
1533
self._dirblocks.append((current_dirname, current_block))
1534
append_entry = current_block.append
1535
# we know current_dirname == dirname, so re-use it to avoid
1536
# creating new strings
1537
entry = ((current_dirname, name, file_id),
1540
next(), # fingerprint
1541
_int(next()), # size
1542
next() == 'y', # executable
1543
next(), # packed_stat or revision_id
1547
next(), # fingerprint
1548
_int(next()), # size
1549
next() == 'y', # executable
1550
next(), # packed_stat or revision_id
1554
assert trailing == '\n'
1555
# append the entry to the current block
1557
self._split_root_dirblock_into_contents()
1559
fields_to_entry = self._get_fields_to_entry()
1560
entries = [fields_to_entry(fields[pos:pos+entry_size])
1561
for pos in xrange(cur, field_count, entry_size)]
1562
self._entries_to_current_state(entries)
1563
# To convert from format 2 => format 3
1564
# self._dirblocks = sorted(self._dirblocks,
1565
# key=lambda blk:blk[0].split('/'))
1566
# To convert from format 3 => format 2
1567
# self._dirblocks = sorted(self._dirblocks)
1568
self._dirblock_state = DirState.IN_MEMORY_UNMODIFIED
1570
def _read_header(self):
1571
"""This reads in the metadata header, and the parent ids.
1573
After reading in, the file should be positioned at the null
1574
just before the start of the first record in the file.
1576
:return: (expected adler checksum, number of entries, parent list)
1578
self._read_prelude()
1579
parent_line = self._state_file.readline()
1580
info = parent_line.split('\0')
1581
num_parents = int(info[0])
1582
assert num_parents == len(info)-2, 'incorrect parent info line'
1583
self._parents = info[1:-1]
1585
ghost_line = self._state_file.readline()
1586
info = ghost_line.split('\0')
1587
num_ghosts = int(info[1])
1588
assert num_ghosts == len(info)-3, 'incorrect ghost info line'
1589
self._ghosts = info[2:-1]
1590
self._header_state = DirState.IN_MEMORY_UNMODIFIED
1591
self._end_of_header = self._state_file.tell()
1593
def _read_header_if_needed(self):
1594
"""Read the header of the dirstate file if needed."""
1595
# inline this as it will be called a lot
1596
if not self._lock_token:
1597
raise errors.ObjectNotLocked(self)
1598
if self._header_state == DirState.NOT_IN_MEMORY:
1601
def _read_prelude(self):
1602
"""Read in the prelude header of the dirstate file
1604
This only reads in the stuff that is not connected to the adler
1605
checksum. The position will be correct to read in the rest of
1606
the file and check the checksum after this point.
1607
The next entry in the file should be the number of parents,
1608
and their ids. Followed by a newline.
1610
header = self._state_file.readline()
1611
assert header == DirState.HEADER_FORMAT_3, \
1612
'invalid header line: %r' % (header,)
1613
adler_line = self._state_file.readline()
1614
assert adler_line.startswith('adler32: '), 'missing adler32 checksum'
1615
self.adler_expected = int(adler_line[len('adler32: '):-1])
1616
num_entries_line = self._state_file.readline()
1617
assert num_entries_line.startswith('num_entries: '), 'missing num_entries line'
1618
self._num_entries = int(num_entries_line[len('num_entries: '):-1])
1621
"""Save any pending changes created during this session.
1623
We reuse the existing file, because that prevents race conditions with
1624
file creation, and use oslocks on it to prevent concurrent modification
1625
and reads - because dirstates incremental data aggretation is not
1626
compatible with reading a modified file, and replacing a file in use by
1627
another process is impossible on windows.
1629
A dirstate in read only mode should be smart enough though to validate
1630
that the file has not changed, and otherwise discard its cache and
1631
start over, to allow for fine grained read lock duration, so 'status'
1632
wont block 'commit' - for example.
1634
if (self._header_state == DirState.IN_MEMORY_MODIFIED or
1635
self._dirblock_state == DirState.IN_MEMORY_MODIFIED):
1637
if self._lock_state == 'w':
1638
out_file = self._state_file
1641
# Try to grab a write lock so that we can update the file.
1643
wlock = lock.WriteLock(self._filename)
1644
except (errors.LockError, errors.LockContention), e:
1645
# We couldn't grab the lock, so just leave things dirty in
1649
# This may be a read-only tree, or someone else may have a
1650
# ReadLock. so handle the case when we cannot grab a write
1652
if e.errno in (errno.ENOENT, errno.EPERM, errno.EACCES,
1654
# Ignore these errors and just don't save anything
1660
out_file.writelines(self.get_lines())
1663
self._header_state = DirState.IN_MEMORY_UNMODIFIED
1664
self._dirblock_state = DirState.IN_MEMORY_UNMODIFIED
1666
if wlock is not None:
1669
def _set_data(self, parent_ids, dirblocks):
1670
"""Set the full dirstate data in memory.
1672
This is an internal function used to completely replace the objects
1673
in memory state. It puts the dirstate into state 'full-dirty'.
1675
:param parent_ids: A list of parent tree revision ids.
1676
:param dirblocks: A list containing one tuple for each directory in the
1677
tree. Each tuple contains the directory path and a list of entries
1678
found in that directory.
1680
# our memory copy is now authoritative.
1681
self._dirblocks = dirblocks
1682
self._header_state = DirState.IN_MEMORY_MODIFIED
1683
self._dirblock_state = DirState.IN_MEMORY_MODIFIED
1684
self._parents = list(parent_ids)
1685
self._id_index = None
1687
def set_path_id(self, path, new_id):
1688
"""Change the id of path to new_id in the current working tree.
1690
:param path: The path inside the tree to set - '' is the root, 'foo'
1691
is the path foo in the root.
1692
:param new_id: The new id to assign to the path. This must be a utf8
1693
file id (not unicode, and not None).
1695
# TODO: start warning here.
1696
assert new_id.__class__ == str
1697
self._read_dirblocks_if_needed()
1699
import pdb;pdb.set_trace()
1701
raise NotImplementedError(self.set_path_id)
1702
# TODO: check new id is unique
1703
entry = self._get_entry(0, path_utf8=path)
1704
if entry[0][2] == new_id:
1705
# Nothing to change.
1707
# mark the old path absent, and insert a new root path
1708
self._make_absent(entry)
1709
self.update_minimal(('', '', new_id), 'd',
1710
path_utf8='', packed_stat=entry[1][0][4])
1711
self._dirblock_state = DirState.IN_MEMORY_MODIFIED
1712
if self._id_index is not None:
1713
self._id_index.setdefault(new_id, set()).add(entry[0])
1715
def set_parent_trees(self, trees, ghosts):
1716
"""Set the parent trees for the dirstate.
1718
:param trees: A list of revision_id, tree tuples. tree must be provided
1719
even if the revision_id refers to a ghost: supply an empty tree in
1721
:param ghosts: A list of the revision_ids that are ghosts at the time
1724
# TODO: generate a list of parent indexes to preserve to save
1725
# processing specific parent trees. In the common case one tree will
1726
# be preserved - the left most parent.
1727
# TODO: if the parent tree is a dirstate, we might want to walk them
1728
# all by path in parallel for 'optimal' common-case performance.
1729
# generate new root row.
1730
self._read_dirblocks_if_needed()
1731
# TODO future sketch: Examine the existing parents to generate a change
1732
# map and then walk the new parent trees only, mapping them into the
1733
# dirstate. Walk the dirstate at the same time to remove unreferenced
1736
# sketch: loop over all entries in the dirstate, cherry picking
1737
# entries from the parent trees, if they are not ghost trees.
1738
# after we finish walking the dirstate, all entries not in the dirstate
1739
# are deletes, so we want to append them to the end as per the design
1740
# discussions. So do a set difference on ids with the parents to
1741
# get deletes, and add them to the end.
1742
# During the update process we need to answer the following questions:
1743
# - find other keys containing a fileid in order to create cross-path
1744
# links. We dont't trivially use the inventory from other trees
1745
# because this leads to either double touching, or to accessing
1747
# - find other keys containing a path
1748
# We accumulate each entry via this dictionary, including the root
1751
# we could do parallel iterators, but because file id data may be
1752
# scattered throughout, we dont save on index overhead: we have to look
1753
# at everything anyway. We can probably save cycles by reusing parent
1754
# data and doing an incremental update when adding an additional
1755
# parent, but for now the common cases are adding a new parent (merge),
1756
# and replacing completely (commit), and commit is more common: so
1757
# optimise merge later.
1759
# ---- start generation of full tree mapping data
1760
# what trees should we use?
1761
parent_trees = [tree for rev_id, tree in trees if rev_id not in ghosts]
1762
# how many trees do we end up with
1763
parent_count = len(parent_trees)
1765
# one: the current tree
1766
for entry in self._iter_entries():
1767
# skip entries not in the current tree
1768
if entry[1][0][0] in ('a', 'r'): # absent, relocated
1770
by_path[entry[0]] = [entry[1][0]] + \
1771
[DirState.NULL_PARENT_DETAILS] * parent_count
1772
id_index[entry[0][2]] = set([entry[0]])
1774
# now the parent trees:
1775
for tree_index, tree in enumerate(parent_trees):
1776
# the index is off by one, adjust it.
1777
tree_index = tree_index + 1
1778
# when we add new locations for a fileid we need these ranges for
1779
# any fileid in this tree as we set the by_path[id] to:
1780
# already_processed_tree_details + new_details + new_location_suffix
1781
# the suffix is from tree_index+1:parent_count+1.
1782
new_location_suffix = [DirState.NULL_PARENT_DETAILS] * (parent_count - tree_index)
1783
# now stitch in all the entries from this tree
1784
for path, entry in tree.inventory.iter_entries_by_dir():
1785
# here we process each trees details for each item in the tree.
1786
# we first update any existing entries for the id at other paths,
1787
# then we either create or update the entry for the id at the
1788
# right path, and finally we add (if needed) a mapping from
1789
# file_id to this path. We do it in this order to allow us to
1790
# avoid checking all known paths for the id when generating a
1791
# new entry at this path: by adding the id->path mapping last,
1792
# all the mappings are valid and have correct relocation
1793
# records where needed.
1794
file_id = entry.file_id
1795
path_utf8 = path.encode('utf8')
1796
dirname, basename = osutils.split(path_utf8)
1797
new_entry_key = (dirname, basename, file_id)
1798
# tree index consistency: All other paths for this id in this tree
1799
# index must point to the correct path.
1800
for entry_key in id_index.setdefault(file_id, set()):
1801
# TODO:PROFILING: It might be faster to just update
1802
# rather than checking if we need to, and then overwrite
1803
# the one we are located at.
1804
if entry_key != new_entry_key:
1805
# this file id is at a different path in one of the
1806
# other trees, so put absent pointers there
1807
# This is the vertical axis in the matrix, all pointing
1809
by_path[entry_key][tree_index] = ('r', path_utf8, 0, False, '')
1810
# by path consistency: Insert into an existing path record (trivial), or
1811
# add a new one with relocation pointers for the other tree indexes.
1812
if new_entry_key in id_index[file_id]:
1813
# there is already an entry where this data belongs, just insert it.
1814
by_path[new_entry_key][tree_index] = \
1815
self._inv_entry_to_details(entry)
1817
# add relocated entries to the horizontal axis - this row
1818
# mapping from path,id. We need to look up the correct path
1819
# for the indexes from 0 to tree_index -1
1821
for lookup_index in xrange(tree_index):
1822
# boundary case: this is the first occurence of file_id
1823
# so there are no id_indexs, possibly take this out of
1825
if not len(id_index[file_id]):
1826
new_details.append(DirState.NULL_PARENT_DETAILS)
1828
# grab any one entry, use it to find the right path.
1829
# TODO: optimise this to reduce memory use in highly
1830
# fragmented situations by reusing the relocation
1832
a_key = iter(id_index[file_id]).next()
1833
if by_path[a_key][lookup_index][0] in ('r', 'a'):
1834
# its a pointer or missing statement, use it as is.
1835
new_details.append(by_path[a_key][lookup_index])
1837
# we have the right key, make a pointer to it.
1838
real_path = ('/'.join(a_key[0:2])).strip('/')
1839
new_details.append(('r', real_path, 0, False, ''))
1840
new_details.append(self._inv_entry_to_details(entry))
1841
new_details.extend(new_location_suffix)
1842
by_path[new_entry_key] = new_details
1843
id_index[file_id].add(new_entry_key)
1844
# --- end generation of full tree mappings
1846
# sort and output all the entries
1847
new_entries = sorted(by_path.items(),
1848
key=lambda entry:(entry[0][0].split('/'), entry[0][1]))
1849
self._entries_to_current_state(new_entries)
1850
self._parents = [rev_id for rev_id, tree in trees]
1851
self._ghosts = list(ghosts)
1852
self._header_state = DirState.IN_MEMORY_MODIFIED
1853
self._dirblock_state = DirState.IN_MEMORY_MODIFIED
1854
self._id_index = id_index
1856
def set_state_from_inventory(self, new_inv):
1857
"""Set new_inv as the current state.
1859
This API is called by tree transform, and will usually occur with
1860
existing parent trees.
1862
:param new_inv: The inventory object to set current state from.
1864
self._read_dirblocks_if_needed()
1866
# incremental algorithm:
1867
# two iterators: current data and new data, both in dirblock order.
1868
new_iterator = new_inv.iter_entries_by_dir()
1869
# we will be modifying the dirstate, so we need a stable iterator. In
1870
# future we might write one, for now we just clone the state into a
1871
# list - which is a shallow copy, so each
1872
old_iterator = iter(list(self._iter_entries()))
1873
# both must have roots so this is safe:
1874
current_new = new_iterator.next()
1875
current_old = old_iterator.next()
1876
def advance(iterator):
1878
return iterator.next()
1879
except StopIteration:
1881
while current_new or current_old:
1882
# skip entries in old that are not really there
1883
if current_old and current_old[1][0][0] in ('r', 'a'):
1884
# relocated or absent
1885
current_old = advance(old_iterator)
1888
# convert new into dirblock style
1889
new_path_utf8 = current_new[0].encode('utf8')
1890
new_dirname, new_basename = osutils.split(new_path_utf8)
1891
new_id = current_new[1].file_id
1892
new_entry_key = (new_dirname, new_basename, new_id)
1893
current_new_minikind = \
1894
DirState._kind_to_minikind[current_new[1].kind]
1896
# for safety disable variables
1897
new_path_utf8 = new_dirname = new_basename = new_id = new_entry_key = None
1898
# 5 cases, we dont have a value that is strictly greater than everything, so
1899
# we make both end conditions explicit
1901
# old is finished: insert current_new into the state.
1902
self.update_minimal(new_entry_key, current_new_minikind,
1903
executable=current_new[1].executable,
1904
path_utf8=new_path_utf8)
1905
current_new = advance(new_iterator)
1906
elif not current_new:
1908
self._make_absent(current_old)
1909
current_old = advance(old_iterator)
1910
elif new_entry_key == current_old[0]:
1911
# same - common case
1912
# TODO: update the record if anything significant has changed.
1913
# the minimal required trigger is if the execute bit or cached
1915
if (current_old[1][0][3] != current_new[1].executable or
1916
current_old[1][0][0] != current_new_minikind):
1917
self.update_minimal(current_old[0], current_new_minikind,
1918
executable=current_new[1].executable,
1919
path_utf8=new_path_utf8)
1920
# both sides are dealt with, move on
1921
current_old = advance(old_iterator)
1922
current_new = advance(new_iterator)
1923
elif new_entry_key < current_old[0]:
1925
# add a entry for this and advance new
1926
self.update_minimal(new_entry_key, current_new_minikind,
1927
executable=current_new[1].executable,
1928
path_utf8=new_path_utf8)
1929
current_new = advance(new_iterator)
1932
self._make_absent(current_old)
1933
current_old = advance(old_iterator)
1934
self._dirblock_state = DirState.IN_MEMORY_MODIFIED
1935
self._id_index = None
1937
def _make_absent(self, current_old):
1938
"""Mark current_old - an entry - as absent for tree 0.
1940
:return: True if this was the last details entry for they entry key:
1941
that is, if the underlying block has had the entry removed, thus
1942
shrinking in length.
1944
# build up paths that this id will be left at after the change is made,
1945
# so we can update their cross references in tree 0
1946
all_remaining_keys = set()
1947
# Dont check the working tree, because its going.
1948
for details in current_old[1][1:]:
1949
if details[0] not in ('a', 'r'): # absent, relocated
1950
all_remaining_keys.add(current_old[0])
1951
elif details[0] == 'r': # relocated
1952
# record the key for the real path.
1953
all_remaining_keys.add(tuple(osutils.split(details[1])) + (current_old[0][2],))
1954
# absent rows are not present at any path.
1955
last_reference = current_old[0] not in all_remaining_keys
1957
# the current row consists entire of the current item (being marked
1958
# absent), and relocated or absent entries for the other trees:
1959
# Remove it, its meaningless.
1960
block = self._find_block(current_old[0])
1961
entry_index, present = self._find_entry_index(current_old[0], block[1])
1962
assert present, 'could not find entry for %s' % (current_old,)
1963
block[1].pop(entry_index)
1964
# if we have an id_index in use, remove this key from it for this id.
1965
if self._id_index is not None:
1966
self._id_index[current_old[0][2]].remove(current_old[0])
1967
# update all remaining keys for this id to record it as absent. The
1968
# existing details may either be the record we are making as deleted
1969
# (if there were other trees with the id present at this path), or may
1971
for update_key in all_remaining_keys:
1972
update_block_index, present = \
1973
self._find_block_index_from_key(update_key)
1974
assert present, 'could not find block for %s' % (update_key,)
1975
update_entry_index, present = \
1976
self._find_entry_index(update_key, self._dirblocks[update_block_index][1])
1977
assert present, 'could not find entry for %s' % (update_key,)
1978
update_tree_details = self._dirblocks[update_block_index][1][update_entry_index][1]
1979
# it must not be absent at the moment
1980
assert update_tree_details[0][0] != 'a' # absent
1981
update_tree_details[0] = DirState.NULL_PARENT_DETAILS
1982
self._dirblock_state = DirState.IN_MEMORY_MODIFIED
1983
return last_reference
1985
def update_minimal(self, key, minikind, executable=False, fingerprint='',
1986
packed_stat=None, size=0, path_utf8=None):
1987
"""Update an entry to the state in tree 0.
1989
This will either create a new entry at 'key' or update an existing one.
1990
It also makes sure that any other records which might mention this are
1993
:param key: (dir, name, file_id) for the new entry
1994
:param minikind: The type for the entry ('f' == 'file', 'd' ==
1996
:param executable: Should the executable bit be set?
1997
:param fingerprint: Simple fingerprint for new entry.
1998
:param packed_stat: packed stat value for new entry.
1999
:param size: Size information for new entry
2000
:param path_utf8: key[0] + '/' + key[1], just passed in to avoid doing
2003
block = self._find_block(key)[1]
2004
if packed_stat is None:
2005
packed_stat = DirState.NULLSTAT
2006
entry_index, present = self._find_entry_index(key, block)
2007
new_details = (minikind, fingerprint, size, executable, packed_stat)
2008
id_index = self._get_id_index()
2010
# new entry, synthesis cross reference here,
2011
existing_keys = id_index.setdefault(key[2], set())
2012
if not existing_keys:
2013
# not currently in the state, simplest case
2014
new_entry = key, [new_details] + self._empty_parent_info()
2016
# present at one or more existing other paths.
2017
# grab one of them and use it to generate parent
2018
# relocation/absent entries.
2019
new_entry = key, [new_details]
2020
for other_key in existing_keys:
2021
# change the record at other to be a pointer to this new
2022
# record. The loop looks similar to the change to
2023
# relocations when updating an existing record but its not:
2024
# the test for existing kinds is different: this can be
2025
# factored out to a helper though.
2026
other_block_index, present = self._find_block_index_from_key(other_key)
2028
import pdb; pdb.set_trace()
2029
assert present, 'could not find block for %s' % (other_key,)
2030
other_entry_index, present = self._find_entry_index(other_key,
2031
self._dirblocks[other_block_index][1])
2033
import pdb; pdb.set_trace()
2034
assert present, 'could not find entry for %s' % (other_key,)
2035
assert path_utf8 is not None
2036
self._dirblocks[other_block_index][1][other_entry_index][1][0] = \
2037
('r', path_utf8, 0, False, '')
2039
num_present_parents = self._num_present_parents()
2040
for lookup_index in xrange(1, num_present_parents + 1):
2041
# grab any one entry, use it to find the right path.
2042
# TODO: optimise this to reduce memory use in highly
2043
# fragmented situations by reusing the relocation
2045
update_block_index, present = \
2046
self._find_block_index_from_key(other_key)
2047
assert present, 'could not find block for %s' % (other_key,)
2048
update_entry_index, present = \
2049
self._find_entry_index(other_key, self._dirblocks[update_block_index][1])
2050
assert present, 'could not find entry for %s' % (other_key,)
2051
update_details = self._dirblocks[update_block_index][1][update_entry_index][1][lookup_index]
2052
if update_details[0] in ('r', 'a'): # relocated, absent
2053
# its a pointer or absent in lookup_index's tree, use
2055
new_entry[1].append(update_details)
2057
# we have the right key, make a pointer to it.
2058
pointer_path = osutils.pathjoin(*other_key[0:2])
2059
new_entry[1].append(('r', pointer_path, 0, False, ''))
2060
block.insert(entry_index, new_entry)
2061
existing_keys.add(key)
2063
# Does the new state matter?
2064
block[entry_index][1][0] = new_details
2065
# parents cannot be affected by what we do.
2066
# other occurences of this id can be found
2067
# from the id index.
2069
# tree index consistency: All other paths for this id in this tree
2070
# index must point to the correct path. We have to loop here because
2071
# we may have passed entries in the state with this file id already
2072
# that were absent - where parent entries are - and they need to be
2073
# converted to relocated.
2074
assert path_utf8 is not None
2075
for entry_key in id_index.setdefault(key[2], set()):
2076
# TODO:PROFILING: It might be faster to just update
2077
# rather than checking if we need to, and then overwrite
2078
# the one we are located at.
2079
if entry_key != key:
2080
# this file id is at a different path in one of the
2081
# other trees, so put absent pointers there
2082
# This is the vertical axis in the matrix, all pointing
2084
block_index, present = self._find_block_index_from_key(entry_key)
2086
entry_index, present = self._find_entry_index(entry_key, self._dirblocks[block_index][1])
2088
self._dirblocks[block_index][1][entry_index][1][0] = \
2089
('r', path_utf8, 0, False, '')
2090
# add a containing dirblock if needed.
2091
if new_details[0] == 'd':
2092
subdir_key = (osutils.pathjoin(*key[0:2]), '', '')
2093
block_index, present = self._find_block_index_from_key(subdir_key)
2095
self._dirblocks.insert(block_index, (subdir_key[0], []))
2097
self._dirblock_state = DirState.IN_MEMORY_MODIFIED
2099
def _validate(self):
2100
"""Check that invariants on the dirblock are correct.
2102
This can be useful in debugging; it shouldn't be necessary in
2105
from pprint import pformat
2106
if len(self._dirblocks) > 0:
2107
assert self._dirblocks[0][0] == '', \
2108
"dirblocks don't start with root block:\n" + \
2110
if len(self._dirblocks) > 1:
2111
assert self._dirblocks[1][0] == '', \
2112
"dirblocks missing root directory:\n" + \
2114
assert self._dirblocks[1:] == sorted(self._dirblocks[1:]), \
2115
"dirblocks are not in sorted order:\n" + \
2116
pformat(self._dirblocks)
2117
for dirblock in self._dirblocks:
2118
assert dirblock[1] == sorted(dirblock[1]), \
2119
"dirblock for %r is not sorted:\n%s" % \
2120
(dirblock[0], pformat(dirblock))
2122
def _wipe_state(self):
2123
"""Forget all state information about the dirstate."""
2124
self._header_state = DirState.NOT_IN_MEMORY
2125
self._dirblock_state = DirState.NOT_IN_MEMORY
2128
self._dirblocks = []
2130
def lock_read(self):
2131
"""Acquire a read lock on the dirstate"""
2132
if self._lock_token is not None:
2133
raise errors.LockContention(self._lock_token)
2134
# TODO: jam 20070301 Rather than wiping completely, if the blocks are
2135
# already in memory, we could read just the header and check for
2136
# any modification. If not modified, we can just leave things
2138
self._lock_token = lock.ReadLock(self._filename)
2139
self._lock_state = 'r'
2140
self._state_file = self._lock_token.f
2143
def lock_write(self):
2144
"""Acquire a write lock on the dirstate"""
2145
if self._lock_token is not None:
2146
raise errors.LockContention(self._lock_token)
2147
# TODO: jam 20070301 Rather than wiping completely, if the blocks are
2148
# already in memory, we could read just the header and check for
2149
# any modification. If not modified, we can just leave things
2151
self._lock_token = lock.WriteLock(self._filename)
2152
self._lock_state = 'w'
2153
self._state_file = self._lock_token.f
2157
"""Drop any locks held on the dirstate"""
2158
if self._lock_token is None:
2159
raise errors.LockNotHeld(self)
2160
# TODO: jam 20070301 Rather than wiping completely, if the blocks are
2161
# already in memory, we could read just the header and check for
2162
# any modification. If not modified, we can just leave things
2164
self._state_file = None
2165
self._lock_state = None
2166
self._lock_token.unlock()
2167
self._lock_token = None
2168
self._split_path_cache = {}
2170
def _requires_lock(self):
2171
"""Checks that a lock is currently held by someone on the dirstate"""
2172
if not self._lock_token:
2173
raise errors.ObjectNotLocked(self)
2176
def bisect_dirblock(dirblocks, dirname, lo=0, hi=None, cache={}):
2177
"""Return the index where to insert dirname into the dirblocks.
2179
The return value idx is such that all directories blocks in dirblock[:idx]
2180
have names < dirname, and all blocks in dirblock[idx:] have names >=
2183
Optional args lo (default 0) and hi (default len(dirblocks)) bound the
2184
slice of a to be searched.
2189
dirname_split = cache[dirname]
2191
dirname_split = dirname.split('/')
2192
cache[dirname] = dirname_split
2195
# Grab the dirname for the current dirblock
2196
cur = dirblocks[mid][0]
2198
cur_split = cache[cur]
2200
cur_split = cur.split('/')
2201
cache[cur] = cur_split
2202
if cur_split < dirname_split: lo = mid+1
2207
_base64_encoder = codecs.getencoder('base64')
2210
def pack_stat(st, _encode=_base64_encoder, _pack=struct.pack):
2211
"""Convert stat values into a packed representation."""
2212
# jam 20060614 it isn't really worth removing more entries if we
2213
# are going to leave it in packed form.
2214
# With only st_mtime and st_mode filesize is 5.5M and read time is 275ms
2215
# With all entries filesize is 5.9M and read time is mabye 280ms
2216
# well within the noise margin
2218
# base64.encode always adds a final newline, so strip it off
2219
return _encode(_pack('>llllll'
2220
, st.st_size, int(st.st_mtime), int(st.st_ctime)
2221
, st.st_dev, st.st_ino, st.st_mode))[0][:-1]