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
206
import bzrlib.inventory
207
from bzrlib import osutils
208
from bzrlib.osutils import (
216
class DirState(object):
217
"""Record directory and metadata state for fast access.
219
A dirstate is a specialised data structure for managing local working
220
tree state information. Its not yet well defined whether it is platform
221
specific, and if it is how we detect/parameterise that.
224
_kind_to_minikind = {'absent':'a', 'file':'f', 'directory':'d', 'relocated':'r', 'symlink':'l'}
225
_minikind_to_kind = {'a':'absent', 'f':'file', 'd':'directory', 'l':'symlink', 'r':'relocated'}
226
_to_yesno = {True:'y', False: 'n'} # TODO profile the performance gain
227
# of using int conversion rather than a dict here. AND BLAME ANDREW IF
230
# TODO: jam 20070221 Make sure we handle when there are duplicated records
231
# (like when we remove + add the same path, or we have a rename)
232
# TODO: jam 20070221 Figure out what to do if we have a record that exceeds
233
# the BISECT_PAGE_SIZE.
234
BISECT_PAGE_SIZE = 4096
237
IN_MEMORY_UNMODIFIED = 1
238
IN_MEMORY_MODIFIED = 2
240
# A pack_stat (the x's) that is just noise and will never match the output
243
NULL_PARENT_DETAILS = ('a', '', 0, False, '')
246
"""Create a DirState object.
250
:attr _root_entrie: The root row of the directory/file information,
251
- contains the path to / - '', ''
252
- kind of 'directory',
253
- the file id of the root in utf8
256
- and no sha information.
258
# _header_state and _dirblock_state represent the current state
259
# of the dirstate metadata and the per-row data respectiely.
260
# NOT_IN_MEMORY indicates that no data is in memory
261
# IN_MEMORY_UNMODIFIED indicates that what we have in memory
262
# is the same as is on disk
263
# IN_MEMORY_MODIFIED indicates that we have a modified version
264
# of what is on disk.
265
# In future we will add more granularity, for instance _dirblock_state
266
# will probably support partially-in-memory as a separate variable,
267
# allowing for partially-in-memory unmodified and partially-in-memory
269
self._header_state = DirState.NOT_IN_MEMORY
270
self._dirblock_state = DirState.NOT_IN_MEMORY
274
self._state_file=None
276
def add(self, path, file_id, kind, stat, link_or_sha1):
277
"""Add a path to be tracked.
279
:param path: The path within the dirstate - '' is the root, 'foo' is the
280
path foo within the root, 'foo/bar' is the path bar within foo
282
:param file_id: The file id of the path being added.
283
:param kind: The kind of the path.
284
:param stat: The output of os.lstate for the path.
285
:param link_or_sha1: The sha value of the file, or the target of a
286
symlink. '' for directories.
289
# find the block its in.
290
# find the location in the block.
291
# check its not there
293
#------- copied from bzrlib.inventory.make_entry
294
# --- normalized_filename wants a unicode basename only, so get one.
295
dirname, basename = os.path.split(path)
296
# we dont import normalized_filename directly because we want to be
297
# able to change the implementation at runtime for tests.
298
norm_name, can_access = osutils.normalized_filename(basename)
299
if norm_name != basename:
303
raise errors.InvalidNormalization(path)
304
# now that we've normalised, we need the correct utf8 path and
305
# dirname and basename elements. This single encode and split should be
306
# faster than three separate encodes.
307
utf8path = (dirname + '/' + basename).strip('/').encode('utf8')
308
dirname, basename = os.path.split(utf8path)
309
assert file_id.__class__ == str, \
310
"must be a utf8 file_id not %s" % (type(file_id))
311
entry_key = (dirname, basename, file_id)
312
self._read_dirblocks_if_needed()
313
block_index, present = self._find_block_index_from_key(entry_key)
315
# TODO: This test is not complete - an empty directory, or a
316
# directory for a parent tree will fool it.
317
# some parent path has not been added - its an error to add this
319
raise errors.NotVersionedError(path, str(self))
320
block = self._dirblocks[block_index][1]
323
packed_stat = DirState.NULLSTAT
326
packed_stat = pack_stat(stat)
327
parent_info = self._empty_parent_info()
328
minikind = DirState._kind_to_minikind[kind]
330
entry_data = entry_key, [
331
(minikind, link_or_sha1, size, False, packed_stat),
333
elif kind == 'directory':
334
entry_data = entry_key, [
335
(minikind, '', 0, False, packed_stat),
337
elif kind == 'symlink':
338
entry_data = entry_key, [
339
(minikind, link_or_sha1, size, False, packed_stat),
342
raise errors.BzrError('unknown kind %r' % kind)
343
entry_index, present = self._find_entry_index(entry_key, block)
344
assert not present, "basename %r already added" % basename
345
block.insert(entry_index, entry_data)
347
if kind == 'directory':
348
# insert a new dirblock
349
self._ensure_block(block_index, entry_index, utf8path)
350
self._dirblock_state = DirState.IN_MEMORY_MODIFIED
352
def _empty_parent_info(self):
353
return [DirState.NULL_PARENT_DETAILS] * (len(self._parents) -
356
def _ensure_block(self, parent_block_index, parent_row_index, dirname):
357
"""Enssure a block for dirname exists.
359
This function exists to let callers which know that there is a
360
directory dirname ensure that the block for it exists. This block can
361
fail to exist because of demand loading, or because a directory had no
362
children. In either case it is not an error. It is however an error to
363
call this if there is no parent entry for the directory, and thus the
364
function requires the coordinates of such an entry to be provided.
366
The root row is special cased and can be indicated with a parent block
369
:param parent_block_index: The index of the block in which dirname's row
371
:param parent_row_index: The index in the parent block where the row
373
:param dirname: The utf8 dirname to ensure there is a block for.
374
:return: The index for the block.
377
# the basename of the directory must be the end of its full name.
378
if not (parent_block_index == -1 and
379
parent_block_index == -1 and dirname == ''):
380
assert dirname.endswith(
381
self._dirblocks[parent_block_index][1][parent_row_index][0][1])
382
block_index, present = self._find_block_index_from_key((dirname, '', ''))
384
## In future, when doing partial parsing, this should load and
385
# populate the entire block.
386
self._dirblocks.insert(block_index, (dirname, []))
389
def _entries_to_current_state(self, new_entries):
390
"""Load new_entries into self.dirblocks.
392
Process new_entries into the current state object, making them the active
395
:param new_entries: A sorted list of entries. This function does not sort
396
to prevent unneeded overhead when callers have a sorted list already.
399
assert new_entries[0][0][0:2] == ('', ''), \
400
"Missing root row %r" % new_entries[0][0]
401
# The two blocks here are deliberate: the root block and the
402
# contents-of-root block.
403
self._dirblocks = [('', []), ('', [])]
404
current_block = self._dirblocks[0][1]
407
append_entry = current_block.append
408
for entry in new_entries:
409
if entry[0][0] != current_dirname:
410
# new block - different dirname
412
current_dirname = entry[0][0]
413
self._dirblocks.append((current_dirname, current_block))
414
append_entry = current_block.append
415
# append the entry to the current block
417
self._split_root_dirblock_into_contents()
419
def _split_root_dirblock_into_contents(self):
420
"""Split the root dirblocks into root and contents-of-root.
422
After parsing by path, we end up with root entries and contents-of-root
423
entries in the same block. This loop splits them out again.
425
# The above loop leaves the "root block" entries mixed with the
426
# "contents-of-root block". But we don't want an if check on
427
# all entries, so instead we just fix it up here.
428
assert self._dirblocks[1] == ('', [])
430
contents_of_root_block = []
431
for entry in self._dirblocks[0][1]:
432
if not entry[0][1]: # This is a root entry
433
root_block.append(entry)
435
contents_of_root_block.append(entry)
436
self._dirblocks[0] = ('', root_block)
437
self._dirblocks[1] = ('', contents_of_root_block)
439
def _entry_to_line(self, entry):
440
"""Serialize entry to a NULL delimited line ready for _get_output_lines.
442
:param entry: An entry_tuple as defined in the module docstring.
444
entire_entry = list(entry[0])
445
for tree_number, tree_data in enumerate(entry[1]):
446
# (minikind, fingerprint, size, executable, tree_specific_string)
447
entire_entry.extend(tree_data)
448
# 3 for the key, 5 for the fields per tree.
449
tree_offset = 3 + tree_number * 5
451
entire_entry[tree_offset + 0] = tree_data[0]
453
entire_entry[tree_offset + 2] = str(tree_data[2])
455
entire_entry[tree_offset + 3] = DirState._to_yesno[tree_data[3]]
456
return '\0'.join(entire_entry)
458
def _fields_per_row(self):
459
"""How many null separated fields should be in each entry row.
461
Each line now has an extra '\n' field which is not used
462
so we just skip over it
465
+ number of fields per tree_data (5) * tree count
468
tree_count = 1 + self._num_present_parents()
469
return 3 + 5 * tree_count + 1
471
def _find_block(self, key, add_if_missing=False):
472
"""Return the block that key should be present in.
474
:param key: A dirstate entry key.
475
:return: The block tuple.
477
block_index, present = self._find_block_index_from_key(key)
479
if not add_if_missing:
480
# check to see if key is versioned itself - we might want to
481
# add it anyway, because dirs with no entries dont get a
482
# dirblock at parse time.
483
# This is an uncommon branch to take: most dirs have children,
484
# and most code works with versioned paths.
485
parent_base, parent_name = os.path.split(key[0])
486
if not self._get_block_entry_index(parent_base, parent_name, 0)[3]:
487
# some parent path has not been added - its an error to add
489
raise errors.NotVersionedError(key[0:2], str(self))
490
self._dirblocks.insert(block_index, (key[0], []))
491
return self._dirblocks[block_index]
493
def _find_block_index_from_key(self, key):
494
"""Find the dirblock index for a key.
496
:return: The block index, True if the block for the key is present.
498
if key[0:2] == ('', ''):
500
block_index = bisect.bisect_left(self._dirblocks, (key[0], []), 1)
501
# _right returns one-past-where-key is so we have to subtract
502
# one to use it. we use _right here because there are two
503
# '' blocks - the root, and the contents of root
504
# we always have a minimum of 2 in self._dirblocks: root and
505
# root-contents, and for '', we get 2 back, so this is
506
# simple and correct:
507
present = (block_index < len(self._dirblocks) and
508
self._dirblocks[block_index][0] == key[0])
509
return block_index, present
511
def _find_entry_index(self, key, block):
512
"""Find the entry index for a key in a block.
514
:return: The entry index, True if the entry for the key is present.
516
entry_index = bisect.bisect_left(block, (key, []))
517
present = (entry_index < len(block) and
518
block[entry_index][0] == key)
519
return entry_index, present
522
def from_tree(tree, dir_state_filename):
523
"""Create a dirstate from a bzr Tree.
525
:param tree: The tree which should provide parent information and
528
result = DirState.initialize(dir_state_filename)
530
parent_ids = tree.get_parent_ids()
531
num_parents = len(parent_ids)
533
for parent_id in parent_ids:
534
parent_trees.append((parent_id, tree.branch.repository.revision_tree(parent_id)))
535
parent_trees[-1][1].lock_read()
536
result.set_parent_trees(parent_trees, [])
537
result.set_state_from_inventory(tree.inventory)
539
for revid, parent in parent_trees:
544
def get_ghosts(self):
545
"""Return a list of the parent tree revision ids that are ghosts."""
546
self._read_header_if_needed()
550
"""Serialise the entire dirstate to a sequence of lines."""
551
if (self._header_state == DirState.IN_MEMORY_UNMODIFIED and
552
self._dirblock_state == DirState.IN_MEMORY_UNMODIFIED):
553
# read whats on disk.
554
self._state_file.seek(0)
555
return self._state_file.readlines()
557
lines.append(self._get_parents_line(self.get_parent_ids()))
558
lines.append(self._get_ghosts_line(self._ghosts))
559
# append the root line which is special cased
560
lines.extend(map(self._entry_to_line, self._iter_entries()))
561
return self._get_output_lines(lines)
563
def _get_ghosts_line(self, ghost_ids):
564
"""Create a line for the state file for ghost information."""
565
return '\0'.join([str(len(ghost_ids))] + ghost_ids)
567
def _get_parents_line(self, parent_ids):
568
"""Create a line for the state file for parents information."""
569
return '\0'.join([str(len(parent_ids))] + parent_ids)
571
def _get_fields_to_entry(self):
572
"""Get a function which converts entry fields into a entry record.
574
This handles size and executable, as well as parent records.
576
:return: A function which takes a list of fields, and returns an
577
appropriate record for storing in memory.
579
# This is intentionally unrolled for performance
580
num_present_parents = self._num_present_parents()
581
if num_present_parents == 0:
582
def fields_to_entry_0_parents(fields, _int=int):
583
path_name_file_id_key = (fields[0], fields[1], fields[2])
584
return (path_name_file_id_key, [
586
fields[3], # minikind
587
fields[4], # fingerprint
588
_int(fields[5]), # size
589
fields[6] == 'y', # executable
590
fields[7], # packed_stat or revision_id
592
return fields_to_entry_0_parents
593
elif num_present_parents == 1:
594
def fields_to_entry_1_parent(fields, _int=int):
595
path_name_file_id_key = (fields[0], fields[1], fields[2])
596
return (path_name_file_id_key, [
598
fields[3], # minikind
599
fields[4], # fingerprint
600
_int(fields[5]), # size
601
fields[6] == 'y', # executable
602
fields[7], # packed_stat or revision_id
605
fields[8], # minikind
606
fields[9], # fingerprint
607
_int(fields[10]), # size
608
fields[11] == 'y', # executable
609
fields[12], # packed_stat or revision_id
612
return fields_to_entry_1_parent
613
elif num_present_parents == 2:
614
def fields_to_entry_2_parents(fields, _int=int):
615
path_name_file_id_key = (fields[0], fields[1], fields[2])
616
return (path_name_file_id_key, [
618
fields[3], # minikind
619
fields[4], # fingerprint
620
_int(fields[5]), # size
621
fields[6] == 'y', # executable
622
fields[7], # packed_stat or revision_id
625
fields[8], # minikind
626
fields[9], # fingerprint
627
_int(fields[10]), # size
628
fields[11] == 'y', # executable
629
fields[12], # packed_stat or revision_id
632
fields[13], # minikind
633
fields[14], # fingerprint
634
_int(fields[15]), # size
635
fields[16] == 'y', # executable
636
fields[17], # packed_stat or revision_id
639
return fields_to_entry_2_parents
641
def fields_to_entry_n_parents(fields, _int=int):
642
path_name_file_id_key = (fields[0], fields[1], fields[2])
643
trees = [(fields[cur], # minikind
644
fields[cur+1], # fingerprint
645
_int(fields[cur+2]), # size
646
fields[cur+3] == 'y', # executable
647
fields[cur+4], # stat or revision_id
648
) for cur in xrange(3, len(fields)-1, 5)]
649
return path_name_file_id_key, trees
650
return fields_to_entry_n_parents
652
def get_parent_ids(self):
653
"""Return a list of the parent tree ids for the directory state."""
654
self._read_header_if_needed()
655
return list(self._parents)
657
def _get_block_entry_index(self, dirname, basename, tree_index):
658
"""Get the coordinates for a path in the state structure.
660
:param dirname: The utf8 dirname to lookup.
661
:param basename: The utf8 basename to lookup.
662
:param tree_index: The index of the tree for which this lookup should
664
:return: A tuple describing where the path is located, or should be
665
inserted. The tuple contains four fields: the block index, the row
666
index, anda two booleans are True when the directory is present, and
667
when the entire path is present. There is no guarantee that either
668
coordinate is currently reachable unless the found field for it is
669
True. For instance, a directory not present in the searched tree
670
may be returned with a value one greater than the current highest
671
block offset. The directory present field will always be True when
672
the path present field is True. The directory present field does
673
NOT indicate that the directory is present in the searched tree,
674
rather it indicates that there are at least some files in some
677
self._read_dirblocks_if_needed()
678
key = dirname, basename, ''
679
block_index, present = self._find_block_index_from_key(key)
681
# no such directory - return the dir index and 0 for the row.
682
return block_index, 0, False, False
683
block = self._dirblocks[block_index][1] # access the entries only
684
entry_index, present = self._find_entry_index(key, block)
685
# linear search through present entries at this path to find the one
687
while entry_index < len(block) and block[entry_index][0][1] == basename:
688
if block[entry_index][1][tree_index][0] not in \
689
('a', 'r'): # absent, relocated
690
return block_index, entry_index, True, True
692
return block_index, entry_index, True, False
694
def _get_entry(self, tree_index, fileid_utf8=None, path_utf8=None):
695
"""Get the dirstate entry for path in tree tree_index
697
If either file_id or path is supplied, it is used as the key to lookup.
698
If both are supplied, the fastest lookup is used, and an error is
699
raised if they do not both point at the same row.
701
:param tree_index: The index of the tree we wish to locate this path
702
in. If the path is present in that tree, the entry containing its
703
details is returned, otherwise (None, None) is returned
704
:param fileid_utf8: A utf8 file_id to look up.
705
:param path_utf8: An utf8 path to be looked up.
706
:return: The dirstate entry tuple for path, or (None, None)
708
self._read_dirblocks_if_needed()
709
if path_utf8 is not None:
710
assert path_utf8.__class__ == str, 'path_utf8 is not a str: %s %s' % (type(path_utf8), path_utf8)
711
# path lookups are faster
712
dirname, basename = os.path.split(path_utf8)
713
block_index, entry_index, dir_present, file_present = \
714
self._get_block_entry_index(dirname, basename, tree_index)
717
entry = self._dirblocks[block_index][1][entry_index]
718
assert entry[0][2] and entry[1][tree_index][0] not in ('a', 'r'), 'unversioned entry?!?!'
720
if entry[0][2] != fileid_utf8:
721
raise BzrError('integrity error ? : mismatching tree_index, file_id and path')
724
for entry in self._iter_entries():
725
if entry[0][2] == fileid_utf8:
726
if entry[1][tree_index][0] == 'r': # relocated
727
# look up the real location directly by path
728
return self._get_entry(tree_index,
729
fileid_utf8=fileid_utf8,
730
path_utf8=entry[1][tree_index][1])
731
if entry[1][tree_index][0] == 'a': # absent
732
# not in the tree at all.
738
def initialize(path):
739
"""Create a new dirstate on path.
741
The new dirstate will be an empty tree - that is it has no parents,
742
and only a root node - which has id ROOT_ID.
744
:param path: The name of the file for the dirstate.
745
:return: A DirState object.
747
# This constructs a new DirState object on a path, sets the _state_file
748
# to a new empty file for that path. It then calls _set_data() with our
749
# stock empty dirstate information - a root with ROOT_ID, no children,
750
# and no parents. Finally it calls save() to ensure that this data will
753
result._state_file = open(path, 'wb+')
754
# root dir and root dir contents with no children.
755
empty_tree_dirblocks = [('', []), ('', [])]
756
# a new root directory, with a NULLSTAT.
757
empty_tree_dirblocks[0][1].append(
758
(('', '', bzrlib.inventory.ROOT_ID), [
759
('d', '', 0, False, DirState.NULLSTAT),
761
result._set_data([], empty_tree_dirblocks)
765
result._state_file.close()
769
def _inv_entry_to_details(self, inv_entry):
770
"""Convert an inventory entry (from a revision tree) to state details.
772
:param inv_entry: An inventory entry whose sha1 and link targets can be
773
relied upon, and which has a revision set.
774
:return: A details tuple - the details for a single tree at a path +
777
kind = inv_entry.kind
778
minikind = DirState._kind_to_minikind[kind]
779
tree_data = inv_entry.revision
780
assert len(tree_data) > 0, 'empty revision for the inv_entry.'
781
if kind == 'directory':
785
elif kind == 'symlink':
786
fingerprint = inv_entry.symlink_target or ''
790
fingerprint = inv_entry.text_sha1 or ''
791
size = inv_entry.text_size or 0
792
executable = inv_entry.executable
795
return (minikind, fingerprint, size, executable, tree_data)
797
def _iter_entries(self):
798
"""Iterate over all the entries in the dirstate.
800
Each yelt item is an entry in the standard format described in the
801
docstring of bzrlib.dirstate.
803
self._read_dirblocks_if_needed()
804
for directory in self._dirblocks:
805
for entry in directory[1]:
808
def _get_id_index(self):
809
"""Get an id index of self._dirblocks."""
811
for key, tree_details in self._iter_entries():
812
id_index.setdefault(key[2], set()).add(key)
815
def _get_output_lines(self, lines):
816
"""format lines for final output.
818
:param lines: A sequece of lines containing the parents list and the
821
output_lines = ['#bazaar dirstate flat format 2\n']
822
lines.append('') # a final newline
823
inventory_text = '\0\n\0'.join(lines)
824
output_lines.append('adler32: %s\n' % (zlib.adler32(inventory_text),))
825
# -3, 1 for num parents, 1 for ghosts, 1 for final newline
826
num_entries = len(lines)-3
827
output_lines.append('num_entries: %s\n' % (num_entries,))
828
output_lines.append(inventory_text)
831
def _make_deleted_row(self, fileid_utf8, parents):
832
"""Return a deleted for for fileid_utf8."""
833
return ('/', 'RECYCLED.BIN', 'file', fileid_utf8, 0, DirState.NULLSTAT,
836
def _num_present_parents(self):
837
"""The number of parent entries in each record row."""
838
return len(self._parents) - len(self._ghosts)
842
"""Construct a DirState on the file at path path."""
844
result._state_file = open(path, 'rb+')
847
def _read_dirblocks_if_needed(self):
848
"""Read in all the dirblocks from the file if they are not in memory.
850
This populates self._dirblocks, and sets self._dirblock_state to
851
IN_MEMORY_UNMODIFIED. It is not currently ready for incremental block
854
self._read_header_if_needed()
855
if self._dirblock_state == DirState.NOT_IN_MEMORY:
856
# the _state_file pointer will be positioned at the start of the
858
text = self._state_file.read()
859
# TODO: check the adler checksums. adler_measured = zlib.adler32(text)
861
fields = text.split('\0')
862
# Remove the last blank entry
863
trailing = fields.pop()
864
assert trailing == ''
865
# consider turning fields into a tuple.
867
# skip the first field which is the trailing null from the header.
869
# Each line now has an extra '\n' field which is not used
870
# so we just skip over it
872
# 3 fields for the key
873
# + number of fields per tree_data (5) * tree count
875
num_present_parents = self._num_present_parents()
876
tree_count = 1 + num_present_parents
877
entry_size = self._fields_per_row()
878
expected_field_count = entry_size * self._num_entries
879
if len(fields) - cur > expected_field_count:
880
fields = fields[:expected_field_count + cur]
881
trace.mutter('Unexpectedly long dirstate field count!')
882
print "XXX: incorrectly truncated dirstate file bug triggered."
883
field_count = len(fields)
884
# this checks our adjustment, and also catches file too short.
885
assert field_count - cur == expected_field_count, \
886
'field count incorrect %s != %s, entry_size=%s, '\
887
'num_entries=%s fields=%r' % (
888
field_count - cur, expected_field_count, entry_size,
889
self._num_entries, fields)
891
if num_present_parents == 1:
892
# Bind external functions to local names
894
# We access all fields in order, so we can just iterate over
895
# them. Grab an straight iterator over the fields. (We use an
896
# iterator because we don't want to do a lot of additions, nor
897
# do we want to do a lot of slicing)
898
next = iter(fields).next
899
# Move the iterator to the current position
900
for x in xrange(cur):
902
# The two blocks here are deliberate: the root block and the
903
# contents-of-root block.
904
self._dirblocks = [('', []), ('', [])]
905
current_block = self._dirblocks[0][1]
907
append_entry = current_block.append
908
for count in xrange(self._num_entries):
912
if dirname != current_dirname:
913
# new block - different dirname
915
current_dirname = dirname
916
self._dirblocks.append((current_dirname, current_block))
917
append_entry = current_block.append
918
# we know current_dirname == dirname, so re-use it to avoid
919
# creating new strings
920
entry = ((current_dirname, name, file_id),
923
next(), # fingerprint
925
next() == 'y', # executable
926
next(), # packed_stat or revision_id
930
next(), # fingerprint
932
next() == 'y', # executable
933
next(), # packed_stat or revision_id
937
assert trailing == '\n'
938
# append the entry to the current block
940
self._split_root_dirblock_into_contents()
942
fields_to_entry = self._get_fields_to_entry()
943
entries = [fields_to_entry(fields[pos:pos+entry_size])
944
for pos in xrange(cur, field_count, entry_size)]
945
self._entries_to_current_state(entries)
946
self._dirblock_state = DirState.IN_MEMORY_UNMODIFIED
948
def _read_header(self):
949
"""This reads in the metadata header, and the parent ids.
951
After reading in, the file should be positioned at the null
952
just before the start of the first record in the file.
954
:return: (expected adler checksum, number of entries, parent list)
957
parent_line = self._state_file.readline()
958
info = parent_line.split('\0')
959
num_parents = int(info[0])
960
assert num_parents == len(info)-2, 'incorrect parent info line'
961
self._parents = info[1:-1]
963
ghost_line = self._state_file.readline()
964
info = ghost_line.split('\0')
965
num_ghosts = int(info[1])
966
assert num_ghosts == len(info)-3, 'incorrect ghost info line'
967
self._ghosts = info[2:-1]
968
self._header_state = DirState.IN_MEMORY_UNMODIFIED
970
def _read_header_if_needed(self):
971
"""Read the header of the dirstate file if needed."""
972
if self._header_state == DirState.NOT_IN_MEMORY:
975
def _read_prelude(self):
976
"""Read in the prelude header of the dirstate file
978
This only reads in the stuff that is not connected to the adler
979
checksum. The position will be correct to read in the rest of
980
the file and check the checksum after this point.
981
The next entry in the file should be the number of parents,
982
and their ids. Followed by a newline.
984
header = self._state_file.readline()
985
assert header == '#bazaar dirstate flat format 2\n', \
986
'invalid header line: %r' % (header,)
987
adler_line = self._state_file.readline()
988
assert adler_line.startswith('adler32: '), 'missing adler32 checksum'
989
self.adler_expected = int(adler_line[len('adler32: '):-1])
990
num_entries_line = self._state_file.readline()
991
assert num_entries_line.startswith('num_entries: '), 'missing num_entries line'
992
self._num_entries = int(num_entries_line[len('num_entries: '):-1])
995
"""Save any pending changes created during this session.
997
We reuse the existing file, because that prevents race conditions with
998
file creation, and we expect to be using oslocks on it in the near
999
future to prevent concurrent modification and reads - because dirstates
1000
incremental data aggretation is not compatible with reading a modified
1001
file, and replacing a file in use by another process is impossible on
1004
A dirstate in read only mode should be smart enough though to validate
1005
that the file has not changed, and otherwise discard its cache and
1006
start over, to allow for fine grained read lock duration, so 'status'
1007
wont block 'commit' - for example.
1009
if (self._header_state == DirState.IN_MEMORY_MODIFIED or
1010
self._dirblock_state == DirState.IN_MEMORY_MODIFIED):
1011
self._state_file.seek(0)
1012
self._state_file.writelines(self.get_lines())
1013
self._state_file.truncate()
1014
self._state_file.flush()
1015
self._header_state = DirState.IN_MEMORY_UNMODIFIED
1016
self._dirblock_state = DirState.IN_MEMORY_UNMODIFIED
1018
def _set_data(self, parent_ids, dirblocks):
1019
"""Set the full dirstate data in memory.
1021
This is an internal function used to completely replace the objects
1022
in memory state. It puts the dirstate into state 'full-dirty'.
1024
:param parent_ids: A list of parent tree revision ids.
1025
:param dirblocks: A list containing one tuple for each directory in the
1026
tree. Each tuple contains the directory path and a list of entries
1027
found in that directory.
1029
# our memory copy is now authoritative.
1030
self._dirblocks = dirblocks
1031
self._header_state = DirState.IN_MEMORY_MODIFIED
1032
self._dirblock_state = DirState.IN_MEMORY_MODIFIED
1033
self._parents = list(parent_ids)
1035
def set_path_id(self, path, new_id):
1036
"""Change the id of path to new_id in the current working tree.
1038
:param path: The path inside the tree to set - '' is the root, 'foo'
1039
is the path foo in the root.
1040
:param new_id: The new id to assign to the path. This must be a utf8
1041
file id (not unicode, and not None).
1043
# TODO: start warning here.
1044
assert new_id.__class__ == str
1045
self._read_dirblocks_if_needed()
1047
import pdb;pdb.set_trace()
1049
raise NotImplementedError(self.set_path_id)
1050
# TODO: check new id is unique
1051
entry = self._get_entry(0, path_utf8=path)
1052
# mark the old path absent, and insert a new root path
1053
present_parents = len(entry[1]) - 1
1054
self._make_absent(entry)
1055
id_index = self._get_id_index()
1056
self.update_minimal(('', '', new_id), 'directory', present_parents,
1057
path_utf8='', id_index=id_index, packed_stat=entry[1][0][4])
1058
self._dirblock_state = DirState.IN_MEMORY_MODIFIED
1060
def set_parent_trees(self, trees, ghosts):
1061
"""Set the parent trees for the dirstate.
1063
:param trees: A list of revision_id, tree tuples. tree must be provided
1064
even if the revision_id refers to a ghost: supply an empty tree in
1066
:param ghosts: A list of the revision_ids that are ghosts at the time
1069
# TODO: generate a list of parent indexes to preserve to save
1070
# processing specific parent trees. In the common case one tree will
1071
# be preserved - the left most parent.
1072
# TODO: if the parent tree is a dirstate, we might want to walk them
1073
# all by path in parallel for 'optimal' common-case performance.
1074
# generate new root row.
1075
self._read_dirblocks_if_needed()
1076
# TODO future sketch: Examine the existing parents to generate a change
1077
# map and then walk the new parent trees only, mapping them into the
1078
# dirstate. Walk the dirstate at the same time to remove unreferenced
1081
# sketch: loop over all entries in the dirstate, cherry picking
1082
# entries from the parent trees, if they are not ghost trees.
1083
# after we finish walking the dirstate, all entries not in the dirstate
1084
# are deletes, so we want to append them to the end as per the design
1085
# discussions. So do a set difference on ids with the parents to
1086
# get deletes, and add them to the end.
1087
# During the update process we need to answer the following questions:
1088
# - find other keys containing a fileid in order to create cross-path
1089
# links. We dont't trivially use the inventory from other trees
1090
# because this leads to either double touching, or to accessing
1092
# - find other keys containing a path
1093
# We accumulate each entry via this dictionary, including the root
1096
# we could do parallel iterators, but because file id data may be
1097
# scattered throughout, we dont save on index overhead: we have to look
1098
# at everything anyway. We can probably save cycles by reusing parent
1099
# data and doing an incremental update when adding an additional
1100
# parent, but for now the common cases are adding a new parent (merge),
1101
# and replacing completely (commit), and commit is more common: so
1102
# optimise merge later.
1104
# ---- start generation of full tree mapping data
1105
# what trees should we use?
1106
parent_trees = [tree for rev_id, tree in trees if rev_id not in ghosts]
1107
# how many trees do we end up with
1108
parent_count = len(parent_trees)
1110
# one: the current tree
1111
for entry in self._iter_entries():
1112
# skip entries not in the current tree
1113
if entry[1][0][0] in ('a', 'r'): # absent, relocated
1115
by_path[entry[0]] = [entry[1][0]] + \
1116
[DirState.NULL_PARENT_DETAILS] * parent_count
1117
id_index[entry[0][2]] = set([entry[0]])
1119
# now the parent trees:
1120
for tree_index, tree in enumerate(parent_trees):
1121
# the index is off by one, adjust it.
1122
tree_index = tree_index + 1
1123
# when we add new locations for a fileid we need these ranges for
1124
# any fileid in this tree as we set the by_path[id] to:
1125
# already_processed_tree_details + new_details + new_location_suffix
1126
# the suffix is from tree_index+1:parent_count+1.
1127
new_location_suffix = [DirState.NULL_PARENT_DETAILS] * (parent_count - tree_index)
1128
# now stitch in all the entries from this tree
1129
for path, entry in tree.inventory.iter_entries_by_dir():
1130
# here we process each trees details for each item in the tree.
1131
# we first update any existing entries for the id at other paths,
1132
# then we either create or update the entry for the id at the
1133
# right path, and finally we add (if needed) a mapping from
1134
# file_id to this path. We do it in this order to allow us to
1135
# avoid checking all known paths for the id when generating a
1136
# new entry at this path: by adding the id->path mapping last,
1137
# all the mappings are valid and have correct relocation
1138
# records where needed.
1139
file_id = entry.file_id
1140
path_utf8 = path.encode('utf8')
1141
dirname, basename = os.path.split(path_utf8)
1142
new_entry_key = (dirname, basename, file_id)
1143
# tree index consistency: All other paths for this id in this tree
1144
# index must point to the correct path.
1145
for entry_key in id_index.setdefault(file_id, set()):
1146
# TODO:PROFILING: It might be faster to just update
1147
# rather than checking if we need to, and then overwrite
1148
# the one we are located at.
1149
if entry_key != new_entry_key:
1150
# this file id is at a different path in one of the
1151
# other trees, so put absent pointers there
1152
# This is the vertical axis in the matrix, all pointing
1154
by_path[entry_key][tree_index] = ('r', path_utf8, 0, False, '')
1155
# by path consistency: Insert into an existing path record (trivial), or
1156
# add a new one with relocation pointers for the other tree indexes.
1157
if new_entry_key in id_index[file_id]:
1158
# there is already an entry where this data belongs, just insert it.
1159
by_path[new_entry_key][tree_index] = \
1160
self._inv_entry_to_details(entry)
1162
# add relocated entries to the horizontal axis - this row
1163
# mapping from path,id. We need to look up the correct path
1164
# for the indexes from 0 to tree_index -1
1166
for lookup_index in xrange(tree_index):
1167
# boundary case: this is the first occurence of file_id
1168
# so there are no id_indexs, possibly take this out of
1170
if not len(id_index[file_id]):
1171
new_details.append(DirState.NULL_PARENT_DETAILS)
1173
# grab any one entry, use it to find the right path.
1174
# TODO: optimise this to reduce memory use in highly
1175
# fragmented situations by reusing the relocation
1177
a_key = iter(id_index[file_id]).next()
1178
if by_path[a_key][lookup_index][0] in ('r', 'a'):
1179
# its a pointer or missing statement, use it as is.
1180
new_details.append(by_path[a_key][lookup_index])
1182
# we have the right key, make a pointer to it.
1183
real_path = ('/'.join(a_key[0:2])).strip('/')
1184
new_details.append(('r', real_path, 0, False, ''))
1185
new_details.append(self._inv_entry_to_details(entry))
1186
new_details.extend(new_location_suffix)
1187
by_path[new_entry_key] = new_details
1188
id_index[file_id].add(new_entry_key)
1189
# --- end generation of full tree mappings
1191
# sort and output all the entries
1192
new_entries = sorted(by_path.items())
1193
self._entries_to_current_state(new_entries)
1194
self._parents = [rev_id for rev_id, tree in trees]
1195
self._ghosts = list(ghosts)
1196
self._header_state = DirState.IN_MEMORY_MODIFIED
1197
self._dirblock_state = DirState.IN_MEMORY_MODIFIED
1199
def set_state_from_inventory(self, new_inv):
1200
"""Set new_inv as the current state.
1202
This API is called by tree transform, and will usually occur with
1203
existing parent trees.
1205
:param new_inv: The inventory object to set current state from.
1207
self._read_dirblocks_if_needed()
1209
# generate a byid index of the dirstate
1210
id_index = self._get_id_index()
1212
num_present_parents = len(self._parents) - len(self._ghosts)
1213
# incremental algorithm:
1214
# two iterators: current data and new data, both in dirblock order.
1215
new_iterator = new_inv.iter_entries_by_dir()
1216
# we will be modifying the dirstate, so we need a stable iterator. In
1217
# future we might write one, for now we just clone the state into a
1218
# list - which is a shallow copy, so each
1219
old_iterator = iter(list(self._iter_entries()))
1220
# both must have roots so this is safe:
1221
current_new = new_iterator.next()
1222
current_old = old_iterator.next()
1223
def advance(iterator):
1225
return iterator.next()
1226
except StopIteration:
1228
while current_new or current_old:
1229
# skip entries in old that are not really there
1230
if current_old and current_old[1][0][0] in ('r', 'a'):
1231
# relocated or absent
1232
current_old = advance(old_iterator)
1235
# convert new into dirblock style
1236
new_path_utf8 = current_new[0].encode('utf8')
1237
new_dirname, new_basename = os.path.split(new_path_utf8)
1238
new_id = current_new[1].file_id
1239
new_entry_key = (new_dirname, new_basename, new_id)
1241
# for safety disable variables
1242
new_path_utf8 = new_dirname = new_basename = new_id = new_entry_key = None
1243
# 5 cases, we dont have a value that is strictly greater than everything, so
1244
# we make both end conditions explicit
1246
# old is finished: insert current_new into the state.
1247
self.update_minimal(new_entry_key, current_new[1].kind,
1248
num_present_parents, executable=current_new[1].executable,
1249
id_index=id_index, path_utf8=new_path_utf8)
1250
current_new = advance(new_iterator)
1251
elif not current_new:
1253
self._make_absent(current_old, id_index)
1254
current_old = advance(old_iterator)
1255
elif new_entry_key == current_old[0]:
1256
# same - common case
1257
# TODO: update the record if anything significant has changed.
1258
# the minimal required trigger is if the execute bit or cached
1260
kind = DirState._minikind_to_kind[current_old[1][0][0]]
1261
if (current_old[1][0][3] != current_new[1].executable or
1262
kind != current_new[1].kind):
1263
self.update_minimal(current_old[0], current_new[1].kind,
1264
num_present_parents,
1265
executable=current_new[1].executable,
1266
id_index=id_index, path_utf8=new_path_utf8)
1267
# both sides are dealt with, move on
1268
current_old = advance(old_iterator)
1269
current_new = advance(new_iterator)
1270
elif new_entry_key < current_old[0]:
1272
# add a entry for this and advance new
1273
self.update_minimal(new_entry_key, current_new[1].kind,
1274
num_present_parents, executable=current_new[1].executable,
1275
id_index=id_index, path_utf8=new_path_utf8)
1276
current_new = advance(new_iterator)
1279
self._make_absent(current_old, id_index)
1280
current_old = advance(old_iterator)
1281
self._dirblock_state = DirState.IN_MEMORY_MODIFIED
1283
def _make_absent(self, current_old, id_index=None):
1284
"""Mark current_old - an entry - as absent for tree 0.
1286
:param id_index: An index from fileid_utf8 to sets of keys, used by
1287
some functions. If provided it will be updated if needed.
1288
:return: True if this was the last details entry for they entry key:
1289
that is, if the underlying block has had the entry removed, thus
1290
shrinking in legnth.
1292
# build up paths that this id will be left at after the change is made,
1293
# so we can update their cross references in tree 0
1294
all_remaining_keys = set()
1295
# Dont check the working tree, because its going.
1296
for details in current_old[1][1:]:
1297
if details[0] not in ('a', 'r'): # absent, relocated
1298
all_remaining_keys.add(current_old[0])
1299
elif details[0] == 'r': # relocated
1300
# record the key for the real path.
1301
all_remaining_keys.add(tuple(os.path.split(details[1])) + (current_old[0][2],))
1302
# absent rows are not present at any path.
1303
last_reference = current_old[0] not in all_remaining_keys
1305
# the current row consists entire of the current item (being marked
1306
# absent), and relocated or absent entries for the other trees:
1307
# Remove it, its meaningless.
1308
block = self._find_block(current_old[0])
1309
entry_index, present = self._find_entry_index(current_old[0], block[1])
1311
block[1].pop(entry_index)
1312
# if we have an id_index in use, remove this key from it for this id.
1313
if id_index is not None:
1314
id_index[current_old[0][2]].remove(current_old[0])
1315
# update all remaining keys for this id to record it as absent. The
1316
# existing details may either be the record we are making as deleted
1317
# (if there were other trees with the id present at this path), or may
1319
for update_key in all_remaining_keys:
1320
update_block_index, present = \
1321
self._find_block_index_from_key(update_key)
1323
update_entry_index, present = \
1324
self._find_entry_index(update_key, self._dirblocks[update_block_index][1])
1326
update_tree_details = self._dirblocks[update_block_index][1][update_entry_index][1]
1327
# it must not be absent at the moment
1328
assert update_tree_details[0][0] != 'a' # absent
1329
update_tree_details[0] = DirState.NULL_PARENT_DETAILS
1330
self._dirblock_state = DirState.IN_MEMORY_MODIFIED
1331
return last_reference
1333
def update_minimal(self, key, kind, num_present_parents, executable=False,
1334
fingerprint='', packed_stat=None, size=0, id_index=None,
1336
"""Update an entry to the state in tree 0."""
1337
block = self._find_block(key)[1]
1338
if packed_stat is None:
1339
packed_stat = DirState.NULLSTAT
1340
entry_index, present = self._find_entry_index(key, block)
1341
minikind = DirState._kind_to_minikind[kind]
1342
new_details = (minikind, fingerprint, size, executable, packed_stat)
1343
assert id_index is not None, 'need an id index to do updates for now !'
1345
# new entry, synthesis cross reference here,
1346
existing_keys = id_index.setdefault(key[2], set())
1347
if not existing_keys:
1348
# not currently in the state, simplest case
1349
new_entry = key, [new_details] + self._empty_parent_info()
1351
# present at one or more existing other paths.
1352
# grab one of them and use it to generate parent
1353
# relocation/absent entries.
1354
new_entry = key, [new_details]
1355
for other_key in existing_keys:
1356
# change the record at other to be a pointer to this new
1357
# record. The loop looks similar to the change to
1358
# relocations when updating an existing record but its not:
1359
# the test for existing kinds is different: this can be
1360
# factored out to a helper though.
1361
other_block_index, present = self._find_block_index_from_key(other_key)
1363
other_entry_index, present = self._find_entry_index(other_key, self._dirblocks[other_block_index][1])
1365
assert path_utf8 is not None
1366
self._dirblocks[other_block_index][1][other_entry_index][1][0] = \
1367
('r', path_utf8, 0, False, '')
1369
for lookup_index in xrange(1, num_present_parents + 1):
1370
# grab any one entry, use it to find the right path.
1371
# TODO: optimise this to reduce memory use in highly
1372
# fragmented situations by reusing the relocation
1374
update_block_index, present = \
1375
self._find_block_index_from_key(other_key)
1377
update_entry_index, present = \
1378
self._find_entry_index(other_key, self._dirblocks[update_block_index][1])
1380
update_details = self._dirblocks[update_block_index][1][update_entry_index][1][lookup_index]
1381
if update_details[0] in ('r', 'a'): # relocated, absent
1382
# its a pointer or absent in lookup_index's tree, use
1384
new_entry[1].append(update_details)
1386
# we have the right key, make a pointer to it.
1387
pointer_path = os.path.join(*other_key[0:2])
1388
new_entry[1].append(('r', pointer_path, 0, False, ''))
1389
block.insert(entry_index, new_entry)
1390
existing_keys.add(key)
1392
# Does the new state matter?
1393
block[entry_index][1][0] = new_details
1394
# parents cannot be affected by what we do.
1395
# other occurences of this id can be found
1396
# from the id index.
1398
# tree index consistency: All other paths for this id in this tree
1399
# index must point to the correct path. We have to loop here because
1400
# we may have passed entries in the state with this file id already
1401
# that were absent - where parent entries are - and they need to be
1402
# converted to relocated.
1403
assert path_utf8 is not None
1404
for entry_key in id_index.setdefault(key[2], set()):
1405
# TODO:PROFILING: It might be faster to just update
1406
# rather than checking if we need to, and then overwrite
1407
# the one we are located at.
1408
if entry_key != key:
1409
# this file id is at a different path in one of the
1410
# other trees, so put absent pointers there
1411
# This is the vertical axis in the matrix, all pointing
1413
block_index, present = self._find_block_index_from_key(entry_key)
1415
entry_index, present = self._find_entry_index(entry_key, self._dirblocks[block_index][1])
1417
self._dirblocks[block_index][1][entry_index][1][0] = \
1418
('r', path_utf8, 0, False, '')
1419
# add a containing dirblock if needed.
1420
if new_details[0] == 'd':
1421
subdir_key = (os.path.join(*key[0:2]), '', '')
1422
block_index, present = self._find_block_index_from_key(subdir_key)
1424
self._dirblocks.insert(block_index, (subdir_key[0], []))
1426
self._dirblock_state = DirState.IN_MEMORY_MODIFIED
1430
def pack_stat(st, _encode=base64.encodestring, _pack=struct.pack):
1431
"""Convert stat values into a packed representation."""
1432
# jam 20060614 it isn't really worth removing more entries if we
1433
# are going to leave it in packed form.
1434
# With only st_mtime and st_mode filesize is 5.5M and read time is 275ms
1435
# With all entries filesize is 5.9M and read time is mabye 280ms
1436
# well within the noise margin
1438
# base64.encode always adds a final newline, so strip it off
1439
return _encode(_pack('>llllll'
1440
, st.st_size, st.st_mtime, st.st_ctime
1441
, st.st_dev, st.st_ino, st.st_mode))[:-1]