/brz/remove-bazaar

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