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._end_of_header = None
285
self._bisect_page_size = DirState.BISECT_PAGE_SIZE
287
def add(self, path, file_id, kind, stat, link_or_sha1):
288
"""Add a path to be tracked.
290
:param path: The path within the dirstate - '' is the root, 'foo' is the
291
path foo within the root, 'foo/bar' is the path bar within foo
293
:param file_id: The file id of the path being added.
294
:param kind: The kind of the path.
295
:param stat: The output of os.lstate for the path.
296
:param link_or_sha1: The sha value of the file, or the target of a
297
symlink. '' for directories.
300
# find the block its in.
301
# find the location in the block.
302
# check its not there
304
#------- copied from bzrlib.inventory.make_entry
305
# --- normalized_filename wants a unicode basename only, so get one.
306
dirname, basename = os.path.split(path)
307
# we dont import normalized_filename directly because we want to be
308
# able to change the implementation at runtime for tests.
309
norm_name, can_access = osutils.normalized_filename(basename)
310
if norm_name != basename:
314
raise errors.InvalidNormalization(path)
315
# now that we've normalised, we need the correct utf8 path and
316
# dirname and basename elements. This single encode and split should be
317
# faster than three separate encodes.
318
utf8path = (dirname + '/' + basename).strip('/').encode('utf8')
319
dirname, basename = os.path.split(utf8path)
320
assert file_id.__class__ == str, \
321
"must be a utf8 file_id not %s" % (type(file_id))
322
entry_key = (dirname, basename, file_id)
323
self._read_dirblocks_if_needed()
324
block_index, present = self._find_block_index_from_key(entry_key)
326
# TODO: This test is not complete - an empty directory, or a
327
# directory for a parent tree will fool it.
328
# some parent path has not been added - its an error to add this
330
raise errors.NotVersionedError(path, str(self))
331
block = self._dirblocks[block_index][1]
334
packed_stat = DirState.NULLSTAT
337
packed_stat = pack_stat(stat)
338
parent_info = self._empty_parent_info()
339
minikind = DirState._kind_to_minikind[kind]
341
entry_data = entry_key, [
342
(minikind, link_or_sha1, size, False, packed_stat),
344
elif kind == 'directory':
345
entry_data = entry_key, [
346
(minikind, '', 0, False, packed_stat),
348
elif kind == 'symlink':
349
entry_data = entry_key, [
350
(minikind, link_or_sha1, size, False, packed_stat),
353
raise errors.BzrError('unknown kind %r' % kind)
354
entry_index, present = self._find_entry_index(entry_key, block)
355
assert not present, "basename %r already added" % basename
356
block.insert(entry_index, entry_data)
358
if kind == 'directory':
359
# insert a new dirblock
360
self._ensure_block(block_index, entry_index, utf8path)
361
self._dirblock_state = DirState.IN_MEMORY_MODIFIED
363
def _bisect(self, dir_name_list):
364
"""Bisect through the disk structure for specific rows."""
365
self._requires_lock()
366
# We need the file pointer to be right after the initial header block
367
self._read_header_if_needed()
368
# If _dirblock_state was in memory, we should just return info from
369
# there, this function is only meant to handle when we want to read
371
assert self._dirblock_state == DirState.NOT_IN_MEMORY
373
# The disk representation is generally info + '\0\n\0' at the end. But
374
# for bisecting, it is easier to treat this as '\0' + info + '\0\n'
375
# Because it means we can sync on the '\n'
376
state_file = self._state_file
377
file_size = os.fstat(state_file.fileno()).st_size
378
# We end up with 2 extra fields, we should have a trailing '\n' to
379
# ensure that we read the whole record, and we should have a precursur
380
# '' which ensures that we start after the previous '\n'
381
entry_field_count = self._fields_per_entry() + 1
383
low = self._end_of_header
384
high = file_size - 1 # Ignore the final '\0'
385
# Map from (dir, name) => entry
388
# Avoid infinite seeking
389
max_count = 30*len(dir_name_list)
391
# pending is a list of places to look.
392
# each entry is a tuple of low, high, dir_names
393
# low -> the first byte offset to read (inclusive)
394
# high -> the last byte offset (inclusive)
395
# dir_names -> The list of (dir, name) pairs that should be found in
396
# the [low, high] range
397
pending = [(low, high, dir_name_list)]
399
page_size = self._bisect_page_size
401
fields_to_entry = self._get_fields_to_entry()
404
low, high, cur_files = pending.pop()
407
# No files to look for
411
# Did not find cur_files, these will be returned as None
412
# However, other logic should probably prevent this from ever
417
if count > max_count:
418
raise errors.BzrError('Too many seeks, most likely a bug.')
420
mid = max(low, (low+high-page_size)/2)
423
# limit the read size, so we don't end up reading data that we have
425
read_size = min(page_size, (high-mid)+1)
426
block = state_file.read(read_size)
429
entries = block.split('\n')
432
# We didn't find a '\n', so we cannot have found any records.
433
# So put this range back and try again. But we know we have to
434
# increase the page size, because a single read did not contain
435
# a record break (so records must be larger than page_size)
437
pending.append((low, high, cur_files))
440
# Check the first and last entries, in case they are partial, or if
441
# we don't care about the rest of this page
443
first_fields = entries[0].split('\0')
444
if len(first_fields) < entry_field_count:
445
# We didn't get the complete first entry
446
# so move start, and grab the next, which
447
# should be a full entry
448
start += len(entries[0])+1
449
first_fields = entries[1].split('\0')
452
if len(first_fields) <= 2:
453
# We didn't even get a filename here... what do we do?
454
# Try a large page size and repeat this query
456
pending.append((low, high, cur_files))
459
# Find what entries we are looking for, which occur before and
460
# after this first record.
462
first_dir_name = (first_fields[1], first_fields[2])
463
first_loc = bisect.bisect_left(cur_files, first_dir_name)
465
# These exist before the current location
466
pre = cur_files[:first_loc]
467
# These occur after the current location, which may be in the
468
# data we read, or might be after the last entry
469
post = cur_files[first_loc:]
471
if post and len(first_fields) >= entry_field_count:
472
# We have files after the first entry
474
# Parse the last entry
475
last_entry_num = len(entries)-1
476
last_fields = entries[last_entry_num].split('\0')
477
if len(last_fields) < entry_field_count:
478
# The very last hunk was not complete,
479
# read the previous hunk
480
after = mid + len(block) - len(entries[-1])
482
last_fields = entries[last_entry_num].split('\0')
484
after = mid + len(block)
486
last_dir_name = (last_fields[1], last_fields[2])
487
last_loc = bisect.bisect_right(post, last_dir_name)
489
middle_files = post[:last_loc]
490
post = post[last_loc:]
493
# We have files that should occur in this block
494
# (>= first, <= last)
495
# Either we will find them here, or we can mark them as
498
if middle_files[0] == first_dir_name:
499
# We might need to go before this location
500
pre.append(first_dir_name)
501
if middle_files[-1] == last_dir_name:
502
post.insert(0, last_dir_name)
504
# Find out what paths we have
505
paths = {first_dir_name:[first_fields]}
506
# last_dir_name might == first_dir_name so we need to be
507
# careful if we should append rather than overwrite
508
if last_entry_num != first_entry_num:
509
paths.setdefault(last_dir_name, []).append(last_fields)
510
for num in xrange(first_entry_num+1, last_entry_num):
511
# TODO: jam 20070223 We are already splitting here, so
512
# shouldn't we just split the whole thing rather
513
# than doing the split again in add_one_record?
514
fields = entries[num].split('\0')
515
dir_name = (fields[1], fields[2])
516
paths.setdefault(dir_name, []).append(fields)
518
for dir_name in middle_files:
519
for fields in paths.get(dir_name, []):
520
# offset by 1 because of the opening '\0'
521
# consider changing fields_to_entry to avoid the
523
entry = fields_to_entry(fields[1:])
524
found.setdefault(dir_name, []).append(entry)
526
# Now we have split up everything into pre, middle, and post, and
527
# we have handled everything that fell in 'middle'.
528
# We add 'post' first, so that we prefer to seek towards the
529
# beginning, so that we will tend to go as early as we need, and
530
# then only seek forward after that.
532
pending.append((after, high, post))
534
pending.append((low, start-1, pre))
536
return [found.get(dir_name, None) for dir_name in dir_name_list]
538
def _empty_parent_info(self):
539
return [DirState.NULL_PARENT_DETAILS] * (len(self._parents) -
542
def _ensure_block(self, parent_block_index, parent_row_index, dirname):
543
"""Enssure a block for dirname exists.
545
This function exists to let callers which know that there is a
546
directory dirname ensure that the block for it exists. This block can
547
fail to exist because of demand loading, or because a directory had no
548
children. In either case it is not an error. It is however an error to
549
call this if there is no parent entry for the directory, and thus the
550
function requires the coordinates of such an entry to be provided.
552
The root row is special cased and can be indicated with a parent block
555
:param parent_block_index: The index of the block in which dirname's row
557
:param parent_row_index: The index in the parent block where the row
559
:param dirname: The utf8 dirname to ensure there is a block for.
560
:return: The index for the block.
563
# the basename of the directory must be the end of its full name.
564
if not (parent_block_index == -1 and
565
parent_block_index == -1 and dirname == ''):
566
assert dirname.endswith(
567
self._dirblocks[parent_block_index][1][parent_row_index][0][1])
568
block_index, present = self._find_block_index_from_key((dirname, '', ''))
570
## In future, when doing partial parsing, this should load and
571
# populate the entire block.
572
self._dirblocks.insert(block_index, (dirname, []))
575
def _entries_to_current_state(self, new_entries):
576
"""Load new_entries into self.dirblocks.
578
Process new_entries into the current state object, making them the active
581
:param new_entries: A sorted list of entries. This function does not sort
582
to prevent unneeded overhead when callers have a sorted list already.
585
assert new_entries[0][0][0:2] == ('', ''), \
586
"Missing root row %r" % new_entries[0][0]
587
# The two blocks here are deliberate: the root block and the
588
# contents-of-root block.
589
self._dirblocks = [('', []), ('', [])]
590
current_block = self._dirblocks[0][1]
593
append_entry = current_block.append
594
for entry in new_entries:
595
if entry[0][0] != current_dirname:
596
# new block - different dirname
598
current_dirname = entry[0][0]
599
self._dirblocks.append((current_dirname, current_block))
600
append_entry = current_block.append
601
# append the entry to the current block
603
self._split_root_dirblock_into_contents()
605
def _split_root_dirblock_into_contents(self):
606
"""Split the root dirblocks into root and contents-of-root.
608
After parsing by path, we end up with root entries and contents-of-root
609
entries in the same block. This loop splits them out again.
611
# The above loop leaves the "root block" entries mixed with the
612
# "contents-of-root block". But we don't want an if check on
613
# all entries, so instead we just fix it up here.
614
assert self._dirblocks[1] == ('', [])
616
contents_of_root_block = []
617
for entry in self._dirblocks[0][1]:
618
if not entry[0][1]: # This is a root entry
619
root_block.append(entry)
621
contents_of_root_block.append(entry)
622
self._dirblocks[0] = ('', root_block)
623
self._dirblocks[1] = ('', contents_of_root_block)
625
def _entry_to_line(self, entry):
626
"""Serialize entry to a NULL delimited line ready for _get_output_lines.
628
:param entry: An entry_tuple as defined in the module docstring.
630
entire_entry = list(entry[0])
631
for tree_number, tree_data in enumerate(entry[1]):
632
# (minikind, fingerprint, size, executable, tree_specific_string)
633
entire_entry.extend(tree_data)
634
# 3 for the key, 5 for the fields per tree.
635
tree_offset = 3 + tree_number * 5
637
entire_entry[tree_offset + 0] = tree_data[0]
639
entire_entry[tree_offset + 2] = str(tree_data[2])
641
entire_entry[tree_offset + 3] = DirState._to_yesno[tree_data[3]]
642
return '\0'.join(entire_entry)
644
def _fields_per_entry(self):
645
"""How many null separated fields should be in each entry row.
647
Each line now has an extra '\n' field which is not used
648
so we just skip over it
651
+ number of fields per tree_data (5) * tree count
654
tree_count = 1 + self._num_present_parents()
655
return 3 + 5 * tree_count + 1
657
def _find_block(self, key, add_if_missing=False):
658
"""Return the block that key should be present in.
660
:param key: A dirstate entry key.
661
:return: The block tuple.
663
block_index, present = self._find_block_index_from_key(key)
665
if not add_if_missing:
666
# check to see if key is versioned itself - we might want to
667
# add it anyway, because dirs with no entries dont get a
668
# dirblock at parse time.
669
# This is an uncommon branch to take: most dirs have children,
670
# and most code works with versioned paths.
671
parent_base, parent_name = os.path.split(key[0])
672
if not self._get_block_entry_index(parent_base, parent_name, 0)[3]:
673
# some parent path has not been added - its an error to add
675
raise errors.NotVersionedError(key[0:2], str(self))
676
self._dirblocks.insert(block_index, (key[0], []))
677
return self._dirblocks[block_index]
679
def _find_block_index_from_key(self, key):
680
"""Find the dirblock index for a key.
682
:return: The block index, True if the block for the key is present.
684
if key[0:2] == ('', ''):
686
block_index = bisect.bisect_left(self._dirblocks, (key[0], []), 1)
687
# _right returns one-past-where-key is so we have to subtract
688
# one to use it. we use _right here because there are two
689
# '' blocks - the root, and the contents of root
690
# we always have a minimum of 2 in self._dirblocks: root and
691
# root-contents, and for '', we get 2 back, so this is
692
# simple and correct:
693
present = (block_index < len(self._dirblocks) and
694
self._dirblocks[block_index][0] == key[0])
695
return block_index, present
697
def _find_entry_index(self, key, block):
698
"""Find the entry index for a key in a block.
700
:return: The entry index, True if the entry for the key is present.
702
entry_index = bisect.bisect_left(block, (key, []))
703
present = (entry_index < len(block) and
704
block[entry_index][0] == key)
705
return entry_index, present
708
def from_tree(tree, dir_state_filename):
709
"""Create a dirstate from a bzr Tree.
711
:param tree: The tree which should provide parent information and
713
:return: a DirState object which is currently locked for writing.
714
(it was locked by DirState.initialize)
716
result = DirState.initialize(dir_state_filename)
720
parent_ids = tree.get_parent_ids()
721
num_parents = len(parent_ids)
723
for parent_id in parent_ids:
724
parent_tree = tree.branch.repository.revision_tree(parent_id)
725
parent_trees.append((parent_id, parent_tree))
726
parent_tree.lock_read()
727
result.set_parent_trees(parent_trees, [])
728
result.set_state_from_inventory(tree.inventory)
730
for revid, parent_tree in parent_trees:
734
# The caller won't have a chance to unlock this, so make sure we
740
def get_ghosts(self):
741
"""Return a list of the parent tree revision ids that are ghosts."""
742
self._read_header_if_needed()
746
"""Serialise the entire dirstate to a sequence of lines."""
747
if (self._header_state == DirState.IN_MEMORY_UNMODIFIED and
748
self._dirblock_state == DirState.IN_MEMORY_UNMODIFIED):
749
# read whats on disk.
750
self._state_file.seek(0)
751
return self._state_file.readlines()
753
lines.append(self._get_parents_line(self.get_parent_ids()))
754
lines.append(self._get_ghosts_line(self._ghosts))
755
# append the root line which is special cased
756
lines.extend(map(self._entry_to_line, self._iter_entries()))
757
return self._get_output_lines(lines)
759
def _get_ghosts_line(self, ghost_ids):
760
"""Create a line for the state file for ghost information."""
761
return '\0'.join([str(len(ghost_ids))] + ghost_ids)
763
def _get_parents_line(self, parent_ids):
764
"""Create a line for the state file for parents information."""
765
return '\0'.join([str(len(parent_ids))] + parent_ids)
767
def _get_fields_to_entry(self):
768
"""Get a function which converts entry fields into a entry record.
770
This handles size and executable, as well as parent records.
772
:return: A function which takes a list of fields, and returns an
773
appropriate record for storing in memory.
775
# This is intentionally unrolled for performance
776
num_present_parents = self._num_present_parents()
777
if num_present_parents == 0:
778
def fields_to_entry_0_parents(fields, _int=int):
779
path_name_file_id_key = (fields[0], fields[1], fields[2])
780
return (path_name_file_id_key, [
782
fields[3], # minikind
783
fields[4], # fingerprint
784
_int(fields[5]), # size
785
fields[6] == 'y', # executable
786
fields[7], # packed_stat or revision_id
788
return fields_to_entry_0_parents
789
elif num_present_parents == 1:
790
def fields_to_entry_1_parent(fields, _int=int):
791
path_name_file_id_key = (fields[0], fields[1], fields[2])
792
return (path_name_file_id_key, [
794
fields[3], # minikind
795
fields[4], # fingerprint
796
_int(fields[5]), # size
797
fields[6] == 'y', # executable
798
fields[7], # packed_stat or revision_id
801
fields[8], # minikind
802
fields[9], # fingerprint
803
_int(fields[10]), # size
804
fields[11] == 'y', # executable
805
fields[12], # packed_stat or revision_id
808
return fields_to_entry_1_parent
809
elif num_present_parents == 2:
810
def fields_to_entry_2_parents(fields, _int=int):
811
path_name_file_id_key = (fields[0], fields[1], fields[2])
812
return (path_name_file_id_key, [
814
fields[3], # minikind
815
fields[4], # fingerprint
816
_int(fields[5]), # size
817
fields[6] == 'y', # executable
818
fields[7], # packed_stat or revision_id
821
fields[8], # minikind
822
fields[9], # fingerprint
823
_int(fields[10]), # size
824
fields[11] == 'y', # executable
825
fields[12], # packed_stat or revision_id
828
fields[13], # minikind
829
fields[14], # fingerprint
830
_int(fields[15]), # size
831
fields[16] == 'y', # executable
832
fields[17], # packed_stat or revision_id
835
return fields_to_entry_2_parents
837
def fields_to_entry_n_parents(fields, _int=int):
838
path_name_file_id_key = (fields[0], fields[1], fields[2])
839
trees = [(fields[cur], # minikind
840
fields[cur+1], # fingerprint
841
_int(fields[cur+2]), # size
842
fields[cur+3] == 'y', # executable
843
fields[cur+4], # stat or revision_id
844
) for cur in xrange(3, len(fields)-1, 5)]
845
return path_name_file_id_key, trees
846
return fields_to_entry_n_parents
848
def get_parent_ids(self):
849
"""Return a list of the parent tree ids for the directory state."""
850
self._read_header_if_needed()
851
return list(self._parents)
853
def _get_block_entry_index(self, dirname, basename, tree_index):
854
"""Get the coordinates for a path in the state structure.
856
:param dirname: The utf8 dirname to lookup.
857
:param basename: The utf8 basename to lookup.
858
:param tree_index: The index of the tree for which this lookup should
860
:return: A tuple describing where the path is located, or should be
861
inserted. The tuple contains four fields: the block index, the row
862
index, anda two booleans are True when the directory is present, and
863
when the entire path is present. There is no guarantee that either
864
coordinate is currently reachable unless the found field for it is
865
True. For instance, a directory not present in the searched tree
866
may be returned with a value one greater than the current highest
867
block offset. The directory present field will always be True when
868
the path present field is True. The directory present field does
869
NOT indicate that the directory is present in the searched tree,
870
rather it indicates that there are at least some files in some
873
self._read_dirblocks_if_needed()
874
key = dirname, basename, ''
875
block_index, present = self._find_block_index_from_key(key)
877
# no such directory - return the dir index and 0 for the row.
878
return block_index, 0, False, False
879
block = self._dirblocks[block_index][1] # access the entries only
880
entry_index, present = self._find_entry_index(key, block)
881
# linear search through present entries at this path to find the one
883
while entry_index < len(block) and block[entry_index][0][1] == basename:
884
if block[entry_index][1][tree_index][0] not in \
885
('a', 'r'): # absent, relocated
886
return block_index, entry_index, True, True
888
return block_index, entry_index, True, False
890
def _get_entry(self, tree_index, fileid_utf8=None, path_utf8=None):
891
"""Get the dirstate entry for path in tree tree_index
893
If either file_id or path is supplied, it is used as the key to lookup.
894
If both are supplied, the fastest lookup is used, and an error is
895
raised if they do not both point at the same row.
897
:param tree_index: The index of the tree we wish to locate this path
898
in. If the path is present in that tree, the entry containing its
899
details is returned, otherwise (None, None) is returned
900
:param fileid_utf8: A utf8 file_id to look up.
901
:param path_utf8: An utf8 path to be looked up.
902
:return: The dirstate entry tuple for path, or (None, None)
904
self._read_dirblocks_if_needed()
905
if path_utf8 is not None:
906
assert path_utf8.__class__ == str, 'path_utf8 is not a str: %s %s' % (type(path_utf8), path_utf8)
907
# path lookups are faster
908
dirname, basename = os.path.split(path_utf8)
909
block_index, entry_index, dir_present, file_present = \
910
self._get_block_entry_index(dirname, basename, tree_index)
913
entry = self._dirblocks[block_index][1][entry_index]
914
assert entry[0][2] and entry[1][tree_index][0] not in ('a', 'r'), 'unversioned entry?!?!'
916
if entry[0][2] != fileid_utf8:
917
raise BzrError('integrity error ? : mismatching tree_index, file_id and path')
920
for entry in self._iter_entries():
921
if entry[0][2] == fileid_utf8:
922
if entry[1][tree_index][0] == 'r': # relocated
923
# look up the real location directly by path
924
return self._get_entry(tree_index,
925
fileid_utf8=fileid_utf8,
926
path_utf8=entry[1][tree_index][1])
927
if entry[1][tree_index][0] == 'a': # absent
928
# not in the tree at all.
934
def initialize(path):
935
"""Create a new dirstate on path.
937
The new dirstate will be an empty tree - that is it has no parents,
938
and only a root node - which has id ROOT_ID.
940
The object will be write locked when returned to the caller,
941
unless there was an exception in the writing, in which case it
944
:param path: The name of the file for the dirstate.
945
:return: A DirState object.
947
# This constructs a new DirState object on a path, sets the _state_file
948
# to a new empty file for that path. It then calls _set_data() with our
949
# stock empty dirstate information - a root with ROOT_ID, no children,
950
# and no parents. Finally it calls save() to ensure that this data will
952
result = DirState(path)
953
# root dir and root dir contents with no children.
954
empty_tree_dirblocks = [('', []), ('', [])]
955
# a new root directory, with a NULLSTAT.
956
empty_tree_dirblocks[0][1].append(
957
(('', '', bzrlib.inventory.ROOT_ID), [
958
('d', '', 0, False, DirState.NULLSTAT),
962
result._set_data([], empty_tree_dirblocks)
969
def _inv_entry_to_details(self, inv_entry):
970
"""Convert an inventory entry (from a revision tree) to state details.
972
:param inv_entry: An inventory entry whose sha1 and link targets can be
973
relied upon, and which has a revision set.
974
:return: A details tuple - the details for a single tree at a path +
977
kind = inv_entry.kind
978
minikind = DirState._kind_to_minikind[kind]
979
tree_data = inv_entry.revision
980
assert len(tree_data) > 0, 'empty revision for the inv_entry.'
981
if kind == 'directory':
985
elif kind == 'symlink':
986
fingerprint = inv_entry.symlink_target or ''
990
fingerprint = inv_entry.text_sha1 or ''
991
size = inv_entry.text_size or 0
992
executable = inv_entry.executable
995
return (minikind, fingerprint, size, executable, tree_data)
997
def _iter_entries(self):
998
"""Iterate over all the entries in the dirstate.
1000
Each yelt item is an entry in the standard format described in the
1001
docstring of bzrlib.dirstate.
1003
self._read_dirblocks_if_needed()
1004
for directory in self._dirblocks:
1005
for entry in directory[1]:
1008
def _get_id_index(self):
1009
"""Get an id index of self._dirblocks."""
1011
for key, tree_details in self._iter_entries():
1012
id_index.setdefault(key[2], set()).add(key)
1015
def _get_output_lines(self, lines):
1016
"""format lines for final output.
1018
:param lines: A sequece of lines containing the parents list and the
1021
output_lines = ['#bazaar dirstate flat format 2\n']
1022
lines.append('') # a final newline
1023
inventory_text = '\0\n\0'.join(lines)
1024
output_lines.append('adler32: %s\n' % (zlib.adler32(inventory_text),))
1025
# -3, 1 for num parents, 1 for ghosts, 1 for final newline
1026
num_entries = len(lines)-3
1027
output_lines.append('num_entries: %s\n' % (num_entries,))
1028
output_lines.append(inventory_text)
1031
def _make_deleted_row(self, fileid_utf8, parents):
1032
"""Return a deleted for for fileid_utf8."""
1033
return ('/', 'RECYCLED.BIN', 'file', fileid_utf8, 0, DirState.NULLSTAT,
1036
def _num_present_parents(self):
1037
"""The number of parent entries in each record row."""
1038
return len(self._parents) - len(self._ghosts)
1042
"""Construct a DirState on the file at path path.
1044
:return: An unlocked DirState object, associated with the given path.
1046
result = DirState(path)
1049
def _read_dirblocks_if_needed(self):
1050
"""Read in all the dirblocks from the file if they are not in memory.
1052
This populates self._dirblocks, and sets self._dirblock_state to
1053
IN_MEMORY_UNMODIFIED. It is not currently ready for incremental block
1056
self._read_header_if_needed()
1057
if self._dirblock_state == DirState.NOT_IN_MEMORY:
1058
# the _state_file pointer will be positioned at the start of the
1060
text = self._state_file.read()
1061
# TODO: check the adler checksums. adler_measured = zlib.adler32(text)
1063
fields = text.split('\0')
1064
# Remove the last blank entry
1065
trailing = fields.pop()
1066
assert trailing == ''
1067
# consider turning fields into a tuple.
1069
# skip the first field which is the trailing null from the header.
1071
# Each line now has an extra '\n' field which is not used
1072
# so we just skip over it
1074
# 3 fields for the key
1075
# + number of fields per tree_data (5) * tree count
1077
num_present_parents = self._num_present_parents()
1078
tree_count = 1 + num_present_parents
1079
entry_size = self._fields_per_entry()
1080
expected_field_count = entry_size * self._num_entries
1081
if len(fields) - cur > expected_field_count:
1082
fields = fields[:expected_field_count + cur]
1083
trace.mutter('Unexpectedly long dirstate field count!')
1084
print "XXX: incorrectly truncated dirstate file bug triggered."
1085
field_count = len(fields)
1086
# this checks our adjustment, and also catches file too short.
1087
assert field_count - cur == expected_field_count, \
1088
'field count incorrect %s != %s, entry_size=%s, '\
1089
'num_entries=%s fields=%r' % (
1090
field_count - cur, expected_field_count, entry_size,
1091
self._num_entries, fields)
1093
if num_present_parents == 1:
1094
# Bind external functions to local names
1096
# We access all fields in order, so we can just iterate over
1097
# them. Grab an straight iterator over the fields. (We use an
1098
# iterator because we don't want to do a lot of additions, nor
1099
# do we want to do a lot of slicing)
1100
next = iter(fields).next
1101
# Move the iterator to the current position
1102
for x in xrange(cur):
1104
# The two blocks here are deliberate: the root block and the
1105
# contents-of-root block.
1106
self._dirblocks = [('', []), ('', [])]
1107
current_block = self._dirblocks[0][1]
1108
current_dirname = ''
1109
append_entry = current_block.append
1110
for count in xrange(self._num_entries):
1114
if dirname != current_dirname:
1115
# new block - different dirname
1117
current_dirname = dirname
1118
self._dirblocks.append((current_dirname, current_block))
1119
append_entry = current_block.append
1120
# we know current_dirname == dirname, so re-use it to avoid
1121
# creating new strings
1122
entry = ((current_dirname, name, file_id),
1125
next(), # fingerprint
1126
_int(next()), # size
1127
next() == 'y', # executable
1128
next(), # packed_stat or revision_id
1132
next(), # fingerprint
1133
_int(next()), # size
1134
next() == 'y', # executable
1135
next(), # packed_stat or revision_id
1139
assert trailing == '\n'
1140
# append the entry to the current block
1142
self._split_root_dirblock_into_contents()
1144
fields_to_entry = self._get_fields_to_entry()
1145
entries = [fields_to_entry(fields[pos:pos+entry_size])
1146
for pos in xrange(cur, field_count, entry_size)]
1147
self._entries_to_current_state(entries)
1148
self._dirblock_state = DirState.IN_MEMORY_UNMODIFIED
1150
def _read_header(self):
1151
"""This reads in the metadata header, and the parent ids.
1153
After reading in, the file should be positioned at the null
1154
just before the start of the first record in the file.
1156
:return: (expected adler checksum, number of entries, parent list)
1158
self._read_prelude()
1159
parent_line = self._state_file.readline()
1160
info = parent_line.split('\0')
1161
num_parents = int(info[0])
1162
assert num_parents == len(info)-2, 'incorrect parent info line'
1163
self._parents = info[1:-1]
1165
ghost_line = self._state_file.readline()
1166
info = ghost_line.split('\0')
1167
num_ghosts = int(info[1])
1168
assert num_ghosts == len(info)-3, 'incorrect ghost info line'
1169
self._ghosts = info[2:-1]
1170
self._header_state = DirState.IN_MEMORY_UNMODIFIED
1171
self._end_of_header = self._state_file.tell()
1173
def _read_header_if_needed(self):
1174
"""Read the header of the dirstate file if needed."""
1175
# inline this as it will be called a lot
1176
if not self._lock_token:
1177
raise errors.ObjectNotLocked(self)
1178
if self._header_state == DirState.NOT_IN_MEMORY:
1181
def _read_prelude(self):
1182
"""Read in the prelude header of the dirstate file
1184
This only reads in the stuff that is not connected to the adler
1185
checksum. The position will be correct to read in the rest of
1186
the file and check the checksum after this point.
1187
The next entry in the file should be the number of parents,
1188
and their ids. Followed by a newline.
1190
header = self._state_file.readline()
1191
assert header == '#bazaar dirstate flat format 2\n', \
1192
'invalid header line: %r' % (header,)
1193
adler_line = self._state_file.readline()
1194
assert adler_line.startswith('adler32: '), 'missing adler32 checksum'
1195
self.adler_expected = int(adler_line[len('adler32: '):-1])
1196
num_entries_line = self._state_file.readline()
1197
assert num_entries_line.startswith('num_entries: '), 'missing num_entries line'
1198
self._num_entries = int(num_entries_line[len('num_entries: '):-1])
1201
"""Save any pending changes created during this session.
1203
We reuse the existing file, because that prevents race conditions with
1204
file creation, and we expect to be using oslocks on it in the near
1205
future to prevent concurrent modification and reads - because dirstates
1206
incremental data aggretation is not compatible with reading a modified
1207
file, and replacing a file in use by another process is impossible on
1210
A dirstate in read only mode should be smart enough though to validate
1211
that the file has not changed, and otherwise discard its cache and
1212
start over, to allow for fine grained read lock duration, so 'status'
1213
wont block 'commit' - for example.
1215
if (self._header_state == DirState.IN_MEMORY_MODIFIED or
1216
self._dirblock_state == DirState.IN_MEMORY_MODIFIED):
1217
self._state_file.seek(0)
1218
self._state_file.writelines(self.get_lines())
1219
self._state_file.truncate()
1220
self._state_file.flush()
1221
self._header_state = DirState.IN_MEMORY_UNMODIFIED
1222
self._dirblock_state = DirState.IN_MEMORY_UNMODIFIED
1224
def _set_data(self, parent_ids, dirblocks):
1225
"""Set the full dirstate data in memory.
1227
This is an internal function used to completely replace the objects
1228
in memory state. It puts the dirstate into state 'full-dirty'.
1230
:param parent_ids: A list of parent tree revision ids.
1231
:param dirblocks: A list containing one tuple for each directory in the
1232
tree. Each tuple contains the directory path and a list of entries
1233
found in that directory.
1235
# our memory copy is now authoritative.
1236
self._dirblocks = dirblocks
1237
self._header_state = DirState.IN_MEMORY_MODIFIED
1238
self._dirblock_state = DirState.IN_MEMORY_MODIFIED
1239
self._parents = list(parent_ids)
1241
def set_path_id(self, path, new_id):
1242
"""Change the id of path to new_id in the current working tree.
1244
:param path: The path inside the tree to set - '' is the root, 'foo'
1245
is the path foo in the root.
1246
:param new_id: The new id to assign to the path. This must be a utf8
1247
file id (not unicode, and not None).
1249
# TODO: start warning here.
1250
assert new_id.__class__ == str
1251
self._read_dirblocks_if_needed()
1253
import pdb;pdb.set_trace()
1255
raise NotImplementedError(self.set_path_id)
1256
# TODO: check new id is unique
1257
entry = self._get_entry(0, path_utf8=path)
1258
# mark the old path absent, and insert a new root path
1259
present_parents = len(entry[1]) - 1
1260
self._make_absent(entry)
1261
id_index = self._get_id_index()
1262
self.update_minimal(('', '', new_id), 'directory', present_parents,
1263
path_utf8='', id_index=id_index, packed_stat=entry[1][0][4])
1264
self._dirblock_state = DirState.IN_MEMORY_MODIFIED
1266
def set_parent_trees(self, trees, ghosts):
1267
"""Set the parent trees for the dirstate.
1269
:param trees: A list of revision_id, tree tuples. tree must be provided
1270
even if the revision_id refers to a ghost: supply an empty tree in
1272
:param ghosts: A list of the revision_ids that are ghosts at the time
1275
# TODO: generate a list of parent indexes to preserve to save
1276
# processing specific parent trees. In the common case one tree will
1277
# be preserved - the left most parent.
1278
# TODO: if the parent tree is a dirstate, we might want to walk them
1279
# all by path in parallel for 'optimal' common-case performance.
1280
# generate new root row.
1281
self._read_dirblocks_if_needed()
1282
# TODO future sketch: Examine the existing parents to generate a change
1283
# map and then walk the new parent trees only, mapping them into the
1284
# dirstate. Walk the dirstate at the same time to remove unreferenced
1287
# sketch: loop over all entries in the dirstate, cherry picking
1288
# entries from the parent trees, if they are not ghost trees.
1289
# after we finish walking the dirstate, all entries not in the dirstate
1290
# are deletes, so we want to append them to the end as per the design
1291
# discussions. So do a set difference on ids with the parents to
1292
# get deletes, and add them to the end.
1293
# During the update process we need to answer the following questions:
1294
# - find other keys containing a fileid in order to create cross-path
1295
# links. We dont't trivially use the inventory from other trees
1296
# because this leads to either double touching, or to accessing
1298
# - find other keys containing a path
1299
# We accumulate each entry via this dictionary, including the root
1302
# we could do parallel iterators, but because file id data may be
1303
# scattered throughout, we dont save on index overhead: we have to look
1304
# at everything anyway. We can probably save cycles by reusing parent
1305
# data and doing an incremental update when adding an additional
1306
# parent, but for now the common cases are adding a new parent (merge),
1307
# and replacing completely (commit), and commit is more common: so
1308
# optimise merge later.
1310
# ---- start generation of full tree mapping data
1311
# what trees should we use?
1312
parent_trees = [tree for rev_id, tree in trees if rev_id not in ghosts]
1313
# how many trees do we end up with
1314
parent_count = len(parent_trees)
1316
# one: the current tree
1317
for entry in self._iter_entries():
1318
# skip entries not in the current tree
1319
if entry[1][0][0] in ('a', 'r'): # absent, relocated
1321
by_path[entry[0]] = [entry[1][0]] + \
1322
[DirState.NULL_PARENT_DETAILS] * parent_count
1323
id_index[entry[0][2]] = set([entry[0]])
1325
# now the parent trees:
1326
for tree_index, tree in enumerate(parent_trees):
1327
# the index is off by one, adjust it.
1328
tree_index = tree_index + 1
1329
# when we add new locations for a fileid we need these ranges for
1330
# any fileid in this tree as we set the by_path[id] to:
1331
# already_processed_tree_details + new_details + new_location_suffix
1332
# the suffix is from tree_index+1:parent_count+1.
1333
new_location_suffix = [DirState.NULL_PARENT_DETAILS] * (parent_count - tree_index)
1334
# now stitch in all the entries from this tree
1335
for path, entry in tree.inventory.iter_entries_by_dir():
1336
# here we process each trees details for each item in the tree.
1337
# we first update any existing entries for the id at other paths,
1338
# then we either create or update the entry for the id at the
1339
# right path, and finally we add (if needed) a mapping from
1340
# file_id to this path. We do it in this order to allow us to
1341
# avoid checking all known paths for the id when generating a
1342
# new entry at this path: by adding the id->path mapping last,
1343
# all the mappings are valid and have correct relocation
1344
# records where needed.
1345
file_id = entry.file_id
1346
path_utf8 = path.encode('utf8')
1347
dirname, basename = os.path.split(path_utf8)
1348
new_entry_key = (dirname, basename, file_id)
1349
# tree index consistency: All other paths for this id in this tree
1350
# index must point to the correct path.
1351
for entry_key in id_index.setdefault(file_id, set()):
1352
# TODO:PROFILING: It might be faster to just update
1353
# rather than checking if we need to, and then overwrite
1354
# the one we are located at.
1355
if entry_key != new_entry_key:
1356
# this file id is at a different path in one of the
1357
# other trees, so put absent pointers there
1358
# This is the vertical axis in the matrix, all pointing
1360
by_path[entry_key][tree_index] = ('r', path_utf8, 0, False, '')
1361
# by path consistency: Insert into an existing path record (trivial), or
1362
# add a new one with relocation pointers for the other tree indexes.
1363
if new_entry_key in id_index[file_id]:
1364
# there is already an entry where this data belongs, just insert it.
1365
by_path[new_entry_key][tree_index] = \
1366
self._inv_entry_to_details(entry)
1368
# add relocated entries to the horizontal axis - this row
1369
# mapping from path,id. We need to look up the correct path
1370
# for the indexes from 0 to tree_index -1
1372
for lookup_index in xrange(tree_index):
1373
# boundary case: this is the first occurence of file_id
1374
# so there are no id_indexs, possibly take this out of
1376
if not len(id_index[file_id]):
1377
new_details.append(DirState.NULL_PARENT_DETAILS)
1379
# grab any one entry, use it to find the right path.
1380
# TODO: optimise this to reduce memory use in highly
1381
# fragmented situations by reusing the relocation
1383
a_key = iter(id_index[file_id]).next()
1384
if by_path[a_key][lookup_index][0] in ('r', 'a'):
1385
# its a pointer or missing statement, use it as is.
1386
new_details.append(by_path[a_key][lookup_index])
1388
# we have the right key, make a pointer to it.
1389
real_path = ('/'.join(a_key[0:2])).strip('/')
1390
new_details.append(('r', real_path, 0, False, ''))
1391
new_details.append(self._inv_entry_to_details(entry))
1392
new_details.extend(new_location_suffix)
1393
by_path[new_entry_key] = new_details
1394
id_index[file_id].add(new_entry_key)
1395
# --- end generation of full tree mappings
1397
# sort and output all the entries
1398
new_entries = sorted(by_path.items())
1399
self._entries_to_current_state(new_entries)
1400
self._parents = [rev_id for rev_id, tree in trees]
1401
self._ghosts = list(ghosts)
1402
self._header_state = DirState.IN_MEMORY_MODIFIED
1403
self._dirblock_state = DirState.IN_MEMORY_MODIFIED
1405
def set_state_from_inventory(self, new_inv):
1406
"""Set new_inv as the current state.
1408
This API is called by tree transform, and will usually occur with
1409
existing parent trees.
1411
:param new_inv: The inventory object to set current state from.
1413
self._read_dirblocks_if_needed()
1415
# generate a byid index of the dirstate
1416
id_index = self._get_id_index()
1418
num_present_parents = len(self._parents) - len(self._ghosts)
1419
# incremental algorithm:
1420
# two iterators: current data and new data, both in dirblock order.
1421
new_iterator = new_inv.iter_entries_by_dir()
1422
# we will be modifying the dirstate, so we need a stable iterator. In
1423
# future we might write one, for now we just clone the state into a
1424
# list - which is a shallow copy, so each
1425
old_iterator = iter(list(self._iter_entries()))
1426
# both must have roots so this is safe:
1427
current_new = new_iterator.next()
1428
current_old = old_iterator.next()
1429
def advance(iterator):
1431
return iterator.next()
1432
except StopIteration:
1434
while current_new or current_old:
1435
# skip entries in old that are not really there
1436
if current_old and current_old[1][0][0] in ('r', 'a'):
1437
# relocated or absent
1438
current_old = advance(old_iterator)
1441
# convert new into dirblock style
1442
new_path_utf8 = current_new[0].encode('utf8')
1443
new_dirname, new_basename = os.path.split(new_path_utf8)
1444
new_id = current_new[1].file_id
1445
new_entry_key = (new_dirname, new_basename, new_id)
1447
# for safety disable variables
1448
new_path_utf8 = new_dirname = new_basename = new_id = new_entry_key = None
1449
# 5 cases, we dont have a value that is strictly greater than everything, so
1450
# we make both end conditions explicit
1452
# old is finished: insert current_new into the state.
1453
self.update_minimal(new_entry_key, current_new[1].kind,
1454
num_present_parents, executable=current_new[1].executable,
1455
id_index=id_index, path_utf8=new_path_utf8)
1456
current_new = advance(new_iterator)
1457
elif not current_new:
1459
self._make_absent(current_old, id_index)
1460
current_old = advance(old_iterator)
1461
elif new_entry_key == current_old[0]:
1462
# same - common case
1463
# TODO: update the record if anything significant has changed.
1464
# the minimal required trigger is if the execute bit or cached
1466
kind = DirState._minikind_to_kind[current_old[1][0][0]]
1467
if (current_old[1][0][3] != current_new[1].executable or
1468
kind != current_new[1].kind):
1469
self.update_minimal(current_old[0], current_new[1].kind,
1470
num_present_parents,
1471
executable=current_new[1].executable,
1472
id_index=id_index, path_utf8=new_path_utf8)
1473
# both sides are dealt with, move on
1474
current_old = advance(old_iterator)
1475
current_new = advance(new_iterator)
1476
elif new_entry_key < current_old[0]:
1478
# add a entry for this and advance new
1479
self.update_minimal(new_entry_key, current_new[1].kind,
1480
num_present_parents, executable=current_new[1].executable,
1481
id_index=id_index, path_utf8=new_path_utf8)
1482
current_new = advance(new_iterator)
1485
self._make_absent(current_old, id_index)
1486
current_old = advance(old_iterator)
1487
self._dirblock_state = DirState.IN_MEMORY_MODIFIED
1489
def _make_absent(self, current_old, id_index=None):
1490
"""Mark current_old - an entry - as absent for tree 0.
1492
:param id_index: An index from fileid_utf8 to sets of keys, used by
1493
some functions. If provided it will be updated if needed.
1494
:return: True if this was the last details entry for they entry key:
1495
that is, if the underlying block has had the entry removed, thus
1496
shrinking in legnth.
1498
# build up paths that this id will be left at after the change is made,
1499
# so we can update their cross references in tree 0
1500
all_remaining_keys = set()
1501
# Dont check the working tree, because its going.
1502
for details in current_old[1][1:]:
1503
if details[0] not in ('a', 'r'): # absent, relocated
1504
all_remaining_keys.add(current_old[0])
1505
elif details[0] == 'r': # relocated
1506
# record the key for the real path.
1507
all_remaining_keys.add(tuple(os.path.split(details[1])) + (current_old[0][2],))
1508
# absent rows are not present at any path.
1509
last_reference = current_old[0] not in all_remaining_keys
1511
# the current row consists entire of the current item (being marked
1512
# absent), and relocated or absent entries for the other trees:
1513
# Remove it, its meaningless.
1514
block = self._find_block(current_old[0])
1515
entry_index, present = self._find_entry_index(current_old[0], block[1])
1517
block[1].pop(entry_index)
1518
# if we have an id_index in use, remove this key from it for this id.
1519
if id_index is not None:
1520
id_index[current_old[0][2]].remove(current_old[0])
1521
# update all remaining keys for this id to record it as absent. The
1522
# existing details may either be the record we are making as deleted
1523
# (if there were other trees with the id present at this path), or may
1525
for update_key in all_remaining_keys:
1526
update_block_index, present = \
1527
self._find_block_index_from_key(update_key)
1529
update_entry_index, present = \
1530
self._find_entry_index(update_key, self._dirblocks[update_block_index][1])
1532
update_tree_details = self._dirblocks[update_block_index][1][update_entry_index][1]
1533
# it must not be absent at the moment
1534
assert update_tree_details[0][0] != 'a' # absent
1535
update_tree_details[0] = DirState.NULL_PARENT_DETAILS
1536
self._dirblock_state = DirState.IN_MEMORY_MODIFIED
1537
return last_reference
1539
def update_minimal(self, key, kind, num_present_parents, executable=False,
1540
fingerprint='', packed_stat=None, size=0, id_index=None,
1542
"""Update an entry to the state in tree 0."""
1543
block = self._find_block(key)[1]
1544
if packed_stat is None:
1545
packed_stat = DirState.NULLSTAT
1546
entry_index, present = self._find_entry_index(key, block)
1547
minikind = DirState._kind_to_minikind[kind]
1548
new_details = (minikind, fingerprint, size, executable, packed_stat)
1549
assert id_index is not None, 'need an id index to do updates for now !'
1551
# new entry, synthesis cross reference here,
1552
existing_keys = id_index.setdefault(key[2], set())
1553
if not existing_keys:
1554
# not currently in the state, simplest case
1555
new_entry = key, [new_details] + self._empty_parent_info()
1557
# present at one or more existing other paths.
1558
# grab one of them and use it to generate parent
1559
# relocation/absent entries.
1560
new_entry = key, [new_details]
1561
for other_key in existing_keys:
1562
# change the record at other to be a pointer to this new
1563
# record. The loop looks similar to the change to
1564
# relocations when updating an existing record but its not:
1565
# the test for existing kinds is different: this can be
1566
# factored out to a helper though.
1567
other_block_index, present = self._find_block_index_from_key(other_key)
1569
other_entry_index, present = self._find_entry_index(other_key, self._dirblocks[other_block_index][1])
1571
assert path_utf8 is not None
1572
self._dirblocks[other_block_index][1][other_entry_index][1][0] = \
1573
('r', path_utf8, 0, False, '')
1575
for lookup_index in xrange(1, num_present_parents + 1):
1576
# grab any one entry, use it to find the right path.
1577
# TODO: optimise this to reduce memory use in highly
1578
# fragmented situations by reusing the relocation
1580
update_block_index, present = \
1581
self._find_block_index_from_key(other_key)
1583
update_entry_index, present = \
1584
self._find_entry_index(other_key, self._dirblocks[update_block_index][1])
1586
update_details = self._dirblocks[update_block_index][1][update_entry_index][1][lookup_index]
1587
if update_details[0] in ('r', 'a'): # relocated, absent
1588
# its a pointer or absent in lookup_index's tree, use
1590
new_entry[1].append(update_details)
1592
# we have the right key, make a pointer to it.
1593
pointer_path = os.path.join(*other_key[0:2])
1594
new_entry[1].append(('r', pointer_path, 0, False, ''))
1595
block.insert(entry_index, new_entry)
1596
existing_keys.add(key)
1598
# Does the new state matter?
1599
block[entry_index][1][0] = new_details
1600
# parents cannot be affected by what we do.
1601
# other occurences of this id can be found
1602
# from the id index.
1604
# tree index consistency: All other paths for this id in this tree
1605
# index must point to the correct path. We have to loop here because
1606
# we may have passed entries in the state with this file id already
1607
# that were absent - where parent entries are - and they need to be
1608
# converted to relocated.
1609
assert path_utf8 is not None
1610
for entry_key in id_index.setdefault(key[2], set()):
1611
# TODO:PROFILING: It might be faster to just update
1612
# rather than checking if we need to, and then overwrite
1613
# the one we are located at.
1614
if entry_key != key:
1615
# this file id is at a different path in one of the
1616
# other trees, so put absent pointers there
1617
# This is the vertical axis in the matrix, all pointing
1619
block_index, present = self._find_block_index_from_key(entry_key)
1621
entry_index, present = self._find_entry_index(entry_key, self._dirblocks[block_index][1])
1623
self._dirblocks[block_index][1][entry_index][1][0] = \
1624
('r', path_utf8, 0, False, '')
1625
# add a containing dirblock if needed.
1626
if new_details[0] == 'd':
1627
subdir_key = (os.path.join(*key[0:2]), '', '')
1628
block_index, present = self._find_block_index_from_key(subdir_key)
1630
self._dirblocks.insert(block_index, (subdir_key[0], []))
1632
self._dirblock_state = DirState.IN_MEMORY_MODIFIED
1635
def _wipe_state(self):
1636
"""Forget all state information about the dirstate."""
1637
self._header_state = DirState.NOT_IN_MEMORY
1638
self._dirblock_state = DirState.NOT_IN_MEMORY
1641
self._dirblocks = []
1643
def lock_read(self):
1644
"""Acquire a read lock on the dirstate"""
1645
if self._lock_token is not None:
1646
raise errors.LockContention(self._lock_token)
1647
self._lock_token = lock.ReadLock(self._filename)
1648
self._state_file = self._lock_token.f
1651
def lock_write(self):
1652
"""Acquire a write lock on the dirstate"""
1653
if self._lock_token is not None:
1654
raise errors.LockContention(self._lock_token)
1655
self._lock_token = lock.WriteLock(self._filename)
1656
self._state_file = self._lock_token.f
1660
"""Drop any locks held on the dirstate"""
1661
if self._lock_token is None:
1662
raise errors.LockNotHeld(self)
1663
self._state_file = None
1664
self._lock_token.unlock()
1665
self._lock_token = None
1667
def _requires_lock(self):
1668
"""Checks that a lock is currently held by someone on the dirstate"""
1669
if not self._lock_token:
1670
raise errors.ObjectNotLocked(self)
1672
def pack_stat(st, _encode=base64.encodestring, _pack=struct.pack):
1673
"""Convert stat values into a packed representation."""
1674
# jam 20060614 it isn't really worth removing more entries if we
1675
# are going to leave it in packed form.
1676
# With only st_mtime and st_mode filesize is 5.5M and read time is 275ms
1677
# With all entries filesize is 5.9M and read time is mabye 280ms
1678
# well within the noise margin
1680
# base64.encode always adds a final newline, so strip it off
1681
return _encode(_pack('>llllll'
1682
, st.st_size, st.st_mtime, st.st_ctime
1683
, st.st_dev, st.st_ino, st.st_mode))[:-1]