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
207
import bzrlib.inventory
208
from bzrlib import osutils
209
from bzrlib.osutils import (
217
class _Bisector(object):
218
"""This just keeps track of information as we are bisecting."""
221
class DirState(object):
222
"""Record directory and metadata state for fast access.
224
A dirstate is a specialised data structure for managing local working
225
tree state information. Its not yet well defined whether it is platform
226
specific, and if it is how we detect/parameterise that.
229
_kind_to_minikind = {'absent':'a', 'file':'f', 'directory':'d', 'relocated':'r', 'symlink':'l'}
230
_minikind_to_kind = {'a':'absent', 'f':'file', 'd':'directory', 'l':'symlink', 'r':'relocated'}
231
_to_yesno = {True:'y', False: 'n'} # TODO profile the performance gain
232
# of using int conversion rather than a dict here. AND BLAME ANDREW IF
235
# TODO: jam 20070221 Make sure we handle when there are duplicated records
236
# (like when we remove + add the same path, or we have a rename)
237
# TODO: jam 20070221 Figure out what to do if we have a record that exceeds
238
# the BISECT_PAGE_SIZE. For now, we just have to make it large enough
239
# that we are sure a single record will always fit.
240
BISECT_PAGE_SIZE = 4096
243
IN_MEMORY_UNMODIFIED = 1
244
IN_MEMORY_MODIFIED = 2
246
# A pack_stat (the x's) that is just noise and will never match the output
249
NULL_PARENT_DETAILS = ('a', '', 0, False, '')
251
def __init__(self, path):
252
"""Create a DirState object.
256
:attr _root_entrie: The root row of the directory/file information,
257
- contains the path to / - '', ''
258
- kind of 'directory',
259
- the file id of the root in utf8
262
- and no sha information.
263
:param path: The path at which the dirstate file on disk should live.
265
# _header_state and _dirblock_state represent the current state
266
# of the dirstate metadata and the per-row data respectiely.
267
# NOT_IN_MEMORY indicates that no data is in memory
268
# IN_MEMORY_UNMODIFIED indicates that what we have in memory
269
# is the same as is on disk
270
# IN_MEMORY_MODIFIED indicates that we have a modified version
271
# of what is on disk.
272
# In future we will add more granularity, for instance _dirblock_state
273
# will probably support partially-in-memory as a separate variable,
274
# allowing for partially-in-memory unmodified and partially-in-memory
276
self._header_state = DirState.NOT_IN_MEMORY
277
self._dirblock_state = DirState.NOT_IN_MEMORY
281
self._state_file = None
282
self._filename = path
283
self._lock_token = None
284
self._id_index = None
285
self._end_of_header = None
286
self._bisect_page_size = DirState.BISECT_PAGE_SIZE
288
def add(self, path, file_id, kind, stat, link_or_sha1):
289
"""Add a path to be tracked.
291
:param path: The path within the dirstate - '' is the root, 'foo' is the
292
path foo within the root, 'foo/bar' is the path bar within foo
294
:param file_id: The file id of the path being added.
295
:param kind: The kind of the path.
296
:param stat: The output of os.lstate for the path.
297
:param link_or_sha1: The sha value of the file, or the target of a
298
symlink. '' for directories.
301
# find the block its in.
302
# find the location in the block.
303
# check its not there
305
#------- copied from bzrlib.inventory.make_entry
306
# --- normalized_filename wants a unicode basename only, so get one.
307
dirname, basename = osutils.split(path)
308
# we dont import normalized_filename directly because we want to be
309
# able to change the implementation at runtime for tests.
310
norm_name, can_access = osutils.normalized_filename(basename)
311
if norm_name != basename:
315
raise errors.InvalidNormalization(path)
316
# now that we've normalised, we need the correct utf8 path and
317
# dirname and basename elements. This single encode and split should be
318
# faster than three separate encodes.
319
utf8path = (dirname + '/' + basename).strip('/').encode('utf8')
320
dirname, basename = osutils.split(utf8path)
321
assert file_id.__class__ == str, \
322
"must be a utf8 file_id not %s" % (type(file_id))
323
# Make sure the file_id does not exist in this tree
324
file_id_entry = self._get_entry(0, fileid_utf8=file_id)
325
if file_id_entry != (None, None):
326
path = osutils.pathjoin(file_id_entry[0][0], file_id_entry[0][1])
327
kind = DirState._minikind_to_kind[file_id_entry[1][0][0]]
328
info = '%s:%s' % (kind, path)
329
raise errors.DuplicateFileId(file_id, info)
330
entry_key = (dirname, basename, file_id)
331
self._read_dirblocks_if_needed()
332
block_index, present = self._find_block_index_from_key(entry_key)
334
# The block where we want to put the file is not present. But it
335
# might be because the directory was empty, or not loaded yet. Look
336
# for a parent entry, if not found, raise NotVersionedError
337
parent_dir, parent_base = osutils.split(dirname)
338
parent_block_idx, parent_entry_idx, _, parent_present = \
339
self._get_block_entry_index(parent_dir, parent_base, 0)
340
if not parent_present:
341
raise errors.NotVersionedError(path, str(self))
342
self._ensure_block(parent_block_idx, parent_entry_idx, dirname)
343
block = self._dirblocks[block_index][1]
346
packed_stat = DirState.NULLSTAT
349
packed_stat = pack_stat(stat)
350
parent_info = self._empty_parent_info()
351
minikind = DirState._kind_to_minikind[kind]
353
entry_data = entry_key, [
354
(minikind, link_or_sha1, size, False, packed_stat),
356
elif kind == 'directory':
357
entry_data = entry_key, [
358
(minikind, '', 0, False, packed_stat),
360
elif kind == 'symlink':
361
entry_data = entry_key, [
362
(minikind, link_or_sha1, size, False, packed_stat),
365
raise errors.BzrError('unknown kind %r' % kind)
366
entry_index, present = self._find_entry_index(entry_key, block)
367
assert not present, "basename %r already added" % basename
368
block.insert(entry_index, entry_data)
370
if kind == 'directory':
371
# insert a new dirblock
372
self._ensure_block(block_index, entry_index, utf8path)
373
self._dirblock_state = DirState.IN_MEMORY_MODIFIED
375
self._id_index.setdefault(entry_key[2], set()).add(entry_key)
377
def _bisect(self, dir_name_list):
378
"""Bisect through the disk structure for specific rows.
380
:param dir_name_list: A list of (dir, name) pairs.
381
:return: A dict mapping (dir, name) => entry for found entries. Missing
382
entries will not be in the map.
384
self._requires_lock()
385
# We need the file pointer to be right after the initial header block
386
self._read_header_if_needed()
387
# If _dirblock_state was in memory, we should just return info from
388
# there, this function is only meant to handle when we want to read
390
assert self._dirblock_state == DirState.NOT_IN_MEMORY
392
# The disk representation is generally info + '\0\n\0' at the end. But
393
# for bisecting, it is easier to treat this as '\0' + info + '\0\n'
394
# Because it means we can sync on the '\n'
395
state_file = self._state_file
396
file_size = os.fstat(state_file.fileno()).st_size
397
# We end up with 2 extra fields, we should have a trailing '\n' to
398
# ensure that we read the whole record, and we should have a precursur
399
# '' which ensures that we start after the previous '\n'
400
entry_field_count = self._fields_per_entry() + 1
402
low = self._end_of_header
403
high = file_size - 1 # Ignore the final '\0'
404
# Map from (dir, name) => entry
407
# Avoid infinite seeking
408
max_count = 30*len(dir_name_list)
410
# pending is a list of places to look.
411
# each entry is a tuple of low, high, dir_names
412
# low -> the first byte offset to read (inclusive)
413
# high -> the last byte offset (inclusive)
414
# dir_names -> The list of (dir, name) pairs that should be found in
415
# the [low, high] range
416
pending = [(low, high, dir_name_list)]
418
page_size = self._bisect_page_size
420
fields_to_entry = self._get_fields_to_entry()
423
low, high, cur_files = pending.pop()
425
if not cur_files or low >= high:
430
if count > max_count:
431
raise errors.BzrError('Too many seeks, most likely a bug.')
433
mid = max(low, (low+high-page_size)/2)
436
# limit the read size, so we don't end up reading data that we have
438
read_size = min(page_size, (high-mid)+1)
439
block = state_file.read(read_size)
442
entries = block.split('\n')
445
# We didn't find a '\n', so we cannot have found any records.
446
# So put this range back and try again. But we know we have to
447
# increase the page size, because a single read did not contain
448
# a record break (so records must be larger than page_size)
450
pending.append((low, high, cur_files))
453
# Check the first and last entries, in case they are partial, or if
454
# we don't care about the rest of this page
456
first_fields = entries[0].split('\0')
457
if len(first_fields) < entry_field_count:
458
# We didn't get the complete first entry
459
# so move start, and grab the next, which
460
# should be a full entry
461
start += len(entries[0])+1
462
first_fields = entries[1].split('\0')
465
if len(first_fields) <= 2:
466
# We didn't even get a filename here... what do we do?
467
# Try a large page size and repeat this query
469
pending.append((low, high, cur_files))
472
# Find what entries we are looking for, which occur before and
473
# after this first record.
475
first_dir_name = (first_fields[1], first_fields[2])
476
first_loc = bisect.bisect_left(cur_files, first_dir_name)
478
# These exist before the current location
479
pre = cur_files[:first_loc]
480
# These occur after the current location, which may be in the
481
# data we read, or might be after the last entry
482
post = cur_files[first_loc:]
484
if post and len(first_fields) >= entry_field_count:
485
# We have files after the first entry
487
# Parse the last entry
488
last_entry_num = len(entries)-1
489
last_fields = entries[last_entry_num].split('\0')
490
if len(last_fields) < entry_field_count:
491
# The very last hunk was not complete,
492
# read the previous hunk
493
after = mid + len(block) - len(entries[-1])
495
last_fields = entries[last_entry_num].split('\0')
497
after = mid + len(block)
499
last_dir_name = (last_fields[1], last_fields[2])
500
last_loc = bisect.bisect_right(post, last_dir_name)
502
middle_files = post[:last_loc]
503
post = post[last_loc:]
506
# We have files that should occur in this block
507
# (>= first, <= last)
508
# Either we will find them here, or we can mark them as
511
if middle_files[0] == first_dir_name:
512
# We might need to go before this location
513
pre.append(first_dir_name)
514
if middle_files[-1] == last_dir_name:
515
post.insert(0, last_dir_name)
517
# Find out what paths we have
518
paths = {first_dir_name:[first_fields]}
519
# last_dir_name might == first_dir_name so we need to be
520
# careful if we should append rather than overwrite
521
if last_entry_num != first_entry_num:
522
paths.setdefault(last_dir_name, []).append(last_fields)
523
for num in xrange(first_entry_num+1, last_entry_num):
524
# TODO: jam 20070223 We are already splitting here, so
525
# shouldn't we just split the whole thing rather
526
# than doing the split again in add_one_record?
527
fields = entries[num].split('\0')
528
dir_name = (fields[1], fields[2])
529
paths.setdefault(dir_name, []).append(fields)
531
for dir_name in middle_files:
532
for fields in paths.get(dir_name, []):
533
# offset by 1 because of the opening '\0'
534
# consider changing fields_to_entry to avoid the
536
entry = fields_to_entry(fields[1:])
537
found.setdefault(dir_name, []).append(entry)
539
# Now we have split up everything into pre, middle, and post, and
540
# we have handled everything that fell in 'middle'.
541
# We add 'post' first, so that we prefer to seek towards the
542
# beginning, so that we will tend to go as early as we need, and
543
# then only seek forward after that.
545
pending.append((after, high, post))
547
pending.append((low, start-1, pre))
549
# Consider that we may want to return the directory entries in sorted
550
# order. For now, we just return them in whatever order we found them,
551
# and leave it up to the caller if they care if it is ordered or not.
554
def _bisect_dirblocks(self, dir_list):
555
"""Bisect through the disk structure to find entries in given dirs.
557
_bisect_dirblocks is meant to find the contents of directories, which
558
differs from _bisect, which only finds individual entries.
560
:param dir_list: An sorted list of directory names ['', 'dir', 'foo'].
561
:return: A map from dir => entries_for_dir
563
# TODO: jam 20070223 A lot of the bisecting logic could be shared
564
# between this and _bisect. It would require parameterizing the
565
# inner loop with a function, though. We should evaluate the
566
# performance difference.
567
self._requires_lock()
568
# We need the file pointer to be right after the initial header block
569
self._read_header_if_needed()
570
# If _dirblock_state was in memory, we should just return info from
571
# there, this function is only meant to handle when we want to read
573
assert self._dirblock_state == DirState.NOT_IN_MEMORY
575
# The disk representation is generally info + '\0\n\0' at the end. But
576
# for bisecting, it is easier to treat this as '\0' + info + '\0\n'
577
# Because it means we can sync on the '\n'
578
state_file = self._state_file
579
file_size = os.fstat(state_file.fileno()).st_size
580
# We end up with 2 extra fields, we should have a trailing '\n' to
581
# ensure that we read the whole record, and we should have a precursur
582
# '' which ensures that we start after the previous '\n'
583
entry_field_count = self._fields_per_entry() + 1
585
low = self._end_of_header
586
high = file_size - 1 # Ignore the final '\0'
587
# Map from dir => entry
590
# Avoid infinite seeking
591
max_count = 30*len(dir_list)
593
# pending is a list of places to look.
594
# each entry is a tuple of low, high, dir_names
595
# low -> the first byte offset to read (inclusive)
596
# high -> the last byte offset (inclusive)
597
# dirs -> The list of directories that should be found in
598
# the [low, high] range
599
pending = [(low, high, dir_list)]
601
page_size = self._bisect_page_size
603
fields_to_entry = self._get_fields_to_entry()
606
low, high, cur_dirs = pending.pop()
608
if not cur_dirs or low >= high:
613
if count > max_count:
614
raise errors.BzrError('Too many seeks, most likely a bug.')
616
mid = max(low, (low+high-page_size)/2)
619
# limit the read size, so we don't end up reading data that we have
621
read_size = min(page_size, (high-mid)+1)
622
block = state_file.read(read_size)
625
entries = block.split('\n')
628
# We didn't find a '\n', so we cannot have found any records.
629
# So put this range back and try again. But we know we have to
630
# increase the page size, because a single read did not contain
631
# a record break (so records must be larger than page_size)
633
pending.append((low, high, cur_dirs))
636
# Check the first and last entries, in case they are partial, or if
637
# we don't care about the rest of this page
639
first_fields = entries[0].split('\0')
640
if len(first_fields) < entry_field_count:
641
# We didn't get the complete first entry
642
# so move start, and grab the next, which
643
# should be a full entry
644
start += len(entries[0])+1
645
first_fields = entries[1].split('\0')
648
if len(first_fields) <= 1:
649
# We didn't even get a dirname here... what do we do?
650
# Try a large page size and repeat this query
652
pending.append((low, high, cur_dirs))
655
# Find what entries we are looking for, which occur before and
656
# after this first record.
658
first_dir = first_fields[1]
659
first_loc = bisect.bisect_left(cur_dirs, first_dir)
661
# These exist before the current location
662
pre = cur_dirs[: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_dirs[first_loc:]
667
if post and len(first_fields) >= entry_field_count:
668
# We have records to look at 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)
682
last_dir = last_fields[1]
683
last_loc = bisect.bisect_right(post, last_dir)
685
middle_files = post[:last_loc]
686
post = post[last_loc:]
689
# We have files that should occur in this block
690
# (>= first, <= last)
691
# Either we will find them here, or we can mark them as
694
if middle_files[0] == first_dir:
695
# We might need to go before this location
696
pre.append(first_dir)
697
if middle_files[-1] == last_dir:
698
post.insert(0, last_dir)
700
# Find out what paths we have
701
paths = {first_dir:[first_fields]}
702
# last_dir might == first_dir so we need to be
703
# careful if we should append rather than overwrite
704
if last_entry_num != first_entry_num:
705
paths.setdefault(last_dir, []).append(last_fields)
706
for num in xrange(first_entry_num+1, last_entry_num):
707
# TODO: jam 20070223 We are already splitting here, so
708
# shouldn't we just split the whole thing rather
709
# than doing the split again in add_one_record?
710
fields = entries[num].split('\0')
711
paths.setdefault(fields[1], []).append(fields)
713
for cur_dir in middle_files:
714
for fields in paths.get(cur_dir, []):
715
# offset by 1 because of the opening '\0'
716
# consider changing fields_to_entry to avoid the
718
entry = fields_to_entry(fields[1:])
719
found.setdefault(cur_dir, []).append(entry)
721
# Now we have split up everything into pre, middle, and post, and
722
# we have handled everything that fell in 'middle'.
723
# We add 'post' first, so that we prefer to seek towards the
724
# beginning, so that we will tend to go as early as we need, and
725
# then only seek forward after that.
727
pending.append((after, high, post))
729
pending.append((low, start-1, pre))
733
def _bisect_recursive(self, dir_name_list):
734
"""Bisect for entries for all paths and their children.
736
This will use bisect to find all records for the supplied paths. It
737
will then continue to bisect for any records which are marked as
738
directories. (and renames?)
740
:param paths: A sorted list of (dir, name) pairs
741
eg: [('', 'a'), ('', 'f'), ('a/b', 'c')]
742
:return: A dictionary mapping (dir, name, file_id) => [tree_info]
744
# Map from (dir, name, file_id) => [tree_info]
747
found_dir_names = set()
749
# Directories that have been read
750
processed_dirs = set()
751
# Get the ball rolling with the first bisect for all entries.
752
newly_found = self._bisect(dir_name_list)
755
# Directories that need to be read
757
paths_to_search = set()
758
for entry_list in newly_found.itervalues():
759
for dir_name_id, trees_info in entry_list:
760
found[dir_name_id] = trees_info
761
found_dir_names.add(dir_name_id[:2])
763
for tree_info in trees_info:
764
minikind = tree_info[0]
767
# We already processed this one as a directory,
768
# we don't need to do the extra work again.
770
subdir, name, file_id = dir_name_id
771
path = osutils.pathjoin(subdir, name)
773
if path not in processed_dirs:
774
pending_dirs.add(path)
775
elif minikind == 'r':
776
# Rename, we need to directly search the target
777
# which is contained in the fingerprint column
778
dir_name = osutils.split(tree_info[1])
779
if dir_name[0] in pending_dirs:
780
# This entry will be found in the dir search
782
# TODO: We need to check if this entry has
783
# already been found. Otherwise we might be
784
# hitting infinite recursion.
785
if dir_name not in found_dir_names:
786
paths_to_search.add(dir_name)
787
# Now we have a list of paths to look for directly, and
788
# directory blocks that need to be read.
789
# newly_found is mixing the keys between (dir, name) and path
790
# entries, but that is okay, because we only really care about the
792
newly_found = self._bisect(sorted(paths_to_search))
793
newly_found.update(self._bisect_dirblocks(sorted(pending_dirs)))
794
processed_dirs.update(pending_dirs)
797
def _empty_parent_info(self):
798
return [DirState.NULL_PARENT_DETAILS] * (len(self._parents) -
801
def _ensure_block(self, parent_block_index, parent_row_index, dirname):
802
"""Ensure a block for dirname exists.
804
This function exists to let callers which know that there is a
805
directory dirname ensure that the block for it exists. This block can
806
fail to exist because of demand loading, or because a directory had no
807
children. In either case it is not an error. It is however an error to
808
call this if there is no parent entry for the directory, and thus the
809
function requires the coordinates of such an entry to be provided.
811
The root row is special cased and can be indicated with a parent block
814
:param parent_block_index: The index of the block in which dirname's row
816
:param parent_row_index: The index in the parent block where the row
818
:param dirname: The utf8 dirname to ensure there is a block for.
819
:return: The index for the block.
821
if dirname == '' and parent_row_index == 0 and parent_block_index == 0:
822
# This is the signature of the root row, and the
823
# contents-of-root row is always index 1
825
# the basename of the directory must be the end of its full name.
826
if not (parent_block_index == -1 and
827
parent_block_index == -1 and dirname == ''):
828
assert dirname.endswith(
829
self._dirblocks[parent_block_index][1][parent_row_index][0][1])
830
block_index, present = self._find_block_index_from_key((dirname, '', ''))
832
## In future, when doing partial parsing, this should load and
833
# populate the entire block.
834
self._dirblocks.insert(block_index, (dirname, []))
837
def _entries_to_current_state(self, new_entries):
838
"""Load new_entries into self.dirblocks.
840
Process new_entries into the current state object, making them the active
843
:param new_entries: A sorted list of entries. This function does not sort
844
to prevent unneeded overhead when callers have a sorted list already.
847
assert new_entries[0][0][0:2] == ('', ''), \
848
"Missing root row %r" % new_entries[0][0]
849
# The two blocks here are deliberate: the root block and the
850
# contents-of-root block.
851
self._dirblocks = [('', []), ('', [])]
852
current_block = self._dirblocks[0][1]
855
append_entry = current_block.append
856
for entry in new_entries:
857
if entry[0][0] != current_dirname:
858
# new block - different dirname
860
current_dirname = entry[0][0]
861
self._dirblocks.append((current_dirname, current_block))
862
append_entry = current_block.append
863
# append the entry to the current block
865
self._split_root_dirblock_into_contents()
867
def _split_root_dirblock_into_contents(self):
868
"""Split the root dirblocks into root and contents-of-root.
870
After parsing by path, we end up with root entries and contents-of-root
871
entries in the same block. This loop splits them out again.
873
# The above loop leaves the "root block" entries mixed with the
874
# "contents-of-root block". But we don't want an if check on
875
# all entries, so instead we just fix it up here.
876
assert self._dirblocks[1] == ('', [])
878
contents_of_root_block = []
879
for entry in self._dirblocks[0][1]:
880
if not entry[0][1]: # This is a root entry
881
root_block.append(entry)
883
contents_of_root_block.append(entry)
884
self._dirblocks[0] = ('', root_block)
885
self._dirblocks[1] = ('', contents_of_root_block)
887
def _entry_to_line(self, entry):
888
"""Serialize entry to a NULL delimited line ready for _get_output_lines.
890
:param entry: An entry_tuple as defined in the module docstring.
892
entire_entry = list(entry[0])
893
for tree_number, tree_data in enumerate(entry[1]):
894
# (minikind, fingerprint, size, executable, tree_specific_string)
895
entire_entry.extend(tree_data)
896
# 3 for the key, 5 for the fields per tree.
897
tree_offset = 3 + tree_number * 5
899
entire_entry[tree_offset + 0] = tree_data[0]
901
entire_entry[tree_offset + 2] = str(tree_data[2])
903
entire_entry[tree_offset + 3] = DirState._to_yesno[tree_data[3]]
904
return '\0'.join(entire_entry)
906
def _fields_per_entry(self):
907
"""How many null separated fields should be in each entry row.
909
Each line now has an extra '\n' field which is not used
910
so we just skip over it
913
+ number of fields per tree_data (5) * tree count
916
tree_count = 1 + self._num_present_parents()
917
return 3 + 5 * tree_count + 1
919
def _find_block(self, key, add_if_missing=False):
920
"""Return the block that key should be present in.
922
:param key: A dirstate entry key.
923
:return: The block tuple.
925
block_index, present = self._find_block_index_from_key(key)
927
if not add_if_missing:
928
# check to see if key is versioned itself - we might want to
929
# add it anyway, because dirs with no entries dont get a
930
# dirblock at parse time.
931
# This is an uncommon branch to take: most dirs have children,
932
# and most code works with versioned paths.
933
parent_base, parent_name = osutils.split(key[0])
934
if not self._get_block_entry_index(parent_base, parent_name, 0)[3]:
935
# some parent path has not been added - its an error to add
937
raise errors.NotVersionedError(key[0:2], str(self))
938
self._dirblocks.insert(block_index, (key[0], []))
939
return self._dirblocks[block_index]
941
def _find_block_index_from_key(self, key):
942
"""Find the dirblock index for a key.
944
:return: The block index, True if the block for the key is present.
946
if key[0:2] == ('', ''):
948
block_index = bisect.bisect_left(self._dirblocks, (key[0], []), 1)
949
# _right returns one-past-where-key is so we have to subtract
950
# one to use it. we use _right here because there are two
951
# '' blocks - the root, and the contents of root
952
# we always have a minimum of 2 in self._dirblocks: root and
953
# root-contents, and for '', we get 2 back, so this is
954
# simple and correct:
955
present = (block_index < len(self._dirblocks) and
956
self._dirblocks[block_index][0] == key[0])
957
return block_index, present
959
def _find_entry_index(self, key, block):
960
"""Find the entry index for a key in a block.
962
:return: The entry index, True if the entry for the key is present.
964
entry_index = bisect.bisect_left(block, (key, []))
965
present = (entry_index < len(block) and
966
block[entry_index][0] == key)
967
return entry_index, present
970
def from_tree(tree, dir_state_filename):
971
"""Create a dirstate from a bzr Tree.
973
:param tree: The tree which should provide parent information and
975
:return: a DirState object which is currently locked for writing.
976
(it was locked by DirState.initialize)
978
result = DirState.initialize(dir_state_filename)
982
parent_ids = tree.get_parent_ids()
983
num_parents = len(parent_ids)
985
for parent_id in parent_ids:
986
parent_tree = tree.branch.repository.revision_tree(parent_id)
987
parent_trees.append((parent_id, parent_tree))
988
parent_tree.lock_read()
989
result.set_parent_trees(parent_trees, [])
990
result.set_state_from_inventory(tree.inventory)
992
for revid, parent_tree in parent_trees:
996
# The caller won't have a chance to unlock this, so make sure we
1002
def get_ghosts(self):
1003
"""Return a list of the parent tree revision ids that are ghosts."""
1004
self._read_header_if_needed()
1007
def get_lines(self):
1008
"""Serialise the entire dirstate to a sequence of lines."""
1009
if (self._header_state == DirState.IN_MEMORY_UNMODIFIED and
1010
self._dirblock_state == DirState.IN_MEMORY_UNMODIFIED):
1011
# read whats on disk.
1012
self._state_file.seek(0)
1013
return self._state_file.readlines()
1015
lines.append(self._get_parents_line(self.get_parent_ids()))
1016
lines.append(self._get_ghosts_line(self._ghosts))
1017
# append the root line which is special cased
1018
lines.extend(map(self._entry_to_line, self._iter_entries()))
1019
return self._get_output_lines(lines)
1021
def _get_ghosts_line(self, ghost_ids):
1022
"""Create a line for the state file for ghost information."""
1023
return '\0'.join([str(len(ghost_ids))] + ghost_ids)
1025
def _get_parents_line(self, parent_ids):
1026
"""Create a line for the state file for parents information."""
1027
return '\0'.join([str(len(parent_ids))] + parent_ids)
1029
def _get_fields_to_entry(self):
1030
"""Get a function which converts entry fields into a entry record.
1032
This handles size and executable, as well as parent records.
1034
:return: A function which takes a list of fields, and returns an
1035
appropriate record for storing in memory.
1037
# This is intentionally unrolled for performance
1038
num_present_parents = self._num_present_parents()
1039
if num_present_parents == 0:
1040
def fields_to_entry_0_parents(fields, _int=int):
1041
path_name_file_id_key = (fields[0], fields[1], fields[2])
1042
return (path_name_file_id_key, [
1044
fields[3], # minikind
1045
fields[4], # fingerprint
1046
_int(fields[5]), # size
1047
fields[6] == 'y', # executable
1048
fields[7], # packed_stat or revision_id
1050
return fields_to_entry_0_parents
1051
elif num_present_parents == 1:
1052
def fields_to_entry_1_parent(fields, _int=int):
1053
path_name_file_id_key = (fields[0], fields[1], fields[2])
1054
return (path_name_file_id_key, [
1056
fields[3], # minikind
1057
fields[4], # fingerprint
1058
_int(fields[5]), # size
1059
fields[6] == 'y', # executable
1060
fields[7], # packed_stat or revision_id
1063
fields[8], # minikind
1064
fields[9], # fingerprint
1065
_int(fields[10]), # size
1066
fields[11] == 'y', # executable
1067
fields[12], # packed_stat or revision_id
1070
return fields_to_entry_1_parent
1071
elif num_present_parents == 2:
1072
def fields_to_entry_2_parents(fields, _int=int):
1073
path_name_file_id_key = (fields[0], fields[1], fields[2])
1074
return (path_name_file_id_key, [
1076
fields[3], # minikind
1077
fields[4], # fingerprint
1078
_int(fields[5]), # size
1079
fields[6] == 'y', # executable
1080
fields[7], # packed_stat or revision_id
1083
fields[8], # minikind
1084
fields[9], # fingerprint
1085
_int(fields[10]), # size
1086
fields[11] == 'y', # executable
1087
fields[12], # packed_stat or revision_id
1090
fields[13], # minikind
1091
fields[14], # fingerprint
1092
_int(fields[15]), # size
1093
fields[16] == 'y', # executable
1094
fields[17], # packed_stat or revision_id
1097
return fields_to_entry_2_parents
1099
def fields_to_entry_n_parents(fields, _int=int):
1100
path_name_file_id_key = (fields[0], fields[1], fields[2])
1101
trees = [(fields[cur], # minikind
1102
fields[cur+1], # fingerprint
1103
_int(fields[cur+2]), # size
1104
fields[cur+3] == 'y', # executable
1105
fields[cur+4], # stat or revision_id
1106
) for cur in xrange(3, len(fields)-1, 5)]
1107
return path_name_file_id_key, trees
1108
return fields_to_entry_n_parents
1110
def get_parent_ids(self):
1111
"""Return a list of the parent tree ids for the directory state."""
1112
self._read_header_if_needed()
1113
return list(self._parents)
1115
def _get_block_entry_index(self, dirname, basename, tree_index):
1116
"""Get the coordinates for a path in the state structure.
1118
:param dirname: The utf8 dirname to lookup.
1119
:param basename: The utf8 basename to lookup.
1120
:param tree_index: The index of the tree for which this lookup should
1122
:return: A tuple describing where the path is located, or should be
1123
inserted. The tuple contains four fields: the block index, the row
1124
index, anda two booleans are True when the directory is present, and
1125
when the entire path is present. There is no guarantee that either
1126
coordinate is currently reachable unless the found field for it is
1127
True. For instance, a directory not present in the searched tree
1128
may be returned with a value one greater than the current highest
1129
block offset. The directory present field will always be True when
1130
the path present field is True. The directory present field does
1131
NOT indicate that the directory is present in the searched tree,
1132
rather it indicates that there are at least some files in some
1135
self._read_dirblocks_if_needed()
1136
key = dirname, basename, ''
1137
block_index, present = self._find_block_index_from_key(key)
1139
# no such directory - return the dir index and 0 for the row.
1140
return block_index, 0, False, False
1141
block = self._dirblocks[block_index][1] # access the entries only
1142
entry_index, present = self._find_entry_index(key, block)
1143
# linear search through present entries at this path to find the one
1145
while entry_index < len(block) and block[entry_index][0][1] == basename:
1146
if block[entry_index][1][tree_index][0] not in \
1147
('a', 'r'): # absent, relocated
1148
return block_index, entry_index, True, True
1150
return block_index, entry_index, True, False
1152
def _get_entry(self, tree_index, fileid_utf8=None, path_utf8=None):
1153
"""Get the dirstate entry for path in tree tree_index
1155
If either file_id or path is supplied, it is used as the key to lookup.
1156
If both are supplied, the fastest lookup is used, and an error is
1157
raised if they do not both point at the same row.
1159
:param tree_index: The index of the tree we wish to locate this path
1160
in. If the path is present in that tree, the entry containing its
1161
details is returned, otherwise (None, None) is returned
1162
:param fileid_utf8: A utf8 file_id to look up.
1163
:param path_utf8: An utf8 path to be looked up.
1164
:return: The dirstate entry tuple for path, or (None, None)
1166
self._read_dirblocks_if_needed()
1167
if path_utf8 is not None:
1168
assert path_utf8.__class__ == str, 'path_utf8 is not a str: %s %s' % (type(path_utf8), path_utf8)
1169
# path lookups are faster
1170
dirname, basename = osutils.split(path_utf8)
1171
block_index, entry_index, dir_present, file_present = \
1172
self._get_block_entry_index(dirname, basename, tree_index)
1173
if not file_present:
1175
entry = self._dirblocks[block_index][1][entry_index]
1176
assert entry[0][2] and entry[1][tree_index][0] not in ('a', 'r'), 'unversioned entry?!?!'
1178
if entry[0][2] != fileid_utf8:
1179
raise errors.BzrError('integrity error ? : mismatching'
1180
' tree_index, file_id and path')
1183
assert fileid_utf8 is not None
1184
possible_keys = self._get_id_index().get(fileid_utf8, None)
1185
if not possible_keys:
1187
for key in possible_keys:
1188
(block_index, entry_index, dir_present,
1189
file_present) = self._get_block_entry_index(key[0], key[1],
1192
entry = self._dirblocks[block_index][1][entry_index]
1193
# _get_block_entry_index only returns entries that are not
1194
# absent in the current tree. _get_id_index will return
1195
# both locations for a renamed file. It is possible that a
1196
# new file was added at the same location that the old file
1197
# was renamed away. So _get_block_entry_index will actually
1198
# match the new file, skipping the fact that the real entry
1199
# we want is the rename. By just continuing here, we should
1200
# find the record at the target location, because
1201
# _get_id_index should return all locations.
1202
if entry[0][2] != fileid_utf8:
1204
assert entry[1][tree_index][0] not in ('a', 'r')
1205
assert key == entry[0], ('We were told that %s would be at'
1206
' %s, %s, but we found %s' % (key, block_index,
1207
entry_index, entry))
1212
def initialize(path):
1213
"""Create a new dirstate on path.
1215
The new dirstate will be an empty tree - that is it has no parents,
1216
and only a root node - which has id ROOT_ID.
1218
The object will be write locked when returned to the caller,
1219
unless there was an exception in the writing, in which case it
1222
:param path: The name of the file for the dirstate.
1223
:return: A DirState object.
1225
# This constructs a new DirState object on a path, sets the _state_file
1226
# to a new empty file for that path. It then calls _set_data() with our
1227
# stock empty dirstate information - a root with ROOT_ID, no children,
1228
# and no parents. Finally it calls save() to ensure that this data will
1230
result = DirState(path)
1231
# root dir and root dir contents with no children.
1232
empty_tree_dirblocks = [('', []), ('', [])]
1233
# a new root directory, with a NULLSTAT.
1234
empty_tree_dirblocks[0][1].append(
1235
(('', '', bzrlib.inventory.ROOT_ID), [
1236
('d', '', 0, False, DirState.NULLSTAT),
1240
result._set_data([], empty_tree_dirblocks)
1247
def _inv_entry_to_details(self, inv_entry):
1248
"""Convert an inventory entry (from a revision tree) to state details.
1250
:param inv_entry: An inventory entry whose sha1 and link targets can be
1251
relied upon, and which has a revision set.
1252
:return: A details tuple - the details for a single tree at a path +
1255
kind = inv_entry.kind
1256
minikind = DirState._kind_to_minikind[kind]
1257
tree_data = inv_entry.revision
1258
assert len(tree_data) > 0, 'empty revision for the inv_entry.'
1259
if kind == 'directory':
1263
elif kind == 'symlink':
1264
fingerprint = inv_entry.symlink_target or ''
1267
elif kind == 'file':
1268
fingerprint = inv_entry.text_sha1 or ''
1269
size = inv_entry.text_size or 0
1270
executable = inv_entry.executable
1273
return (minikind, fingerprint, size, executable, tree_data)
1275
def _iter_entries(self):
1276
"""Iterate over all the entries in the dirstate.
1278
Each yelt item is an entry in the standard format described in the
1279
docstring of bzrlib.dirstate.
1281
self._read_dirblocks_if_needed()
1282
for directory in self._dirblocks:
1283
for entry in directory[1]:
1286
def _get_id_index(self):
1287
"""Get an id index of self._dirblocks."""
1288
if self._id_index is None:
1290
for key, tree_details in self._iter_entries():
1291
id_index.setdefault(key[2], set()).add(key)
1292
self._id_index = id_index
1293
return self._id_index
1295
def _get_output_lines(self, lines):
1296
"""format lines for final output.
1298
:param lines: A sequece of lines containing the parents list and the
1301
output_lines = ['#bazaar dirstate flat format 2\n']
1302
lines.append('') # a final newline
1303
inventory_text = '\0\n\0'.join(lines)
1304
output_lines.append('adler32: %s\n' % (zlib.adler32(inventory_text),))
1305
# -3, 1 for num parents, 1 for ghosts, 1 for final newline
1306
num_entries = len(lines)-3
1307
output_lines.append('num_entries: %s\n' % (num_entries,))
1308
output_lines.append(inventory_text)
1311
def _make_deleted_row(self, fileid_utf8, parents):
1312
"""Return a deleted for for fileid_utf8."""
1313
return ('/', 'RECYCLED.BIN', 'file', fileid_utf8, 0, DirState.NULLSTAT,
1316
def _num_present_parents(self):
1317
"""The number of parent entries in each record row."""
1318
return len(self._parents) - len(self._ghosts)
1322
"""Construct a DirState on the file at path path.
1324
:return: An unlocked DirState object, associated with the given path.
1326
result = DirState(path)
1329
def _read_dirblocks_if_needed(self):
1330
"""Read in all the dirblocks from the file if they are not in memory.
1332
This populates self._dirblocks, and sets self._dirblock_state to
1333
IN_MEMORY_UNMODIFIED. It is not currently ready for incremental block
1336
self._read_header_if_needed()
1337
if self._dirblock_state == DirState.NOT_IN_MEMORY:
1338
# move the _state_file pointer to after the header (in case bisect
1339
# has been called in the mean time)
1340
self._state_file.seek(self._end_of_header)
1341
text = self._state_file.read()
1342
# TODO: check the adler checksums. adler_measured = zlib.adler32(text)
1344
fields = text.split('\0')
1345
# Remove the last blank entry
1346
trailing = fields.pop()
1347
assert trailing == ''
1348
# consider turning fields into a tuple.
1350
# skip the first field which is the trailing null from the header.
1352
# Each line now has an extra '\n' field which is not used
1353
# so we just skip over it
1355
# 3 fields for the key
1356
# + number of fields per tree_data (5) * tree count
1358
num_present_parents = self._num_present_parents()
1359
tree_count = 1 + num_present_parents
1360
entry_size = self._fields_per_entry()
1361
expected_field_count = entry_size * self._num_entries
1362
if len(fields) - cur > expected_field_count:
1363
fields = fields[:expected_field_count + cur]
1364
trace.mutter('Unexpectedly long dirstate field count!')
1365
print "XXX: incorrectly truncated dirstate file bug triggered."
1366
field_count = len(fields)
1367
# this checks our adjustment, and also catches file too short.
1368
assert field_count - cur == expected_field_count, \
1369
'field count incorrect %s != %s, entry_size=%s, '\
1370
'num_entries=%s fields=%r' % (
1371
field_count - cur, expected_field_count, entry_size,
1372
self._num_entries, fields)
1374
if num_present_parents == 1:
1375
# Bind external functions to local names
1377
# We access all fields in order, so we can just iterate over
1378
# them. Grab an straight iterator over the fields. (We use an
1379
# iterator because we don't want to do a lot of additions, nor
1380
# do we want to do a lot of slicing)
1381
next = iter(fields).next
1382
# Move the iterator to the current position
1383
for x in xrange(cur):
1385
# The two blocks here are deliberate: the root block and the
1386
# contents-of-root block.
1387
self._dirblocks = [('', []), ('', [])]
1388
current_block = self._dirblocks[0][1]
1389
current_dirname = ''
1390
append_entry = current_block.append
1391
for count in xrange(self._num_entries):
1395
if dirname != current_dirname:
1396
# new block - different dirname
1398
current_dirname = dirname
1399
self._dirblocks.append((current_dirname, current_block))
1400
append_entry = current_block.append
1401
# we know current_dirname == dirname, so re-use it to avoid
1402
# creating new strings
1403
entry = ((current_dirname, name, file_id),
1406
next(), # fingerprint
1407
_int(next()), # size
1408
next() == 'y', # executable
1409
next(), # packed_stat or revision_id
1413
next(), # fingerprint
1414
_int(next()), # size
1415
next() == 'y', # executable
1416
next(), # packed_stat or revision_id
1420
assert trailing == '\n'
1421
# append the entry to the current block
1423
self._split_root_dirblock_into_contents()
1425
fields_to_entry = self._get_fields_to_entry()
1426
entries = [fields_to_entry(fields[pos:pos+entry_size])
1427
for pos in xrange(cur, field_count, entry_size)]
1428
self._entries_to_current_state(entries)
1429
self._dirblock_state = DirState.IN_MEMORY_UNMODIFIED
1431
def _read_header(self):
1432
"""This reads in the metadata header, and the parent ids.
1434
After reading in, the file should be positioned at the null
1435
just before the start of the first record in the file.
1437
:return: (expected adler checksum, number of entries, parent list)
1439
self._read_prelude()
1440
parent_line = self._state_file.readline()
1441
info = parent_line.split('\0')
1442
num_parents = int(info[0])
1443
assert num_parents == len(info)-2, 'incorrect parent info line'
1444
self._parents = info[1:-1]
1446
ghost_line = self._state_file.readline()
1447
info = ghost_line.split('\0')
1448
num_ghosts = int(info[1])
1449
assert num_ghosts == len(info)-3, 'incorrect ghost info line'
1450
self._ghosts = info[2:-1]
1451
self._header_state = DirState.IN_MEMORY_UNMODIFIED
1452
self._end_of_header = self._state_file.tell()
1454
def _read_header_if_needed(self):
1455
"""Read the header of the dirstate file if needed."""
1456
# inline this as it will be called a lot
1457
if not self._lock_token:
1458
raise errors.ObjectNotLocked(self)
1459
if self._header_state == DirState.NOT_IN_MEMORY:
1462
def _read_prelude(self):
1463
"""Read in the prelude header of the dirstate file
1465
This only reads in the stuff that is not connected to the adler
1466
checksum. The position will be correct to read in the rest of
1467
the file and check the checksum after this point.
1468
The next entry in the file should be the number of parents,
1469
and their ids. Followed by a newline.
1471
header = self._state_file.readline()
1472
assert header == '#bazaar dirstate flat format 2\n', \
1473
'invalid header line: %r' % (header,)
1474
adler_line = self._state_file.readline()
1475
assert adler_line.startswith('adler32: '), 'missing adler32 checksum'
1476
self.adler_expected = int(adler_line[len('adler32: '):-1])
1477
num_entries_line = self._state_file.readline()
1478
assert num_entries_line.startswith('num_entries: '), 'missing num_entries line'
1479
self._num_entries = int(num_entries_line[len('num_entries: '):-1])
1482
"""Save any pending changes created during this session.
1484
We reuse the existing file, because that prevents race conditions with
1485
file creation, and we expect to be using oslocks on it in the near
1486
future to prevent concurrent modification and reads - because dirstates
1487
incremental data aggretation is not compatible with reading a modified
1488
file, and replacing a file in use by another process is impossible on
1491
A dirstate in read only mode should be smart enough though to validate
1492
that the file has not changed, and otherwise discard its cache and
1493
start over, to allow for fine grained read lock duration, so 'status'
1494
wont block 'commit' - for example.
1496
if (self._header_state == DirState.IN_MEMORY_MODIFIED or
1497
self._dirblock_state == DirState.IN_MEMORY_MODIFIED):
1498
self._state_file.seek(0)
1499
self._state_file.writelines(self.get_lines())
1500
self._state_file.truncate()
1501
self._state_file.flush()
1502
self._header_state = DirState.IN_MEMORY_UNMODIFIED
1503
self._dirblock_state = DirState.IN_MEMORY_UNMODIFIED
1505
def _set_data(self, parent_ids, dirblocks):
1506
"""Set the full dirstate data in memory.
1508
This is an internal function used to completely replace the objects
1509
in memory state. It puts the dirstate into state 'full-dirty'.
1511
:param parent_ids: A list of parent tree revision ids.
1512
:param dirblocks: A list containing one tuple for each directory in the
1513
tree. Each tuple contains the directory path and a list of entries
1514
found in that directory.
1516
# our memory copy is now authoritative.
1517
self._dirblocks = dirblocks
1518
self._header_state = DirState.IN_MEMORY_MODIFIED
1519
self._dirblock_state = DirState.IN_MEMORY_MODIFIED
1520
self._parents = list(parent_ids)
1521
self._id_index = None
1523
def set_path_id(self, path, new_id):
1524
"""Change the id of path to new_id in the current working tree.
1526
:param path: The path inside the tree to set - '' is the root, 'foo'
1527
is the path foo in the root.
1528
:param new_id: The new id to assign to the path. This must be a utf8
1529
file id (not unicode, and not None).
1531
# TODO: start warning here.
1532
assert new_id.__class__ == str
1533
self._read_dirblocks_if_needed()
1535
import pdb;pdb.set_trace()
1537
raise NotImplementedError(self.set_path_id)
1538
# TODO: check new id is unique
1539
entry = self._get_entry(0, path_utf8=path)
1540
if entry[0][2] == new_id:
1541
# Nothing to change.
1543
# mark the old path absent, and insert a new root path
1544
self._make_absent(entry)
1545
self.update_minimal(('', '', new_id), 'd',
1546
path_utf8='', packed_stat=entry[1][0][4])
1547
self._dirblock_state = DirState.IN_MEMORY_MODIFIED
1548
if self._id_index is not None:
1549
self._id_index.setdefault(new_id, set()).add(entry[0])
1551
def set_parent_trees(self, trees, ghosts):
1552
"""Set the parent trees for the dirstate.
1554
:param trees: A list of revision_id, tree tuples. tree must be provided
1555
even if the revision_id refers to a ghost: supply an empty tree in
1557
:param ghosts: A list of the revision_ids that are ghosts at the time
1560
# TODO: generate a list of parent indexes to preserve to save
1561
# processing specific parent trees. In the common case one tree will
1562
# be preserved - the left most parent.
1563
# TODO: if the parent tree is a dirstate, we might want to walk them
1564
# all by path in parallel for 'optimal' common-case performance.
1565
# generate new root row.
1566
self._read_dirblocks_if_needed()
1567
# TODO future sketch: Examine the existing parents to generate a change
1568
# map and then walk the new parent trees only, mapping them into the
1569
# dirstate. Walk the dirstate at the same time to remove unreferenced
1572
# sketch: loop over all entries in the dirstate, cherry picking
1573
# entries from the parent trees, if they are not ghost trees.
1574
# after we finish walking the dirstate, all entries not in the dirstate
1575
# are deletes, so we want to append them to the end as per the design
1576
# discussions. So do a set difference on ids with the parents to
1577
# get deletes, and add them to the end.
1578
# During the update process we need to answer the following questions:
1579
# - find other keys containing a fileid in order to create cross-path
1580
# links. We dont't trivially use the inventory from other trees
1581
# because this leads to either double touching, or to accessing
1583
# - find other keys containing a path
1584
# We accumulate each entry via this dictionary, including the root
1587
# we could do parallel iterators, but because file id data may be
1588
# scattered throughout, we dont save on index overhead: we have to look
1589
# at everything anyway. We can probably save cycles by reusing parent
1590
# data and doing an incremental update when adding an additional
1591
# parent, but for now the common cases are adding a new parent (merge),
1592
# and replacing completely (commit), and commit is more common: so
1593
# optimise merge later.
1595
# ---- start generation of full tree mapping data
1596
# what trees should we use?
1597
parent_trees = [tree for rev_id, tree in trees if rev_id not in ghosts]
1598
# how many trees do we end up with
1599
parent_count = len(parent_trees)
1601
# one: the current tree
1602
for entry in self._iter_entries():
1603
# skip entries not in the current tree
1604
if entry[1][0][0] in ('a', 'r'): # absent, relocated
1606
by_path[entry[0]] = [entry[1][0]] + \
1607
[DirState.NULL_PARENT_DETAILS] * parent_count
1608
id_index[entry[0][2]] = set([entry[0]])
1610
# now the parent trees:
1611
for tree_index, tree in enumerate(parent_trees):
1612
# the index is off by one, adjust it.
1613
tree_index = tree_index + 1
1614
# when we add new locations for a fileid we need these ranges for
1615
# any fileid in this tree as we set the by_path[id] to:
1616
# already_processed_tree_details + new_details + new_location_suffix
1617
# the suffix is from tree_index+1:parent_count+1.
1618
new_location_suffix = [DirState.NULL_PARENT_DETAILS] * (parent_count - tree_index)
1619
# now stitch in all the entries from this tree
1620
for path, entry in tree.inventory.iter_entries_by_dir():
1621
# here we process each trees details for each item in the tree.
1622
# we first update any existing entries for the id at other paths,
1623
# then we either create or update the entry for the id at the
1624
# right path, and finally we add (if needed) a mapping from
1625
# file_id to this path. We do it in this order to allow us to
1626
# avoid checking all known paths for the id when generating a
1627
# new entry at this path: by adding the id->path mapping last,
1628
# all the mappings are valid and have correct relocation
1629
# records where needed.
1630
file_id = entry.file_id
1631
path_utf8 = path.encode('utf8')
1632
dirname, basename = osutils.split(path_utf8)
1633
new_entry_key = (dirname, basename, file_id)
1634
# tree index consistency: All other paths for this id in this tree
1635
# index must point to the correct path.
1636
for entry_key in id_index.setdefault(file_id, set()):
1637
# TODO:PROFILING: It might be faster to just update
1638
# rather than checking if we need to, and then overwrite
1639
# the one we are located at.
1640
if entry_key != new_entry_key:
1641
# this file id is at a different path in one of the
1642
# other trees, so put absent pointers there
1643
# This is the vertical axis in the matrix, all pointing
1645
by_path[entry_key][tree_index] = ('r', path_utf8, 0, False, '')
1646
# by path consistency: Insert into an existing path record (trivial), or
1647
# add a new one with relocation pointers for the other tree indexes.
1648
if new_entry_key in id_index[file_id]:
1649
# there is already an entry where this data belongs, just insert it.
1650
by_path[new_entry_key][tree_index] = \
1651
self._inv_entry_to_details(entry)
1653
# add relocated entries to the horizontal axis - this row
1654
# mapping from path,id. We need to look up the correct path
1655
# for the indexes from 0 to tree_index -1
1657
for lookup_index in xrange(tree_index):
1658
# boundary case: this is the first occurence of file_id
1659
# so there are no id_indexs, possibly take this out of
1661
if not len(id_index[file_id]):
1662
new_details.append(DirState.NULL_PARENT_DETAILS)
1664
# grab any one entry, use it to find the right path.
1665
# TODO: optimise this to reduce memory use in highly
1666
# fragmented situations by reusing the relocation
1668
a_key = iter(id_index[file_id]).next()
1669
if by_path[a_key][lookup_index][0] in ('r', 'a'):
1670
# its a pointer or missing statement, use it as is.
1671
new_details.append(by_path[a_key][lookup_index])
1673
# we have the right key, make a pointer to it.
1674
real_path = ('/'.join(a_key[0:2])).strip('/')
1675
new_details.append(('r', real_path, 0, False, ''))
1676
new_details.append(self._inv_entry_to_details(entry))
1677
new_details.extend(new_location_suffix)
1678
by_path[new_entry_key] = new_details
1679
id_index[file_id].add(new_entry_key)
1680
# --- end generation of full tree mappings
1682
# sort and output all the entries
1683
new_entries = sorted(by_path.items())
1684
self._entries_to_current_state(new_entries)
1685
self._parents = [rev_id for rev_id, tree in trees]
1686
self._ghosts = list(ghosts)
1687
self._header_state = DirState.IN_MEMORY_MODIFIED
1688
self._dirblock_state = DirState.IN_MEMORY_MODIFIED
1689
self._id_index = id_index
1691
def set_state_from_inventory(self, new_inv):
1692
"""Set new_inv as the current state.
1694
This API is called by tree transform, and will usually occur with
1695
existing parent trees.
1697
:param new_inv: The inventory object to set current state from.
1699
self._read_dirblocks_if_needed()
1701
# incremental algorithm:
1702
# two iterators: current data and new data, both in dirblock order.
1703
new_iterator = new_inv.iter_entries_by_dir()
1704
# we will be modifying the dirstate, so we need a stable iterator. In
1705
# future we might write one, for now we just clone the state into a
1706
# list - which is a shallow copy, so each
1707
old_iterator = iter(list(self._iter_entries()))
1708
# both must have roots so this is safe:
1709
current_new = new_iterator.next()
1710
current_old = old_iterator.next()
1711
def advance(iterator):
1713
return iterator.next()
1714
except StopIteration:
1716
while current_new or current_old:
1717
# skip entries in old that are not really there
1718
if current_old and current_old[1][0][0] in ('r', 'a'):
1719
# relocated or absent
1720
current_old = advance(old_iterator)
1723
# convert new into dirblock style
1724
new_path_utf8 = current_new[0].encode('utf8')
1725
new_dirname, new_basename = osutils.split(new_path_utf8)
1726
new_id = current_new[1].file_id
1727
new_entry_key = (new_dirname, new_basename, new_id)
1728
current_new_minikind = \
1729
DirState._kind_to_minikind[current_new[1].kind]
1731
# for safety disable variables
1732
new_path_utf8 = new_dirname = new_basename = new_id = new_entry_key = None
1733
# 5 cases, we dont have a value that is strictly greater than everything, so
1734
# we make both end conditions explicit
1736
# old is finished: insert current_new into the state.
1737
self.update_minimal(new_entry_key, current_new_minikind,
1738
executable=current_new[1].executable,
1739
path_utf8=new_path_utf8)
1740
current_new = advance(new_iterator)
1741
elif not current_new:
1743
self._make_absent(current_old)
1744
current_old = advance(old_iterator)
1745
elif new_entry_key == current_old[0]:
1746
# same - common case
1747
# TODO: update the record if anything significant has changed.
1748
# the minimal required trigger is if the execute bit or cached
1750
if (current_old[1][0][3] != current_new[1].executable or
1751
current_old[1][0][0] != current_new_minikind):
1752
self.update_minimal(current_old[0], current_new_minikind,
1753
executable=current_new[1].executable,
1754
path_utf8=new_path_utf8)
1755
# both sides are dealt with, move on
1756
current_old = advance(old_iterator)
1757
current_new = advance(new_iterator)
1758
elif new_entry_key < current_old[0]:
1760
# add a entry for this and advance new
1761
self.update_minimal(new_entry_key, current_new_minikind,
1762
executable=current_new[1].executable,
1763
path_utf8=new_path_utf8)
1764
current_new = advance(new_iterator)
1767
self._make_absent(current_old)
1768
current_old = advance(old_iterator)
1769
self._dirblock_state = DirState.IN_MEMORY_MODIFIED
1770
self._id_index = None
1772
def _make_absent(self, current_old):
1773
"""Mark current_old - an entry - as absent for tree 0.
1775
:return: True if this was the last details entry for they entry key:
1776
that is, if the underlying block has had the entry removed, thus
1777
shrinking in length.
1779
# build up paths that this id will be left at after the change is made,
1780
# so we can update their cross references in tree 0
1781
all_remaining_keys = set()
1782
# Dont check the working tree, because its going.
1783
for details in current_old[1][1:]:
1784
if details[0] not in ('a', 'r'): # absent, relocated
1785
all_remaining_keys.add(current_old[0])
1786
elif details[0] == 'r': # relocated
1787
# record the key for the real path.
1788
all_remaining_keys.add(tuple(osutils.split(details[1])) + (current_old[0][2],))
1789
# absent rows are not present at any path.
1790
last_reference = current_old[0] not in all_remaining_keys
1792
# the current row consists entire of the current item (being marked
1793
# absent), and relocated or absent entries for the other trees:
1794
# Remove it, its meaningless.
1795
block = self._find_block(current_old[0])
1796
entry_index, present = self._find_entry_index(current_old[0], block[1])
1798
block[1].pop(entry_index)
1799
# if we have an id_index in use, remove this key from it for this id.
1800
if self._id_index is not None:
1801
self._id_index[current_old[0][2]].remove(current_old[0])
1802
# update all remaining keys for this id to record it as absent. The
1803
# existing details may either be the record we are making as deleted
1804
# (if there were other trees with the id present at this path), or may
1806
for update_key in all_remaining_keys:
1807
update_block_index, present = \
1808
self._find_block_index_from_key(update_key)
1810
update_entry_index, present = \
1811
self._find_entry_index(update_key, self._dirblocks[update_block_index][1])
1813
update_tree_details = self._dirblocks[update_block_index][1][update_entry_index][1]
1814
# it must not be absent at the moment
1815
assert update_tree_details[0][0] != 'a' # absent
1816
update_tree_details[0] = DirState.NULL_PARENT_DETAILS
1817
self._dirblock_state = DirState.IN_MEMORY_MODIFIED
1818
return last_reference
1820
def update_minimal(self, key, minikind, executable=False, fingerprint='',
1821
packed_stat=None, size=0, path_utf8=None):
1822
"""Update an entry to the state in tree 0.
1824
This will either create a new entry at 'key' or update an existing one.
1825
It also makes sure that any other records which might mention this are
1828
:param key: (dir, name, file_id) for the new entry
1829
:param minikind: The type for the entry ('f' == 'file', 'd' ==
1831
:param executable: Should the executable bit be set?
1832
:param fingerprint: Simple fingerprint for new entry.
1833
:param packed_stat: packed stat value for new entry.
1834
:param size: Size information for new entry
1835
:param path_utf8: key[0] + '/' + key[1], just passed in to avoid doing
1838
block = self._find_block(key)[1]
1839
if packed_stat is None:
1840
packed_stat = DirState.NULLSTAT
1841
entry_index, present = self._find_entry_index(key, block)
1842
new_details = (minikind, fingerprint, size, executable, packed_stat)
1843
id_index = self._get_id_index()
1845
# new entry, synthesis cross reference here,
1846
existing_keys = id_index.setdefault(key[2], set())
1847
if not existing_keys:
1848
# not currently in the state, simplest case
1849
new_entry = key, [new_details] + self._empty_parent_info()
1851
# present at one or more existing other paths.
1852
# grab one of them and use it to generate parent
1853
# relocation/absent entries.
1854
new_entry = key, [new_details]
1855
for other_key in existing_keys:
1856
# change the record at other to be a pointer to this new
1857
# record. The loop looks similar to the change to
1858
# relocations when updating an existing record but its not:
1859
# the test for existing kinds is different: this can be
1860
# factored out to a helper though.
1861
other_block_index, present = self._find_block_index_from_key(other_key)
1863
other_entry_index, present = self._find_entry_index(other_key, self._dirblocks[other_block_index][1])
1865
assert path_utf8 is not None
1866
self._dirblocks[other_block_index][1][other_entry_index][1][0] = \
1867
('r', path_utf8, 0, False, '')
1869
num_present_parents = self._num_present_parents()
1870
for lookup_index in xrange(1, num_present_parents + 1):
1871
# grab any one entry, use it to find the right path.
1872
# TODO: optimise this to reduce memory use in highly
1873
# fragmented situations by reusing the relocation
1875
update_block_index, present = \
1876
self._find_block_index_from_key(other_key)
1878
update_entry_index, present = \
1879
self._find_entry_index(other_key, self._dirblocks[update_block_index][1])
1881
update_details = self._dirblocks[update_block_index][1][update_entry_index][1][lookup_index]
1882
if update_details[0] in ('r', 'a'): # relocated, absent
1883
# its a pointer or absent in lookup_index's tree, use
1885
new_entry[1].append(update_details)
1887
# we have the right key, make a pointer to it.
1888
pointer_path = osutils.pathjoin(*other_key[0:2])
1889
new_entry[1].append(('r', pointer_path, 0, False, ''))
1890
block.insert(entry_index, new_entry)
1891
existing_keys.add(key)
1893
# Does the new state matter?
1894
block[entry_index][1][0] = new_details
1895
# parents cannot be affected by what we do.
1896
# other occurences of this id can be found
1897
# from the id index.
1899
# tree index consistency: All other paths for this id in this tree
1900
# index must point to the correct path. We have to loop here because
1901
# we may have passed entries in the state with this file id already
1902
# that were absent - where parent entries are - and they need to be
1903
# converted to relocated.
1904
assert path_utf8 is not None
1905
for entry_key in id_index.setdefault(key[2], set()):
1906
# TODO:PROFILING: It might be faster to just update
1907
# rather than checking if we need to, and then overwrite
1908
# the one we are located at.
1909
if entry_key != key:
1910
# this file id is at a different path in one of the
1911
# other trees, so put absent pointers there
1912
# This is the vertical axis in the matrix, all pointing
1914
block_index, present = self._find_block_index_from_key(entry_key)
1916
entry_index, present = self._find_entry_index(entry_key, self._dirblocks[block_index][1])
1918
self._dirblocks[block_index][1][entry_index][1][0] = \
1919
('r', path_utf8, 0, False, '')
1920
# add a containing dirblock if needed.
1921
if new_details[0] == 'd':
1922
subdir_key = (osutils.pathjoin(*key[0:2]), '', '')
1923
block_index, present = self._find_block_index_from_key(subdir_key)
1925
self._dirblocks.insert(block_index, (subdir_key[0], []))
1927
self._dirblock_state = DirState.IN_MEMORY_MODIFIED
1930
def _wipe_state(self):
1931
"""Forget all state information about the dirstate."""
1932
self._header_state = DirState.NOT_IN_MEMORY
1933
self._dirblock_state = DirState.NOT_IN_MEMORY
1936
self._dirblocks = []
1938
def lock_read(self):
1939
"""Acquire a read lock on the dirstate"""
1940
if self._lock_token is not None:
1941
raise errors.LockContention(self._lock_token)
1942
self._lock_token = lock.ReadLock(self._filename)
1943
self._state_file = self._lock_token.f
1946
def lock_write(self):
1947
"""Acquire a write lock on the dirstate"""
1948
if self._lock_token is not None:
1949
raise errors.LockContention(self._lock_token)
1950
self._lock_token = lock.WriteLock(self._filename)
1951
self._state_file = self._lock_token.f
1955
"""Drop any locks held on the dirstate"""
1956
if self._lock_token is None:
1957
raise errors.LockNotHeld(self)
1958
self._state_file = None
1959
self._lock_token.unlock()
1960
self._lock_token = None
1962
def _requires_lock(self):
1963
"""Checks that a lock is currently held by someone on the dirstate"""
1964
if not self._lock_token:
1965
raise errors.ObjectNotLocked(self)
1967
def pack_stat(st, _encode=base64.encodestring, _pack=struct.pack):
1968
"""Convert stat values into a packed representation."""
1969
# jam 20060614 it isn't really worth removing more entries if we
1970
# are going to leave it in packed form.
1971
# With only st_mtime and st_mode filesize is 5.5M and read time is 275ms
1972
# With all entries filesize is 5.9M and read time is mabye 280ms
1973
# well within the noise margin
1975
# base64.encode always adds a final newline, so strip it off
1976
return _encode(_pack('>llllll'
1977
, st.st_size, st.st_mtime, st.st_ctime
1978
, st.st_dev, st.st_ino, st.st_mode))[:-1]