/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

Implement _bisect_recursive, which uses multiple bisect calls to
handle renames and finding entries in subdirs.
As is, this could be hooked into paths2ids() if the dirstate has not been loaded yet.
However, it doesn't quite provide enough, since the parsed entries would probably not
be saved. Further, the multiple bisect calls are less efficient then they could be,
because they do not remember the last bisect call.
We should explore switching to a caching structure, which maintains all records that
have been processed, in a structure that can be in-memory searched before going back
to disk.

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