/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/dirstate.py

  • Committer: John Arbash Meinel
  • Date: 2007-03-01 19:58:38 UTC
  • mto: (2255.7.84 dirstate)
  • mto: This revision was merged to the branch mainline in revision 2322.
  • Revision ID: john@arbash-meinel.com-20070301195838-7p053os20qwr6qf7
Update WorkingTree4 so that it doesn't use a HashCache,
instead caching the sha values and stat fingerprint in the 'current'
section.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2006, 2007 Canonical Ltd
 
2
#
 
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.
 
7
#
 
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.
 
12
#
 
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
 
16
 
 
17
"""DirState objects record the state of a directory and its bzr metadata.
 
18
 
 
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.
 
22
 
 
23
MINIKIND = "f" | "d" | "l" | "a" | "r";
 
24
NL = "\n";
 
25
NULL = "\0";
 
26
WHOLE_NUMBER = {digit}, digit;
 
27
BOOLEAN = "y" | "n";
 
28
REVISION_ID = a non-empty utf8 string;
 
29
 
 
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;
 
37
entries = {entry};
 
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;
 
45
executable = BOOLEAN;
 
46
size = WHOLE_NUMBER;
 
47
fingerprint = a nonempty utf8 sequence with meaning defined by minikind.
 
48
 
 
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)
 
52
entry[0][0]: dirname
 
53
entry[0][1]: basename
 
54
entry[0][2]: 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
 
58
 
 
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
 
62
entry[1][0][2]: size
 
63
entry[1][0][3]: executable
 
64
entry[1][0][4]: packed_stat
 
65
OR (for non tree-0)
 
66
entry[1][1][4]: revision_id
 
67
 
 
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
 
72
entries[0][0]: ''
 
73
entries[0][1]: ''
 
74
entries[0][2]: file_id
 
75
entries[1][0]: The tree data for the current tree for this fileid at /
 
76
etc.
 
77
 
 
78
Kinds:
 
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
 
86
    sha1 value.
 
87
'l' is a symlink entry: As for directory, but a symlink. The fingerprint is the
 
88
    link target.
 
89
 
 
90
 
 
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, 
 
94
    {PARENT ROW}
 
95
PARENT ROW = NULL, revision_utf8, NULL, MINIKIND, NULL, dirname, NULL,
 
96
    basename, NULL, WHOLE NUMBER (* size *), NULL, "y" | "n", NULL,
 
97
    SHA1
 
98
 
 
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.
 
102
 
 
103
 
 
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.
 
107
 
 
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
 
113
looked for.
 
114
 
 
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
 
117
it.
 
118
 
 
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. 
 
125
----
 
126
 
 
127
Design priorities:
 
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)
 
132
 
 
133
 
 
134
Locking:
 
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.
 
139
 
 
140
Memory representation:
 
141
 vector of all directories, and vector of the childen ?
 
142
   i.e. 
 
143
     root_entrie = (direntry for root, [parent_direntries_for_root]), 
 
144
     dirblocks = [
 
145
     ('', ['data for achild', 'data for bchild', 'data for cchild'])
 
146
     ('dir', ['achild', 'cchild', 'echild'])
 
147
     ]
 
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.
 
160
open questions:
 
161
 
 
162
maybe we should do a test profile of these core structure - 10K simulated searches/lookups/etc?
 
163
 
 
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.
 
178
 
 
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
 
189
desired.
 
190
 
 
191
"""
 
192
 
 
193
 
 
194
import bisect
 
195
import codecs
 
196
import cStringIO
 
197
import os
 
198
import sha
 
199
import struct
 
200
import time
 
201
import zlib
 
202
 
 
203
from bzrlib import (
 
204
    errors,
 
205
    inventory,
 
206
    lock,
 
207
    osutils,
 
208
    trace,
 
209
    )
 
210
from bzrlib.osutils import (
 
211
    pathjoin,
 
212
    sha_file,
 
213
    sha_string,
 
214
    walkdirs,
 
215
    )
 
216
 
 
217
 
 
218
class _Bisector(object):
 
219
    """This just keeps track of information as we are bisecting."""
 
220
 
 
221
 
 
222
class DirState(object):
 
223
    """Record directory and metadata state for fast access.
 
224
 
 
225
    A dirstate is a specialised data structure for managing local working
 
226
    tree state information. Its not yet well defined whether it is platform
 
227
    specific, and if it is how we detect/parameterise that.
 
228
    """
 
229
 
 
230
    _kind_to_minikind = {'absent':'a', 'file':'f', 'directory':'d', 'relocated':'r', 'symlink':'l'}
 
231
    _minikind_to_kind = {'a':'absent', 'f':'file', 'd':'directory', 'l':'symlink', 'r':'relocated'}
 
232
    _to_yesno = {True:'y', False: 'n'} # TODO profile the performance gain
 
233
     # of using int conversion rather than a dict here. AND BLAME ANDREW IF
 
234
     # it is faster.
 
235
 
 
236
    # TODO: jam 20070221 Make sure we handle when there are duplicated records
 
237
    #       (like when we remove + add the same path, or we have a rename)
 
238
    # TODO: jam 20070221 Figure out what to do if we have a record that exceeds
 
239
    #       the BISECT_PAGE_SIZE. For now, we just have to make it large enough
 
240
    #       that we are sure a single record will always fit.
 
241
    BISECT_PAGE_SIZE = 4096
 
242
 
 
243
    NOT_IN_MEMORY = 0
 
244
    IN_MEMORY_UNMODIFIED = 1
 
245
    IN_MEMORY_MODIFIED = 2
 
246
 
 
247
    # A pack_stat (the x's) that is just noise and will never match the output
 
248
    # of base64 encode.
 
249
    NULLSTAT = 'x' * 32
 
250
    NULL_PARENT_DETAILS = ('a', '', 0, False, '')
 
251
 
 
252
    HEADER_FORMAT_2 = '#bazaar dirstate flat format 2\n'
 
253
    HEADER_FORMAT_3 = '#bazaar dirstate flat format 3\n'
 
254
 
 
255
    def __init__(self, path):
 
256
        """Create a  DirState object.
 
257
 
 
258
        Attributes of note:
 
259
 
 
260
        :attr _root_entrie: The root row of the directory/file information,
 
261
            - contains the path to / - '', ''
 
262
            - kind of 'directory',
 
263
            - the file id of the root in utf8
 
264
            - size of 0
 
265
            - a packed state
 
266
            - and no sha information.
 
267
        :param path: The path at which the dirstate file on disk should live.
 
268
        """
 
269
        # _header_state and _dirblock_state represent the current state
 
270
        # of the dirstate metadata and the per-row data respectiely.
 
271
        # NOT_IN_MEMORY indicates that no data is in memory
 
272
        # IN_MEMORY_UNMODIFIED indicates that what we have in memory
 
273
        #   is the same as is on disk
 
274
        # IN_MEMORY_MODIFIED indicates that we have a modified version
 
275
        #   of what is on disk. 
 
276
        # In future we will add more granularity, for instance _dirblock_state
 
277
        # will probably support partially-in-memory as a separate variable,
 
278
        # allowing for partially-in-memory unmodified and partially-in-memory
 
279
        # modified states.
 
280
        self._header_state = DirState.NOT_IN_MEMORY
 
281
        self._dirblock_state = DirState.NOT_IN_MEMORY
 
282
        self._dirblocks = []
 
283
        self._ghosts = []
 
284
        self._parents = []
 
285
        self._state_file = None
 
286
        self._filename = path
 
287
        self._lock_token = None
 
288
        self._id_index = None
 
289
        self._end_of_header = None
 
290
        self._split_path_cache = {}
 
291
        self._bisect_page_size = DirState.BISECT_PAGE_SIZE
 
292
 
 
293
    def add(self, path, file_id, kind, stat, link_or_sha1):
 
294
        """Add a path to be tracked.
 
295
 
 
296
        :param path: The path within the dirstate - '' is the root, 'foo' is the
 
297
            path foo within the root, 'foo/bar' is the path bar within foo 
 
298
            within the root.
 
299
        :param file_id: The file id of the path being added.
 
300
        :param kind: The kind of the path.
 
301
        :param stat: The output of os.lstat for the path.
 
302
        :param link_or_sha1: The sha value of the file, or the target of a
 
303
            symlink. '' for directories.
 
304
        """
 
305
        # adding a file:
 
306
        # find the block its in. 
 
307
        # find the location in the block.
 
308
        # check its not there
 
309
        # add it.
 
310
        #------- copied from inventory.make_entry
 
311
        # --- normalized_filename wants a unicode basename only, so get one.
 
312
        dirname, basename = osutils.split(path)
 
313
        # we dont import normalized_filename directly because we want to be
 
314
        # able to change the implementation at runtime for tests.
 
315
        norm_name, can_access = osutils.normalized_filename(basename)
 
316
        if norm_name != basename:
 
317
            if can_access:
 
318
                basename = norm_name
 
319
            else:
 
320
                raise errors.InvalidNormalization(path)
 
321
        # now that we've normalised, we need the correct utf8 path and 
 
322
        # dirname and basename elements. This single encode and split should be
 
323
        # faster than three separate encodes.
 
324
        utf8path = (dirname + '/' + basename).strip('/').encode('utf8')
 
325
        dirname, basename = osutils.split(utf8path)
 
326
        assert file_id.__class__ == str, \
 
327
            "must be a utf8 file_id not %s" % (type(file_id))
 
328
        # Make sure the file_id does not exist in this tree
 
329
        file_id_entry = self._get_entry(0, fileid_utf8=file_id)
 
330
        if file_id_entry != (None, None):
 
331
            path = osutils.pathjoin(file_id_entry[0][0], file_id_entry[0][1])
 
332
            kind = DirState._minikind_to_kind[file_id_entry[1][0][0]]
 
333
            info = '%s:%s' % (kind, path)
 
334
            raise errors.DuplicateFileId(file_id, info)
 
335
        first_key = (dirname, basename, '')
 
336
        block_index, present = self._find_block_index_from_key(first_key)
 
337
        if present:
 
338
            # check the path is not in the tree
 
339
            block = self._dirblocks[block_index][1]
 
340
            entry_index, _ = self._find_entry_index(first_key, block)
 
341
            while (entry_index < len(block) and 
 
342
                block[entry_index][0][0:2] == first_key[0:2]):
 
343
                if block[entry_index][1][0][0] not in 'ar':
 
344
                    # this path is in the dirstate in the current tree.
 
345
                    raise Exception, "adding already added path!"
 
346
                entry_index += 1
 
347
        else:
 
348
            # The block where we want to put the file is not present. But it
 
349
            # might be because the directory was empty, or not loaded yet. Look
 
350
            # for a parent entry, if not found, raise NotVersionedError
 
351
            parent_dir, parent_base = osutils.split(dirname)
 
352
            parent_block_idx, parent_entry_idx, _, parent_present = \
 
353
                self._get_block_entry_index(parent_dir, parent_base, 0)
 
354
            if not parent_present:
 
355
                raise errors.NotVersionedError(path, str(self))
 
356
            self._ensure_block(parent_block_idx, parent_entry_idx, dirname)
 
357
        block = self._dirblocks[block_index][1]
 
358
        entry_key = (dirname, basename, file_id)
 
359
        if stat is None:
 
360
            size = 0
 
361
            packed_stat = DirState.NULLSTAT
 
362
        else:
 
363
            size = stat.st_size
 
364
            packed_stat = pack_stat(stat)
 
365
        parent_info = self._empty_parent_info()
 
366
        minikind = DirState._kind_to_minikind[kind]
 
367
        if kind == 'file':
 
368
            entry_data = entry_key, [
 
369
                (minikind, link_or_sha1, size, False, packed_stat),
 
370
                ] + parent_info
 
371
        elif kind == 'directory':
 
372
            entry_data = entry_key, [
 
373
                (minikind, '', 0, False, packed_stat),
 
374
                ] + parent_info
 
375
        elif kind == 'symlink':
 
376
            entry_data = entry_key, [
 
377
                (minikind, link_or_sha1, size, False, packed_stat),
 
378
                ] + parent_info
 
379
        else:
 
380
            raise errors.BzrError('unknown kind %r' % kind)
 
381
        entry_index, present = self._find_entry_index(entry_key, block)
 
382
        assert not present, "basename %r already added" % basename
 
383
        block.insert(entry_index, entry_data)
 
384
 
 
385
        if kind == 'directory':
 
386
           # insert a new dirblock
 
387
           self._ensure_block(block_index, entry_index, utf8path)
 
388
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
389
        if self._id_index:
 
390
            self._id_index.setdefault(entry_key[2], set()).add(entry_key)
 
391
 
 
392
    def _bisect(self, dir_name_list):
 
393
        """Bisect through the disk structure for specific rows.
 
394
 
 
395
        :param dir_name_list: A list of (dir, name) pairs.
 
396
        :return: A dict mapping (dir, name) => entry for found entries. Missing
 
397
                 entries will not be in the map.
 
398
        """
 
399
        self._requires_lock()
 
400
        # We need the file pointer to be right after the initial header block
 
401
        self._read_header_if_needed()
 
402
        # If _dirblock_state was in memory, we should just return info from
 
403
        # there, this function is only meant to handle when we want to read
 
404
        # part of the disk.
 
405
        assert self._dirblock_state == DirState.NOT_IN_MEMORY
 
406
 
 
407
        # The disk representation is generally info + '\0\n\0' at the end. But
 
408
        # for bisecting, it is easier to treat this as '\0' + info + '\0\n'
 
409
        # Because it means we can sync on the '\n'
 
410
        state_file = self._state_file
 
411
        file_size = os.fstat(state_file.fileno()).st_size
 
412
        # We end up with 2 extra fields, we should have a trailing '\n' to
 
413
        # ensure that we read the whole record, and we should have a precursur
 
414
        # '' which ensures that we start after the previous '\n'
 
415
        entry_field_count = self._fields_per_entry() + 1
 
416
 
 
417
        low = self._end_of_header
 
418
        high = file_size - 1 # Ignore the final '\0'
 
419
        # Map from (dir, name) => entry
 
420
        found = {}
 
421
 
 
422
        # Avoid infinite seeking
 
423
        max_count = 30*len(dir_name_list)
 
424
        count = 0
 
425
        # pending is a list of places to look.
 
426
        # each entry is a tuple of low, high, dir_names
 
427
        #   low -> the first byte offset to read (inclusive)
 
428
        #   high -> the last byte offset (inclusive)
 
429
        #   dir_names -> The list of (dir, name) pairs that should be found in
 
430
        #                the [low, high] range
 
431
        pending = [(low, high, dir_name_list)]
 
432
 
 
433
        page_size = self._bisect_page_size
 
434
 
 
435
        fields_to_entry = self._get_fields_to_entry()
 
436
 
 
437
        while pending:
 
438
            low, high, cur_files = pending.pop()
 
439
 
 
440
            if not cur_files or low >= high:
 
441
                # Nothing to find
 
442
                continue
 
443
 
 
444
            count += 1
 
445
            if count > max_count:
 
446
                raise errors.BzrError('Too many seeks, most likely a bug.')
 
447
 
 
448
            mid = max(low, (low+high-page_size)/2)
 
449
 
 
450
            state_file.seek(mid)
 
451
            # limit the read size, so we don't end up reading data that we have
 
452
            # already read.
 
453
            read_size = min(page_size, (high-mid)+1)
 
454
            block = state_file.read(read_size)
 
455
 
 
456
            start = mid
 
457
            entries = block.split('\n')
 
458
 
 
459
            if len(entries) < 2:
 
460
                # We didn't find a '\n', so we cannot have found any records.
 
461
                # So put this range back and try again. But we know we have to
 
462
                # increase the page size, because a single read did not contain
 
463
                # a record break (so records must be larger than page_size)
 
464
                page_size *= 2
 
465
                pending.append((low, high, cur_files))
 
466
                continue
 
467
 
 
468
            # Check the first and last entries, in case they are partial, or if
 
469
            # we don't care about the rest of this page
 
470
            first_entry_num = 0
 
471
            first_fields = entries[0].split('\0')
 
472
            if len(first_fields) < entry_field_count:
 
473
                # We didn't get the complete first entry
 
474
                # so move start, and grab the next, which
 
475
                # should be a full entry
 
476
                start += len(entries[0])+1
 
477
                first_fields = entries[1].split('\0')
 
478
                first_entry_num = 1
 
479
 
 
480
            if len(first_fields) <= 2:
 
481
                # We didn't even get a filename here... what do we do?
 
482
                # Try a large page size and repeat this query
 
483
                page_size *= 2
 
484
                pending.append((low, high, cur_files))
 
485
                continue
 
486
            else:
 
487
                # Find what entries we are looking for, which occur before and
 
488
                # after this first record.
 
489
                after = start
 
490
                first_dir_name = (first_fields[1], first_fields[2])
 
491
                first_loc = bisect.bisect_left(cur_files, first_dir_name)
 
492
 
 
493
                # These exist before the current location
 
494
                pre = cur_files[:first_loc]
 
495
                # These occur after the current location, which may be in the
 
496
                # data we read, or might be after the last entry
 
497
                post = cur_files[first_loc:]
 
498
 
 
499
            if post and len(first_fields) >= entry_field_count:
 
500
                # We have files after the first entry
 
501
 
 
502
                # Parse the last entry
 
503
                last_entry_num = len(entries)-1
 
504
                last_fields = entries[last_entry_num].split('\0')
 
505
                if len(last_fields) < entry_field_count:
 
506
                    # The very last hunk was not complete,
 
507
                    # read the previous hunk
 
508
                    after = mid + len(block) - len(entries[-1])
 
509
                    last_entry_num -= 1
 
510
                    last_fields = entries[last_entry_num].split('\0')
 
511
                else:
 
512
                    after = mid + len(block)
 
513
 
 
514
                last_dir_name = (last_fields[1], last_fields[2])
 
515
                last_loc = bisect.bisect_right(post, last_dir_name)
 
516
 
 
517
                middle_files = post[:last_loc]
 
518
                post = post[last_loc:]
 
519
 
 
520
                if middle_files:
 
521
                    # We have files that should occur in this block
 
522
                    # (>= first, <= last)
 
523
                    # Either we will find them here, or we can mark them as
 
524
                    # missing.
 
525
 
 
526
                    if middle_files[0] == first_dir_name:
 
527
                        # We might need to go before this location
 
528
                        pre.append(first_dir_name)
 
529
                    if middle_files[-1] == last_dir_name:
 
530
                        post.insert(0, last_dir_name)
 
531
 
 
532
                    # Find out what paths we have
 
533
                    paths = {first_dir_name:[first_fields]}
 
534
                    # last_dir_name might == first_dir_name so we need to be
 
535
                    # careful if we should append rather than overwrite
 
536
                    if last_entry_num != first_entry_num:
 
537
                        paths.setdefault(last_dir_name, []).append(last_fields)
 
538
                    for num in xrange(first_entry_num+1, last_entry_num):
 
539
                        # TODO: jam 20070223 We are already splitting here, so
 
540
                        #       shouldn't we just split the whole thing rather
 
541
                        #       than doing the split again in add_one_record?
 
542
                        fields = entries[num].split('\0')
 
543
                        dir_name = (fields[1], fields[2])
 
544
                        paths.setdefault(dir_name, []).append(fields)
 
545
 
 
546
                    for dir_name in middle_files:
 
547
                        for fields in paths.get(dir_name, []):
 
548
                            # offset by 1 because of the opening '\0'
 
549
                            # consider changing fields_to_entry to avoid the
 
550
                            # extra list slice
 
551
                            entry = fields_to_entry(fields[1:])
 
552
                            found.setdefault(dir_name, []).append(entry)
 
553
 
 
554
            # Now we have split up everything into pre, middle, and post, and
 
555
            # we have handled everything that fell in 'middle'.
 
556
            # We add 'post' first, so that we prefer to seek towards the
 
557
            # beginning, so that we will tend to go as early as we need, and
 
558
            # then only seek forward after that.
 
559
            if post:
 
560
                pending.append((after, high, post))
 
561
            if pre:
 
562
                pending.append((low, start-1, pre))
 
563
 
 
564
        # Consider that we may want to return the directory entries in sorted
 
565
        # order. For now, we just return them in whatever order we found them,
 
566
        # and leave it up to the caller if they care if it is ordered or not.
 
567
        return found
 
568
 
 
569
    def _bisect_dirblocks(self, dir_list):
 
570
        """Bisect through the disk structure to find entries in given dirs.
 
571
 
 
572
        _bisect_dirblocks is meant to find the contents of directories, which
 
573
        differs from _bisect, which only finds individual entries.
 
574
 
 
575
        :param dir_list: An sorted list of directory names ['', 'dir', 'foo'].
 
576
        :return: A map from dir => entries_for_dir
 
577
        """
 
578
        # TODO: jam 20070223 A lot of the bisecting logic could be shared
 
579
        #       between this and _bisect. It would require parameterizing the
 
580
        #       inner loop with a function, though. We should evaluate the
 
581
        #       performance difference.
 
582
        self._requires_lock()
 
583
        # We need the file pointer to be right after the initial header block
 
584
        self._read_header_if_needed()
 
585
        # If _dirblock_state was in memory, we should just return info from
 
586
        # there, this function is only meant to handle when we want to read
 
587
        # part of the disk.
 
588
        assert self._dirblock_state == DirState.NOT_IN_MEMORY
 
589
 
 
590
        # The disk representation is generally info + '\0\n\0' at the end. But
 
591
        # for bisecting, it is easier to treat this as '\0' + info + '\0\n'
 
592
        # Because it means we can sync on the '\n'
 
593
        state_file = self._state_file
 
594
        file_size = os.fstat(state_file.fileno()).st_size
 
595
        # We end up with 2 extra fields, we should have a trailing '\n' to
 
596
        # ensure that we read the whole record, and we should have a precursur
 
597
        # '' which ensures that we start after the previous '\n'
 
598
        entry_field_count = self._fields_per_entry() + 1
 
599
 
 
600
        low = self._end_of_header
 
601
        high = file_size - 1 # Ignore the final '\0'
 
602
        # Map from dir => entry
 
603
        found = {}
 
604
 
 
605
        # Avoid infinite seeking
 
606
        max_count = 30*len(dir_list)
 
607
        count = 0
 
608
        # pending is a list of places to look.
 
609
        # each entry is a tuple of low, high, dir_names
 
610
        #   low -> the first byte offset to read (inclusive)
 
611
        #   high -> the last byte offset (inclusive)
 
612
        #   dirs -> The list of directories that should be found in
 
613
        #                the [low, high] range
 
614
        pending = [(low, high, dir_list)]
 
615
 
 
616
        page_size = self._bisect_page_size
 
617
 
 
618
        fields_to_entry = self._get_fields_to_entry()
 
619
 
 
620
        while pending:
 
621
            low, high, cur_dirs = pending.pop()
 
622
 
 
623
            if not cur_dirs or low >= high:
 
624
                # Nothing to find
 
625
                continue
 
626
 
 
627
            count += 1
 
628
            if count > max_count:
 
629
                raise errors.BzrError('Too many seeks, most likely a bug.')
 
630
 
 
631
            mid = max(low, (low+high-page_size)/2)
 
632
 
 
633
            state_file.seek(mid)
 
634
            # limit the read size, so we don't end up reading data that we have
 
635
            # already read.
 
636
            read_size = min(page_size, (high-mid)+1)
 
637
            block = state_file.read(read_size)
 
638
 
 
639
            start = mid
 
640
            entries = block.split('\n')
 
641
 
 
642
            if len(entries) < 2:
 
643
                # We didn't find a '\n', so we cannot have found any records.
 
644
                # So put this range back and try again. But we know we have to
 
645
                # increase the page size, because a single read did not contain
 
646
                # a record break (so records must be larger than page_size)
 
647
                page_size *= 2
 
648
                pending.append((low, high, cur_dirs))
 
649
                continue
 
650
 
 
651
            # Check the first and last entries, in case they are partial, or if
 
652
            # we don't care about the rest of this page
 
653
            first_entry_num = 0
 
654
            first_fields = entries[0].split('\0')
 
655
            if len(first_fields) < entry_field_count:
 
656
                # We didn't get the complete first entry
 
657
                # so move start, and grab the next, which
 
658
                # should be a full entry
 
659
                start += len(entries[0])+1
 
660
                first_fields = entries[1].split('\0')
 
661
                first_entry_num = 1
 
662
 
 
663
            if len(first_fields) <= 1:
 
664
                # We didn't even get a dirname here... what do we do?
 
665
                # Try a large page size and repeat this query
 
666
                page_size *= 2
 
667
                pending.append((low, high, cur_dirs))
 
668
                continue
 
669
            else:
 
670
                # Find what entries we are looking for, which occur before and
 
671
                # after this first record.
 
672
                after = start
 
673
                first_dir = first_fields[1]
 
674
                first_loc = bisect.bisect_left(cur_dirs, first_dir)
 
675
 
 
676
                # These exist before the current location
 
677
                pre = cur_dirs[:first_loc]
 
678
                # These occur after the current location, which may be in the
 
679
                # data we read, or might be after the last entry
 
680
                post = cur_dirs[first_loc:]
 
681
 
 
682
            if post and len(first_fields) >= entry_field_count:
 
683
                # We have records to look at after the first entry
 
684
 
 
685
                # Parse the last entry
 
686
                last_entry_num = len(entries)-1
 
687
                last_fields = entries[last_entry_num].split('\0')
 
688
                if len(last_fields) < entry_field_count:
 
689
                    # The very last hunk was not complete,
 
690
                    # read the previous hunk
 
691
                    after = mid + len(block) - len(entries[-1])
 
692
                    last_entry_num -= 1
 
693
                    last_fields = entries[last_entry_num].split('\0')
 
694
                else:
 
695
                    after = mid + len(block)
 
696
 
 
697
                last_dir = last_fields[1]
 
698
                last_loc = bisect.bisect_right(post, last_dir)
 
699
 
 
700
                middle_files = post[:last_loc]
 
701
                post = post[last_loc:]
 
702
 
 
703
                if middle_files:
 
704
                    # We have files that should occur in this block
 
705
                    # (>= first, <= last)
 
706
                    # Either we will find them here, or we can mark them as
 
707
                    # missing.
 
708
 
 
709
                    if middle_files[0] == first_dir:
 
710
                        # We might need to go before this location
 
711
                        pre.append(first_dir)
 
712
                    if middle_files[-1] == last_dir:
 
713
                        post.insert(0, last_dir)
 
714
 
 
715
                    # Find out what paths we have
 
716
                    paths = {first_dir:[first_fields]}
 
717
                    # last_dir might == first_dir so we need to be
 
718
                    # careful if we should append rather than overwrite
 
719
                    if last_entry_num != first_entry_num:
 
720
                        paths.setdefault(last_dir, []).append(last_fields)
 
721
                    for num in xrange(first_entry_num+1, last_entry_num):
 
722
                        # TODO: jam 20070223 We are already splitting here, so
 
723
                        #       shouldn't we just split the whole thing rather
 
724
                        #       than doing the split again in add_one_record?
 
725
                        fields = entries[num].split('\0')
 
726
                        paths.setdefault(fields[1], []).append(fields)
 
727
 
 
728
                    for cur_dir in middle_files:
 
729
                        for fields in paths.get(cur_dir, []):
 
730
                            # offset by 1 because of the opening '\0'
 
731
                            # consider changing fields_to_entry to avoid the
 
732
                            # extra list slice
 
733
                            entry = fields_to_entry(fields[1:])
 
734
                            found.setdefault(cur_dir, []).append(entry)
 
735
 
 
736
            # Now we have split up everything into pre, middle, and post, and
 
737
            # we have handled everything that fell in 'middle'.
 
738
            # We add 'post' first, so that we prefer to seek towards the
 
739
            # beginning, so that we will tend to go as early as we need, and
 
740
            # then only seek forward after that.
 
741
            if post:
 
742
                pending.append((after, high, post))
 
743
            if pre:
 
744
                pending.append((low, start-1, pre))
 
745
 
 
746
        return found
 
747
 
 
748
    def _bisect_recursive(self, dir_name_list):
 
749
        """Bisect for entries for all paths and their children.
 
750
 
 
751
        This will use bisect to find all records for the supplied paths. It
 
752
        will then continue to bisect for any records which are marked as
 
753
        directories. (and renames?)
 
754
 
 
755
        :param paths: A sorted list of (dir, name) pairs
 
756
             eg: [('', 'a'), ('', 'f'), ('a/b', 'c')]
 
757
        :return: A dictionary mapping (dir, name, file_id) => [tree_info]
 
758
        """
 
759
        # Map from (dir, name, file_id) => [tree_info]
 
760
        found = {}
 
761
 
 
762
        found_dir_names = set()
 
763
 
 
764
        # Directories that have been read
 
765
        processed_dirs = set()
 
766
        # Get the ball rolling with the first bisect for all entries.
 
767
        newly_found = self._bisect(dir_name_list)
 
768
 
 
769
        while newly_found:
 
770
            # Directories that need to be read
 
771
            pending_dirs = set()
 
772
            paths_to_search = set()
 
773
            for entry_list in newly_found.itervalues():
 
774
                for dir_name_id, trees_info in entry_list:
 
775
                    found[dir_name_id] = trees_info
 
776
                    found_dir_names.add(dir_name_id[:2])
 
777
                    is_dir = False
 
778
                    for tree_info in trees_info:
 
779
                        minikind = tree_info[0]
 
780
                        if minikind == 'd':
 
781
                            if is_dir:
 
782
                                # We already processed this one as a directory,
 
783
                                # we don't need to do the extra work again.
 
784
                                continue
 
785
                            subdir, name, file_id = dir_name_id
 
786
                            path = osutils.pathjoin(subdir, name)
 
787
                            is_dir = True
 
788
                            if path not in processed_dirs:
 
789
                                pending_dirs.add(path)
 
790
                        elif minikind == 'r':
 
791
                            # Rename, we need to directly search the target
 
792
                            # which is contained in the fingerprint column
 
793
                            dir_name = osutils.split(tree_info[1])
 
794
                            if dir_name[0] in pending_dirs:
 
795
                                # This entry will be found in the dir search
 
796
                                continue
 
797
                            # TODO: We need to check if this entry has
 
798
                            #       already been found. Otherwise we might be
 
799
                            #       hitting infinite recursion.
 
800
                            if dir_name not in found_dir_names:
 
801
                                paths_to_search.add(dir_name)
 
802
            # Now we have a list of paths to look for directly, and
 
803
            # directory blocks that need to be read.
 
804
            # newly_found is mixing the keys between (dir, name) and path
 
805
            # entries, but that is okay, because we only really care about the
 
806
            # targets.
 
807
            newly_found = self._bisect(sorted(paths_to_search))
 
808
            newly_found.update(self._bisect_dirblocks(sorted(pending_dirs)))
 
809
            processed_dirs.update(pending_dirs)
 
810
        return found
 
811
 
 
812
    def _empty_parent_info(self):
 
813
        return [DirState.NULL_PARENT_DETAILS] * (len(self._parents) -
 
814
                                                    len(self._ghosts))
 
815
 
 
816
    def _ensure_block(self, parent_block_index, parent_row_index, dirname):
 
817
        """Ensure a block for dirname exists.
 
818
 
 
819
        This function exists to let callers which know that there is a
 
820
        directory dirname ensure that the block for it exists. This block can
 
821
        fail to exist because of demand loading, or because a directory had no
 
822
        children. In either case it is not an error. It is however an error to
 
823
        call this if there is no parent entry for the directory, and thus the
 
824
        function requires the coordinates of such an entry to be provided.
 
825
 
 
826
        The root row is special cased and can be indicated with a parent block
 
827
        and row index of -1
 
828
 
 
829
        :param parent_block_index: The index of the block in which dirname's row
 
830
            exists.
 
831
        :param parent_row_index: The index in the parent block where the row
 
832
            exists.
 
833
        :param dirname: The utf8 dirname to ensure there is a block for.
 
834
        :return: The index for the block.
 
835
        """
 
836
        if dirname == '' and parent_row_index == 0 and parent_block_index == 0:
 
837
            # This is the signature of the root row, and the
 
838
            # contents-of-root row is always index 1
 
839
            return 1
 
840
        # the basename of the directory must be the end of its full name.
 
841
        if not (parent_block_index == -1 and
 
842
            parent_block_index == -1 and dirname == ''):
 
843
            assert dirname.endswith(
 
844
                self._dirblocks[parent_block_index][1][parent_row_index][0][1])
 
845
        block_index, present = self._find_block_index_from_key((dirname, '', ''))
 
846
        if not present:
 
847
            ## In future, when doing partial parsing, this should load and 
 
848
            # populate the entire block.
 
849
            self._dirblocks.insert(block_index, (dirname, []))
 
850
        return block_index
 
851
 
 
852
    def _entries_to_current_state(self, new_entries):
 
853
        """Load new_entries into self.dirblocks.
 
854
 
 
855
        Process new_entries into the current state object, making them the active
 
856
        state.
 
857
 
 
858
        :param new_entries: A sorted list of entries. This function does not sort
 
859
            to prevent unneeded overhead when callers have a sorted list already.
 
860
        :return: Nothing.
 
861
        """
 
862
        assert new_entries[0][0][0:2] == ('', ''), \
 
863
            "Missing root row %r" % (new_entries[0][0],)
 
864
        # The two blocks here are deliberate: the root block and the 
 
865
        # contents-of-root block.
 
866
        self._dirblocks = [('', []), ('', [])]
 
867
        current_block = self._dirblocks[0][1]
 
868
        current_dirname = ''
 
869
        root_key = ('', '')
 
870
        append_entry = current_block.append
 
871
        for entry in new_entries:
 
872
            if entry[0][0] != current_dirname:
 
873
                # new block - different dirname
 
874
                current_block = []
 
875
                current_dirname = entry[0][0]
 
876
                self._dirblocks.append((current_dirname, current_block))
 
877
                append_entry = current_block.append
 
878
            # append the entry to the current block
 
879
            append_entry(entry)
 
880
        self._split_root_dirblock_into_contents()
 
881
 
 
882
    def _split_root_dirblock_into_contents(self):
 
883
        """Split the root dirblocks into root and contents-of-root.
 
884
 
 
885
        After parsing by path, we end up with root entries and contents-of-root
 
886
        entries in the same block. This loop splits them out again.
 
887
        """
 
888
        # The above loop leaves the "root block" entries mixed with the
 
889
        # "contents-of-root block". But we don't want an if check on
 
890
        # all entries, so instead we just fix it up here.
 
891
        assert self._dirblocks[1] == ('', [])
 
892
        root_block = []
 
893
        contents_of_root_block = []
 
894
        for entry in self._dirblocks[0][1]:
 
895
            if not entry[0][1]: # This is a root entry
 
896
                root_block.append(entry)
 
897
            else:
 
898
                contents_of_root_block.append(entry)
 
899
        self._dirblocks[0] = ('', root_block)
 
900
        self._dirblocks[1] = ('', contents_of_root_block)
 
901
 
 
902
    def _entry_to_line(self, entry):
 
903
        """Serialize entry to a NULL delimited line ready for _get_output_lines.
 
904
 
 
905
        :param entry: An entry_tuple as defined in the module docstring.
 
906
        """
 
907
        entire_entry = list(entry[0])
 
908
        for tree_number, tree_data in enumerate(entry[1]):
 
909
            # (minikind, fingerprint, size, executable, tree_specific_string)
 
910
            entire_entry.extend(tree_data)
 
911
            # 3 for the key, 5 for the fields per tree.
 
912
            tree_offset = 3 + tree_number * 5
 
913
            # minikind
 
914
            entire_entry[tree_offset + 0] = tree_data[0]
 
915
            # size
 
916
            entire_entry[tree_offset + 2] = str(tree_data[2])
 
917
            # executable
 
918
            entire_entry[tree_offset + 3] = DirState._to_yesno[tree_data[3]]
 
919
        return '\0'.join(entire_entry)
 
920
 
 
921
    def _fields_per_entry(self):
 
922
        """How many null separated fields should be in each entry row.
 
923
 
 
924
        Each line now has an extra '\n' field which is not used
 
925
        so we just skip over it
 
926
        entry size:
 
927
            3 fields for the key
 
928
            + number of fields per tree_data (5) * tree count
 
929
            + newline
 
930
         """
 
931
        tree_count = 1 + self._num_present_parents()
 
932
        return 3 + 5 * tree_count + 1
 
933
 
 
934
    def _find_block(self, key, add_if_missing=False):
 
935
        """Return the block that key should be present in.
 
936
 
 
937
        :param key: A dirstate entry key.
 
938
        :return: The block tuple.
 
939
        """
 
940
        block_index, present = self._find_block_index_from_key(key)
 
941
        if not present:
 
942
            if not add_if_missing:
 
943
                # check to see if key is versioned itself - we might want to
 
944
                # add it anyway, because dirs with no entries dont get a
 
945
                # dirblock at parse time.
 
946
                # This is an uncommon branch to take: most dirs have children,
 
947
                # and most code works with versioned paths.
 
948
                parent_base, parent_name = osutils.split(key[0])
 
949
                if not self._get_block_entry_index(parent_base, parent_name, 0)[3]:
 
950
                    # some parent path has not been added - its an error to add
 
951
                    # this child
 
952
                    raise errors.NotVersionedError(key[0:2], str(self))
 
953
            self._dirblocks.insert(block_index, (key[0], []))
 
954
        return self._dirblocks[block_index]
 
955
 
 
956
    def _find_block_index_from_key(self, key):
 
957
        """Find the dirblock index for a key.
 
958
 
 
959
        :return: The block index, True if the block for the key is present.
 
960
        """
 
961
        if key[0:2] == ('', ''):
 
962
            return 0, True
 
963
        block_index = bisect_dirblock(self._dirblocks, key[0], 1,
 
964
                                      cache=self._split_path_cache)
 
965
        # _right returns one-past-where-key is so we have to subtract
 
966
        # one to use it. we use _right here because there are two
 
967
        # '' blocks - the root, and the contents of root
 
968
        # we always have a minimum of 2 in self._dirblocks: root and
 
969
        # root-contents, and for '', we get 2 back, so this is 
 
970
        # simple and correct:
 
971
        present = (block_index < len(self._dirblocks) and
 
972
            self._dirblocks[block_index][0] == key[0])
 
973
        return block_index, present
 
974
 
 
975
    def _find_entry_index(self, key, block):
 
976
        """Find the entry index for a key in a block.
 
977
 
 
978
        :return: The entry index, True if the entry for the key is present.
 
979
        """
 
980
        entry_index = bisect.bisect_left(block, (key, []))
 
981
        present = (entry_index < len(block) and
 
982
            block[entry_index][0] == key)
 
983
        return entry_index, present
 
984
 
 
985
    @staticmethod
 
986
    def from_tree(tree, dir_state_filename):
 
987
        """Create a dirstate from a bzr Tree.
 
988
 
 
989
        :param tree: The tree which should provide parent information and
 
990
            inventory ids.
 
991
        :return: a DirState object which is currently locked for writing.
 
992
            (it was locked by DirState.initialize)
 
993
        """
 
994
        result = DirState.initialize(dir_state_filename)
 
995
        try:
 
996
            tree.lock_read()
 
997
            try:
 
998
                parent_ids = tree.get_parent_ids()
 
999
                num_parents = len(parent_ids)
 
1000
                parent_trees = []
 
1001
                for parent_id in parent_ids:
 
1002
                    parent_tree = tree.branch.repository.revision_tree(parent_id)
 
1003
                    parent_trees.append((parent_id, parent_tree))
 
1004
                    parent_tree.lock_read()
 
1005
                result.set_parent_trees(parent_trees, [])
 
1006
                result.set_state_from_inventory(tree.inventory)
 
1007
            finally:
 
1008
                for revid, parent_tree in parent_trees:
 
1009
                    parent_tree.unlock()
 
1010
                tree.unlock()
 
1011
        except:
 
1012
            # The caller won't have a chance to unlock this, so make sure we
 
1013
            # cleanup ourselves
 
1014
            result.unlock()
 
1015
            raise
 
1016
        return result
 
1017
 
 
1018
    def get_sha1_for_entry(self, entry, abspath, stat_value=None):
 
1019
        """Return the sha1 sum for a given file.
 
1020
 
 
1021
        :param entry: This is the dirblock entry for the file in question.
 
1022
        :param abspath: The path on disk for this file.
 
1023
        :param stat_value: (optional) if we already have done a stat on the
 
1024
            file, re-use it.
 
1025
        :return: The sha1 hexdigest of the file (40 bytes)
 
1026
        """
 
1027
        # This code assumes that the entry passed in is directly held in one of
 
1028
        # the internal _dirblocks. So the dirblock state must have already been
 
1029
        # read.
 
1030
        assert self._dirblock_state != DirState.NOT_IN_MEMORY
 
1031
        assert entry[1][0][0] == 'f', \
 
1032
            'can only get sha1 for a file not: %s %s' % (
 
1033
            DirState._minikind_to_kind[entry[1][0][0]], entry[0])
 
1034
        if stat_value is None:
 
1035
            stat_value = os.lstat(abspath)
 
1036
        packed_stat = pack_stat(stat_value)
 
1037
        saved_sha1_digest = entry[1][0][1]
 
1038
        saved_file_size = entry[1][0][2]
 
1039
        saved_packed_stat = entry[1][0][4]
 
1040
        if (packed_stat == saved_packed_stat
 
1041
            and saved_sha1_digest != ''
 
1042
            # size should also be in packed_stat
 
1043
            and saved_file_size == stat_value.st_size):
 
1044
            # The stat hasn't changed since we saved, so we can potentially
 
1045
            # re-use the saved sha hash.
 
1046
            cutoff = self._sha_cutoff_time()
 
1047
            if (stat_value.st_mtime < cutoff
 
1048
                and stat_value.st_ctime < cutoff):
 
1049
                # Return the existing fingerprint
 
1050
                return saved_sha1_digest
 
1051
        # If we have gotten this far, that means that we need to actually
 
1052
        # process the file.
 
1053
        new_sha1_digest = self._sha1_file(abspath)
 
1054
        # TODO: jam 20070301 Is it worth checking to see if the new sha is
 
1055
        #       actually different? I'm guessing not, because we wouldn't have
 
1056
        #       gotten this far otherwise.
 
1057
        entry[1][0] = ('f', new_sha1_digest, stat_value.st_size,
 
1058
                       entry[1][0][3], # Executable?
 
1059
                       packed_stat
 
1060
                      )
 
1061
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
1062
        return new_sha1_digest
 
1063
 
 
1064
    def _sha_cutoff_time(self):
 
1065
        """Return cutoff time.
 
1066
 
 
1067
        Files modified more recently than this time are at risk of being
 
1068
        undetectably modified and so can't be cached.
 
1069
        """
 
1070
        return int(time.time()) - 3
 
1071
 
 
1072
    def _sha1_file(self, abspath):
 
1073
        """Calculate the SHA1 of a file by reading the full text"""
 
1074
        f = file(abspath, 'rb', buffering=65000)
 
1075
        try:
 
1076
            return osutils.sha_file(f)
 
1077
        finally:
 
1078
            f.close()
 
1079
 
 
1080
    def get_ghosts(self):
 
1081
        """Return a list of the parent tree revision ids that are ghosts."""
 
1082
        self._read_header_if_needed()
 
1083
        return self._ghosts
 
1084
 
 
1085
    def get_lines(self):
 
1086
        """Serialise the entire dirstate to a sequence of lines."""
 
1087
        if (self._header_state == DirState.IN_MEMORY_UNMODIFIED and
 
1088
            self._dirblock_state == DirState.IN_MEMORY_UNMODIFIED):
 
1089
            # read whats on disk.
 
1090
            self._state_file.seek(0)
 
1091
            return self._state_file.readlines()
 
1092
        lines = []
 
1093
        lines.append(self._get_parents_line(self.get_parent_ids()))
 
1094
        lines.append(self._get_ghosts_line(self._ghosts))
 
1095
        # append the root line which is special cased
 
1096
        lines.extend(map(self._entry_to_line, self._iter_entries()))
 
1097
        return self._get_output_lines(lines)
 
1098
 
 
1099
    def _get_ghosts_line(self, ghost_ids):
 
1100
        """Create a line for the state file for ghost information."""
 
1101
        return '\0'.join([str(len(ghost_ids))] + ghost_ids)
 
1102
 
 
1103
    def _get_parents_line(self, parent_ids):
 
1104
        """Create a line for the state file for parents information."""
 
1105
        return '\0'.join([str(len(parent_ids))] + parent_ids)
 
1106
 
 
1107
    def _get_fields_to_entry(self):
 
1108
        """Get a function which converts entry fields into a entry record.
 
1109
 
 
1110
        This handles size and executable, as well as parent records.
 
1111
 
 
1112
        :return: A function which takes a list of fields, and returns an
 
1113
            appropriate record for storing in memory.
 
1114
        """
 
1115
        # This is intentionally unrolled for performance
 
1116
        num_present_parents = self._num_present_parents()
 
1117
        if num_present_parents == 0:
 
1118
            def fields_to_entry_0_parents(fields, _int=int):
 
1119
                path_name_file_id_key = (fields[0], fields[1], fields[2])
 
1120
                return (path_name_file_id_key, [
 
1121
                    ( # Current tree
 
1122
                        fields[3],                # minikind
 
1123
                        fields[4],                # fingerprint
 
1124
                        _int(fields[5]),          # size
 
1125
                        fields[6] == 'y',         # executable
 
1126
                        fields[7],                # packed_stat or revision_id
 
1127
                    )])
 
1128
            return fields_to_entry_0_parents
 
1129
        elif num_present_parents == 1:
 
1130
            def fields_to_entry_1_parent(fields, _int=int):
 
1131
                path_name_file_id_key = (fields[0], fields[1], fields[2])
 
1132
                return (path_name_file_id_key, [
 
1133
                    ( # Current tree
 
1134
                        fields[3],                # minikind
 
1135
                        fields[4],                # fingerprint
 
1136
                        _int(fields[5]),          # size
 
1137
                        fields[6] == 'y',         # executable
 
1138
                        fields[7],                # packed_stat or revision_id
 
1139
                    ),
 
1140
                    ( # Parent 1
 
1141
                        fields[8],                # minikind
 
1142
                        fields[9],                # fingerprint
 
1143
                        _int(fields[10]),         # size
 
1144
                        fields[11] == 'y',        # executable
 
1145
                        fields[12],               # packed_stat or revision_id
 
1146
                    ),
 
1147
                    ])
 
1148
            return fields_to_entry_1_parent
 
1149
        elif num_present_parents == 2:
 
1150
            def fields_to_entry_2_parents(fields, _int=int):
 
1151
                path_name_file_id_key = (fields[0], fields[1], fields[2])
 
1152
                return (path_name_file_id_key, [
 
1153
                    ( # Current tree
 
1154
                        fields[3],                # minikind
 
1155
                        fields[4],                # fingerprint
 
1156
                        _int(fields[5]),          # size
 
1157
                        fields[6] == 'y',         # executable
 
1158
                        fields[7],                # packed_stat or revision_id
 
1159
                    ),
 
1160
                    ( # Parent 1
 
1161
                        fields[8],                # minikind
 
1162
                        fields[9],                # fingerprint
 
1163
                        _int(fields[10]),         # size
 
1164
                        fields[11] == 'y',        # executable
 
1165
                        fields[12],               # packed_stat or revision_id
 
1166
                    ),
 
1167
                    ( # Parent 2
 
1168
                        fields[13],               # minikind
 
1169
                        fields[14],               # fingerprint
 
1170
                        _int(fields[15]),         # size
 
1171
                        fields[16] == 'y',        # executable
 
1172
                        fields[17],               # packed_stat or revision_id
 
1173
                    ),
 
1174
                    ])
 
1175
            return fields_to_entry_2_parents
 
1176
        else:
 
1177
            def fields_to_entry_n_parents(fields, _int=int):
 
1178
                path_name_file_id_key = (fields[0], fields[1], fields[2])
 
1179
                trees = [(fields[cur],                # minikind
 
1180
                          fields[cur+1],              # fingerprint
 
1181
                          _int(fields[cur+2]),        # size
 
1182
                          fields[cur+3] == 'y',       # executable
 
1183
                          fields[cur+4],              # stat or revision_id
 
1184
                         ) for cur in xrange(3, len(fields)-1, 5)]
 
1185
                return path_name_file_id_key, trees
 
1186
            return fields_to_entry_n_parents
 
1187
 
 
1188
    def get_parent_ids(self):
 
1189
        """Return a list of the parent tree ids for the directory state."""
 
1190
        self._read_header_if_needed()
 
1191
        return list(self._parents)
 
1192
 
 
1193
    def _get_block_entry_index(self, dirname, basename, tree_index):
 
1194
        """Get the coordinates for a path in the state structure.
 
1195
 
 
1196
        :param dirname: The utf8 dirname to lookup.
 
1197
        :param basename: The utf8 basename to lookup.
 
1198
        :param tree_index: The index of the tree for which this lookup should
 
1199
            be attempted.
 
1200
        :return: A tuple describing where the path is located, or should be
 
1201
            inserted. The tuple contains four fields: the block index, the row
 
1202
            index, anda two booleans are True when the directory is present, and
 
1203
            when the entire path is present.  There is no guarantee that either
 
1204
            coordinate is currently reachable unless the found field for it is
 
1205
            True. For instance, a directory not present in the searched tree
 
1206
            may be returned with a value one greater than the current highest
 
1207
            block offset. The directory present field will always be True when
 
1208
            the path present field is True. The directory present field does
 
1209
            NOT indicate that the directory is present in the searched tree,
 
1210
            rather it indicates that there are at least some files in some
 
1211
            tree present there.
 
1212
        """
 
1213
        self._read_dirblocks_if_needed()
 
1214
        key = dirname, basename, ''
 
1215
        block_index, present = self._find_block_index_from_key(key)
 
1216
        if not present:
 
1217
            # no such directory - return the dir index and 0 for the row.
 
1218
            return block_index, 0, False, False
 
1219
        block = self._dirblocks[block_index][1] # access the entries only
 
1220
        entry_index, present = self._find_entry_index(key, block)
 
1221
        # linear search through present entries at this path to find the one
 
1222
        # requested.
 
1223
        while entry_index < len(block) and block[entry_index][0][1] == basename:
 
1224
            if block[entry_index][1][tree_index][0] not in \
 
1225
                       ('a', 'r'): # absent, relocated
 
1226
                return block_index, entry_index, True, True
 
1227
            entry_index += 1
 
1228
        return block_index, entry_index, True, False
 
1229
 
 
1230
    def _get_entry(self, tree_index, fileid_utf8=None, path_utf8=None):
 
1231
        """Get the dirstate entry for path in tree tree_index
 
1232
 
 
1233
        If either file_id or path is supplied, it is used as the key to lookup.
 
1234
        If both are supplied, the fastest lookup is used, and an error is
 
1235
        raised if they do not both point at the same row.
 
1236
 
 
1237
        :param tree_index: The index of the tree we wish to locate this path
 
1238
            in. If the path is present in that tree, the entry containing its
 
1239
            details is returned, otherwise (None, None) is returned
 
1240
        :param fileid_utf8: A utf8 file_id to look up.
 
1241
        :param path_utf8: An utf8 path to be looked up.
 
1242
        :return: The dirstate entry tuple for path, or (None, None)
 
1243
        """
 
1244
        self._read_dirblocks_if_needed()
 
1245
        if path_utf8 is not None:
 
1246
            assert path_utf8.__class__ == str, 'path_utf8 is not a str: %s %s' % (type(path_utf8), path_utf8)
 
1247
            # path lookups are faster
 
1248
            dirname, basename = osutils.split(path_utf8)
 
1249
            block_index, entry_index, dir_present, file_present = \
 
1250
                self._get_block_entry_index(dirname, basename, tree_index)
 
1251
            if not file_present:
 
1252
                return None, None
 
1253
            entry = self._dirblocks[block_index][1][entry_index]
 
1254
            assert entry[0][2] and entry[1][tree_index][0] not in ('a', 'r'), 'unversioned entry?!?!'
 
1255
            if fileid_utf8:
 
1256
                if entry[0][2] != fileid_utf8:
 
1257
                    raise errors.BzrError('integrity error ? : mismatching'
 
1258
                                          ' tree_index, file_id and path')
 
1259
            return entry
 
1260
        else:
 
1261
            assert fileid_utf8 is not None
 
1262
            possible_keys = self._get_id_index().get(fileid_utf8, None)
 
1263
            if not possible_keys:
 
1264
                return None, None
 
1265
            for key in possible_keys:
 
1266
                block_index, present = \
 
1267
                    self._find_block_index_from_key(key)
 
1268
                # strange, probably indicates an out of date
 
1269
                # id index - for now, allow this.
 
1270
                if not present:
 
1271
                    continue
 
1272
                # WARNING: DO not change this code to use _get_block_entry_index
 
1273
                # as that function is not suitable: it does not use the key
 
1274
                # to lookup, and thus the wront coordinates are returned.
 
1275
                block = self._dirblocks[block_index][1]
 
1276
                entry_index, present = self._find_entry_index(key, block)
 
1277
                if present:
 
1278
                    entry = self._dirblocks[block_index][1][entry_index]
 
1279
                    if entry[1][tree_index][0] in 'fdl':
 
1280
                        # this is the result we are looking for: the  
 
1281
                        # real home of this file_id in this tree.
 
1282
                        return entry
 
1283
                    if entry[1][tree_index][0] == 'a':
 
1284
                        # there is no home for this entry in this tree
 
1285
                        return None, None
 
1286
                    assert entry[1][tree_index][0] == 'r'
 
1287
                    real_path = entry[1][tree_index][1]
 
1288
                    return self._get_entry(tree_index, fileid_utf8=fileid_utf8,
 
1289
                        path_utf8=real_path)
 
1290
            return None, None
 
1291
 
 
1292
    @classmethod
 
1293
    def initialize(cls, path):
 
1294
        """Create a new dirstate on path.
 
1295
 
 
1296
        The new dirstate will be an empty tree - that is it has no parents,
 
1297
        and only a root node - which has id ROOT_ID.
 
1298
 
 
1299
        The object will be write locked when returned to the caller,
 
1300
        unless there was an exception in the writing, in which case it
 
1301
        will be unlocked.
 
1302
 
 
1303
        :param path: The name of the file for the dirstate.
 
1304
        :return: A DirState object.
 
1305
        """
 
1306
        # This constructs a new DirState object on a path, sets the _state_file
 
1307
        # to a new empty file for that path. It then calls _set_data() with our
 
1308
        # stock empty dirstate information - a root with ROOT_ID, no children,
 
1309
        # and no parents. Finally it calls save() to ensure that this data will
 
1310
        # persist.
 
1311
        result = cls(path)
 
1312
        # root dir and root dir contents with no children.
 
1313
        empty_tree_dirblocks = [('', []), ('', [])]
 
1314
        # a new root directory, with a NULLSTAT.
 
1315
        empty_tree_dirblocks[0][1].append(
 
1316
            (('', '', inventory.ROOT_ID), [
 
1317
                ('d', '', 0, False, DirState.NULLSTAT),
 
1318
            ]))
 
1319
        result.lock_write()
 
1320
        try:
 
1321
            result._set_data([], empty_tree_dirblocks)
 
1322
            result.save()
 
1323
        except:
 
1324
            result.unlock()
 
1325
            raise
 
1326
        return result
 
1327
 
 
1328
    def _inv_entry_to_details(self, inv_entry):
 
1329
        """Convert an inventory entry (from a revision tree) to state details.
 
1330
 
 
1331
        :param inv_entry: An inventory entry whose sha1 and link targets can be
 
1332
            relied upon, and which has a revision set.
 
1333
        :return: A details tuple - the details for a single tree at a path +
 
1334
            id.
 
1335
        """
 
1336
        kind = inv_entry.kind
 
1337
        minikind = DirState._kind_to_minikind[kind]
 
1338
        tree_data = inv_entry.revision
 
1339
        assert len(tree_data) > 0, 'empty revision for the inv_entry.'
 
1340
        if kind == 'directory':
 
1341
            fingerprint = ''
 
1342
            size = 0
 
1343
            executable = False
 
1344
        elif kind == 'symlink':
 
1345
            fingerprint = inv_entry.symlink_target or ''
 
1346
            size = 0
 
1347
            executable = False
 
1348
        elif kind == 'file':
 
1349
            fingerprint = inv_entry.text_sha1 or ''
 
1350
            size = inv_entry.text_size or 0
 
1351
            executable = inv_entry.executable
 
1352
        else:
 
1353
            raise Exception
 
1354
        return (minikind, fingerprint, size, executable, tree_data)
 
1355
 
 
1356
    def _iter_entries(self):
 
1357
        """Iterate over all the entries in the dirstate.
 
1358
 
 
1359
        Each yelt item is an entry in the standard format described in the
 
1360
        docstring of bzrlib.dirstate.
 
1361
        """
 
1362
        self._read_dirblocks_if_needed()
 
1363
        for directory in self._dirblocks:
 
1364
            for entry in directory[1]:
 
1365
                yield entry
 
1366
 
 
1367
    def _get_id_index(self):
 
1368
        """Get an id index of self._dirblocks."""
 
1369
        if self._id_index is None:
 
1370
            id_index = {}
 
1371
            for key, tree_details in self._iter_entries():
 
1372
                id_index.setdefault(key[2], set()).add(key)
 
1373
            self._id_index = id_index
 
1374
        return self._id_index
 
1375
 
 
1376
    def _get_output_lines(self, lines):
 
1377
        """format lines for final output.
 
1378
 
 
1379
        :param lines: A sequece of lines containing the parents list and the
 
1380
            path lines.
 
1381
        """
 
1382
        output_lines = [DirState.HEADER_FORMAT_3]
 
1383
        lines.append('') # a final newline
 
1384
        inventory_text = '\0\n\0'.join(lines)
 
1385
        output_lines.append('adler32: %s\n' % (zlib.adler32(inventory_text),))
 
1386
        # -3, 1 for num parents, 1 for ghosts, 1 for final newline
 
1387
        num_entries = len(lines)-3
 
1388
        output_lines.append('num_entries: %s\n' % (num_entries,))
 
1389
        output_lines.append(inventory_text)
 
1390
        return output_lines
 
1391
 
 
1392
    def _make_deleted_row(self, fileid_utf8, parents):
 
1393
        """Return a deleted for for fileid_utf8."""
 
1394
        return ('/', 'RECYCLED.BIN', 'file', fileid_utf8, 0, DirState.NULLSTAT,
 
1395
            ''), parents
 
1396
 
 
1397
    def _num_present_parents(self):
 
1398
        """The number of parent entries in each record row."""
 
1399
        return len(self._parents) - len(self._ghosts)
 
1400
 
 
1401
    @staticmethod
 
1402
    def on_file(path):
 
1403
        """Construct a DirState on the file at path path.
 
1404
 
 
1405
        :return: An unlocked DirState object, associated with the given path.
 
1406
        """
 
1407
        result = DirState(path)
 
1408
        return result
 
1409
 
 
1410
    def _read_dirblocks_if_needed(self):
 
1411
        """Read in all the dirblocks from the file if they are not in memory.
 
1412
        
 
1413
        This populates self._dirblocks, and sets self._dirblock_state to
 
1414
        IN_MEMORY_UNMODIFIED. It is not currently ready for incremental block
 
1415
        loading.
 
1416
        """
 
1417
        self._read_header_if_needed()
 
1418
        if self._dirblock_state == DirState.NOT_IN_MEMORY:
 
1419
            # move the _state_file pointer to after the header (in case bisect
 
1420
            # has been called in the mean time)
 
1421
            self._state_file.seek(self._end_of_header)
 
1422
            text = self._state_file.read()
 
1423
            # TODO: check the adler checksums. adler_measured = zlib.adler32(text)
 
1424
 
 
1425
            fields = text.split('\0')
 
1426
            # Remove the last blank entry
 
1427
            trailing = fields.pop()
 
1428
            assert trailing == ''
 
1429
            # consider turning fields into a tuple.
 
1430
 
 
1431
            # skip the first field which is the trailing null from the header.
 
1432
            cur = 1
 
1433
            # Each line now has an extra '\n' field which is not used
 
1434
            # so we just skip over it
 
1435
            # entry size:
 
1436
            #  3 fields for the key
 
1437
            #  + number of fields per tree_data (5) * tree count
 
1438
            #  + newline
 
1439
            num_present_parents = self._num_present_parents()
 
1440
            tree_count = 1 + num_present_parents
 
1441
            entry_size = self._fields_per_entry()
 
1442
            expected_field_count = entry_size * self._num_entries
 
1443
            if len(fields) - cur > expected_field_count:
 
1444
                fields = fields[:expected_field_count + cur]
 
1445
                trace.mutter('Unexpectedly long dirstate field count!')
 
1446
                print "XXX: incorrectly truncated dirstate file bug triggered."
 
1447
            field_count = len(fields)
 
1448
            # this checks our adjustment, and also catches file too short.
 
1449
            assert field_count - cur == expected_field_count, \
 
1450
                'field count incorrect %s != %s, entry_size=%s, '\
 
1451
                'num_entries=%s fields=%r' % (
 
1452
                    field_count - cur, expected_field_count, entry_size,
 
1453
                    self._num_entries, fields)
 
1454
 
 
1455
            if num_present_parents == 1:
 
1456
                # Bind external functions to local names
 
1457
                _int = int
 
1458
                # We access all fields in order, so we can just iterate over
 
1459
                # them. Grab an straight iterator over the fields. (We use an
 
1460
                # iterator because we don't want to do a lot of additions, nor
 
1461
                # do we want to do a lot of slicing)
 
1462
                next = iter(fields).next
 
1463
                # Move the iterator to the current position
 
1464
                for x in xrange(cur):
 
1465
                    next()
 
1466
                # The two blocks here are deliberate: the root block and the
 
1467
                # contents-of-root block.
 
1468
                self._dirblocks = [('', []), ('', [])]
 
1469
                current_block = self._dirblocks[0][1]
 
1470
                current_dirname = ''
 
1471
                append_entry = current_block.append
 
1472
                for count in xrange(self._num_entries):
 
1473
                    dirname = next()
 
1474
                    name = next()
 
1475
                    file_id = next()
 
1476
                    if dirname != current_dirname:
 
1477
                        # new block - different dirname
 
1478
                        current_block = []
 
1479
                        current_dirname = dirname
 
1480
                        self._dirblocks.append((current_dirname, current_block))
 
1481
                        append_entry = current_block.append
 
1482
                    # we know current_dirname == dirname, so re-use it to avoid
 
1483
                    # creating new strings
 
1484
                    entry = ((current_dirname, name, file_id),
 
1485
                             [(# Current Tree
 
1486
                                 next(),                # minikind
 
1487
                                 next(),                # fingerprint
 
1488
                                 _int(next()),          # size
 
1489
                                 next() == 'y',         # executable
 
1490
                                 next(),                # packed_stat or revision_id
 
1491
                             ),
 
1492
                             ( # Parent 1
 
1493
                                 next(),                # minikind
 
1494
                                 next(),                # fingerprint
 
1495
                                 _int(next()),          # size
 
1496
                                 next() == 'y',         # executable
 
1497
                                 next(),                # packed_stat or revision_id
 
1498
                             ),
 
1499
                             ])
 
1500
                    trailing = next()
 
1501
                    assert trailing == '\n'
 
1502
                    # append the entry to the current block
 
1503
                    append_entry(entry)
 
1504
                self._split_root_dirblock_into_contents()
 
1505
            else:
 
1506
                fields_to_entry = self._get_fields_to_entry()
 
1507
                entries = [fields_to_entry(fields[pos:pos+entry_size])
 
1508
                           for pos in xrange(cur, field_count, entry_size)]
 
1509
                self._entries_to_current_state(entries)
 
1510
            # To convert from format 2  => format 3
 
1511
            # self._dirblocks = sorted(self._dirblocks,
 
1512
            #                          key=lambda blk:blk[0].split('/'))
 
1513
            # To convert from format 3 => format 2
 
1514
            # self._dirblocks = sorted(self._dirblocks)
 
1515
            self._dirblock_state = DirState.IN_MEMORY_UNMODIFIED
 
1516
 
 
1517
    def _read_header(self):
 
1518
        """This reads in the metadata header, and the parent ids.
 
1519
 
 
1520
        After reading in, the file should be positioned at the null
 
1521
        just before the start of the first record in the file.
 
1522
 
 
1523
        :return: (expected adler checksum, number of entries, parent list)
 
1524
        """
 
1525
        self._read_prelude()
 
1526
        parent_line = self._state_file.readline()
 
1527
        info = parent_line.split('\0')
 
1528
        num_parents = int(info[0])
 
1529
        assert num_parents == len(info)-2, 'incorrect parent info line'
 
1530
        self._parents = info[1:-1]
 
1531
 
 
1532
        ghost_line = self._state_file.readline()
 
1533
        info = ghost_line.split('\0')
 
1534
        num_ghosts = int(info[1])
 
1535
        assert num_ghosts == len(info)-3, 'incorrect ghost info line'
 
1536
        self._ghosts = info[2:-1]
 
1537
        self._header_state = DirState.IN_MEMORY_UNMODIFIED
 
1538
        self._end_of_header = self._state_file.tell()
 
1539
 
 
1540
    def _read_header_if_needed(self):
 
1541
        """Read the header of the dirstate file if needed."""
 
1542
        # inline this as it will be called a lot
 
1543
        if not self._lock_token:
 
1544
            raise errors.ObjectNotLocked(self)
 
1545
        if self._header_state == DirState.NOT_IN_MEMORY:
 
1546
            self._read_header()
 
1547
 
 
1548
    def _read_prelude(self):
 
1549
        """Read in the prelude header of the dirstate file
 
1550
 
 
1551
        This only reads in the stuff that is not connected to the adler
 
1552
        checksum. The position will be correct to read in the rest of
 
1553
        the file and check the checksum after this point.
 
1554
        The next entry in the file should be the number of parents,
 
1555
        and their ids. Followed by a newline.
 
1556
        """
 
1557
        header = self._state_file.readline()
 
1558
        assert header == DirState.HEADER_FORMAT_3, \
 
1559
            'invalid header line: %r' % (header,)
 
1560
        adler_line = self._state_file.readline()
 
1561
        assert adler_line.startswith('adler32: '), 'missing adler32 checksum'
 
1562
        self.adler_expected = int(adler_line[len('adler32: '):-1])
 
1563
        num_entries_line = self._state_file.readline()
 
1564
        assert num_entries_line.startswith('num_entries: '), 'missing num_entries line'
 
1565
        self._num_entries = int(num_entries_line[len('num_entries: '):-1])
 
1566
    
 
1567
    def save(self):
 
1568
        """Save any pending changes created during this session.
 
1569
        
 
1570
        We reuse the existing file, because that prevents race conditions with
 
1571
        file creation, and we expect to be using oslocks on it in the near 
 
1572
        future to prevent concurrent modification and reads - because dirstates
 
1573
        incremental data aggretation is not compatible with reading a modified
 
1574
        file, and replacing a file in use by another process is impossible on 
 
1575
        windows.
 
1576
 
 
1577
        A dirstate in read only mode should be smart enough though to validate
 
1578
        that the file has not changed, and otherwise discard its cache and
 
1579
        start over, to allow for fine grained read lock duration, so 'status'
 
1580
        wont block 'commit' - for example.
 
1581
        """
 
1582
        if (self._header_state == DirState.IN_MEMORY_MODIFIED or
 
1583
            self._dirblock_state == DirState.IN_MEMORY_MODIFIED):
 
1584
            self._state_file.seek(0)
 
1585
            self._state_file.writelines(self.get_lines())
 
1586
            self._state_file.truncate()
 
1587
            self._state_file.flush()
 
1588
            self._header_state = DirState.IN_MEMORY_UNMODIFIED
 
1589
            self._dirblock_state = DirState.IN_MEMORY_UNMODIFIED
 
1590
 
 
1591
    def _set_data(self, parent_ids, dirblocks):
 
1592
        """Set the full dirstate data in memory.
 
1593
 
 
1594
        This is an internal function used to completely replace the objects
 
1595
        in memory state. It puts the dirstate into state 'full-dirty'.
 
1596
 
 
1597
        :param parent_ids: A list of parent tree revision ids.
 
1598
        :param dirblocks: A list containing one tuple for each directory in the
 
1599
            tree. Each tuple contains the directory path and a list of entries 
 
1600
            found in that directory.
 
1601
        """
 
1602
        # our memory copy is now authoritative.
 
1603
        self._dirblocks = dirblocks
 
1604
        self._header_state = DirState.IN_MEMORY_MODIFIED
 
1605
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
1606
        self._parents = list(parent_ids)
 
1607
        self._id_index = None
 
1608
 
 
1609
    def set_path_id(self, path, new_id):
 
1610
        """Change the id of path to new_id in the current working tree.
 
1611
 
 
1612
        :param path: The path inside the tree to set - '' is the root, 'foo'
 
1613
            is the path foo in the root.
 
1614
        :param new_id: The new id to assign to the path. This must be a utf8
 
1615
            file id (not unicode, and not None).
 
1616
        """
 
1617
        # TODO: start warning here.
 
1618
        assert new_id.__class__ == str
 
1619
        self._read_dirblocks_if_needed()
 
1620
        if len(path):
 
1621
            import pdb;pdb.set_trace()
 
1622
            # logic not written
 
1623
            raise NotImplementedError(self.set_path_id)
 
1624
        # TODO: check new id is unique
 
1625
        entry = self._get_entry(0, path_utf8=path)
 
1626
        if entry[0][2] == new_id:
 
1627
            # Nothing to change.
 
1628
            return
 
1629
        # mark the old path absent, and insert a new root path
 
1630
        self._make_absent(entry)
 
1631
        self.update_minimal(('', '', new_id), 'd',
 
1632
            path_utf8='', packed_stat=entry[1][0][4])
 
1633
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
1634
        if self._id_index is not None:
 
1635
            self._id_index.setdefault(new_id, set()).add(entry[0])
 
1636
 
 
1637
    def set_parent_trees(self, trees, ghosts):
 
1638
        """Set the parent trees for the dirstate.
 
1639
 
 
1640
        :param trees: A list of revision_id, tree tuples. tree must be provided
 
1641
            even if the revision_id refers to a ghost: supply an empty tree in 
 
1642
            this case.
 
1643
        :param ghosts: A list of the revision_ids that are ghosts at the time
 
1644
            of setting.
 
1645
        """ 
 
1646
        # TODO: generate a list of parent indexes to preserve to save 
 
1647
        # processing specific parent trees. In the common case one tree will
 
1648
        # be preserved - the left most parent.
 
1649
        # TODO: if the parent tree is a dirstate, we might want to walk them
 
1650
        # all by path in parallel for 'optimal' common-case performance.
 
1651
        # generate new root row.
 
1652
        self._read_dirblocks_if_needed()
 
1653
        # TODO future sketch: Examine the existing parents to generate a change
 
1654
        # map and then walk the new parent trees only, mapping them into the
 
1655
        # dirstate. Walk the dirstate at the same time to remove unreferenced
 
1656
        # entries.
 
1657
        # for now: 
 
1658
        # sketch: loop over all entries in the dirstate, cherry picking 
 
1659
        # entries from the parent trees, if they are not ghost trees.
 
1660
        # after we finish walking the dirstate, all entries not in the dirstate
 
1661
        # are deletes, so we want to append them to the end as per the design
 
1662
        # discussions. So do a set difference on ids with the parents to
 
1663
        # get deletes, and add them to the end.
 
1664
        # During the update process we need to answer the following questions:
 
1665
        # - find other keys containing a fileid in order to create cross-path
 
1666
        #   links. We dont't trivially use the inventory from other trees
 
1667
        #   because this leads to either double touching, or to accessing
 
1668
        #   missing keys,
 
1669
        # - find other keys containing a path 
 
1670
        # We accumulate each entry via this dictionary, including the root 
 
1671
        by_path = {}
 
1672
        id_index = {}
 
1673
        # we could do parallel iterators, but because file id data may be
 
1674
        # scattered throughout, we dont save on index overhead: we have to look
 
1675
        # at everything anyway. We can probably save cycles by reusing parent
 
1676
        # data and doing an incremental update when adding an additional
 
1677
        # parent, but for now the common cases are adding a new parent (merge),
 
1678
        # and replacing completely (commit), and commit is more common: so
 
1679
        # optimise merge later.
 
1680
        
 
1681
        # ---- start generation of full tree mapping data
 
1682
        # what trees should we use?
 
1683
        parent_trees = [tree for rev_id, tree in trees if rev_id not in ghosts]
 
1684
        # how many trees do we end up with 
 
1685
        parent_count = len(parent_trees)
 
1686
 
 
1687
        # one: the current tree
 
1688
        for entry in self._iter_entries():
 
1689
            # skip entries not in the current tree
 
1690
            if entry[1][0][0] in ('a', 'r'): # absent, relocated
 
1691
                continue
 
1692
            by_path[entry[0]] = [entry[1][0]] + \
 
1693
                [DirState.NULL_PARENT_DETAILS] * parent_count
 
1694
            id_index[entry[0][2]] = set([entry[0]])
 
1695
        
 
1696
        # now the parent trees:
 
1697
        for tree_index, tree in enumerate(parent_trees):
 
1698
            # the index is off by one, adjust it.
 
1699
            tree_index = tree_index + 1
 
1700
            # when we add new locations for a fileid we need these ranges for
 
1701
            # any fileid in this tree as we set the by_path[id] to:
 
1702
            # already_processed_tree_details + new_details + new_location_suffix
 
1703
            # the suffix is from tree_index+1:parent_count+1.
 
1704
            new_location_suffix = [DirState.NULL_PARENT_DETAILS] * (parent_count - tree_index)
 
1705
            # now stitch in all the entries from this tree
 
1706
            for path, entry in tree.inventory.iter_entries_by_dir():
 
1707
                # here we process each trees details for each item in the tree.
 
1708
                # we first update any existing entries for the id at other paths,
 
1709
                # then we either create or update the entry for the id at the
 
1710
                # right path, and finally we add (if needed) a mapping from
 
1711
                # file_id to this path. We do it in this order to allow us to
 
1712
                # avoid checking all known paths for the id when generating a
 
1713
                # new entry at this path: by adding the id->path mapping last,
 
1714
                # all the mappings are valid and have correct relocation
 
1715
                # records where needed. 
 
1716
                file_id = entry.file_id
 
1717
                path_utf8 = path.encode('utf8')
 
1718
                dirname, basename = osutils.split(path_utf8)
 
1719
                new_entry_key = (dirname, basename, file_id)
 
1720
                # tree index consistency: All other paths for this id in this tree
 
1721
                # index must point to the correct path.
 
1722
                for entry_key in id_index.setdefault(file_id, set()):
 
1723
                    # TODO:PROFILING: It might be faster to just update
 
1724
                    # rather than checking if we need to, and then overwrite
 
1725
                    # the one we are located at.
 
1726
                    if entry_key != new_entry_key:
 
1727
                        # this file id is at a different path in one of the
 
1728
                        # other trees, so put absent pointers there
 
1729
                        # This is the vertical axis in the matrix, all pointing
 
1730
                        # tot he real path.
 
1731
                        by_path[entry_key][tree_index] = ('r', path_utf8, 0, False, '')
 
1732
                # by path consistency: Insert into an existing path record (trivial), or 
 
1733
                # add a new one with relocation pointers for the other tree indexes.
 
1734
                if new_entry_key in id_index[file_id]:
 
1735
                    # there is already an entry where this data belongs, just insert it.
 
1736
                    by_path[new_entry_key][tree_index] = \
 
1737
                        self._inv_entry_to_details(entry)
 
1738
                else:
 
1739
                    # add relocated entries to the horizontal axis - this row
 
1740
                    # mapping from path,id. We need to look up the correct path
 
1741
                    # for the indexes from 0 to tree_index -1
 
1742
                    new_details = []
 
1743
                    for lookup_index in xrange(tree_index):
 
1744
                        # boundary case: this is the first occurence of file_id
 
1745
                        # so there are no id_indexs, possibly take this out of
 
1746
                        # the loop?
 
1747
                        if not len(id_index[file_id]):
 
1748
                            new_details.append(DirState.NULL_PARENT_DETAILS)
 
1749
                        else:
 
1750
                            # grab any one entry, use it to find the right path.
 
1751
                            # TODO: optimise this to reduce memory use in highly 
 
1752
                            # fragmented situations by reusing the relocation
 
1753
                            # records.
 
1754
                            a_key = iter(id_index[file_id]).next()
 
1755
                            if by_path[a_key][lookup_index][0] in ('r', 'a'):
 
1756
                                # its a pointer or missing statement, use it as is.
 
1757
                                new_details.append(by_path[a_key][lookup_index])
 
1758
                            else:
 
1759
                                # we have the right key, make a pointer to it.
 
1760
                                real_path = ('/'.join(a_key[0:2])).strip('/')
 
1761
                                new_details.append(('r', real_path, 0, False, ''))
 
1762
                    new_details.append(self._inv_entry_to_details(entry))
 
1763
                    new_details.extend(new_location_suffix)
 
1764
                    by_path[new_entry_key] = new_details
 
1765
                    id_index[file_id].add(new_entry_key)
 
1766
        # --- end generation of full tree mappings
 
1767
 
 
1768
        # sort and output all the entries
 
1769
        new_entries = sorted(by_path.items(),
 
1770
                        key=lambda entry:(entry[0][0].split('/'), entry[0][1]))
 
1771
        self._entries_to_current_state(new_entries)
 
1772
        self._parents = [rev_id for rev_id, tree in trees]
 
1773
        self._ghosts = list(ghosts)
 
1774
        self._header_state = DirState.IN_MEMORY_MODIFIED
 
1775
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
1776
        self._id_index = id_index
 
1777
 
 
1778
    def set_state_from_inventory(self, new_inv):
 
1779
        """Set new_inv as the current state. 
 
1780
 
 
1781
        This API is called by tree transform, and will usually occur with
 
1782
        existing parent trees.
 
1783
 
 
1784
        :param new_inv: The inventory object to set current state from.
 
1785
        """
 
1786
        self._read_dirblocks_if_needed()
 
1787
        # sketch:
 
1788
        # incremental algorithm:
 
1789
        # two iterators: current data and new data, both in dirblock order. 
 
1790
        new_iterator = new_inv.iter_entries_by_dir()
 
1791
        # we will be modifying the dirstate, so we need a stable iterator. In
 
1792
        # future we might write one, for now we just clone the state into a
 
1793
        # list - which is a shallow copy, so each 
 
1794
        old_iterator = iter(list(self._iter_entries()))
 
1795
        # both must have roots so this is safe:
 
1796
        current_new = new_iterator.next()
 
1797
        current_old = old_iterator.next()
 
1798
        def advance(iterator):
 
1799
            try:
 
1800
                return iterator.next()
 
1801
            except StopIteration:
 
1802
                return None
 
1803
        while current_new or current_old:
 
1804
            # skip entries in old that are not really there
 
1805
            if current_old and current_old[1][0][0] in ('r', 'a'):
 
1806
                # relocated or absent
 
1807
                current_old = advance(old_iterator)
 
1808
                continue
 
1809
            if current_new:
 
1810
                # convert new into dirblock style
 
1811
                new_path_utf8 = current_new[0].encode('utf8')
 
1812
                new_dirname, new_basename = osutils.split(new_path_utf8)
 
1813
                new_id = current_new[1].file_id
 
1814
                new_entry_key = (new_dirname, new_basename, new_id)
 
1815
                current_new_minikind = \
 
1816
                    DirState._kind_to_minikind[current_new[1].kind]
 
1817
            else:
 
1818
                # for safety disable variables
 
1819
                new_path_utf8 = new_dirname = new_basename = new_id = new_entry_key = None
 
1820
            # 5 cases, we dont have a value that is strictly greater than everything, so
 
1821
            # we make both end conditions explicit
 
1822
            if not current_old:
 
1823
                # old is finished: insert current_new into the state.
 
1824
                self.update_minimal(new_entry_key, current_new_minikind,
 
1825
                    executable=current_new[1].executable,
 
1826
                    path_utf8=new_path_utf8)
 
1827
                current_new = advance(new_iterator)
 
1828
            elif not current_new:
 
1829
                # new is finished
 
1830
                self._make_absent(current_old)
 
1831
                current_old = advance(old_iterator)
 
1832
            elif new_entry_key == current_old[0]:
 
1833
                # same -  common case
 
1834
                # TODO: update the record if anything significant has changed.
 
1835
                # the minimal required trigger is if the execute bit or cached
 
1836
                # kind has changed.
 
1837
                if (current_old[1][0][3] != current_new[1].executable or
 
1838
                    current_old[1][0][0] != current_new_minikind):
 
1839
                    self.update_minimal(current_old[0], current_new_minikind,
 
1840
                        executable=current_new[1].executable,
 
1841
                        path_utf8=new_path_utf8)
 
1842
                # both sides are dealt with, move on
 
1843
                current_old = advance(old_iterator)
 
1844
                current_new = advance(new_iterator)
 
1845
            elif new_entry_key < current_old[0]:
 
1846
                # new comes before:
 
1847
                # add a entry for this and advance new
 
1848
                self.update_minimal(new_entry_key, current_new_minikind,
 
1849
                    executable=current_new[1].executable,
 
1850
                    path_utf8=new_path_utf8)
 
1851
                current_new = advance(new_iterator)
 
1852
            else:
 
1853
                # old comes before:
 
1854
                self._make_absent(current_old)
 
1855
                current_old = advance(old_iterator)
 
1856
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
1857
        self._id_index = None
 
1858
 
 
1859
    def _make_absent(self, current_old):
 
1860
        """Mark current_old - an entry - as absent for tree 0.
 
1861
 
 
1862
        :return: True if this was the last details entry for they entry key:
 
1863
            that is, if the underlying block has had the entry removed, thus
 
1864
            shrinking in length.
 
1865
        """
 
1866
        # build up paths that this id will be left at after the change is made,
 
1867
        # so we can update their cross references in tree 0
 
1868
        all_remaining_keys = set()
 
1869
        # Dont check the working tree, because its going.
 
1870
        for details in current_old[1][1:]:
 
1871
            if details[0] not in ('a', 'r'): # absent, relocated
 
1872
                all_remaining_keys.add(current_old[0])
 
1873
            elif details[0] == 'r': # relocated
 
1874
                # record the key for the real path.
 
1875
                all_remaining_keys.add(tuple(osutils.split(details[1])) + (current_old[0][2],))
 
1876
            # absent rows are not present at any path.
 
1877
        last_reference = current_old[0] not in all_remaining_keys
 
1878
        if last_reference:
 
1879
            # the current row consists entire of the current item (being marked
 
1880
            # absent), and relocated or absent entries for the other trees:
 
1881
            # Remove it, its meaningless.
 
1882
            block = self._find_block(current_old[0])
 
1883
            entry_index, present = self._find_entry_index(current_old[0], block[1])
 
1884
            assert present, 'could not find entry for %s' % (current_old,)
 
1885
            block[1].pop(entry_index)
 
1886
            # if we have an id_index in use, remove this key from it for this id.
 
1887
            if self._id_index is not None:
 
1888
                self._id_index[current_old[0][2]].remove(current_old[0])
 
1889
        # update all remaining keys for this id to record it as absent. The
 
1890
        # existing details may either be the record we are making as deleted
 
1891
        # (if there were other trees with the id present at this path), or may
 
1892
        # be relocations.
 
1893
        for update_key in all_remaining_keys:
 
1894
            update_block_index, present = \
 
1895
                self._find_block_index_from_key(update_key)
 
1896
            assert present, 'could not find block for %s' % (update_key,)
 
1897
            update_entry_index, present = \
 
1898
                self._find_entry_index(update_key, self._dirblocks[update_block_index][1])
 
1899
            assert present, 'could not find entry for %s' % (update_key,)
 
1900
            update_tree_details = self._dirblocks[update_block_index][1][update_entry_index][1]
 
1901
            # it must not be absent at the moment
 
1902
            assert update_tree_details[0][0] != 'a' # absent
 
1903
            update_tree_details[0] = DirState.NULL_PARENT_DETAILS
 
1904
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
1905
        return last_reference
 
1906
 
 
1907
    def update_minimal(self, key, minikind, executable=False, fingerprint='',
 
1908
                       packed_stat=None, size=0, path_utf8=None):
 
1909
        """Update an entry to the state in tree 0.
 
1910
 
 
1911
        This will either create a new entry at 'key' or update an existing one.
 
1912
        It also makes sure that any other records which might mention this are
 
1913
        updated as well.
 
1914
 
 
1915
        :param key: (dir, name, file_id) for the new entry
 
1916
        :param minikind: The type for the entry ('f' == 'file', 'd' ==
 
1917
                'directory'), etc.
 
1918
        :param executable: Should the executable bit be set?
 
1919
        :param fingerprint: Simple fingerprint for new entry.
 
1920
        :param packed_stat: packed stat value for new entry.
 
1921
        :param size: Size information for new entry
 
1922
        :param path_utf8: key[0] + '/' + key[1], just passed in to avoid doing
 
1923
                extra computation.
 
1924
        """
 
1925
        block = self._find_block(key)[1]
 
1926
        if packed_stat is None:
 
1927
            packed_stat = DirState.NULLSTAT
 
1928
        entry_index, present = self._find_entry_index(key, block)
 
1929
        new_details = (minikind, fingerprint, size, executable, packed_stat)
 
1930
        id_index = self._get_id_index()
 
1931
        if not present:
 
1932
            # new entry, synthesis cross reference here,
 
1933
            existing_keys = id_index.setdefault(key[2], set())
 
1934
            if not existing_keys:
 
1935
                # not currently in the state, simplest case
 
1936
                new_entry = key, [new_details] + self._empty_parent_info()
 
1937
            else:
 
1938
                # present at one or more existing other paths.
 
1939
                # grab one of them and use it to generate parent
 
1940
                # relocation/absent entries.
 
1941
                new_entry = key, [new_details]
 
1942
                for other_key in existing_keys:
 
1943
                    # change the record at other to be a pointer to this new
 
1944
                    # record. The loop looks similar to the change to
 
1945
                    # relocations when updating an existing record but its not:
 
1946
                    # the test for existing kinds is different: this can be
 
1947
                    # factored out to a helper though.
 
1948
                    other_block_index, present = self._find_block_index_from_key(other_key)
 
1949
                    if not present:
 
1950
                        import pdb; pdb.set_trace()
 
1951
                    assert present, 'could not find block for %s' % (other_key,)
 
1952
                    other_entry_index, present = self._find_entry_index(other_key,
 
1953
                                            self._dirblocks[other_block_index][1])
 
1954
                    if not present:
 
1955
                        import pdb; pdb.set_trace()
 
1956
                    assert present, 'could not find entry for %s' % (other_key,)
 
1957
                    assert path_utf8 is not None
 
1958
                    self._dirblocks[other_block_index][1][other_entry_index][1][0] = \
 
1959
                        ('r', path_utf8, 0, False, '')
 
1960
 
 
1961
                num_present_parents = self._num_present_parents()
 
1962
                for lookup_index in xrange(1, num_present_parents + 1):
 
1963
                    # grab any one entry, use it to find the right path.
 
1964
                    # TODO: optimise this to reduce memory use in highly 
 
1965
                    # fragmented situations by reusing the relocation
 
1966
                    # records.
 
1967
                    update_block_index, present = \
 
1968
                        self._find_block_index_from_key(other_key)
 
1969
                    assert present, 'could not find block for %s' % (other_key,)
 
1970
                    update_entry_index, present = \
 
1971
                        self._find_entry_index(other_key, self._dirblocks[update_block_index][1])
 
1972
                    assert present, 'could not find entry for %s' % (other_key,)
 
1973
                    update_details = self._dirblocks[update_block_index][1][update_entry_index][1][lookup_index]
 
1974
                    if update_details[0] in ('r', 'a'): # relocated, absent
 
1975
                        # its a pointer or absent in lookup_index's tree, use
 
1976
                        # it as is.
 
1977
                        new_entry[1].append(update_details)
 
1978
                    else:
 
1979
                        # we have the right key, make a pointer to it.
 
1980
                        pointer_path = osutils.pathjoin(*other_key[0:2])
 
1981
                        new_entry[1].append(('r', pointer_path, 0, False, ''))
 
1982
            block.insert(entry_index, new_entry)
 
1983
            existing_keys.add(key)
 
1984
        else:
 
1985
            # Does the new state matter? 
 
1986
            block[entry_index][1][0] = new_details
 
1987
            # parents cannot be affected by what we do.
 
1988
            # other occurences of this id can be found 
 
1989
            # from the id index.
 
1990
            # ---
 
1991
            # tree index consistency: All other paths for this id in this tree
 
1992
            # index must point to the correct path. We have to loop here because
 
1993
            # we may have passed entries in the state with this file id already
 
1994
            # that were absent - where parent entries are - and they need to be
 
1995
            # converted to relocated.
 
1996
            assert path_utf8 is not None
 
1997
            for entry_key in id_index.setdefault(key[2], set()):
 
1998
                # TODO:PROFILING: It might be faster to just update
 
1999
                # rather than checking if we need to, and then overwrite
 
2000
                # the one we are located at.
 
2001
                if entry_key != key:
 
2002
                    # this file id is at a different path in one of the
 
2003
                    # other trees, so put absent pointers there
 
2004
                    # This is the vertical axis in the matrix, all pointing
 
2005
                    # to the real path.
 
2006
                    block_index, present = self._find_block_index_from_key(entry_key)
 
2007
                    assert present
 
2008
                    entry_index, present = self._find_entry_index(entry_key, self._dirblocks[block_index][1])
 
2009
                    assert present
 
2010
                    self._dirblocks[block_index][1][entry_index][1][0] = \
 
2011
                        ('r', path_utf8, 0, False, '')
 
2012
        # add a containing dirblock if needed.
 
2013
        if new_details[0] == 'd':
 
2014
            subdir_key = (osutils.pathjoin(*key[0:2]), '', '')
 
2015
            block_index, present = self._find_block_index_from_key(subdir_key)
 
2016
            if not present:
 
2017
                self._dirblocks.insert(block_index, (subdir_key[0], []))
 
2018
 
 
2019
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
2020
 
 
2021
    def _validate(self):
 
2022
        """Check that invariants on the dirblock are correct.
 
2023
 
 
2024
        This can be useful in debugging; it shouldn't be necessary in 
 
2025
        normal code.
 
2026
        """
 
2027
        from pprint import pformat
 
2028
        if len(self._dirblocks) > 0:
 
2029
            assert self._dirblocks[0][0] == '', \
 
2030
                    "dirblocks don't start with root block:\n" + \
 
2031
                    pformat(dirblocks)
 
2032
        if len(self._dirblocks) > 1:
 
2033
            assert self._dirblocks[1][0] == '', \
 
2034
                    "dirblocks missing root directory:\n" + \
 
2035
                    pformat(dirblocks)
 
2036
        assert self._dirblocks[1:] == sorted(self._dirblocks[1:]), \
 
2037
                "dirblocks are not in sorted order:\n" + \
 
2038
                pformat(self._dirblocks)
 
2039
        for dirblock in self._dirblocks:
 
2040
            assert dirblock[1] == sorted(dirblock[1]), \
 
2041
                "dirblock for %r is not sorted:\n%s" % \
 
2042
                (dirblock[0], pformat(dirblock))
 
2043
 
 
2044
    def _wipe_state(self):
 
2045
        """Forget all state information about the dirstate."""
 
2046
        self._header_state = DirState.NOT_IN_MEMORY
 
2047
        self._dirblock_state = DirState.NOT_IN_MEMORY
 
2048
        self._parents = []
 
2049
        self._ghosts = []
 
2050
        self._dirblocks = []
 
2051
 
 
2052
    def lock_read(self):
 
2053
        """Acquire a read lock on the dirstate"""
 
2054
        if self._lock_token is not None:
 
2055
            raise errors.LockContention(self._lock_token)
 
2056
        self._lock_token = lock.ReadLock(self._filename)
 
2057
        self._state_file = self._lock_token.f
 
2058
        self._wipe_state()
 
2059
 
 
2060
    def lock_write(self):
 
2061
        """Acquire a write lock on the dirstate"""
 
2062
        if self._lock_token is not None:
 
2063
            raise errors.LockContention(self._lock_token)
 
2064
        self._lock_token = lock.WriteLock(self._filename)
 
2065
        self._state_file = self._lock_token.f
 
2066
        self._wipe_state()
 
2067
 
 
2068
    def unlock(self):
 
2069
        """Drop any locks held on the dirstate"""
 
2070
        if self._lock_token is None:
 
2071
            raise errors.LockNotHeld(self)
 
2072
        self._state_file = None
 
2073
        self._lock_token.unlock()
 
2074
        self._lock_token = None
 
2075
        self._split_path_cache = {}
 
2076
 
 
2077
    def _requires_lock(self):
 
2078
        """Checks that a lock is currently held by someone on the dirstate"""
 
2079
        if not self._lock_token:
 
2080
            raise errors.ObjectNotLocked(self)
 
2081
 
 
2082
 
 
2083
def bisect_dirblock(dirblocks, dirname, lo=0, hi=None, cache={}):
 
2084
    """Return the index where to insert dirname into the dirblocks.
 
2085
 
 
2086
    The return value idx is such that all directories blocks in dirblock[:idx]
 
2087
    have names < dirname, and all blocks in dirblock[idx:] have names >=
 
2088
    dirname.
 
2089
 
 
2090
    Optional args lo (default 0) and hi (default len(dirblocks)) bound the
 
2091
    slice of a to be searched.
 
2092
    """
 
2093
    if hi is None:
 
2094
        hi = len(dirblocks)
 
2095
    try:
 
2096
        dirname_split = cache[dirname]
 
2097
    except KeyError:
 
2098
        dirname_split = dirname.split('/')
 
2099
        cache[dirname] = dirname_split
 
2100
    while lo < hi:
 
2101
        mid = (lo+hi)//2
 
2102
        # Grab the dirname for the current dirblock
 
2103
        cur = dirblocks[mid][0]
 
2104
        try:
 
2105
            cur_split = cache[cur]
 
2106
        except KeyError:
 
2107
            cur_split = cur.split('/')
 
2108
            cache[cur] = cur_split
 
2109
        if cur_split < dirname_split: lo = mid+1
 
2110
        else: hi = mid
 
2111
    return lo
 
2112
 
 
2113
 
 
2114
_base64_encoder = codecs.getencoder('base64')
 
2115
 
 
2116
 
 
2117
def pack_stat(st, _encode=_base64_encoder, _pack=struct.pack):
 
2118
    """Convert stat values into a packed representation."""
 
2119
    # jam 20060614 it isn't really worth removing more entries if we
 
2120
    # are going to leave it in packed form.
 
2121
    # With only st_mtime and st_mode filesize is 5.5M and read time is 275ms
 
2122
    # With all entries filesize is 5.9M and read time is mabye 280ms
 
2123
    # well within the noise margin
 
2124
 
 
2125
    # base64.encode always adds a final newline, so strip it off
 
2126
    return _encode(_pack('>llllll'
 
2127
        , st.st_size, int(st.st_mtime), int(st.st_ctime)
 
2128
        , st.st_dev, st.st_ino, st.st_mode))[0][:-1]