~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/dirstate.py

  • Committer: Vincent Ladeuil
  • Date: 2010-10-26 08:08:23 UTC
  • mfrom: (5514.1.1 665100-content-type)
  • mto: This revision was merged to the branch mainline in revision 5516.
  • Revision ID: v.ladeuil+lp@free.fr-20101026080823-3wggo03b7cpn9908
Correctly set the Content-Type header when POSTing http requests

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2006-2010 Canonical Ltd
 
2
#
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
 
17
"""DirState objects record the state of a directory and its bzr metadata.
 
18
 
 
19
Pseudo EBNF grammar for the state file. Fields are separated by NULLs, and
 
20
lines by NL. The field delimiters are ommitted in the grammar, line delimiters
 
21
are not - this is done for clarity of reading. All string data is in utf8.
 
22
 
 
23
MINIKIND = "f" | "d" | "l" | "a" | "r" | "t";
 
24
NL = "\n";
 
25
NULL = "\0";
 
26
WHOLE_NUMBER = {digit}, digit;
 
27
BOOLEAN = "y" | "n";
 
28
REVISION_ID = a non-empty utf8 string;
 
29
 
 
30
dirstate format = header line, full checksum, row count, parent details,
 
31
 ghost_details, entries;
 
32
header line = "#bazaar dirstate flat format 3", NL;
 
33
full checksum = "crc32: ", ["-"], WHOLE_NUMBER, NL;
 
34
row count = "num_entries: ", WHOLE_NUMBER, NL;
 
35
parent_details = WHOLE NUMBER, {REVISION_ID}* NL;
 
36
ghost_details = WHOLE NUMBER, {REVISION_ID}*, NL;
 
37
entries = {entry};
 
38
entry = entry_key, current_entry_details, {parent_entry_details};
 
39
entry_key = dirname,  basename, fileid;
 
40
current_entry_details = common_entry_details, working_entry_details;
 
41
parent_entry_details = common_entry_details, history_entry_details;
 
42
common_entry_details = MINIKIND, fingerprint, size, executable
 
43
working_entry_details = packed_stat
 
44
history_entry_details = REVISION_ID;
 
45
executable = BOOLEAN;
 
46
size = WHOLE_NUMBER;
 
47
fingerprint = a nonempty utf8 sequence with meaning defined by minikind.
 
48
 
 
49
Given this definition, the following is useful to know:
 
50
entry (aka row) - all the data for a given key.
 
51
entry[0]: The key (dirname, basename, fileid)
 
52
entry[0][0]: dirname
 
53
entry[0][1]: basename
 
54
entry[0][2]: fileid
 
55
entry[1]: The tree(s) data for this path and id combination.
 
56
entry[1][0]: The current tree
 
57
entry[1][1]: The second tree
 
58
 
 
59
For an entry for a tree, we have (using tree 0 - current tree) to demonstrate:
 
60
entry[1][0][0]: minikind
 
61
entry[1][0][1]: fingerprint
 
62
entry[1][0][2]: size
 
63
entry[1][0][3]: executable
 
64
entry[1][0][4]: packed_stat
 
65
OR (for non tree-0)
 
66
entry[1][1][4]: revision_id
 
67
 
 
68
There may be multiple rows at the root, one per id present in the root, so the
 
69
in memory root row is now:
 
70
self._dirblocks[0] -> ('', [entry ...]),
 
71
and the entries in there are
 
72
entries[0][0]: ''
 
73
entries[0][1]: ''
 
74
entries[0][2]: file_id
 
75
entries[1][0]: The tree data for the current tree for this fileid at /
 
76
etc.
 
77
 
 
78
Kinds:
 
79
'r' is a relocated entry: This path is not present in this tree with this id,
 
80
    but the id can be found at another location. The fingerprint is used to
 
81
    point to the target location.
 
82
'a' is an absent entry: In that tree the id is not present at this path.
 
83
'd' is a directory entry: This path in this tree is a directory with the
 
84
    current file id. There is no fingerprint for directories.
 
85
'f' is a file entry: As for directory, but it's a file. The fingerprint is the
 
86
    sha1 value of the file's canonical form, i.e. after any read filters have
 
87
    been applied to the convenience form stored in the working tree.
 
88
'l' is a symlink entry: As for directory, but a symlink. The fingerprint is the
 
89
    link target.
 
90
't' is a reference to a nested subtree; the fingerprint is the referenced
 
91
    revision.
 
92
 
 
93
Ordering:
 
94
 
 
95
The entries on disk and in memory are ordered according to the following keys:
 
96
 
 
97
    directory, as a list of components
 
98
    filename
 
99
    file-id
 
100
 
 
101
--- Format 1 had the following different definition: ---
 
102
rows = dirname, NULL, basename, NULL, MINIKIND, NULL, fileid_utf8, NULL,
 
103
    WHOLE NUMBER (* size *), NULL, packed stat, NULL, sha1|symlink target,
 
104
    {PARENT ROW}
 
105
PARENT ROW = NULL, revision_utf8, NULL, MINIKIND, NULL, dirname, NULL,
 
106
    basename, NULL, WHOLE NUMBER (* size *), NULL, "y" | "n", NULL,
 
107
    SHA1
 
108
 
 
109
PARENT ROW's are emitted for every parent that is not in the ghosts details
 
110
line. That is, if the parents are foo, bar, baz, and the ghosts are bar, then
 
111
each row will have a PARENT ROW for foo and baz, but not for bar.
 
112
 
 
113
 
 
114
In any tree, a kind of 'moved' indicates that the fingerprint field
 
115
(which we treat as opaque data specific to the 'kind' anyway) has the
 
116
details for the id of this row in that tree.
 
117
 
 
118
I'm strongly tempted to add a id->path index as well, but I think that
 
119
where we need id->path mapping; we also usually read the whole file, so
 
120
I'm going to skip that for the moment, as we have the ability to locate
 
121
via bisect any path in any tree, and if we lookup things by path, we can
 
122
accumulate an id->path mapping as we go, which will tend to match what we
 
123
looked for.
 
124
 
 
125
I plan to implement this asap, so please speak up now to alter/tweak the
 
126
design - and once we stabilise on this, I'll update the wiki page for
 
127
it.
 
128
 
 
129
The rationale for all this is that we want fast operations for the
 
130
common case (diff/status/commit/merge on all files) and extremely fast
 
131
operations for the less common but still occurs a lot status/diff/commit
 
132
on specific files). Operations on specific files involve a scan for all
 
133
the children of a path, *in every involved tree*, which the current
 
134
format did not accommodate.
 
135
----
 
136
 
 
137
Design priorities:
 
138
 1) Fast end to end use for bzr's top 5 uses cases. (commmit/diff/status/merge/???)
 
139
 2) fall back current object model as needed.
 
140
 3) scale usably to the largest trees known today - say 50K entries. (mozilla
 
141
    is an example of this)
 
142
 
 
143
 
 
144
Locking:
 
145
 Eventually reuse dirstate objects across locks IFF the dirstate file has not
 
146
 been modified, but will require that we flush/ignore cached stat-hit data
 
147
 because we won't want to restat all files on disk just because a lock was
 
148
 acquired, yet we cannot trust the data after the previous lock was released.
 
149
 
 
150
Memory representation:
 
151
 vector of all directories, and vector of the childen ?
 
152
   i.e.
 
153
     root_entrie = (direntry for root, [parent_direntries_for_root]),
 
154
     dirblocks = [
 
155
     ('', ['data for achild', 'data for bchild', 'data for cchild'])
 
156
     ('dir', ['achild', 'cchild', 'echild'])
 
157
     ]
 
158
    - single bisect to find N subtrees from a path spec
 
159
    - in-order for serialisation - this is 'dirblock' grouping.
 
160
    - insertion of a file '/a' affects only the '/' child-vector, that is, to
 
161
      insert 10K elements from scratch does not generates O(N^2) memoves of a
 
162
      single vector, rather each individual, which tends to be limited to a
 
163
      manageable number. Will scale badly on trees with 10K entries in a
 
164
      single directory. compare with Inventory.InventoryDirectory which has
 
165
      a dictionary for the children. No bisect capability, can only probe for
 
166
      exact matches, or grab all elements and sort.
 
167
    - What's the risk of error here? Once we have the base format being processed
 
168
      we should have a net win regardless of optimality. So we are going to
 
169
      go with what seems reasonable.
 
170
open questions:
 
171
 
 
172
Maybe we should do a test profile of the core structure - 10K simulated
 
173
searches/lookups/etc?
 
174
 
 
175
Objects for each row?
 
176
The lifetime of Dirstate objects is current per lock, but see above for
 
177
possible extensions. The lifetime of a row from a dirstate is expected to be
 
178
very short in the optimistic case: which we are optimising for. For instance,
 
179
subtree status will determine from analysis of the disk data what rows need to
 
180
be examined at all, and will be able to determine from a single row whether
 
181
that file has altered or not, so we are aiming to process tens of thousands of
 
182
entries each second within the dirstate context, before exposing anything to
 
183
the larger codebase. This suggests we want the time for a single file
 
184
comparison to be < 0.1 milliseconds. That would give us 10000 paths per second
 
185
processed, and to scale to 100 thousand we'll another order of magnitude to do
 
186
that. Now, as the lifetime for all unchanged entries is the time to parse, stat
 
187
the file on disk, and then immediately discard, the overhead of object creation
 
188
becomes a significant cost.
 
189
 
 
190
Figures: Creating a tuple from 3 elements was profiled at 0.0625
 
191
microseconds, whereas creating a object which is subclassed from tuple was
 
192
0.500 microseconds, and creating an object with 3 elements and slots was 3
 
193
microseconds long. 0.1 milliseconds is 100 microseconds, and ideally we'll get
 
194
down to 10 microseconds for the total processing - having 33% of that be object
 
195
creation is a huge overhead. There is a potential cost in using tuples within
 
196
each row which is that the conditional code to do comparisons may be slower
 
197
than method invocation, but method invocation is known to be slow due to stack
 
198
frame creation, so avoiding methods in these tight inner loops in unfortunately
 
199
desirable. We can consider a pyrex version of this with objects in future if
 
200
desired.
 
201
 
 
202
"""
 
203
 
 
204
import bisect
 
205
import binascii
 
206
import errno
 
207
import operator
 
208
import os
 
209
from stat import S_IEXEC
 
210
import stat
 
211
import struct
 
212
import sys
 
213
import time
 
214
import zlib
 
215
 
 
216
from bzrlib import (
 
217
    cache_utf8,
 
218
    debug,
 
219
    errors,
 
220
    inventory,
 
221
    lock,
 
222
    osutils,
 
223
    static_tuple,
 
224
    trace,
 
225
    )
 
226
 
 
227
 
 
228
# This is the Windows equivalent of ENOTDIR
 
229
# It is defined in pywin32.winerror, but we don't want a strong dependency for
 
230
# just an error code.
 
231
ERROR_PATH_NOT_FOUND = 3
 
232
ERROR_DIRECTORY = 267
 
233
 
 
234
 
 
235
if not getattr(struct, '_compile', None):
 
236
    # Cannot pre-compile the dirstate pack_stat
 
237
    def pack_stat(st, _encode=binascii.b2a_base64, _pack=struct.pack):
 
238
        """Convert stat values into a packed representation."""
 
239
        return _encode(_pack('>LLLLLL', st.st_size, int(st.st_mtime),
 
240
            int(st.st_ctime), st.st_dev, st.st_ino & 0xFFFFFFFF,
 
241
            st.st_mode))[:-1]
 
242
else:
 
243
    # compile the struct compiler we need, so as to only do it once
 
244
    from _struct import Struct
 
245
    _compiled_pack = Struct('>LLLLLL').pack
 
246
    def pack_stat(st, _encode=binascii.b2a_base64, _pack=_compiled_pack):
 
247
        """Convert stat values into a packed representation."""
 
248
        # jam 20060614 it isn't really worth removing more entries if we
 
249
        # are going to leave it in packed form.
 
250
        # With only st_mtime and st_mode filesize is 5.5M and read time is 275ms
 
251
        # With all entries, filesize is 5.9M and read time is maybe 280ms
 
252
        # well within the noise margin
 
253
 
 
254
        # base64 encoding always adds a final newline, so strip it off
 
255
        # The current version
 
256
        return _encode(_pack(st.st_size, int(st.st_mtime), int(st.st_ctime),
 
257
            st.st_dev, st.st_ino & 0xFFFFFFFF, st.st_mode))[:-1]
 
258
        # This is 0.060s / 1.520s faster by not encoding as much information
 
259
        # return _encode(_pack('>LL', int(st.st_mtime), st.st_mode))[:-1]
 
260
        # This is not strictly faster than _encode(_pack())[:-1]
 
261
        # return '%X.%X.%X.%X.%X.%X' % (
 
262
        #      st.st_size, int(st.st_mtime), int(st.st_ctime),
 
263
        #      st.st_dev, st.st_ino, st.st_mode)
 
264
        # Similar to the _encode(_pack('>LL'))
 
265
        # return '%X.%X' % (int(st.st_mtime), st.st_mode)
 
266
 
 
267
 
 
268
class SHA1Provider(object):
 
269
    """An interface for getting sha1s of a file."""
 
270
 
 
271
    def sha1(self, abspath):
 
272
        """Return the sha1 of a file given its absolute path.
 
273
 
 
274
        :param abspath:  May be a filesystem encoded absolute path
 
275
             or a unicode path.
 
276
        """
 
277
        raise NotImplementedError(self.sha1)
 
278
 
 
279
    def stat_and_sha1(self, abspath):
 
280
        """Return the stat and sha1 of a file given its absolute path.
 
281
        
 
282
        :param abspath:  May be a filesystem encoded absolute path
 
283
             or a unicode path.
 
284
 
 
285
        Note: the stat should be the stat of the physical file
 
286
        while the sha may be the sha of its canonical content.
 
287
        """
 
288
        raise NotImplementedError(self.stat_and_sha1)
 
289
 
 
290
 
 
291
class DefaultSHA1Provider(SHA1Provider):
 
292
    """A SHA1Provider that reads directly from the filesystem."""
 
293
 
 
294
    def sha1(self, abspath):
 
295
        """Return the sha1 of a file given its absolute path."""
 
296
        return osutils.sha_file_by_name(abspath)
 
297
 
 
298
    def stat_and_sha1(self, abspath):
 
299
        """Return the stat and sha1 of a file given its absolute path."""
 
300
        file_obj = file(abspath, 'rb')
 
301
        try:
 
302
            statvalue = os.fstat(file_obj.fileno())
 
303
            sha1 = osutils.sha_file(file_obj)
 
304
        finally:
 
305
            file_obj.close()
 
306
        return statvalue, sha1
 
307
 
 
308
 
 
309
class DirState(object):
 
310
    """Record directory and metadata state for fast access.
 
311
 
 
312
    A dirstate is a specialised data structure for managing local working
 
313
    tree state information. Its not yet well defined whether it is platform
 
314
    specific, and if it is how we detect/parameterize that.
 
315
 
 
316
    Dirstates use the usual lock_write, lock_read and unlock mechanisms.
 
317
    Unlike most bzr disk formats, DirStates must be locked for reading, using
 
318
    lock_read.  (This is an os file lock internally.)  This is necessary
 
319
    because the file can be rewritten in place.
 
320
 
 
321
    DirStates must be explicitly written with save() to commit changes; just
 
322
    unlocking them does not write the changes to disk.
 
323
    """
 
324
 
 
325
    _kind_to_minikind = {
 
326
            'absent': 'a',
 
327
            'file': 'f',
 
328
            'directory': 'd',
 
329
            'relocated': 'r',
 
330
            'symlink': 'l',
 
331
            'tree-reference': 't',
 
332
        }
 
333
    _minikind_to_kind = {
 
334
            'a': 'absent',
 
335
            'f': 'file',
 
336
            'd': 'directory',
 
337
            'l':'symlink',
 
338
            'r': 'relocated',
 
339
            't': 'tree-reference',
 
340
        }
 
341
    _stat_to_minikind = {
 
342
        stat.S_IFDIR:'d',
 
343
        stat.S_IFREG:'f',
 
344
        stat.S_IFLNK:'l',
 
345
    }
 
346
    _to_yesno = {True:'y', False: 'n'} # TODO profile the performance gain
 
347
     # of using int conversion rather than a dict here. AND BLAME ANDREW IF
 
348
     # it is faster.
 
349
 
 
350
    # TODO: jam 20070221 Figure out what to do if we have a record that exceeds
 
351
    #       the BISECT_PAGE_SIZE. For now, we just have to make it large enough
 
352
    #       that we are sure a single record will always fit.
 
353
    BISECT_PAGE_SIZE = 4096
 
354
 
 
355
    NOT_IN_MEMORY = 0
 
356
    IN_MEMORY_UNMODIFIED = 1
 
357
    IN_MEMORY_MODIFIED = 2
 
358
 
 
359
    # A pack_stat (the x's) that is just noise and will never match the output
 
360
    # of base64 encode.
 
361
    NULLSTAT = 'x' * 32
 
362
    NULL_PARENT_DETAILS = ('a', '', 0, False, '')
 
363
 
 
364
    HEADER_FORMAT_2 = '#bazaar dirstate flat format 2\n'
 
365
    HEADER_FORMAT_3 = '#bazaar dirstate flat format 3\n'
 
366
 
 
367
    def __init__(self, path, sha1_provider):
 
368
        """Create a  DirState object.
 
369
 
 
370
        :param path: The path at which the dirstate file on disk should live.
 
371
        :param sha1_provider: an object meeting the SHA1Provider interface.
 
372
        """
 
373
        # _header_state and _dirblock_state represent the current state
 
374
        # of the dirstate metadata and the per-row data respectiely.
 
375
        # NOT_IN_MEMORY indicates that no data is in memory
 
376
        # IN_MEMORY_UNMODIFIED indicates that what we have in memory
 
377
        #   is the same as is on disk
 
378
        # IN_MEMORY_MODIFIED indicates that we have a modified version
 
379
        #   of what is on disk.
 
380
        # In future we will add more granularity, for instance _dirblock_state
 
381
        # will probably support partially-in-memory as a separate variable,
 
382
        # allowing for partially-in-memory unmodified and partially-in-memory
 
383
        # modified states.
 
384
        self._header_state = DirState.NOT_IN_MEMORY
 
385
        self._dirblock_state = DirState.NOT_IN_MEMORY
 
386
        # If true, an error has been detected while updating the dirstate, and
 
387
        # for safety we're not going to commit to disk.
 
388
        self._changes_aborted = False
 
389
        self._dirblocks = []
 
390
        self._ghosts = []
 
391
        self._parents = []
 
392
        self._state_file = None
 
393
        self._filename = path
 
394
        self._lock_token = None
 
395
        self._lock_state = None
 
396
        self._id_index = None
 
397
        # a map from packed_stat to sha's.
 
398
        self._packed_stat_index = None
 
399
        self._end_of_header = None
 
400
        self._cutoff_time = None
 
401
        self._split_path_cache = {}
 
402
        self._bisect_page_size = DirState.BISECT_PAGE_SIZE
 
403
        self._sha1_provider = sha1_provider
 
404
        if 'hashcache' in debug.debug_flags:
 
405
            self._sha1_file = self._sha1_file_and_mutter
 
406
        else:
 
407
            self._sha1_file = self._sha1_provider.sha1
 
408
        # These two attributes provide a simple cache for lookups into the
 
409
        # dirstate in-memory vectors. By probing respectively for the last
 
410
        # block, and for the next entry, we save nearly 2 bisections per path
 
411
        # during commit.
 
412
        self._last_block_index = None
 
413
        self._last_entry_index = None
 
414
 
 
415
    def __repr__(self):
 
416
        return "%s(%r)" % \
 
417
            (self.__class__.__name__, self._filename)
 
418
 
 
419
    def add(self, path, file_id, kind, stat, fingerprint):
 
420
        """Add a path to be tracked.
 
421
 
 
422
        :param path: The path within the dirstate - '' is the root, 'foo' is the
 
423
            path foo within the root, 'foo/bar' is the path bar within foo
 
424
            within the root.
 
425
        :param file_id: The file id of the path being added.
 
426
        :param kind: The kind of the path, as a string like 'file',
 
427
            'directory', etc.
 
428
        :param stat: The output of os.lstat for the path.
 
429
        :param fingerprint: The sha value of the file's canonical form (i.e.
 
430
            after any read filters have been applied),
 
431
            or the target of a symlink,
 
432
            or the referenced revision id for tree-references,
 
433
            or '' for directories.
 
434
        """
 
435
        # adding a file:
 
436
        # find the block its in.
 
437
        # find the location in the block.
 
438
        # check its not there
 
439
        # add it.
 
440
        #------- copied from inventory.ensure_normalized_name - keep synced.
 
441
        # --- normalized_filename wants a unicode basename only, so get one.
 
442
        dirname, basename = osutils.split(path)
 
443
        # we dont import normalized_filename directly because we want to be
 
444
        # able to change the implementation at runtime for tests.
 
445
        norm_name, can_access = osutils.normalized_filename(basename)
 
446
        if norm_name != basename:
 
447
            if can_access:
 
448
                basename = norm_name
 
449
            else:
 
450
                raise errors.InvalidNormalization(path)
 
451
        # you should never have files called . or ..; just add the directory
 
452
        # in the parent, or according to the special treatment for the root
 
453
        if basename == '.' or basename == '..':
 
454
            raise errors.InvalidEntryName(path)
 
455
        # now that we've normalised, we need the correct utf8 path and
 
456
        # dirname and basename elements. This single encode and split should be
 
457
        # faster than three separate encodes.
 
458
        utf8path = (dirname + '/' + basename).strip('/').encode('utf8')
 
459
        dirname, basename = osutils.split(utf8path)
 
460
        # uses __class__ for speed; the check is needed for safety
 
461
        if file_id.__class__ is not str:
 
462
            raise AssertionError(
 
463
                "must be a utf8 file_id not %s" % (type(file_id), ))
 
464
        # Make sure the file_id does not exist in this tree
 
465
        rename_from = None
 
466
        file_id_entry = self._get_entry(0, fileid_utf8=file_id, include_deleted=True)
 
467
        if file_id_entry != (None, None):
 
468
            if file_id_entry[1][0][0] == 'a':
 
469
                if file_id_entry[0] != (dirname, basename, file_id):
 
470
                    # set the old name's current operation to rename
 
471
                    self.update_minimal(file_id_entry[0],
 
472
                        'r',
 
473
                        path_utf8='',
 
474
                        packed_stat='',
 
475
                        fingerprint=utf8path
 
476
                    )
 
477
                    rename_from = file_id_entry[0][0:2]
 
478
            else:
 
479
                path = osutils.pathjoin(file_id_entry[0][0], file_id_entry[0][1])
 
480
                kind = DirState._minikind_to_kind[file_id_entry[1][0][0]]
 
481
                info = '%s:%s' % (kind, path)
 
482
                raise errors.DuplicateFileId(file_id, info)
 
483
        first_key = (dirname, basename, '')
 
484
        block_index, present = self._find_block_index_from_key(first_key)
 
485
        if present:
 
486
            # check the path is not in the tree
 
487
            block = self._dirblocks[block_index][1]
 
488
            entry_index, _ = self._find_entry_index(first_key, block)
 
489
            while (entry_index < len(block) and
 
490
                block[entry_index][0][0:2] == first_key[0:2]):
 
491
                if block[entry_index][1][0][0] not in 'ar':
 
492
                    # this path is in the dirstate in the current tree.
 
493
                    raise Exception, "adding already added path!"
 
494
                entry_index += 1
 
495
        else:
 
496
            # The block where we want to put the file is not present. But it
 
497
            # might be because the directory was empty, or not loaded yet. Look
 
498
            # for a parent entry, if not found, raise NotVersionedError
 
499
            parent_dir, parent_base = osutils.split(dirname)
 
500
            parent_block_idx, parent_entry_idx, _, parent_present = \
 
501
                self._get_block_entry_index(parent_dir, parent_base, 0)
 
502
            if not parent_present:
 
503
                raise errors.NotVersionedError(path, str(self))
 
504
            self._ensure_block(parent_block_idx, parent_entry_idx, dirname)
 
505
        block = self._dirblocks[block_index][1]
 
506
        entry_key = (dirname, basename, file_id)
 
507
        if stat is None:
 
508
            size = 0
 
509
            packed_stat = DirState.NULLSTAT
 
510
        else:
 
511
            size = stat.st_size
 
512
            packed_stat = pack_stat(stat)
 
513
        parent_info = self._empty_parent_info()
 
514
        minikind = DirState._kind_to_minikind[kind]
 
515
        if rename_from is not None:
 
516
            if rename_from[0]:
 
517
                old_path_utf8 = '%s/%s' % rename_from
 
518
            else:
 
519
                old_path_utf8 = rename_from[1]
 
520
            parent_info[0] = ('r', old_path_utf8, 0, False, '')
 
521
        if kind == 'file':
 
522
            entry_data = entry_key, [
 
523
                (minikind, fingerprint, size, False, packed_stat),
 
524
                ] + parent_info
 
525
        elif kind == 'directory':
 
526
            entry_data = entry_key, [
 
527
                (minikind, '', 0, False, packed_stat),
 
528
                ] + parent_info
 
529
        elif kind == 'symlink':
 
530
            entry_data = entry_key, [
 
531
                (minikind, fingerprint, size, False, packed_stat),
 
532
                ] + parent_info
 
533
        elif kind == 'tree-reference':
 
534
            entry_data = entry_key, [
 
535
                (minikind, fingerprint, 0, False, packed_stat),
 
536
                ] + parent_info
 
537
        else:
 
538
            raise errors.BzrError('unknown kind %r' % kind)
 
539
        entry_index, present = self._find_entry_index(entry_key, block)
 
540
        if not present:
 
541
            block.insert(entry_index, entry_data)
 
542
        else:
 
543
            if block[entry_index][1][0][0] != 'a':
 
544
                raise AssertionError(" %r(%r) already added" % (basename, file_id))
 
545
            block[entry_index][1][0] = entry_data[1][0]
 
546
 
 
547
        if kind == 'directory':
 
548
           # insert a new dirblock
 
549
           self._ensure_block(block_index, entry_index, utf8path)
 
550
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
551
        if self._id_index:
 
552
            self._add_to_id_index(self._id_index, entry_key)
 
553
 
 
554
    def _bisect(self, paths):
 
555
        """Bisect through the disk structure for specific rows.
 
556
 
 
557
        :param paths: A list of paths to find
 
558
        :return: A dict mapping path => entries for found entries. Missing
 
559
                 entries will not be in the map.
 
560
                 The list is not sorted, and entries will be populated
 
561
                 based on when they were read.
 
562
        """
 
563
        self._requires_lock()
 
564
        # We need the file pointer to be right after the initial header block
 
565
        self._read_header_if_needed()
 
566
        # If _dirblock_state was in memory, we should just return info from
 
567
        # there, this function is only meant to handle when we want to read
 
568
        # part of the disk.
 
569
        if self._dirblock_state != DirState.NOT_IN_MEMORY:
 
570
            raise AssertionError("bad dirblock state %r" % self._dirblock_state)
 
571
 
 
572
        # The disk representation is generally info + '\0\n\0' at the end. But
 
573
        # for bisecting, it is easier to treat this as '\0' + info + '\0\n'
 
574
        # Because it means we can sync on the '\n'
 
575
        state_file = self._state_file
 
576
        file_size = os.fstat(state_file.fileno()).st_size
 
577
        # We end up with 2 extra fields, we should have a trailing '\n' to
 
578
        # ensure that we read the whole record, and we should have a precursur
 
579
        # '' which ensures that we start after the previous '\n'
 
580
        entry_field_count = self._fields_per_entry() + 1
 
581
 
 
582
        low = self._end_of_header
 
583
        high = file_size - 1 # Ignore the final '\0'
 
584
        # Map from (dir, name) => entry
 
585
        found = {}
 
586
 
 
587
        # Avoid infinite seeking
 
588
        max_count = 30*len(paths)
 
589
        count = 0
 
590
        # pending is a list of places to look.
 
591
        # each entry is a tuple of low, high, dir_names
 
592
        #   low -> the first byte offset to read (inclusive)
 
593
        #   high -> the last byte offset (inclusive)
 
594
        #   dir_names -> The list of (dir, name) pairs that should be found in
 
595
        #                the [low, high] range
 
596
        pending = [(low, high, paths)]
 
597
 
 
598
        page_size = self._bisect_page_size
 
599
 
 
600
        fields_to_entry = self._get_fields_to_entry()
 
601
 
 
602
        while pending:
 
603
            low, high, cur_files = pending.pop()
 
604
 
 
605
            if not cur_files or low >= high:
 
606
                # Nothing to find
 
607
                continue
 
608
 
 
609
            count += 1
 
610
            if count > max_count:
 
611
                raise errors.BzrError('Too many seeks, most likely a bug.')
 
612
 
 
613
            mid = max(low, (low+high-page_size)/2)
 
614
 
 
615
            state_file.seek(mid)
 
616
            # limit the read size, so we don't end up reading data that we have
 
617
            # already read.
 
618
            read_size = min(page_size, (high-mid)+1)
 
619
            block = state_file.read(read_size)
 
620
 
 
621
            start = mid
 
622
            entries = block.split('\n')
 
623
 
 
624
            if len(entries) < 2:
 
625
                # We didn't find a '\n', so we cannot have found any records.
 
626
                # So put this range back and try again. But we know we have to
 
627
                # increase the page size, because a single read did not contain
 
628
                # a record break (so records must be larger than page_size)
 
629
                page_size *= 2
 
630
                pending.append((low, high, cur_files))
 
631
                continue
 
632
 
 
633
            # Check the first and last entries, in case they are partial, or if
 
634
            # we don't care about the rest of this page
 
635
            first_entry_num = 0
 
636
            first_fields = entries[0].split('\0')
 
637
            if len(first_fields) < entry_field_count:
 
638
                # We didn't get the complete first entry
 
639
                # so move start, and grab the next, which
 
640
                # should be a full entry
 
641
                start += len(entries[0])+1
 
642
                first_fields = entries[1].split('\0')
 
643
                first_entry_num = 1
 
644
 
 
645
            if len(first_fields) <= 2:
 
646
                # We didn't even get a filename here... what do we do?
 
647
                # Try a large page size and repeat this query
 
648
                page_size *= 2
 
649
                pending.append((low, high, cur_files))
 
650
                continue
 
651
            else:
 
652
                # Find what entries we are looking for, which occur before and
 
653
                # after this first record.
 
654
                after = start
 
655
                if first_fields[1]:
 
656
                    first_path = first_fields[1] + '/' + first_fields[2]
 
657
                else:
 
658
                    first_path = first_fields[2]
 
659
                first_loc = _bisect_path_left(cur_files, first_path)
 
660
 
 
661
                # These exist before the current location
 
662
                pre = cur_files[:first_loc]
 
663
                # These occur after the current location, which may be in the
 
664
                # data we read, or might be after the last entry
 
665
                post = cur_files[first_loc:]
 
666
 
 
667
            if post and len(first_fields) >= entry_field_count:
 
668
                # We have files after the first entry
 
669
 
 
670
                # Parse the last entry
 
671
                last_entry_num = len(entries)-1
 
672
                last_fields = entries[last_entry_num].split('\0')
 
673
                if len(last_fields) < entry_field_count:
 
674
                    # The very last hunk was not complete,
 
675
                    # read the previous hunk
 
676
                    after = mid + len(block) - len(entries[-1])
 
677
                    last_entry_num -= 1
 
678
                    last_fields = entries[last_entry_num].split('\0')
 
679
                else:
 
680
                    after = mid + len(block)
 
681
 
 
682
                if last_fields[1]:
 
683
                    last_path = last_fields[1] + '/' + last_fields[2]
 
684
                else:
 
685
                    last_path = last_fields[2]
 
686
                last_loc = _bisect_path_right(post, last_path)
 
687
 
 
688
                middle_files = post[:last_loc]
 
689
                post = post[last_loc:]
 
690
 
 
691
                if middle_files:
 
692
                    # We have files that should occur in this block
 
693
                    # (>= first, <= last)
 
694
                    # Either we will find them here, or we can mark them as
 
695
                    # missing.
 
696
 
 
697
                    if middle_files[0] == first_path:
 
698
                        # We might need to go before this location
 
699
                        pre.append(first_path)
 
700
                    if middle_files[-1] == last_path:
 
701
                        post.insert(0, last_path)
 
702
 
 
703
                    # Find out what paths we have
 
704
                    paths = {first_path:[first_fields]}
 
705
                    # last_path might == first_path so we need to be
 
706
                    # careful if we should append rather than overwrite
 
707
                    if last_entry_num != first_entry_num:
 
708
                        paths.setdefault(last_path, []).append(last_fields)
 
709
                    for num in xrange(first_entry_num+1, last_entry_num):
 
710
                        # TODO: jam 20070223 We are already splitting here, so
 
711
                        #       shouldn't we just split the whole thing rather
 
712
                        #       than doing the split again in add_one_record?
 
713
                        fields = entries[num].split('\0')
 
714
                        if fields[1]:
 
715
                            path = fields[1] + '/' + fields[2]
 
716
                        else:
 
717
                            path = fields[2]
 
718
                        paths.setdefault(path, []).append(fields)
 
719
 
 
720
                    for path in middle_files:
 
721
                        for fields in paths.get(path, []):
 
722
                            # offset by 1 because of the opening '\0'
 
723
                            # consider changing fields_to_entry to avoid the
 
724
                            # extra list slice
 
725
                            entry = fields_to_entry(fields[1:])
 
726
                            found.setdefault(path, []).append(entry)
 
727
 
 
728
            # Now we have split up everything into pre, middle, and post, and
 
729
            # we have handled everything that fell in 'middle'.
 
730
            # We add 'post' first, so that we prefer to seek towards the
 
731
            # beginning, so that we will tend to go as early as we need, and
 
732
            # then only seek forward after that.
 
733
            if post:
 
734
                pending.append((after, high, post))
 
735
            if pre:
 
736
                pending.append((low, start-1, pre))
 
737
 
 
738
        # Consider that we may want to return the directory entries in sorted
 
739
        # order. For now, we just return them in whatever order we found them,
 
740
        # and leave it up to the caller if they care if it is ordered or not.
 
741
        return found
 
742
 
 
743
    def _bisect_dirblocks(self, dir_list):
 
744
        """Bisect through the disk structure to find entries in given dirs.
 
745
 
 
746
        _bisect_dirblocks is meant to find the contents of directories, which
 
747
        differs from _bisect, which only finds individual entries.
 
748
 
 
749
        :param dir_list: A sorted list of directory names ['', 'dir', 'foo'].
 
750
        :return: A map from dir => entries_for_dir
 
751
        """
 
752
        # TODO: jam 20070223 A lot of the bisecting logic could be shared
 
753
        #       between this and _bisect. It would require parameterizing the
 
754
        #       inner loop with a function, though. We should evaluate the
 
755
        #       performance difference.
 
756
        self._requires_lock()
 
757
        # We need the file pointer to be right after the initial header block
 
758
        self._read_header_if_needed()
 
759
        # If _dirblock_state was in memory, we should just return info from
 
760
        # there, this function is only meant to handle when we want to read
 
761
        # part of the disk.
 
762
        if self._dirblock_state != DirState.NOT_IN_MEMORY:
 
763
            raise AssertionError("bad dirblock state %r" % self._dirblock_state)
 
764
        # The disk representation is generally info + '\0\n\0' at the end. But
 
765
        # for bisecting, it is easier to treat this as '\0' + info + '\0\n'
 
766
        # Because it means we can sync on the '\n'
 
767
        state_file = self._state_file
 
768
        file_size = os.fstat(state_file.fileno()).st_size
 
769
        # We end up with 2 extra fields, we should have a trailing '\n' to
 
770
        # ensure that we read the whole record, and we should have a precursur
 
771
        # '' which ensures that we start after the previous '\n'
 
772
        entry_field_count = self._fields_per_entry() + 1
 
773
 
 
774
        low = self._end_of_header
 
775
        high = file_size - 1 # Ignore the final '\0'
 
776
        # Map from dir => entry
 
777
        found = {}
 
778
 
 
779
        # Avoid infinite seeking
 
780
        max_count = 30*len(dir_list)
 
781
        count = 0
 
782
        # pending is a list of places to look.
 
783
        # each entry is a tuple of low, high, dir_names
 
784
        #   low -> the first byte offset to read (inclusive)
 
785
        #   high -> the last byte offset (inclusive)
 
786
        #   dirs -> The list of directories that should be found in
 
787
        #                the [low, high] range
 
788
        pending = [(low, high, dir_list)]
 
789
 
 
790
        page_size = self._bisect_page_size
 
791
 
 
792
        fields_to_entry = self._get_fields_to_entry()
 
793
 
 
794
        while pending:
 
795
            low, high, cur_dirs = pending.pop()
 
796
 
 
797
            if not cur_dirs or low >= high:
 
798
                # Nothing to find
 
799
                continue
 
800
 
 
801
            count += 1
 
802
            if count > max_count:
 
803
                raise errors.BzrError('Too many seeks, most likely a bug.')
 
804
 
 
805
            mid = max(low, (low+high-page_size)/2)
 
806
 
 
807
            state_file.seek(mid)
 
808
            # limit the read size, so we don't end up reading data that we have
 
809
            # already read.
 
810
            read_size = min(page_size, (high-mid)+1)
 
811
            block = state_file.read(read_size)
 
812
 
 
813
            start = mid
 
814
            entries = block.split('\n')
 
815
 
 
816
            if len(entries) < 2:
 
817
                # We didn't find a '\n', so we cannot have found any records.
 
818
                # So put this range back and try again. But we know we have to
 
819
                # increase the page size, because a single read did not contain
 
820
                # a record break (so records must be larger than page_size)
 
821
                page_size *= 2
 
822
                pending.append((low, high, cur_dirs))
 
823
                continue
 
824
 
 
825
            # Check the first and last entries, in case they are partial, or if
 
826
            # we don't care about the rest of this page
 
827
            first_entry_num = 0
 
828
            first_fields = entries[0].split('\0')
 
829
            if len(first_fields) < entry_field_count:
 
830
                # We didn't get the complete first entry
 
831
                # so move start, and grab the next, which
 
832
                # should be a full entry
 
833
                start += len(entries[0])+1
 
834
                first_fields = entries[1].split('\0')
 
835
                first_entry_num = 1
 
836
 
 
837
            if len(first_fields) <= 1:
 
838
                # We didn't even get a dirname here... what do we do?
 
839
                # Try a large page size and repeat this query
 
840
                page_size *= 2
 
841
                pending.append((low, high, cur_dirs))
 
842
                continue
 
843
            else:
 
844
                # Find what entries we are looking for, which occur before and
 
845
                # after this first record.
 
846
                after = start
 
847
                first_dir = first_fields[1]
 
848
                first_loc = bisect.bisect_left(cur_dirs, first_dir)
 
849
 
 
850
                # These exist before the current location
 
851
                pre = cur_dirs[:first_loc]
 
852
                # These occur after the current location, which may be in the
 
853
                # data we read, or might be after the last entry
 
854
                post = cur_dirs[first_loc:]
 
855
 
 
856
            if post and len(first_fields) >= entry_field_count:
 
857
                # We have records to look at after the first entry
 
858
 
 
859
                # Parse the last entry
 
860
                last_entry_num = len(entries)-1
 
861
                last_fields = entries[last_entry_num].split('\0')
 
862
                if len(last_fields) < entry_field_count:
 
863
                    # The very last hunk was not complete,
 
864
                    # read the previous hunk
 
865
                    after = mid + len(block) - len(entries[-1])
 
866
                    last_entry_num -= 1
 
867
                    last_fields = entries[last_entry_num].split('\0')
 
868
                else:
 
869
                    after = mid + len(block)
 
870
 
 
871
                last_dir = last_fields[1]
 
872
                last_loc = bisect.bisect_right(post, last_dir)
 
873
 
 
874
                middle_files = post[:last_loc]
 
875
                post = post[last_loc:]
 
876
 
 
877
                if middle_files:
 
878
                    # We have files that should occur in this block
 
879
                    # (>= first, <= last)
 
880
                    # Either we will find them here, or we can mark them as
 
881
                    # missing.
 
882
 
 
883
                    if middle_files[0] == first_dir:
 
884
                        # We might need to go before this location
 
885
                        pre.append(first_dir)
 
886
                    if middle_files[-1] == last_dir:
 
887
                        post.insert(0, last_dir)
 
888
 
 
889
                    # Find out what paths we have
 
890
                    paths = {first_dir:[first_fields]}
 
891
                    # last_dir might == first_dir so we need to be
 
892
                    # careful if we should append rather than overwrite
 
893
                    if last_entry_num != first_entry_num:
 
894
                        paths.setdefault(last_dir, []).append(last_fields)
 
895
                    for num in xrange(first_entry_num+1, last_entry_num):
 
896
                        # TODO: jam 20070223 We are already splitting here, so
 
897
                        #       shouldn't we just split the whole thing rather
 
898
                        #       than doing the split again in add_one_record?
 
899
                        fields = entries[num].split('\0')
 
900
                        paths.setdefault(fields[1], []).append(fields)
 
901
 
 
902
                    for cur_dir in middle_files:
 
903
                        for fields in paths.get(cur_dir, []):
 
904
                            # offset by 1 because of the opening '\0'
 
905
                            # consider changing fields_to_entry to avoid the
 
906
                            # extra list slice
 
907
                            entry = fields_to_entry(fields[1:])
 
908
                            found.setdefault(cur_dir, []).append(entry)
 
909
 
 
910
            # Now we have split up everything into pre, middle, and post, and
 
911
            # we have handled everything that fell in 'middle'.
 
912
            # We add 'post' first, so that we prefer to seek towards the
 
913
            # beginning, so that we will tend to go as early as we need, and
 
914
            # then only seek forward after that.
 
915
            if post:
 
916
                pending.append((after, high, post))
 
917
            if pre:
 
918
                pending.append((low, start-1, pre))
 
919
 
 
920
        return found
 
921
 
 
922
    def _bisect_recursive(self, paths):
 
923
        """Bisect for entries for all paths and their children.
 
924
 
 
925
        This will use bisect to find all records for the supplied paths. It
 
926
        will then continue to bisect for any records which are marked as
 
927
        directories. (and renames?)
 
928
 
 
929
        :param paths: A sorted list of (dir, name) pairs
 
930
             eg: [('', 'a'), ('', 'f'), ('a/b', 'c')]
 
931
        :return: A dictionary mapping (dir, name, file_id) => [tree_info]
 
932
        """
 
933
        # Map from (dir, name, file_id) => [tree_info]
 
934
        found = {}
 
935
 
 
936
        found_dir_names = set()
 
937
 
 
938
        # Directories that have been read
 
939
        processed_dirs = set()
 
940
        # Get the ball rolling with the first bisect for all entries.
 
941
        newly_found = self._bisect(paths)
 
942
 
 
943
        while newly_found:
 
944
            # Directories that need to be read
 
945
            pending_dirs = set()
 
946
            paths_to_search = set()
 
947
            for entry_list in newly_found.itervalues():
 
948
                for dir_name_id, trees_info in entry_list:
 
949
                    found[dir_name_id] = trees_info
 
950
                    found_dir_names.add(dir_name_id[:2])
 
951
                    is_dir = False
 
952
                    for tree_info in trees_info:
 
953
                        minikind = tree_info[0]
 
954
                        if minikind == 'd':
 
955
                            if is_dir:
 
956
                                # We already processed this one as a directory,
 
957
                                # we don't need to do the extra work again.
 
958
                                continue
 
959
                            subdir, name, file_id = dir_name_id
 
960
                            path = osutils.pathjoin(subdir, name)
 
961
                            is_dir = True
 
962
                            if path not in processed_dirs:
 
963
                                pending_dirs.add(path)
 
964
                        elif minikind == 'r':
 
965
                            # Rename, we need to directly search the target
 
966
                            # which is contained in the fingerprint column
 
967
                            dir_name = osutils.split(tree_info[1])
 
968
                            if dir_name[0] in pending_dirs:
 
969
                                # This entry will be found in the dir search
 
970
                                continue
 
971
                            if dir_name not in found_dir_names:
 
972
                                paths_to_search.add(tree_info[1])
 
973
            # Now we have a list of paths to look for directly, and
 
974
            # directory blocks that need to be read.
 
975
            # newly_found is mixing the keys between (dir, name) and path
 
976
            # entries, but that is okay, because we only really care about the
 
977
            # targets.
 
978
            newly_found = self._bisect(sorted(paths_to_search))
 
979
            newly_found.update(self._bisect_dirblocks(sorted(pending_dirs)))
 
980
            processed_dirs.update(pending_dirs)
 
981
        return found
 
982
 
 
983
    def _discard_merge_parents(self):
 
984
        """Discard any parents trees beyond the first.
 
985
 
 
986
        Note that if this fails the dirstate is corrupted.
 
987
 
 
988
        After this function returns the dirstate contains 2 trees, neither of
 
989
        which are ghosted.
 
990
        """
 
991
        self._read_header_if_needed()
 
992
        parents = self.get_parent_ids()
 
993
        if len(parents) < 1:
 
994
            return
 
995
        # only require all dirblocks if we are doing a full-pass removal.
 
996
        self._read_dirblocks_if_needed()
 
997
        dead_patterns = set([('a', 'r'), ('a', 'a'), ('r', 'r'), ('r', 'a')])
 
998
        def iter_entries_removable():
 
999
            for block in self._dirblocks:
 
1000
                deleted_positions = []
 
1001
                for pos, entry in enumerate(block[1]):
 
1002
                    yield entry
 
1003
                    if (entry[1][0][0], entry[1][1][0]) in dead_patterns:
 
1004
                        deleted_positions.append(pos)
 
1005
                if deleted_positions:
 
1006
                    if len(deleted_positions) == len(block[1]):
 
1007
                        del block[1][:]
 
1008
                    else:
 
1009
                        for pos in reversed(deleted_positions):
 
1010
                            del block[1][pos]
 
1011
        # if the first parent is a ghost:
 
1012
        if parents[0] in self.get_ghosts():
 
1013
            empty_parent = [DirState.NULL_PARENT_DETAILS]
 
1014
            for entry in iter_entries_removable():
 
1015
                entry[1][1:] = empty_parent
 
1016
        else:
 
1017
            for entry in iter_entries_removable():
 
1018
                del entry[1][2:]
 
1019
 
 
1020
        self._ghosts = []
 
1021
        self._parents = [parents[0]]
 
1022
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
1023
        self._header_state = DirState.IN_MEMORY_MODIFIED
 
1024
 
 
1025
    def _empty_parent_info(self):
 
1026
        return [DirState.NULL_PARENT_DETAILS] * (len(self._parents) -
 
1027
                                                    len(self._ghosts))
 
1028
 
 
1029
    def _ensure_block(self, parent_block_index, parent_row_index, dirname):
 
1030
        """Ensure a block for dirname exists.
 
1031
 
 
1032
        This function exists to let callers which know that there is a
 
1033
        directory dirname ensure that the block for it exists. This block can
 
1034
        fail to exist because of demand loading, or because a directory had no
 
1035
        children. In either case it is not an error. It is however an error to
 
1036
        call this if there is no parent entry for the directory, and thus the
 
1037
        function requires the coordinates of such an entry to be provided.
 
1038
 
 
1039
        The root row is special cased and can be indicated with a parent block
 
1040
        and row index of -1
 
1041
 
 
1042
        :param parent_block_index: The index of the block in which dirname's row
 
1043
            exists.
 
1044
        :param parent_row_index: The index in the parent block where the row
 
1045
            exists.
 
1046
        :param dirname: The utf8 dirname to ensure there is a block for.
 
1047
        :return: The index for the block.
 
1048
        """
 
1049
        if dirname == '' and parent_row_index == 0 and parent_block_index == 0:
 
1050
            # This is the signature of the root row, and the
 
1051
            # contents-of-root row is always index 1
 
1052
            return 1
 
1053
        # the basename of the directory must be the end of its full name.
 
1054
        if not (parent_block_index == -1 and
 
1055
            parent_block_index == -1 and dirname == ''):
 
1056
            if not dirname.endswith(
 
1057
                    self._dirblocks[parent_block_index][1][parent_row_index][0][1]):
 
1058
                raise AssertionError("bad dirname %r" % dirname)
 
1059
        block_index, present = self._find_block_index_from_key((dirname, '', ''))
 
1060
        if not present:
 
1061
            ## In future, when doing partial parsing, this should load and
 
1062
            # populate the entire block.
 
1063
            self._dirblocks.insert(block_index, (dirname, []))
 
1064
        return block_index
 
1065
 
 
1066
    def _entries_to_current_state(self, new_entries):
 
1067
        """Load new_entries into self.dirblocks.
 
1068
 
 
1069
        Process new_entries into the current state object, making them the active
 
1070
        state.  The entries are grouped together by directory to form dirblocks.
 
1071
 
 
1072
        :param new_entries: A sorted list of entries. This function does not sort
 
1073
            to prevent unneeded overhead when callers have a sorted list already.
 
1074
        :return: Nothing.
 
1075
        """
 
1076
        if new_entries[0][0][0:2] != ('', ''):
 
1077
            raise AssertionError(
 
1078
                "Missing root row %r" % (new_entries[0][0],))
 
1079
        # The two blocks here are deliberate: the root block and the
 
1080
        # contents-of-root block.
 
1081
        self._dirblocks = [('', []), ('', [])]
 
1082
        current_block = self._dirblocks[0][1]
 
1083
        current_dirname = ''
 
1084
        root_key = ('', '')
 
1085
        append_entry = current_block.append
 
1086
        for entry in new_entries:
 
1087
            if entry[0][0] != current_dirname:
 
1088
                # new block - different dirname
 
1089
                current_block = []
 
1090
                current_dirname = entry[0][0]
 
1091
                self._dirblocks.append((current_dirname, current_block))
 
1092
                append_entry = current_block.append
 
1093
            # append the entry to the current block
 
1094
            append_entry(entry)
 
1095
        self._split_root_dirblock_into_contents()
 
1096
 
 
1097
    def _split_root_dirblock_into_contents(self):
 
1098
        """Split the root dirblocks into root and contents-of-root.
 
1099
 
 
1100
        After parsing by path, we end up with root entries and contents-of-root
 
1101
        entries in the same block. This loop splits them out again.
 
1102
        """
 
1103
        # The above loop leaves the "root block" entries mixed with the
 
1104
        # "contents-of-root block". But we don't want an if check on
 
1105
        # all entries, so instead we just fix it up here.
 
1106
        if self._dirblocks[1] != ('', []):
 
1107
            raise ValueError("bad dirblock start %r" % (self._dirblocks[1],))
 
1108
        root_block = []
 
1109
        contents_of_root_block = []
 
1110
        for entry in self._dirblocks[0][1]:
 
1111
            if not entry[0][1]: # This is a root entry
 
1112
                root_block.append(entry)
 
1113
            else:
 
1114
                contents_of_root_block.append(entry)
 
1115
        self._dirblocks[0] = ('', root_block)
 
1116
        self._dirblocks[1] = ('', contents_of_root_block)
 
1117
 
 
1118
    def _entries_for_path(self, path):
 
1119
        """Return a list with all the entries that match path for all ids."""
 
1120
        dirname, basename = os.path.split(path)
 
1121
        key = (dirname, basename, '')
 
1122
        block_index, present = self._find_block_index_from_key(key)
 
1123
        if not present:
 
1124
            # the block which should contain path is absent.
 
1125
            return []
 
1126
        result = []
 
1127
        block = self._dirblocks[block_index][1]
 
1128
        entry_index, _ = self._find_entry_index(key, block)
 
1129
        # we may need to look at multiple entries at this path: walk while the specific_files match.
 
1130
        while (entry_index < len(block) and
 
1131
            block[entry_index][0][0:2] == key[0:2]):
 
1132
            result.append(block[entry_index])
 
1133
            entry_index += 1
 
1134
        return result
 
1135
 
 
1136
    def _entry_to_line(self, entry):
 
1137
        """Serialize entry to a NULL delimited line ready for _get_output_lines.
 
1138
 
 
1139
        :param entry: An entry_tuple as defined in the module docstring.
 
1140
        """
 
1141
        entire_entry = list(entry[0])
 
1142
        for tree_number, tree_data in enumerate(entry[1]):
 
1143
            # (minikind, fingerprint, size, executable, tree_specific_string)
 
1144
            entire_entry.extend(tree_data)
 
1145
            # 3 for the key, 5 for the fields per tree.
 
1146
            tree_offset = 3 + tree_number * 5
 
1147
            # minikind
 
1148
            entire_entry[tree_offset + 0] = tree_data[0]
 
1149
            # size
 
1150
            entire_entry[tree_offset + 2] = str(tree_data[2])
 
1151
            # executable
 
1152
            entire_entry[tree_offset + 3] = DirState._to_yesno[tree_data[3]]
 
1153
        return '\0'.join(entire_entry)
 
1154
 
 
1155
    def _fields_per_entry(self):
 
1156
        """How many null separated fields should be in each entry row.
 
1157
 
 
1158
        Each line now has an extra '\n' field which is not used
 
1159
        so we just skip over it
 
1160
        entry size:
 
1161
            3 fields for the key
 
1162
            + number of fields per tree_data (5) * tree count
 
1163
            + newline
 
1164
         """
 
1165
        tree_count = 1 + self._num_present_parents()
 
1166
        return 3 + 5 * tree_count + 1
 
1167
 
 
1168
    def _find_block(self, key, add_if_missing=False):
 
1169
        """Return the block that key should be present in.
 
1170
 
 
1171
        :param key: A dirstate entry key.
 
1172
        :return: The block tuple.
 
1173
        """
 
1174
        block_index, present = self._find_block_index_from_key(key)
 
1175
        if not present:
 
1176
            if not add_if_missing:
 
1177
                # check to see if key is versioned itself - we might want to
 
1178
                # add it anyway, because dirs with no entries dont get a
 
1179
                # dirblock at parse time.
 
1180
                # This is an uncommon branch to take: most dirs have children,
 
1181
                # and most code works with versioned paths.
 
1182
                parent_base, parent_name = osutils.split(key[0])
 
1183
                if not self._get_block_entry_index(parent_base, parent_name, 0)[3]:
 
1184
                    # some parent path has not been added - its an error to add
 
1185
                    # this child
 
1186
                    raise errors.NotVersionedError(key[0:2], str(self))
 
1187
            self._dirblocks.insert(block_index, (key[0], []))
 
1188
        return self._dirblocks[block_index]
 
1189
 
 
1190
    def _find_block_index_from_key(self, key):
 
1191
        """Find the dirblock index for a key.
 
1192
 
 
1193
        :return: The block index, True if the block for the key is present.
 
1194
        """
 
1195
        if key[0:2] == ('', ''):
 
1196
            return 0, True
 
1197
        try:
 
1198
            if (self._last_block_index is not None and
 
1199
                self._dirblocks[self._last_block_index][0] == key[0]):
 
1200
                return self._last_block_index, True
 
1201
        except IndexError:
 
1202
            pass
 
1203
        block_index = bisect_dirblock(self._dirblocks, key[0], 1,
 
1204
                                      cache=self._split_path_cache)
 
1205
        # _right returns one-past-where-key is so we have to subtract
 
1206
        # one to use it. we use _right here because there are two
 
1207
        # '' blocks - the root, and the contents of root
 
1208
        # we always have a minimum of 2 in self._dirblocks: root and
 
1209
        # root-contents, and for '', we get 2 back, so this is
 
1210
        # simple and correct:
 
1211
        present = (block_index < len(self._dirblocks) and
 
1212
            self._dirblocks[block_index][0] == key[0])
 
1213
        self._last_block_index = block_index
 
1214
        # Reset the entry index cache to the beginning of the block.
 
1215
        self._last_entry_index = -1
 
1216
        return block_index, present
 
1217
 
 
1218
    def _find_entry_index(self, key, block):
 
1219
        """Find the entry index for a key in a block.
 
1220
 
 
1221
        :return: The entry index, True if the entry for the key is present.
 
1222
        """
 
1223
        len_block = len(block)
 
1224
        try:
 
1225
            if self._last_entry_index is not None:
 
1226
                # mini-bisect here.
 
1227
                entry_index = self._last_entry_index + 1
 
1228
                # A hit is when the key is after the last slot, and before or
 
1229
                # equal to the next slot.
 
1230
                if ((entry_index > 0 and block[entry_index - 1][0] < key) and
 
1231
                    key <= block[entry_index][0]):
 
1232
                    self._last_entry_index = entry_index
 
1233
                    present = (block[entry_index][0] == key)
 
1234
                    return entry_index, present
 
1235
        except IndexError:
 
1236
            pass
 
1237
        entry_index = bisect.bisect_left(block, (key, []))
 
1238
        present = (entry_index < len_block and
 
1239
            block[entry_index][0] == key)
 
1240
        self._last_entry_index = entry_index
 
1241
        return entry_index, present
 
1242
 
 
1243
    @staticmethod
 
1244
    def from_tree(tree, dir_state_filename, sha1_provider=None):
 
1245
        """Create a dirstate from a bzr Tree.
 
1246
 
 
1247
        :param tree: The tree which should provide parent information and
 
1248
            inventory ids.
 
1249
        :param sha1_provider: an object meeting the SHA1Provider interface.
 
1250
            If None, a DefaultSHA1Provider is used.
 
1251
        :return: a DirState object which is currently locked for writing.
 
1252
            (it was locked by DirState.initialize)
 
1253
        """
 
1254
        result = DirState.initialize(dir_state_filename,
 
1255
            sha1_provider=sha1_provider)
 
1256
        try:
 
1257
            tree.lock_read()
 
1258
            try:
 
1259
                parent_ids = tree.get_parent_ids()
 
1260
                num_parents = len(parent_ids)
 
1261
                parent_trees = []
 
1262
                for parent_id in parent_ids:
 
1263
                    parent_tree = tree.branch.repository.revision_tree(parent_id)
 
1264
                    parent_trees.append((parent_id, parent_tree))
 
1265
                    parent_tree.lock_read()
 
1266
                result.set_parent_trees(parent_trees, [])
 
1267
                result.set_state_from_inventory(tree.inventory)
 
1268
            finally:
 
1269
                for revid, parent_tree in parent_trees:
 
1270
                    parent_tree.unlock()
 
1271
                tree.unlock()
 
1272
        except:
 
1273
            # The caller won't have a chance to unlock this, so make sure we
 
1274
            # cleanup ourselves
 
1275
            result.unlock()
 
1276
            raise
 
1277
        return result
 
1278
 
 
1279
    def update_by_delta(self, delta):
 
1280
        """Apply an inventory delta to the dirstate for tree 0
 
1281
 
 
1282
        This is the workhorse for apply_inventory_delta in dirstate based
 
1283
        trees.
 
1284
 
 
1285
        :param delta: An inventory delta.  See Inventory.apply_delta for
 
1286
            details.
 
1287
        """
 
1288
        self._read_dirblocks_if_needed()
 
1289
        encode = cache_utf8.encode
 
1290
        insertions = {}
 
1291
        removals = {}
 
1292
        # Accumulate parent references (path_utf8, id), to check for parentless
 
1293
        # items or items placed under files/links/tree-references. We get
 
1294
        # references from every item in the delta that is not a deletion and
 
1295
        # is not itself the root.
 
1296
        parents = set()
 
1297
        # Added ids must not be in the dirstate already. This set holds those
 
1298
        # ids.
 
1299
        new_ids = set()
 
1300
        # This loop transforms the delta to single atomic operations that can
 
1301
        # be executed and validated.
 
1302
        for old_path, new_path, file_id, inv_entry in sorted(
 
1303
            inventory._check_delta_unique_old_paths(
 
1304
            inventory._check_delta_unique_new_paths(
 
1305
            inventory._check_delta_ids_match_entry(
 
1306
            inventory._check_delta_ids_are_valid(
 
1307
            inventory._check_delta_new_path_entry_both_or_None(delta))))),
 
1308
            reverse=True):
 
1309
            if (file_id in insertions) or (file_id in removals):
 
1310
                raise errors.InconsistentDelta(old_path or new_path, file_id,
 
1311
                    "repeated file_id")
 
1312
            if old_path is not None:
 
1313
                old_path = old_path.encode('utf-8')
 
1314
                removals[file_id] = old_path
 
1315
            else:
 
1316
                new_ids.add(file_id)
 
1317
            if new_path is not None:
 
1318
                if inv_entry is None:
 
1319
                    raise errors.InconsistentDelta(new_path, file_id,
 
1320
                        "new_path with no entry")
 
1321
                new_path = new_path.encode('utf-8')
 
1322
                dirname_utf8, basename = osutils.split(new_path)
 
1323
                if basename:
 
1324
                    parents.add((dirname_utf8, inv_entry.parent_id))
 
1325
                key = (dirname_utf8, basename, file_id)
 
1326
                minikind = DirState._kind_to_minikind[inv_entry.kind]
 
1327
                if minikind == 't':
 
1328
                    fingerprint = inv_entry.reference_revision or ''
 
1329
                else:
 
1330
                    fingerprint = ''
 
1331
                insertions[file_id] = (key, minikind, inv_entry.executable,
 
1332
                                       fingerprint, new_path)
 
1333
            # Transform moves into delete+add pairs
 
1334
            if None not in (old_path, new_path):
 
1335
                for child in self._iter_child_entries(0, old_path):
 
1336
                    if child[0][2] in insertions or child[0][2] in removals:
 
1337
                        continue
 
1338
                    child_dirname = child[0][0]
 
1339
                    child_basename = child[0][1]
 
1340
                    minikind = child[1][0][0]
 
1341
                    fingerprint = child[1][0][4]
 
1342
                    executable = child[1][0][3]
 
1343
                    old_child_path = osutils.pathjoin(child_dirname,
 
1344
                                                      child_basename)
 
1345
                    removals[child[0][2]] = old_child_path
 
1346
                    child_suffix = child_dirname[len(old_path):]
 
1347
                    new_child_dirname = (new_path + child_suffix)
 
1348
                    key = (new_child_dirname, child_basename, child[0][2])
 
1349
                    new_child_path = osutils.pathjoin(new_child_dirname,
 
1350
                                                      child_basename)
 
1351
                    insertions[child[0][2]] = (key, minikind, executable,
 
1352
                                               fingerprint, new_child_path)
 
1353
        self._check_delta_ids_absent(new_ids, delta, 0)
 
1354
        try:
 
1355
            self._apply_removals(removals.iteritems())
 
1356
            self._apply_insertions(insertions.values())
 
1357
            # Validate parents
 
1358
            self._after_delta_check_parents(parents, 0)
 
1359
        except errors.BzrError, e:
 
1360
            self._changes_aborted = True
 
1361
            if 'integrity error' not in str(e):
 
1362
                raise
 
1363
            # _get_entry raises BzrError when a request is inconsistent; we
 
1364
            # want such errors to be shown as InconsistentDelta - and that 
 
1365
            # fits the behaviour we trigger.
 
1366
            raise errors.InconsistentDeltaDelta(delta, "error from _get_entry.")
 
1367
 
 
1368
    def _apply_removals(self, removals):
 
1369
        for file_id, path in sorted(removals, reverse=True,
 
1370
            key=operator.itemgetter(1)):
 
1371
            dirname, basename = osutils.split(path)
 
1372
            block_i, entry_i, d_present, f_present = \
 
1373
                self._get_block_entry_index(dirname, basename, 0)
 
1374
            try:
 
1375
                entry = self._dirblocks[block_i][1][entry_i]
 
1376
            except IndexError:
 
1377
                self._changes_aborted = True
 
1378
                raise errors.InconsistentDelta(path, file_id,
 
1379
                    "Wrong path for old path.")
 
1380
            if not f_present or entry[1][0][0] in 'ar':
 
1381
                self._changes_aborted = True
 
1382
                raise errors.InconsistentDelta(path, file_id,
 
1383
                    "Wrong path for old path.")
 
1384
            if file_id != entry[0][2]:
 
1385
                self._changes_aborted = True
 
1386
                raise errors.InconsistentDelta(path, file_id,
 
1387
                    "Attempt to remove path has wrong id - found %r."
 
1388
                    % entry[0][2])
 
1389
            self._make_absent(entry)
 
1390
            # See if we have a malformed delta: deleting a directory must not
 
1391
            # leave crud behind. This increases the number of bisects needed
 
1392
            # substantially, but deletion or renames of large numbers of paths
 
1393
            # is rare enough it shouldn't be an issue (famous last words?) RBC
 
1394
            # 20080730.
 
1395
            block_i, entry_i, d_present, f_present = \
 
1396
                self._get_block_entry_index(path, '', 0)
 
1397
            if d_present:
 
1398
                # The dir block is still present in the dirstate; this could
 
1399
                # be due to it being in a parent tree, or a corrupt delta.
 
1400
                for child_entry in self._dirblocks[block_i][1]:
 
1401
                    if child_entry[1][0][0] not in ('r', 'a'):
 
1402
                        self._changes_aborted = True
 
1403
                        raise errors.InconsistentDelta(path, entry[0][2],
 
1404
                            "The file id was deleted but its children were "
 
1405
                            "not deleted.")
 
1406
 
 
1407
    def _apply_insertions(self, adds):
 
1408
        try:
 
1409
            for key, minikind, executable, fingerprint, path_utf8 in sorted(adds):
 
1410
                self.update_minimal(key, minikind, executable, fingerprint,
 
1411
                                    path_utf8=path_utf8)
 
1412
        except errors.NotVersionedError:
 
1413
            self._changes_aborted = True
 
1414
            raise errors.InconsistentDelta(path_utf8.decode('utf8'), key[2],
 
1415
                "Missing parent")
 
1416
 
 
1417
    def update_basis_by_delta(self, delta, new_revid):
 
1418
        """Update the parents of this tree after a commit.
 
1419
 
 
1420
        This gives the tree one parent, with revision id new_revid. The
 
1421
        inventory delta is applied to the current basis tree to generate the
 
1422
        inventory for the parent new_revid, and all other parent trees are
 
1423
        discarded.
 
1424
 
 
1425
        Note that an exception during the operation of this method will leave
 
1426
        the dirstate in a corrupt state where it should not be saved.
 
1427
 
 
1428
        Finally, we expect all changes to be synchronising the basis tree with
 
1429
        the working tree.
 
1430
 
 
1431
        :param new_revid: The new revision id for the trees parent.
 
1432
        :param delta: An inventory delta (see apply_inventory_delta) describing
 
1433
            the changes from the current left most parent revision to new_revid.
 
1434
        """
 
1435
        self._read_dirblocks_if_needed()
 
1436
        self._discard_merge_parents()
 
1437
        if self._ghosts != []:
 
1438
            raise NotImplementedError(self.update_basis_by_delta)
 
1439
        if len(self._parents) == 0:
 
1440
            # setup a blank tree, the most simple way.
 
1441
            empty_parent = DirState.NULL_PARENT_DETAILS
 
1442
            for entry in self._iter_entries():
 
1443
                entry[1].append(empty_parent)
 
1444
            self._parents.append(new_revid)
 
1445
 
 
1446
        self._parents[0] = new_revid
 
1447
 
 
1448
        delta = sorted(delta, reverse=True)
 
1449
        adds = []
 
1450
        changes = []
 
1451
        deletes = []
 
1452
        # The paths this function accepts are unicode and must be encoded as we
 
1453
        # go.
 
1454
        encode = cache_utf8.encode
 
1455
        inv_to_entry = self._inv_entry_to_details
 
1456
        # delta is now (deletes, changes), (adds) in reverse lexographical
 
1457
        # order.
 
1458
        # deletes in reverse lexographic order are safe to process in situ.
 
1459
        # renames are not, as a rename from any path could go to a path
 
1460
        # lexographically lower, so we transform renames into delete, add pairs,
 
1461
        # expanding them recursively as needed.
 
1462
        # At the same time, to reduce interface friction we convert the input
 
1463
        # inventory entries to dirstate.
 
1464
        root_only = ('', '')
 
1465
        # Accumulate parent references (path_utf8, id), to check for parentless
 
1466
        # items or items placed under files/links/tree-references. We get
 
1467
        # references from every item in the delta that is not a deletion and
 
1468
        # is not itself the root.
 
1469
        parents = set()
 
1470
        # Added ids must not be in the dirstate already. This set holds those
 
1471
        # ids.
 
1472
        new_ids = set()
 
1473
        for old_path, new_path, file_id, inv_entry in delta:
 
1474
            if inv_entry is not None and file_id != inv_entry.file_id:
 
1475
                raise errors.InconsistentDelta(new_path, file_id,
 
1476
                    "mismatched entry file_id %r" % inv_entry)
 
1477
            if new_path is not None:
 
1478
                if inv_entry is None:
 
1479
                    raise errors.InconsistentDelta(new_path, file_id,
 
1480
                        "new_path with no entry")
 
1481
                new_path_utf8 = encode(new_path)
 
1482
                # note the parent for validation
 
1483
                dirname_utf8, basename_utf8 = osutils.split(new_path_utf8)
 
1484
                if basename_utf8:
 
1485
                    parents.add((dirname_utf8, inv_entry.parent_id))
 
1486
            if old_path is None:
 
1487
                adds.append((None, encode(new_path), file_id,
 
1488
                    inv_to_entry(inv_entry), True))
 
1489
                new_ids.add(file_id)
 
1490
            elif new_path is None:
 
1491
                deletes.append((encode(old_path), None, file_id, None, True))
 
1492
            elif (old_path, new_path) != root_only:
 
1493
                # Renames:
 
1494
                # Because renames must preserve their children we must have
 
1495
                # processed all relocations and removes before hand. The sort
 
1496
                # order ensures we've examined the child paths, but we also
 
1497
                # have to execute the removals, or the split to an add/delete
 
1498
                # pair will result in the deleted item being reinserted, or
 
1499
                # renamed items being reinserted twice - and possibly at the
 
1500
                # wrong place. Splitting into a delete/add pair also simplifies
 
1501
                # the handling of entries with ('f', ...), ('r' ...) because
 
1502
                # the target of the 'r' is old_path here, and we add that to
 
1503
                # deletes, meaning that the add handler does not need to check
 
1504
                # for 'r' items on every pass.
 
1505
                self._update_basis_apply_deletes(deletes)
 
1506
                deletes = []
 
1507
                # Split into an add/delete pair recursively.
 
1508
                adds.append((None, new_path_utf8, file_id,
 
1509
                    inv_to_entry(inv_entry), False))
 
1510
                # Expunge deletes that we've seen so that deleted/renamed
 
1511
                # children of a rename directory are handled correctly.
 
1512
                new_deletes = reversed(list(self._iter_child_entries(1,
 
1513
                    encode(old_path))))
 
1514
                # Remove the current contents of the tree at orig_path, and
 
1515
                # reinsert at the correct new path.
 
1516
                for entry in new_deletes:
 
1517
                    if entry[0][0]:
 
1518
                        source_path = entry[0][0] + '/' + entry[0][1]
 
1519
                    else:
 
1520
                        source_path = entry[0][1]
 
1521
                    if new_path_utf8:
 
1522
                        target_path = new_path_utf8 + source_path[len(old_path):]
 
1523
                    else:
 
1524
                        if old_path == '':
 
1525
                            raise AssertionError("cannot rename directory to"
 
1526
                                " itself")
 
1527
                        target_path = source_path[len(old_path) + 1:]
 
1528
                    adds.append((None, target_path, entry[0][2], entry[1][1], False))
 
1529
                    deletes.append(
 
1530
                        (source_path, target_path, entry[0][2], None, False))
 
1531
                deletes.append(
 
1532
                    (encode(old_path), new_path, file_id, None, False))
 
1533
            else:
 
1534
                # changes to just the root should not require remove/insertion
 
1535
                # of everything.
 
1536
                changes.append((encode(old_path), encode(new_path), file_id,
 
1537
                    inv_to_entry(inv_entry)))
 
1538
        self._check_delta_ids_absent(new_ids, delta, 1)
 
1539
        try:
 
1540
            # Finish expunging deletes/first half of renames.
 
1541
            self._update_basis_apply_deletes(deletes)
 
1542
            # Reinstate second half of renames and new paths.
 
1543
            self._update_basis_apply_adds(adds)
 
1544
            # Apply in-situ changes.
 
1545
            self._update_basis_apply_changes(changes)
 
1546
            # Validate parents
 
1547
            self._after_delta_check_parents(parents, 1)
 
1548
        except errors.BzrError, e:
 
1549
            self._changes_aborted = True
 
1550
            if 'integrity error' not in str(e):
 
1551
                raise
 
1552
            # _get_entry raises BzrError when a request is inconsistent; we
 
1553
            # want such errors to be shown as InconsistentDelta - and that 
 
1554
            # fits the behaviour we trigger. Partof this is driven by dirstate
 
1555
            # only supporting deltas that turn the basis into a closer fit to
 
1556
            # the active tree.
 
1557
            raise errors.InconsistentDeltaDelta(delta, "error from _get_entry.")
 
1558
 
 
1559
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
1560
        self._header_state = DirState.IN_MEMORY_MODIFIED
 
1561
        self._id_index = None
 
1562
        return
 
1563
 
 
1564
    def _check_delta_ids_absent(self, new_ids, delta, tree_index):
 
1565
        """Check that none of the file_ids in new_ids are present in a tree."""
 
1566
        if not new_ids:
 
1567
            return
 
1568
        id_index = self._get_id_index()
 
1569
        for file_id in new_ids:
 
1570
            for key in id_index.get(file_id, ()):
 
1571
                block_i, entry_i, d_present, f_present = \
 
1572
                    self._get_block_entry_index(key[0], key[1], tree_index)
 
1573
                if not f_present:
 
1574
                    # In a different tree
 
1575
                    continue
 
1576
                entry = self._dirblocks[block_i][1][entry_i]
 
1577
                if entry[0][2] != file_id:
 
1578
                    # Different file_id, so not what we want.
 
1579
                    continue
 
1580
                # NB: No changes made before this helper is called, so no need
 
1581
                # to set the _changes_aborted flag.
 
1582
                raise errors.InconsistentDelta(
 
1583
                    ("%s/%s" % key[0:2]).decode('utf8'), file_id,
 
1584
                    "This file_id is new in the delta but already present in "
 
1585
                    "the target")
 
1586
 
 
1587
    def _update_basis_apply_adds(self, adds):
 
1588
        """Apply a sequence of adds to tree 1 during update_basis_by_delta.
 
1589
 
 
1590
        They may be adds, or renames that have been split into add/delete
 
1591
        pairs.
 
1592
 
 
1593
        :param adds: A sequence of adds. Each add is a tuple:
 
1594
            (None, new_path_utf8, file_id, (entry_details), real_add). real_add
 
1595
            is False when the add is the second half of a remove-and-reinsert
 
1596
            pair created to handle renames and deletes.
 
1597
        """
 
1598
        # Adds are accumulated partly from renames, so can be in any input
 
1599
        # order - sort it.
 
1600
        adds.sort()
 
1601
        # adds is now in lexographic order, which places all parents before
 
1602
        # their children, so we can process it linearly.
 
1603
        absent = 'ar'
 
1604
        for old_path, new_path, file_id, new_details, real_add in adds:
 
1605
            # the entry for this file_id must be in tree 0.
 
1606
            entry = self._get_entry(0, file_id, new_path)
 
1607
            if entry[0] is None or entry[0][2] != file_id:
 
1608
                self._changes_aborted = True
 
1609
                raise errors.InconsistentDelta(new_path, file_id,
 
1610
                    'working tree does not contain new entry')
 
1611
            if real_add and entry[1][1][0] not in absent:
 
1612
                self._changes_aborted = True
 
1613
                raise errors.InconsistentDelta(new_path, file_id,
 
1614
                    'The entry was considered to be a genuinely new record,'
 
1615
                    ' but there was already an old record for it.')
 
1616
            # We don't need to update the target of an 'r' because the handling
 
1617
            # of renames turns all 'r' situations into a delete at the original
 
1618
            # location.
 
1619
            entry[1][1] = new_details
 
1620
 
 
1621
    def _update_basis_apply_changes(self, changes):
 
1622
        """Apply a sequence of changes to tree 1 during update_basis_by_delta.
 
1623
 
 
1624
        :param adds: A sequence of changes. Each change is a tuple:
 
1625
            (path_utf8, path_utf8, file_id, (entry_details))
 
1626
        """
 
1627
        absent = 'ar'
 
1628
        for old_path, new_path, file_id, new_details in changes:
 
1629
            # the entry for this file_id must be in tree 0.
 
1630
            entry = self._get_entry(0, file_id, new_path)
 
1631
            if entry[0] is None or entry[0][2] != file_id:
 
1632
                self._changes_aborted = True
 
1633
                raise errors.InconsistentDelta(new_path, file_id,
 
1634
                    'working tree does not contain new entry')
 
1635
            if (entry[1][0][0] in absent or
 
1636
                entry[1][1][0] in absent):
 
1637
                self._changes_aborted = True
 
1638
                raise errors.InconsistentDelta(new_path, file_id,
 
1639
                    'changed considered absent')
 
1640
            entry[1][1] = new_details
 
1641
 
 
1642
    def _update_basis_apply_deletes(self, deletes):
 
1643
        """Apply a sequence of deletes to tree 1 during update_basis_by_delta.
 
1644
 
 
1645
        They may be deletes, or renames that have been split into add/delete
 
1646
        pairs.
 
1647
 
 
1648
        :param deletes: A sequence of deletes. Each delete is a tuple:
 
1649
            (old_path_utf8, new_path_utf8, file_id, None, real_delete).
 
1650
            real_delete is True when the desired outcome is an actual deletion
 
1651
            rather than the rename handling logic temporarily deleting a path
 
1652
            during the replacement of a parent.
 
1653
        """
 
1654
        null = DirState.NULL_PARENT_DETAILS
 
1655
        for old_path, new_path, file_id, _, real_delete in deletes:
 
1656
            if real_delete != (new_path is None):
 
1657
                self._changes_aborted = True
 
1658
                raise AssertionError("bad delete delta")
 
1659
            # the entry for this file_id must be in tree 1.
 
1660
            dirname, basename = osutils.split(old_path)
 
1661
            block_index, entry_index, dir_present, file_present = \
 
1662
                self._get_block_entry_index(dirname, basename, 1)
 
1663
            if not file_present:
 
1664
                self._changes_aborted = True
 
1665
                raise errors.InconsistentDelta(old_path, file_id,
 
1666
                    'basis tree does not contain removed entry')
 
1667
            entry = self._dirblocks[block_index][1][entry_index]
 
1668
            if entry[0][2] != file_id:
 
1669
                self._changes_aborted = True
 
1670
                raise errors.InconsistentDelta(old_path, file_id,
 
1671
                    'mismatched file_id in tree 1')
 
1672
            if real_delete:
 
1673
                if entry[1][0][0] != 'a':
 
1674
                    self._changes_aborted = True
 
1675
                    raise errors.InconsistentDelta(old_path, file_id,
 
1676
                            'This was marked as a real delete, but the WT state'
 
1677
                            ' claims that it still exists and is versioned.')
 
1678
                del self._dirblocks[block_index][1][entry_index]
 
1679
            else:
 
1680
                if entry[1][0][0] == 'a':
 
1681
                    self._changes_aborted = True
 
1682
                    raise errors.InconsistentDelta(old_path, file_id,
 
1683
                        'The entry was considered a rename, but the source path'
 
1684
                        ' is marked as absent.')
 
1685
                    # For whatever reason, we were asked to rename an entry
 
1686
                    # that was originally marked as deleted. This could be
 
1687
                    # because we are renaming the parent directory, and the WT
 
1688
                    # current state has the file marked as deleted.
 
1689
                elif entry[1][0][0] == 'r':
 
1690
                    # implement the rename
 
1691
                    del self._dirblocks[block_index][1][entry_index]
 
1692
                else:
 
1693
                    # it is being resurrected here, so blank it out temporarily.
 
1694
                    self._dirblocks[block_index][1][entry_index][1][1] = null
 
1695
 
 
1696
    def _after_delta_check_parents(self, parents, index):
 
1697
        """Check that parents required by the delta are all intact.
 
1698
        
 
1699
        :param parents: An iterable of (path_utf8, file_id) tuples which are
 
1700
            required to be present in tree 'index' at path_utf8 with id file_id
 
1701
            and be a directory.
 
1702
        :param index: The column in the dirstate to check for parents in.
 
1703
        """
 
1704
        for dirname_utf8, file_id in parents:
 
1705
            # Get the entry - the ensures that file_id, dirname_utf8 exists and
 
1706
            # has the right file id.
 
1707
            entry = self._get_entry(index, file_id, dirname_utf8)
 
1708
            if entry[1] is None:
 
1709
                self._changes_aborted = True
 
1710
                raise errors.InconsistentDelta(dirname_utf8.decode('utf8'),
 
1711
                    file_id, "This parent is not present.")
 
1712
            # Parents of things must be directories
 
1713
            if entry[1][index][0] != 'd':
 
1714
                self._changes_aborted = True
 
1715
                raise errors.InconsistentDelta(dirname_utf8.decode('utf8'),
 
1716
                    file_id, "This parent is not a directory.")
 
1717
 
 
1718
    def _observed_sha1(self, entry, sha1, stat_value,
 
1719
        _stat_to_minikind=_stat_to_minikind, _pack_stat=pack_stat):
 
1720
        """Note the sha1 of a file.
 
1721
 
 
1722
        :param entry: The entry the sha1 is for.
 
1723
        :param sha1: The observed sha1.
 
1724
        :param stat_value: The os.lstat for the file.
 
1725
        """
 
1726
        try:
 
1727
            minikind = _stat_to_minikind[stat_value.st_mode & 0170000]
 
1728
        except KeyError:
 
1729
            # Unhandled kind
 
1730
            return None
 
1731
        packed_stat = _pack_stat(stat_value)
 
1732
        if minikind == 'f':
 
1733
            if self._cutoff_time is None:
 
1734
                self._sha_cutoff_time()
 
1735
            if (stat_value.st_mtime < self._cutoff_time
 
1736
                and stat_value.st_ctime < self._cutoff_time):
 
1737
                entry[1][0] = ('f', sha1, entry[1][0][2], entry[1][0][3],
 
1738
                    packed_stat)
 
1739
                self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
1740
 
 
1741
    def _sha_cutoff_time(self):
 
1742
        """Return cutoff time.
 
1743
 
 
1744
        Files modified more recently than this time are at risk of being
 
1745
        undetectably modified and so can't be cached.
 
1746
        """
 
1747
        # Cache the cutoff time as long as we hold a lock.
 
1748
        # time.time() isn't super expensive (approx 3.38us), but
 
1749
        # when you call it 50,000 times it adds up.
 
1750
        # For comparison, os.lstat() costs 7.2us if it is hot.
 
1751
        self._cutoff_time = int(time.time()) - 3
 
1752
        return self._cutoff_time
 
1753
 
 
1754
    def _lstat(self, abspath, entry):
 
1755
        """Return the os.lstat value for this path."""
 
1756
        return os.lstat(abspath)
 
1757
 
 
1758
    def _sha1_file_and_mutter(self, abspath):
 
1759
        # when -Dhashcache is turned on, this is monkey-patched in to log
 
1760
        # file reads
 
1761
        trace.mutter("dirstate sha1 " + abspath)
 
1762
        return self._sha1_provider.sha1(abspath)
 
1763
 
 
1764
    def _is_executable(self, mode, old_executable):
 
1765
        """Is this file executable?"""
 
1766
        return bool(S_IEXEC & mode)
 
1767
 
 
1768
    def _is_executable_win32(self, mode, old_executable):
 
1769
        """On win32 the executable bit is stored in the dirstate."""
 
1770
        return old_executable
 
1771
 
 
1772
    if sys.platform == 'win32':
 
1773
        _is_executable = _is_executable_win32
 
1774
 
 
1775
    def _read_link(self, abspath, old_link):
 
1776
        """Read the target of a symlink"""
 
1777
        # TODO: jam 200700301 On Win32, this could just return the value
 
1778
        #       already in memory. However, this really needs to be done at a
 
1779
        #       higher level, because there either won't be anything on disk,
 
1780
        #       or the thing on disk will be a file.
 
1781
        fs_encoding = osutils._fs_enc
 
1782
        if isinstance(abspath, unicode):
 
1783
            # abspath is defined as the path to pass to lstat. readlink is
 
1784
            # buggy in python < 2.6 (it doesn't encode unicode path into FS
 
1785
            # encoding), so we need to encode ourselves knowing that unicode
 
1786
            # paths are produced by UnicodeDirReader on purpose.
 
1787
            abspath = abspath.encode(fs_encoding)
 
1788
        target = os.readlink(abspath)
 
1789
        if fs_encoding not in ('UTF-8', 'US-ASCII', 'ANSI_X3.4-1968'):
 
1790
            # Change encoding if needed
 
1791
            target = target.decode(fs_encoding).encode('UTF-8')
 
1792
        return target
 
1793
 
 
1794
    def get_ghosts(self):
 
1795
        """Return a list of the parent tree revision ids that are ghosts."""
 
1796
        self._read_header_if_needed()
 
1797
        return self._ghosts
 
1798
 
 
1799
    def get_lines(self):
 
1800
        """Serialise the entire dirstate to a sequence of lines."""
 
1801
        if (self._header_state == DirState.IN_MEMORY_UNMODIFIED and
 
1802
            self._dirblock_state == DirState.IN_MEMORY_UNMODIFIED):
 
1803
            # read whats on disk.
 
1804
            self._state_file.seek(0)
 
1805
            return self._state_file.readlines()
 
1806
        lines = []
 
1807
        lines.append(self._get_parents_line(self.get_parent_ids()))
 
1808
        lines.append(self._get_ghosts_line(self._ghosts))
 
1809
        # append the root line which is special cased
 
1810
        lines.extend(map(self._entry_to_line, self._iter_entries()))
 
1811
        return self._get_output_lines(lines)
 
1812
 
 
1813
    def _get_ghosts_line(self, ghost_ids):
 
1814
        """Create a line for the state file for ghost information."""
 
1815
        return '\0'.join([str(len(ghost_ids))] + ghost_ids)
 
1816
 
 
1817
    def _get_parents_line(self, parent_ids):
 
1818
        """Create a line for the state file for parents information."""
 
1819
        return '\0'.join([str(len(parent_ids))] + parent_ids)
 
1820
 
 
1821
    def _get_fields_to_entry(self):
 
1822
        """Get a function which converts entry fields into a entry record.
 
1823
 
 
1824
        This handles size and executable, as well as parent records.
 
1825
 
 
1826
        :return: A function which takes a list of fields, and returns an
 
1827
            appropriate record for storing in memory.
 
1828
        """
 
1829
        # This is intentionally unrolled for performance
 
1830
        num_present_parents = self._num_present_parents()
 
1831
        if num_present_parents == 0:
 
1832
            def fields_to_entry_0_parents(fields, _int=int):
 
1833
                path_name_file_id_key = (fields[0], fields[1], fields[2])
 
1834
                return (path_name_file_id_key, [
 
1835
                    ( # Current tree
 
1836
                        fields[3],                # minikind
 
1837
                        fields[4],                # fingerprint
 
1838
                        _int(fields[5]),          # size
 
1839
                        fields[6] == 'y',         # executable
 
1840
                        fields[7],                # packed_stat or revision_id
 
1841
                    )])
 
1842
            return fields_to_entry_0_parents
 
1843
        elif num_present_parents == 1:
 
1844
            def fields_to_entry_1_parent(fields, _int=int):
 
1845
                path_name_file_id_key = (fields[0], fields[1], fields[2])
 
1846
                return (path_name_file_id_key, [
 
1847
                    ( # Current tree
 
1848
                        fields[3],                # minikind
 
1849
                        fields[4],                # fingerprint
 
1850
                        _int(fields[5]),          # size
 
1851
                        fields[6] == 'y',         # executable
 
1852
                        fields[7],                # packed_stat or revision_id
 
1853
                    ),
 
1854
                    ( # Parent 1
 
1855
                        fields[8],                # minikind
 
1856
                        fields[9],                # fingerprint
 
1857
                        _int(fields[10]),         # size
 
1858
                        fields[11] == 'y',        # executable
 
1859
                        fields[12],               # packed_stat or revision_id
 
1860
                    ),
 
1861
                    ])
 
1862
            return fields_to_entry_1_parent
 
1863
        elif num_present_parents == 2:
 
1864
            def fields_to_entry_2_parents(fields, _int=int):
 
1865
                path_name_file_id_key = (fields[0], fields[1], fields[2])
 
1866
                return (path_name_file_id_key, [
 
1867
                    ( # Current tree
 
1868
                        fields[3],                # minikind
 
1869
                        fields[4],                # fingerprint
 
1870
                        _int(fields[5]),          # size
 
1871
                        fields[6] == 'y',         # executable
 
1872
                        fields[7],                # packed_stat or revision_id
 
1873
                    ),
 
1874
                    ( # Parent 1
 
1875
                        fields[8],                # minikind
 
1876
                        fields[9],                # fingerprint
 
1877
                        _int(fields[10]),         # size
 
1878
                        fields[11] == 'y',        # executable
 
1879
                        fields[12],               # packed_stat or revision_id
 
1880
                    ),
 
1881
                    ( # Parent 2
 
1882
                        fields[13],               # minikind
 
1883
                        fields[14],               # fingerprint
 
1884
                        _int(fields[15]),         # size
 
1885
                        fields[16] == 'y',        # executable
 
1886
                        fields[17],               # packed_stat or revision_id
 
1887
                    ),
 
1888
                    ])
 
1889
            return fields_to_entry_2_parents
 
1890
        else:
 
1891
            def fields_to_entry_n_parents(fields, _int=int):
 
1892
                path_name_file_id_key = (fields[0], fields[1], fields[2])
 
1893
                trees = [(fields[cur],                # minikind
 
1894
                          fields[cur+1],              # fingerprint
 
1895
                          _int(fields[cur+2]),        # size
 
1896
                          fields[cur+3] == 'y',       # executable
 
1897
                          fields[cur+4],              # stat or revision_id
 
1898
                         ) for cur in xrange(3, len(fields)-1, 5)]
 
1899
                return path_name_file_id_key, trees
 
1900
            return fields_to_entry_n_parents
 
1901
 
 
1902
    def get_parent_ids(self):
 
1903
        """Return a list of the parent tree ids for the directory state."""
 
1904
        self._read_header_if_needed()
 
1905
        return list(self._parents)
 
1906
 
 
1907
    def _get_block_entry_index(self, dirname, basename, tree_index):
 
1908
        """Get the coordinates for a path in the state structure.
 
1909
 
 
1910
        :param dirname: The utf8 dirname to lookup.
 
1911
        :param basename: The utf8 basename to lookup.
 
1912
        :param tree_index: The index of the tree for which this lookup should
 
1913
            be attempted.
 
1914
        :return: A tuple describing where the path is located, or should be
 
1915
            inserted. The tuple contains four fields: the block index, the row
 
1916
            index, the directory is present (boolean), the entire path is
 
1917
            present (boolean).  There is no guarantee that either
 
1918
            coordinate is currently reachable unless the found field for it is
 
1919
            True. For instance, a directory not present in the searched tree
 
1920
            may be returned with a value one greater than the current highest
 
1921
            block offset. The directory present field will always be True when
 
1922
            the path present field is True. The directory present field does
 
1923
            NOT indicate that the directory is present in the searched tree,
 
1924
            rather it indicates that there are at least some files in some
 
1925
            tree present there.
 
1926
        """
 
1927
        self._read_dirblocks_if_needed()
 
1928
        key = dirname, basename, ''
 
1929
        block_index, present = self._find_block_index_from_key(key)
 
1930
        if not present:
 
1931
            # no such directory - return the dir index and 0 for the row.
 
1932
            return block_index, 0, False, False
 
1933
        block = self._dirblocks[block_index][1] # access the entries only
 
1934
        entry_index, present = self._find_entry_index(key, block)
 
1935
        # linear search through entries at this path to find the one
 
1936
        # requested.
 
1937
        while entry_index < len(block) and block[entry_index][0][1] == basename:
 
1938
            if block[entry_index][1][tree_index][0] not in 'ar':
 
1939
                # neither absent or relocated
 
1940
                return block_index, entry_index, True, True
 
1941
            entry_index += 1
 
1942
        return block_index, entry_index, True, False
 
1943
 
 
1944
    def _get_entry(self, tree_index, fileid_utf8=None, path_utf8=None, include_deleted=False):
 
1945
        """Get the dirstate entry for path in tree tree_index.
 
1946
 
 
1947
        If either file_id or path is supplied, it is used as the key to lookup.
 
1948
        If both are supplied, the fastest lookup is used, and an error is
 
1949
        raised if they do not both point at the same row.
 
1950
 
 
1951
        :param tree_index: The index of the tree we wish to locate this path
 
1952
            in. If the path is present in that tree, the entry containing its
 
1953
            details is returned, otherwise (None, None) is returned
 
1954
            0 is the working tree, higher indexes are successive parent
 
1955
            trees.
 
1956
        :param fileid_utf8: A utf8 file_id to look up.
 
1957
        :param path_utf8: An utf8 path to be looked up.
 
1958
        :param include_deleted: If True, and performing a lookup via
 
1959
            fileid_utf8 rather than path_utf8, return an entry for deleted
 
1960
            (absent) paths.
 
1961
        :return: The dirstate entry tuple for path, or (None, None)
 
1962
        """
 
1963
        self._read_dirblocks_if_needed()
 
1964
        if path_utf8 is not None:
 
1965
            if type(path_utf8) is not str:
 
1966
                raise errors.BzrError('path_utf8 is not a str: %s %r'
 
1967
                    % (type(path_utf8), path_utf8))
 
1968
            # path lookups are faster
 
1969
            dirname, basename = osutils.split(path_utf8)
 
1970
            block_index, entry_index, dir_present, file_present = \
 
1971
                self._get_block_entry_index(dirname, basename, tree_index)
 
1972
            if not file_present:
 
1973
                return None, None
 
1974
            entry = self._dirblocks[block_index][1][entry_index]
 
1975
            if not (entry[0][2] and entry[1][tree_index][0] not in ('a', 'r')):
 
1976
                raise AssertionError('unversioned entry?')
 
1977
            if fileid_utf8:
 
1978
                if entry[0][2] != fileid_utf8:
 
1979
                    self._changes_aborted = True
 
1980
                    raise errors.BzrError('integrity error ? : mismatching'
 
1981
                                          ' tree_index, file_id and path')
 
1982
            return entry
 
1983
        else:
 
1984
            possible_keys = self._get_id_index().get(fileid_utf8, ())
 
1985
            if not possible_keys:
 
1986
                return None, None
 
1987
            for key in possible_keys:
 
1988
                block_index, present = \
 
1989
                    self._find_block_index_from_key(key)
 
1990
                # strange, probably indicates an out of date
 
1991
                # id index - for now, allow this.
 
1992
                if not present:
 
1993
                    continue
 
1994
                # WARNING: DO not change this code to use _get_block_entry_index
 
1995
                # as that function is not suitable: it does not use the key
 
1996
                # to lookup, and thus the wrong coordinates are returned.
 
1997
                block = self._dirblocks[block_index][1]
 
1998
                entry_index, present = self._find_entry_index(key, block)
 
1999
                if present:
 
2000
                    entry = self._dirblocks[block_index][1][entry_index]
 
2001
                    # TODO: We might want to assert that entry[0][2] ==
 
2002
                    #       fileid_utf8.
 
2003
                    if entry[1][tree_index][0] in 'fdlt':
 
2004
                        # this is the result we are looking for: the
 
2005
                        # real home of this file_id in this tree.
 
2006
                        return entry
 
2007
                    if entry[1][tree_index][0] == 'a':
 
2008
                        # there is no home for this entry in this tree
 
2009
                        if include_deleted:
 
2010
                            return entry
 
2011
                        return None, None
 
2012
                    if entry[1][tree_index][0] != 'r':
 
2013
                        raise AssertionError(
 
2014
                            "entry %r has invalid minikind %r for tree %r" \
 
2015
                            % (entry,
 
2016
                               entry[1][tree_index][0],
 
2017
                               tree_index))
 
2018
                    real_path = entry[1][tree_index][1]
 
2019
                    return self._get_entry(tree_index, fileid_utf8=fileid_utf8,
 
2020
                        path_utf8=real_path)
 
2021
            return None, None
 
2022
 
 
2023
    @classmethod
 
2024
    def initialize(cls, path, sha1_provider=None):
 
2025
        """Create a new dirstate on path.
 
2026
 
 
2027
        The new dirstate will be an empty tree - that is it has no parents,
 
2028
        and only a root node - which has id ROOT_ID.
 
2029
 
 
2030
        :param path: The name of the file for the dirstate.
 
2031
        :param sha1_provider: an object meeting the SHA1Provider interface.
 
2032
            If None, a DefaultSHA1Provider is used.
 
2033
        :return: A write-locked DirState object.
 
2034
        """
 
2035
        # This constructs a new DirState object on a path, sets the _state_file
 
2036
        # to a new empty file for that path. It then calls _set_data() with our
 
2037
        # stock empty dirstate information - a root with ROOT_ID, no children,
 
2038
        # and no parents. Finally it calls save() to ensure that this data will
 
2039
        # persist.
 
2040
        if sha1_provider is None:
 
2041
            sha1_provider = DefaultSHA1Provider()
 
2042
        result = cls(path, sha1_provider)
 
2043
        # root dir and root dir contents with no children.
 
2044
        empty_tree_dirblocks = [('', []), ('', [])]
 
2045
        # a new root directory, with a NULLSTAT.
 
2046
        empty_tree_dirblocks[0][1].append(
 
2047
            (('', '', inventory.ROOT_ID), [
 
2048
                ('d', '', 0, False, DirState.NULLSTAT),
 
2049
            ]))
 
2050
        result.lock_write()
 
2051
        try:
 
2052
            result._set_data([], empty_tree_dirblocks)
 
2053
            result.save()
 
2054
        except:
 
2055
            result.unlock()
 
2056
            raise
 
2057
        return result
 
2058
 
 
2059
    @staticmethod
 
2060
    def _inv_entry_to_details(inv_entry):
 
2061
        """Convert an inventory entry (from a revision tree) to state details.
 
2062
 
 
2063
        :param inv_entry: An inventory entry whose sha1 and link targets can be
 
2064
            relied upon, and which has a revision set.
 
2065
        :return: A details tuple - the details for a single tree at a path +
 
2066
            id.
 
2067
        """
 
2068
        kind = inv_entry.kind
 
2069
        minikind = DirState._kind_to_minikind[kind]
 
2070
        tree_data = inv_entry.revision
 
2071
        if kind == 'directory':
 
2072
            fingerprint = ''
 
2073
            size = 0
 
2074
            executable = False
 
2075
        elif kind == 'symlink':
 
2076
            if inv_entry.symlink_target is None:
 
2077
                fingerprint = ''
 
2078
            else:
 
2079
                fingerprint = inv_entry.symlink_target.encode('utf8')
 
2080
            size = 0
 
2081
            executable = False
 
2082
        elif kind == 'file':
 
2083
            fingerprint = inv_entry.text_sha1 or ''
 
2084
            size = inv_entry.text_size or 0
 
2085
            executable = inv_entry.executable
 
2086
        elif kind == 'tree-reference':
 
2087
            fingerprint = inv_entry.reference_revision or ''
 
2088
            size = 0
 
2089
            executable = False
 
2090
        else:
 
2091
            raise Exception("can't pack %s" % inv_entry)
 
2092
        return (minikind, fingerprint, size, executable, tree_data)
 
2093
 
 
2094
    def _iter_child_entries(self, tree_index, path_utf8):
 
2095
        """Iterate over all the entries that are children of path_utf.
 
2096
 
 
2097
        This only returns entries that are present (not in 'a', 'r') in
 
2098
        tree_index. tree_index data is not refreshed, so if tree 0 is used,
 
2099
        results may differ from that obtained if paths were statted to
 
2100
        determine what ones were directories.
 
2101
 
 
2102
        Asking for the children of a non-directory will return an empty
 
2103
        iterator.
 
2104
        """
 
2105
        pending_dirs = []
 
2106
        next_pending_dirs = [path_utf8]
 
2107
        absent = 'ar'
 
2108
        while next_pending_dirs:
 
2109
            pending_dirs = next_pending_dirs
 
2110
            next_pending_dirs = []
 
2111
            for path in pending_dirs:
 
2112
                block_index, present = self._find_block_index_from_key(
 
2113
                    (path, '', ''))
 
2114
                if block_index == 0:
 
2115
                    block_index = 1
 
2116
                    if len(self._dirblocks) == 1:
 
2117
                        # asked for the children of the root with no other
 
2118
                        # contents.
 
2119
                        return
 
2120
                if not present:
 
2121
                    # children of a non-directory asked for.
 
2122
                    continue
 
2123
                block = self._dirblocks[block_index]
 
2124
                for entry in block[1]:
 
2125
                    kind = entry[1][tree_index][0]
 
2126
                    if kind not in absent:
 
2127
                        yield entry
 
2128
                    if kind == 'd':
 
2129
                        if entry[0][0]:
 
2130
                            path = entry[0][0] + '/' + entry[0][1]
 
2131
                        else:
 
2132
                            path = entry[0][1]
 
2133
                        next_pending_dirs.append(path)
 
2134
 
 
2135
    def _iter_entries(self):
 
2136
        """Iterate over all the entries in the dirstate.
 
2137
 
 
2138
        Each yelt item is an entry in the standard format described in the
 
2139
        docstring of bzrlib.dirstate.
 
2140
        """
 
2141
        self._read_dirblocks_if_needed()
 
2142
        for directory in self._dirblocks:
 
2143
            for entry in directory[1]:
 
2144
                yield entry
 
2145
 
 
2146
    def _get_id_index(self):
 
2147
        """Get an id index of self._dirblocks.
 
2148
        
 
2149
        This maps from file_id => [(directory, name, file_id)] entries where
 
2150
        that file_id appears in one of the trees.
 
2151
        """
 
2152
        if self._id_index is None:
 
2153
            id_index = {}
 
2154
            for key, tree_details in self._iter_entries():
 
2155
                self._add_to_id_index(id_index, key)
 
2156
            self._id_index = id_index
 
2157
        return self._id_index
 
2158
 
 
2159
    def _add_to_id_index(self, id_index, entry_key):
 
2160
        """Add this entry to the _id_index mapping."""
 
2161
        # This code used to use a set for every entry in the id_index. However,
 
2162
        # it is *rare* to have more than one entry. So a set is a large
 
2163
        # overkill. And even when we do, we won't ever have more than the
 
2164
        # number of parent trees. Which is still a small number (rarely >2). As
 
2165
        # such, we use a simple tuple, and do our own uniqueness checks. While
 
2166
        # the 'in' check is O(N) since N is nicely bounded it shouldn't ever
 
2167
        # cause quadratic failure.
 
2168
        # TODO: This should use StaticTuple
 
2169
        file_id = entry_key[2]
 
2170
        entry_key = static_tuple.StaticTuple.from_sequence(entry_key)
 
2171
        if file_id not in id_index:
 
2172
            id_index[file_id] = static_tuple.StaticTuple(entry_key,)
 
2173
        else:
 
2174
            entry_keys = id_index[file_id]
 
2175
            if entry_key not in entry_keys:
 
2176
                id_index[file_id] = entry_keys + (entry_key,)
 
2177
 
 
2178
    def _remove_from_id_index(self, id_index, entry_key):
 
2179
        """Remove this entry from the _id_index mapping.
 
2180
 
 
2181
        It is an programming error to call this when the entry_key is not
 
2182
        already present.
 
2183
        """
 
2184
        file_id = entry_key[2]
 
2185
        entry_keys = list(id_index[file_id])
 
2186
        entry_keys.remove(entry_key)
 
2187
        id_index[file_id] = static_tuple.StaticTuple.from_sequence(entry_keys)
 
2188
 
 
2189
    def _get_output_lines(self, lines):
 
2190
        """Format lines for final output.
 
2191
 
 
2192
        :param lines: A sequence of lines containing the parents list and the
 
2193
            path lines.
 
2194
        """
 
2195
        output_lines = [DirState.HEADER_FORMAT_3]
 
2196
        lines.append('') # a final newline
 
2197
        inventory_text = '\0\n\0'.join(lines)
 
2198
        output_lines.append('crc32: %s\n' % (zlib.crc32(inventory_text),))
 
2199
        # -3, 1 for num parents, 1 for ghosts, 1 for final newline
 
2200
        num_entries = len(lines)-3
 
2201
        output_lines.append('num_entries: %s\n' % (num_entries,))
 
2202
        output_lines.append(inventory_text)
 
2203
        return output_lines
 
2204
 
 
2205
    def _make_deleted_row(self, fileid_utf8, parents):
 
2206
        """Return a deleted row for fileid_utf8."""
 
2207
        return ('/', 'RECYCLED.BIN', 'file', fileid_utf8, 0, DirState.NULLSTAT,
 
2208
            ''), parents
 
2209
 
 
2210
    def _num_present_parents(self):
 
2211
        """The number of parent entries in each record row."""
 
2212
        return len(self._parents) - len(self._ghosts)
 
2213
 
 
2214
    @staticmethod
 
2215
    def on_file(path, sha1_provider=None):
 
2216
        """Construct a DirState on the file at path "path".
 
2217
 
 
2218
        :param path: The path at which the dirstate file on disk should live.
 
2219
        :param sha1_provider: an object meeting the SHA1Provider interface.
 
2220
            If None, a DefaultSHA1Provider is used.
 
2221
        :return: An unlocked DirState object, associated with the given path.
 
2222
        """
 
2223
        if sha1_provider is None:
 
2224
            sha1_provider = DefaultSHA1Provider()
 
2225
        result = DirState(path, sha1_provider)
 
2226
        return result
 
2227
 
 
2228
    def _read_dirblocks_if_needed(self):
 
2229
        """Read in all the dirblocks from the file if they are not in memory.
 
2230
 
 
2231
        This populates self._dirblocks, and sets self._dirblock_state to
 
2232
        IN_MEMORY_UNMODIFIED. It is not currently ready for incremental block
 
2233
        loading.
 
2234
        """
 
2235
        self._read_header_if_needed()
 
2236
        if self._dirblock_state == DirState.NOT_IN_MEMORY:
 
2237
            _read_dirblocks(self)
 
2238
 
 
2239
    def _read_header(self):
 
2240
        """This reads in the metadata header, and the parent ids.
 
2241
 
 
2242
        After reading in, the file should be positioned at the null
 
2243
        just before the start of the first record in the file.
 
2244
 
 
2245
        :return: (expected crc checksum, number of entries, parent list)
 
2246
        """
 
2247
        self._read_prelude()
 
2248
        parent_line = self._state_file.readline()
 
2249
        info = parent_line.split('\0')
 
2250
        num_parents = int(info[0])
 
2251
        self._parents = info[1:-1]
 
2252
        ghost_line = self._state_file.readline()
 
2253
        info = ghost_line.split('\0')
 
2254
        num_ghosts = int(info[1])
 
2255
        self._ghosts = info[2:-1]
 
2256
        self._header_state = DirState.IN_MEMORY_UNMODIFIED
 
2257
        self._end_of_header = self._state_file.tell()
 
2258
 
 
2259
    def _read_header_if_needed(self):
 
2260
        """Read the header of the dirstate file if needed."""
 
2261
        # inline this as it will be called a lot
 
2262
        if not self._lock_token:
 
2263
            raise errors.ObjectNotLocked(self)
 
2264
        if self._header_state == DirState.NOT_IN_MEMORY:
 
2265
            self._read_header()
 
2266
 
 
2267
    def _read_prelude(self):
 
2268
        """Read in the prelude header of the dirstate file.
 
2269
 
 
2270
        This only reads in the stuff that is not connected to the crc
 
2271
        checksum. The position will be correct to read in the rest of
 
2272
        the file and check the checksum after this point.
 
2273
        The next entry in the file should be the number of parents,
 
2274
        and their ids. Followed by a newline.
 
2275
        """
 
2276
        header = self._state_file.readline()
 
2277
        if header != DirState.HEADER_FORMAT_3:
 
2278
            raise errors.BzrError(
 
2279
                'invalid header line: %r' % (header,))
 
2280
        crc_line = self._state_file.readline()
 
2281
        if not crc_line.startswith('crc32: '):
 
2282
            raise errors.BzrError('missing crc32 checksum: %r' % crc_line)
 
2283
        self.crc_expected = int(crc_line[len('crc32: '):-1])
 
2284
        num_entries_line = self._state_file.readline()
 
2285
        if not num_entries_line.startswith('num_entries: '):
 
2286
            raise errors.BzrError('missing num_entries line')
 
2287
        self._num_entries = int(num_entries_line[len('num_entries: '):-1])
 
2288
 
 
2289
    def sha1_from_stat(self, path, stat_result, _pack_stat=pack_stat):
 
2290
        """Find a sha1 given a stat lookup."""
 
2291
        return self._get_packed_stat_index().get(_pack_stat(stat_result), None)
 
2292
 
 
2293
    def _get_packed_stat_index(self):
 
2294
        """Get a packed_stat index of self._dirblocks."""
 
2295
        if self._packed_stat_index is None:
 
2296
            index = {}
 
2297
            for key, tree_details in self._iter_entries():
 
2298
                if tree_details[0][0] == 'f':
 
2299
                    index[tree_details[0][4]] = tree_details[0][1]
 
2300
            self._packed_stat_index = index
 
2301
        return self._packed_stat_index
 
2302
 
 
2303
    def save(self):
 
2304
        """Save any pending changes created during this session.
 
2305
 
 
2306
        We reuse the existing file, because that prevents race conditions with
 
2307
        file creation, and use oslocks on it to prevent concurrent modification
 
2308
        and reads - because dirstate's incremental data aggregation is not
 
2309
        compatible with reading a modified file, and replacing a file in use by
 
2310
        another process is impossible on Windows.
 
2311
 
 
2312
        A dirstate in read only mode should be smart enough though to validate
 
2313
        that the file has not changed, and otherwise discard its cache and
 
2314
        start over, to allow for fine grained read lock duration, so 'status'
 
2315
        wont block 'commit' - for example.
 
2316
        """
 
2317
        if self._changes_aborted:
 
2318
            # Should this be a warning? For now, I'm expecting that places that
 
2319
            # mark it inconsistent will warn, making a warning here redundant.
 
2320
            trace.mutter('Not saving DirState because '
 
2321
                    '_changes_aborted is set.')
 
2322
            return
 
2323
        if (self._header_state == DirState.IN_MEMORY_MODIFIED or
 
2324
            self._dirblock_state == DirState.IN_MEMORY_MODIFIED):
 
2325
 
 
2326
            grabbed_write_lock = False
 
2327
            if self._lock_state != 'w':
 
2328
                grabbed_write_lock, new_lock = self._lock_token.temporary_write_lock()
 
2329
                # Switch over to the new lock, as the old one may be closed.
 
2330
                # TODO: jam 20070315 We should validate the disk file has
 
2331
                #       not changed contents. Since temporary_write_lock may
 
2332
                #       not be an atomic operation.
 
2333
                self._lock_token = new_lock
 
2334
                self._state_file = new_lock.f
 
2335
                if not grabbed_write_lock:
 
2336
                    # We couldn't grab a write lock, so we switch back to a read one
 
2337
                    return
 
2338
            try:
 
2339
                self._state_file.seek(0)
 
2340
                self._state_file.writelines(self.get_lines())
 
2341
                self._state_file.truncate()
 
2342
                self._state_file.flush()
 
2343
                self._header_state = DirState.IN_MEMORY_UNMODIFIED
 
2344
                self._dirblock_state = DirState.IN_MEMORY_UNMODIFIED
 
2345
            finally:
 
2346
                if grabbed_write_lock:
 
2347
                    self._lock_token = self._lock_token.restore_read_lock()
 
2348
                    self._state_file = self._lock_token.f
 
2349
                    # TODO: jam 20070315 We should validate the disk file has
 
2350
                    #       not changed contents. Since restore_read_lock may
 
2351
                    #       not be an atomic operation.
 
2352
 
 
2353
    def _set_data(self, parent_ids, dirblocks):
 
2354
        """Set the full dirstate data in memory.
 
2355
 
 
2356
        This is an internal function used to completely replace the objects
 
2357
        in memory state. It puts the dirstate into state 'full-dirty'.
 
2358
 
 
2359
        :param parent_ids: A list of parent tree revision ids.
 
2360
        :param dirblocks: A list containing one tuple for each directory in the
 
2361
            tree. Each tuple contains the directory path and a list of entries
 
2362
            found in that directory.
 
2363
        """
 
2364
        # our memory copy is now authoritative.
 
2365
        self._dirblocks = dirblocks
 
2366
        self._header_state = DirState.IN_MEMORY_MODIFIED
 
2367
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
2368
        self._parents = list(parent_ids)
 
2369
        self._id_index = None
 
2370
        self._packed_stat_index = None
 
2371
 
 
2372
    def set_path_id(self, path, new_id):
 
2373
        """Change the id of path to new_id in the current working tree.
 
2374
 
 
2375
        :param path: The path inside the tree to set - '' is the root, 'foo'
 
2376
            is the path foo in the root.
 
2377
        :param new_id: The new id to assign to the path. This must be a utf8
 
2378
            file id (not unicode, and not None).
 
2379
        """
 
2380
        self._read_dirblocks_if_needed()
 
2381
        if len(path):
 
2382
            # TODO: logic not written
 
2383
            raise NotImplementedError(self.set_path_id)
 
2384
        # TODO: check new id is unique
 
2385
        entry = self._get_entry(0, path_utf8=path)
 
2386
        if entry[0][2] == new_id:
 
2387
            # Nothing to change.
 
2388
            return
 
2389
        # mark the old path absent, and insert a new root path
 
2390
        self._make_absent(entry)
 
2391
        self.update_minimal(('', '', new_id), 'd',
 
2392
            path_utf8='', packed_stat=entry[1][0][4])
 
2393
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
2394
 
 
2395
    def set_parent_trees(self, trees, ghosts):
 
2396
        """Set the parent trees for the dirstate.
 
2397
 
 
2398
        :param trees: A list of revision_id, tree tuples. tree must be provided
 
2399
            even if the revision_id refers to a ghost: supply an empty tree in
 
2400
            this case.
 
2401
        :param ghosts: A list of the revision_ids that are ghosts at the time
 
2402
            of setting.
 
2403
        """
 
2404
        # TODO: generate a list of parent indexes to preserve to save
 
2405
        # processing specific parent trees. In the common case one tree will
 
2406
        # be preserved - the left most parent.
 
2407
        # TODO: if the parent tree is a dirstate, we might want to walk them
 
2408
        # all by path in parallel for 'optimal' common-case performance.
 
2409
        # generate new root row.
 
2410
        self._read_dirblocks_if_needed()
 
2411
        # TODO future sketch: Examine the existing parents to generate a change
 
2412
        # map and then walk the new parent trees only, mapping them into the
 
2413
        # dirstate. Walk the dirstate at the same time to remove unreferenced
 
2414
        # entries.
 
2415
        # for now:
 
2416
        # sketch: loop over all entries in the dirstate, cherry picking
 
2417
        # entries from the parent trees, if they are not ghost trees.
 
2418
        # after we finish walking the dirstate, all entries not in the dirstate
 
2419
        # are deletes, so we want to append them to the end as per the design
 
2420
        # discussions. So do a set difference on ids with the parents to
 
2421
        # get deletes, and add them to the end.
 
2422
        # During the update process we need to answer the following questions:
 
2423
        # - find other keys containing a fileid in order to create cross-path
 
2424
        #   links. We dont't trivially use the inventory from other trees
 
2425
        #   because this leads to either double touching, or to accessing
 
2426
        #   missing keys,
 
2427
        # - find other keys containing a path
 
2428
        # We accumulate each entry via this dictionary, including the root
 
2429
        by_path = {}
 
2430
        id_index = {}
 
2431
        # we could do parallel iterators, but because file id data may be
 
2432
        # scattered throughout, we dont save on index overhead: we have to look
 
2433
        # at everything anyway. We can probably save cycles by reusing parent
 
2434
        # data and doing an incremental update when adding an additional
 
2435
        # parent, but for now the common cases are adding a new parent (merge),
 
2436
        # and replacing completely (commit), and commit is more common: so
 
2437
        # optimise merge later.
 
2438
 
 
2439
        # ---- start generation of full tree mapping data
 
2440
        # what trees should we use?
 
2441
        parent_trees = [tree for rev_id, tree in trees if rev_id not in ghosts]
 
2442
        # how many trees do we end up with
 
2443
        parent_count = len(parent_trees)
 
2444
 
 
2445
        # one: the current tree
 
2446
        for entry in self._iter_entries():
 
2447
            # skip entries not in the current tree
 
2448
            if entry[1][0][0] in 'ar': # absent, relocated
 
2449
                continue
 
2450
            by_path[entry[0]] = [entry[1][0]] + \
 
2451
                [DirState.NULL_PARENT_DETAILS] * parent_count
 
2452
            # TODO: Possibly inline this, since we know it isn't present yet
 
2453
            #       id_index[entry[0][2]] = (entry[0],)
 
2454
            self._add_to_id_index(id_index, entry[0])
 
2455
 
 
2456
        # now the parent trees:
 
2457
        for tree_index, tree in enumerate(parent_trees):
 
2458
            # the index is off by one, adjust it.
 
2459
            tree_index = tree_index + 1
 
2460
            # when we add new locations for a fileid we need these ranges for
 
2461
            # any fileid in this tree as we set the by_path[id] to:
 
2462
            # already_processed_tree_details + new_details + new_location_suffix
 
2463
            # the suffix is from tree_index+1:parent_count+1.
 
2464
            new_location_suffix = [DirState.NULL_PARENT_DETAILS] * (parent_count - tree_index)
 
2465
            # now stitch in all the entries from this tree
 
2466
            for path, entry in tree.inventory.iter_entries_by_dir():
 
2467
                # here we process each trees details for each item in the tree.
 
2468
                # we first update any existing entries for the id at other paths,
 
2469
                # then we either create or update the entry for the id at the
 
2470
                # right path, and finally we add (if needed) a mapping from
 
2471
                # file_id to this path. We do it in this order to allow us to
 
2472
                # avoid checking all known paths for the id when generating a
 
2473
                # new entry at this path: by adding the id->path mapping last,
 
2474
                # all the mappings are valid and have correct relocation
 
2475
                # records where needed.
 
2476
                file_id = entry.file_id
 
2477
                path_utf8 = path.encode('utf8')
 
2478
                dirname, basename = osutils.split(path_utf8)
 
2479
                new_entry_key = (dirname, basename, file_id)
 
2480
                # tree index consistency: All other paths for this id in this tree
 
2481
                # index must point to the correct path.
 
2482
                for entry_key in id_index.get(file_id, ()):
 
2483
                    # TODO:PROFILING: It might be faster to just update
 
2484
                    # rather than checking if we need to, and then overwrite
 
2485
                    # the one we are located at.
 
2486
                    if entry_key != new_entry_key:
 
2487
                        # this file id is at a different path in one of the
 
2488
                        # other trees, so put absent pointers there
 
2489
                        # This is the vertical axis in the matrix, all pointing
 
2490
                        # to the real path.
 
2491
                        by_path[entry_key][tree_index] = ('r', path_utf8, 0, False, '')
 
2492
                # by path consistency: Insert into an existing path record (trivial), or
 
2493
                # add a new one with relocation pointers for the other tree indexes.
 
2494
                entry_keys = id_index.get(file_id, ())
 
2495
                if new_entry_key in entry_keys:
 
2496
                    # there is already an entry where this data belongs, just insert it.
 
2497
                    by_path[new_entry_key][tree_index] = \
 
2498
                        self._inv_entry_to_details(entry)
 
2499
                else:
 
2500
                    # add relocated entries to the horizontal axis - this row
 
2501
                    # mapping from path,id. We need to look up the correct path
 
2502
                    # for the indexes from 0 to tree_index -1
 
2503
                    new_details = []
 
2504
                    for lookup_index in xrange(tree_index):
 
2505
                        # boundary case: this is the first occurence of file_id
 
2506
                        # so there are no id_indexes, possibly take this out of
 
2507
                        # the loop?
 
2508
                        if not len(entry_keys):
 
2509
                            new_details.append(DirState.NULL_PARENT_DETAILS)
 
2510
                        else:
 
2511
                            # grab any one entry, use it to find the right path.
 
2512
                            # TODO: optimise this to reduce memory use in highly
 
2513
                            # fragmented situations by reusing the relocation
 
2514
                            # records.
 
2515
                            a_key = iter(entry_keys).next()
 
2516
                            if by_path[a_key][lookup_index][0] in ('r', 'a'):
 
2517
                                # its a pointer or missing statement, use it as is.
 
2518
                                new_details.append(by_path[a_key][lookup_index])
 
2519
                            else:
 
2520
                                # we have the right key, make a pointer to it.
 
2521
                                real_path = ('/'.join(a_key[0:2])).strip('/')
 
2522
                                new_details.append(('r', real_path, 0, False, ''))
 
2523
                    new_details.append(self._inv_entry_to_details(entry))
 
2524
                    new_details.extend(new_location_suffix)
 
2525
                    by_path[new_entry_key] = new_details
 
2526
                    self._add_to_id_index(id_index, new_entry_key)
 
2527
        # --- end generation of full tree mappings
 
2528
 
 
2529
        # sort and output all the entries
 
2530
        new_entries = self._sort_entries(by_path.items())
 
2531
        self._entries_to_current_state(new_entries)
 
2532
        self._parents = [rev_id for rev_id, tree in trees]
 
2533
        self._ghosts = list(ghosts)
 
2534
        self._header_state = DirState.IN_MEMORY_MODIFIED
 
2535
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
2536
        self._id_index = id_index
 
2537
 
 
2538
    def _sort_entries(self, entry_list):
 
2539
        """Given a list of entries, sort them into the right order.
 
2540
 
 
2541
        This is done when constructing a new dirstate from trees - normally we
 
2542
        try to keep everything in sorted blocks all the time, but sometimes
 
2543
        it's easier to sort after the fact.
 
2544
        """
 
2545
        def _key(entry):
 
2546
            # sort by: directory parts, file name, file id
 
2547
            return entry[0][0].split('/'), entry[0][1], entry[0][2]
 
2548
        return sorted(entry_list, key=_key)
 
2549
 
 
2550
    def set_state_from_inventory(self, new_inv):
 
2551
        """Set new_inv as the current state.
 
2552
 
 
2553
        This API is called by tree transform, and will usually occur with
 
2554
        existing parent trees.
 
2555
 
 
2556
        :param new_inv: The inventory object to set current state from.
 
2557
        """
 
2558
        if 'evil' in debug.debug_flags:
 
2559
            trace.mutter_callsite(1,
 
2560
                "set_state_from_inventory called; please mutate the tree instead")
 
2561
        tracing = 'dirstate' in debug.debug_flags
 
2562
        if tracing:
 
2563
            trace.mutter("set_state_from_inventory trace:")
 
2564
        self._read_dirblocks_if_needed()
 
2565
        # sketch:
 
2566
        # Two iterators: current data and new data, both in dirblock order.
 
2567
        # We zip them together, which tells about entries that are new in the
 
2568
        # inventory, or removed in the inventory, or present in both and
 
2569
        # possibly changed.
 
2570
        #
 
2571
        # You might think we could just synthesize a new dirstate directly
 
2572
        # since we're processing it in the right order.  However, we need to
 
2573
        # also consider there may be any number of parent trees and relocation
 
2574
        # pointers, and we don't want to duplicate that here.
 
2575
        new_iterator = new_inv.iter_entries_by_dir()
 
2576
        # we will be modifying the dirstate, so we need a stable iterator. In
 
2577
        # future we might write one, for now we just clone the state into a
 
2578
        # list using a copy so that we see every original item and don't have
 
2579
        # to adjust the position when items are inserted or deleted in the
 
2580
        # underlying dirstate.
 
2581
        old_iterator = iter(list(self._iter_entries()))
 
2582
        # both must have roots so this is safe:
 
2583
        current_new = new_iterator.next()
 
2584
        current_old = old_iterator.next()
 
2585
        def advance(iterator):
 
2586
            try:
 
2587
                return iterator.next()
 
2588
            except StopIteration:
 
2589
                return None
 
2590
        while current_new or current_old:
 
2591
            # skip entries in old that are not really there
 
2592
            if current_old and current_old[1][0][0] in 'ar':
 
2593
                # relocated or absent
 
2594
                current_old = advance(old_iterator)
 
2595
                continue
 
2596
            if current_new:
 
2597
                # convert new into dirblock style
 
2598
                new_path_utf8 = current_new[0].encode('utf8')
 
2599
                new_dirname, new_basename = osutils.split(new_path_utf8)
 
2600
                new_id = current_new[1].file_id
 
2601
                new_entry_key = (new_dirname, new_basename, new_id)
 
2602
                current_new_minikind = \
 
2603
                    DirState._kind_to_minikind[current_new[1].kind]
 
2604
                if current_new_minikind == 't':
 
2605
                    fingerprint = current_new[1].reference_revision or ''
 
2606
                else:
 
2607
                    # We normally only insert or remove records, or update
 
2608
                    # them when it has significantly changed.  Then we want to
 
2609
                    # erase its fingerprint.  Unaffected records should
 
2610
                    # normally not be updated at all.
 
2611
                    fingerprint = ''
 
2612
            else:
 
2613
                # for safety disable variables
 
2614
                new_path_utf8 = new_dirname = new_basename = new_id = \
 
2615
                    new_entry_key = None
 
2616
            # 5 cases, we dont have a value that is strictly greater than everything, so
 
2617
            # we make both end conditions explicit
 
2618
            if not current_old:
 
2619
                # old is finished: insert current_new into the state.
 
2620
                if tracing:
 
2621
                    trace.mutter("Appending from new '%s'.",
 
2622
                        new_path_utf8.decode('utf8'))
 
2623
                self.update_minimal(new_entry_key, current_new_minikind,
 
2624
                    executable=current_new[1].executable,
 
2625
                    path_utf8=new_path_utf8, fingerprint=fingerprint,
 
2626
                    fullscan=True)
 
2627
                current_new = advance(new_iterator)
 
2628
            elif not current_new:
 
2629
                # new is finished
 
2630
                if tracing:
 
2631
                    trace.mutter("Truncating from old '%s/%s'.",
 
2632
                        current_old[0][0].decode('utf8'),
 
2633
                        current_old[0][1].decode('utf8'))
 
2634
                self._make_absent(current_old)
 
2635
                current_old = advance(old_iterator)
 
2636
            elif new_entry_key == current_old[0]:
 
2637
                # same -  common case
 
2638
                # We're looking at the same path and id in both the dirstate
 
2639
                # and inventory, so just need to update the fields in the
 
2640
                # dirstate from the one in the inventory.
 
2641
                # TODO: update the record if anything significant has changed.
 
2642
                # the minimal required trigger is if the execute bit or cached
 
2643
                # kind has changed.
 
2644
                if (current_old[1][0][3] != current_new[1].executable or
 
2645
                    current_old[1][0][0] != current_new_minikind):
 
2646
                    if tracing:
 
2647
                        trace.mutter("Updating in-place change '%s'.",
 
2648
                            new_path_utf8.decode('utf8'))
 
2649
                    self.update_minimal(current_old[0], current_new_minikind,
 
2650
                        executable=current_new[1].executable,
 
2651
                        path_utf8=new_path_utf8, fingerprint=fingerprint,
 
2652
                        fullscan=True)
 
2653
                # both sides are dealt with, move on
 
2654
                current_old = advance(old_iterator)
 
2655
                current_new = advance(new_iterator)
 
2656
            elif (cmp_by_dirs(new_dirname, current_old[0][0]) < 0
 
2657
                  or (new_dirname == current_old[0][0]
 
2658
                      and new_entry_key[1:] < current_old[0][1:])):
 
2659
                # new comes before:
 
2660
                # add a entry for this and advance new
 
2661
                if tracing:
 
2662
                    trace.mutter("Inserting from new '%s'.",
 
2663
                        new_path_utf8.decode('utf8'))
 
2664
                self.update_minimal(new_entry_key, current_new_minikind,
 
2665
                    executable=current_new[1].executable,
 
2666
                    path_utf8=new_path_utf8, fingerprint=fingerprint,
 
2667
                    fullscan=True)
 
2668
                current_new = advance(new_iterator)
 
2669
            else:
 
2670
                # we've advanced past the place where the old key would be,
 
2671
                # without seeing it in the new list.  so it must be gone.
 
2672
                if tracing:
 
2673
                    trace.mutter("Deleting from old '%s/%s'.",
 
2674
                        current_old[0][0].decode('utf8'),
 
2675
                        current_old[0][1].decode('utf8'))
 
2676
                self._make_absent(current_old)
 
2677
                current_old = advance(old_iterator)
 
2678
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
2679
        self._id_index = None
 
2680
        self._packed_stat_index = None
 
2681
        if tracing:
 
2682
            trace.mutter("set_state_from_inventory complete.")
 
2683
 
 
2684
    def _make_absent(self, current_old):
 
2685
        """Mark current_old - an entry - as absent for tree 0.
 
2686
 
 
2687
        :return: True if this was the last details entry for the entry key:
 
2688
            that is, if the underlying block has had the entry removed, thus
 
2689
            shrinking in length.
 
2690
        """
 
2691
        # build up paths that this id will be left at after the change is made,
 
2692
        # so we can update their cross references in tree 0
 
2693
        all_remaining_keys = set()
 
2694
        # Dont check the working tree, because it's going.
 
2695
        for details in current_old[1][1:]:
 
2696
            if details[0] not in 'ar': # absent, relocated
 
2697
                all_remaining_keys.add(current_old[0])
 
2698
            elif details[0] == 'r': # relocated
 
2699
                # record the key for the real path.
 
2700
                all_remaining_keys.add(tuple(osutils.split(details[1])) + (current_old[0][2],))
 
2701
            # absent rows are not present at any path.
 
2702
        last_reference = current_old[0] not in all_remaining_keys
 
2703
        if last_reference:
 
2704
            # the current row consists entire of the current item (being marked
 
2705
            # absent), and relocated or absent entries for the other trees:
 
2706
            # Remove it, its meaningless.
 
2707
            block = self._find_block(current_old[0])
 
2708
            entry_index, present = self._find_entry_index(current_old[0], block[1])
 
2709
            if not present:
 
2710
                raise AssertionError('could not find entry for %s' % (current_old,))
 
2711
            block[1].pop(entry_index)
 
2712
            # if we have an id_index in use, remove this key from it for this id.
 
2713
            if self._id_index is not None:
 
2714
                self._remove_from_id_index(self._id_index, current_old[0])
 
2715
        # update all remaining keys for this id to record it as absent. The
 
2716
        # existing details may either be the record we are marking as deleted
 
2717
        # (if there were other trees with the id present at this path), or may
 
2718
        # be relocations.
 
2719
        for update_key in all_remaining_keys:
 
2720
            update_block_index, present = \
 
2721
                self._find_block_index_from_key(update_key)
 
2722
            if not present:
 
2723
                raise AssertionError('could not find block for %s' % (update_key,))
 
2724
            update_entry_index, present = \
 
2725
                self._find_entry_index(update_key, self._dirblocks[update_block_index][1])
 
2726
            if not present:
 
2727
                raise AssertionError('could not find entry for %s' % (update_key,))
 
2728
            update_tree_details = self._dirblocks[update_block_index][1][update_entry_index][1]
 
2729
            # it must not be absent at the moment
 
2730
            if update_tree_details[0][0] == 'a': # absent
 
2731
                raise AssertionError('bad row %r' % (update_tree_details,))
 
2732
            update_tree_details[0] = DirState.NULL_PARENT_DETAILS
 
2733
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
2734
        return last_reference
 
2735
 
 
2736
    def update_minimal(self, key, minikind, executable=False, fingerprint='',
 
2737
        packed_stat=None, size=0, path_utf8=None, fullscan=False):
 
2738
        """Update an entry to the state in tree 0.
 
2739
 
 
2740
        This will either create a new entry at 'key' or update an existing one.
 
2741
        It also makes sure that any other records which might mention this are
 
2742
        updated as well.
 
2743
 
 
2744
        :param key: (dir, name, file_id) for the new entry
 
2745
        :param minikind: The type for the entry ('f' == 'file', 'd' ==
 
2746
                'directory'), etc.
 
2747
        :param executable: Should the executable bit be set?
 
2748
        :param fingerprint: Simple fingerprint for new entry: canonical-form
 
2749
            sha1 for files, referenced revision id for subtrees, etc.
 
2750
        :param packed_stat: Packed stat value for new entry.
 
2751
        :param size: Size information for new entry
 
2752
        :param path_utf8: key[0] + '/' + key[1], just passed in to avoid doing
 
2753
                extra computation.
 
2754
        :param fullscan: If True then a complete scan of the dirstate is being
 
2755
            done and checking for duplicate rows should not be done. This
 
2756
            should only be set by set_state_from_inventory and similar methods.
 
2757
 
 
2758
        If packed_stat and fingerprint are not given, they're invalidated in
 
2759
        the entry.
 
2760
        """
 
2761
        block = self._find_block(key)[1]
 
2762
        if packed_stat is None:
 
2763
            packed_stat = DirState.NULLSTAT
 
2764
        # XXX: Some callers pass '' as the packed_stat, and it seems to be
 
2765
        # sometimes present in the dirstate - this seems oddly inconsistent.
 
2766
        # mbp 20071008
 
2767
        entry_index, present = self._find_entry_index(key, block)
 
2768
        new_details = (minikind, fingerprint, size, executable, packed_stat)
 
2769
        id_index = self._get_id_index()
 
2770
        if not present:
 
2771
            # New record. Check there isn't a entry at this path already.
 
2772
            if not fullscan:
 
2773
                low_index, _ = self._find_entry_index(key[0:2] + ('',), block)
 
2774
                while low_index < len(block):
 
2775
                    entry = block[low_index]
 
2776
                    if entry[0][0:2] == key[0:2]:
 
2777
                        if entry[1][0][0] not in 'ar':
 
2778
                            # This entry has the same path (but a different id) as
 
2779
                            # the new entry we're adding, and is present in ths
 
2780
                            # tree.
 
2781
                            raise errors.InconsistentDelta(
 
2782
                                ("%s/%s" % key[0:2]).decode('utf8'), key[2],
 
2783
                                "Attempt to add item at path already occupied by "
 
2784
                                "id %r" % entry[0][2])
 
2785
                        low_index += 1
 
2786
                    else:
 
2787
                        break
 
2788
            # new entry, synthesis cross reference here,
 
2789
            existing_keys = id_index.get(key[2], ())
 
2790
            if not existing_keys:
 
2791
                # not currently in the state, simplest case
 
2792
                new_entry = key, [new_details] + self._empty_parent_info()
 
2793
            else:
 
2794
                # present at one or more existing other paths.
 
2795
                # grab one of them and use it to generate parent
 
2796
                # relocation/absent entries.
 
2797
                new_entry = key, [new_details]
 
2798
                # existing_keys can be changed as we iterate.
 
2799
                for other_key in tuple(existing_keys):
 
2800
                    # change the record at other to be a pointer to this new
 
2801
                    # record. The loop looks similar to the change to
 
2802
                    # relocations when updating an existing record but its not:
 
2803
                    # the test for existing kinds is different: this can be
 
2804
                    # factored out to a helper though.
 
2805
                    other_block_index, present = self._find_block_index_from_key(
 
2806
                        other_key)
 
2807
                    if not present:
 
2808
                        raise AssertionError('could not find block for %s' % (
 
2809
                            other_key,))
 
2810
                    other_block = self._dirblocks[other_block_index][1]
 
2811
                    other_entry_index, present = self._find_entry_index(
 
2812
                        other_key, other_block)
 
2813
                    if not present:
 
2814
                        raise AssertionError(
 
2815
                            'update_minimal: could not find other entry for %s'
 
2816
                            % (other_key,))
 
2817
                    if path_utf8 is None:
 
2818
                        raise AssertionError('no path')
 
2819
                    # Turn this other location into a reference to the new
 
2820
                    # location. This also updates the aliased iterator
 
2821
                    # (current_old in set_state_from_inventory) so that the old
 
2822
                    # entry, if not already examined, is skipped over by that
 
2823
                    # loop.
 
2824
                    other_entry = other_block[other_entry_index]
 
2825
                    other_entry[1][0] = ('r', path_utf8, 0, False, '')
 
2826
                    if self._maybe_remove_row(other_block, other_entry_index,
 
2827
                                              id_index):
 
2828
                        # If the row holding this was removed, we need to
 
2829
                        # recompute where this entry goes
 
2830
                        entry_index, _ = self._find_entry_index(key, block)
 
2831
 
 
2832
                # This loop:
 
2833
                # adds a tuple to the new details for each column
 
2834
                #  - either by copying an existing relocation pointer inside that column
 
2835
                #  - or by creating a new pointer to the right row inside that column
 
2836
                num_present_parents = self._num_present_parents()
 
2837
                if num_present_parents:
 
2838
                    # TODO: This re-evaluates the existing_keys set, do we need
 
2839
                    #       to do that ourselves?
 
2840
                    other_key = list(existing_keys)[0]
 
2841
                for lookup_index in xrange(1, num_present_parents + 1):
 
2842
                    # grab any one entry, use it to find the right path.
 
2843
                    # TODO: optimise this to reduce memory use in highly
 
2844
                    # fragmented situations by reusing the relocation
 
2845
                    # records.
 
2846
                    update_block_index, present = \
 
2847
                        self._find_block_index_from_key(other_key)
 
2848
                    if not present:
 
2849
                        raise AssertionError('could not find block for %s' % (other_key,))
 
2850
                    update_entry_index, present = \
 
2851
                        self._find_entry_index(other_key, self._dirblocks[update_block_index][1])
 
2852
                    if not present:
 
2853
                        raise AssertionError('update_minimal: could not find entry for %s' % (other_key,))
 
2854
                    update_details = self._dirblocks[update_block_index][1][update_entry_index][1][lookup_index]
 
2855
                    if update_details[0] in 'ar': # relocated, absent
 
2856
                        # its a pointer or absent in lookup_index's tree, use
 
2857
                        # it as is.
 
2858
                        new_entry[1].append(update_details)
 
2859
                    else:
 
2860
                        # we have the right key, make a pointer to it.
 
2861
                        pointer_path = osutils.pathjoin(*other_key[0:2])
 
2862
                        new_entry[1].append(('r', pointer_path, 0, False, ''))
 
2863
            block.insert(entry_index, new_entry)
 
2864
            self._add_to_id_index(id_index, key)
 
2865
        else:
 
2866
            # Does the new state matter?
 
2867
            block[entry_index][1][0] = new_details
 
2868
            # parents cannot be affected by what we do.
 
2869
            # other occurences of this id can be found
 
2870
            # from the id index.
 
2871
            # ---
 
2872
            # tree index consistency: All other paths for this id in this tree
 
2873
            # index must point to the correct path. We have to loop here because
 
2874
            # we may have passed entries in the state with this file id already
 
2875
            # that were absent - where parent entries are - and they need to be
 
2876
            # converted to relocated.
 
2877
            if path_utf8 is None:
 
2878
                raise AssertionError('no path')
 
2879
            existing_keys = id_index.get(key[2], ())
 
2880
            if key not in existing_keys:
 
2881
                raise AssertionError('We found the entry in the blocks, but'
 
2882
                    ' the key is not in the id_index.'
 
2883
                    ' key: %s, existing_keys: %s' % (key, existing_keys))
 
2884
            for entry_key in existing_keys:
 
2885
                # TODO:PROFILING: It might be faster to just update
 
2886
                # rather than checking if we need to, and then overwrite
 
2887
                # the one we are located at.
 
2888
                if entry_key != key:
 
2889
                    # this file id is at a different path in one of the
 
2890
                    # other trees, so put absent pointers there
 
2891
                    # This is the vertical axis in the matrix, all pointing
 
2892
                    # to the real path.
 
2893
                    block_index, present = self._find_block_index_from_key(entry_key)
 
2894
                    if not present:
 
2895
                        raise AssertionError('not present: %r', entry_key)
 
2896
                    entry_index, present = self._find_entry_index(entry_key, self._dirblocks[block_index][1])
 
2897
                    if not present:
 
2898
                        raise AssertionError('not present: %r', entry_key)
 
2899
                    self._dirblocks[block_index][1][entry_index][1][0] = \
 
2900
                        ('r', path_utf8, 0, False, '')
 
2901
        # add a containing dirblock if needed.
 
2902
        if new_details[0] == 'd':
 
2903
            subdir_key = (osutils.pathjoin(*key[0:2]), '', '')
 
2904
            block_index, present = self._find_block_index_from_key(subdir_key)
 
2905
            if not present:
 
2906
                self._dirblocks.insert(block_index, (subdir_key[0], []))
 
2907
 
 
2908
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
2909
 
 
2910
    def _maybe_remove_row(self, block, index, id_index):
 
2911
        """Remove index if it is absent or relocated across the row.
 
2912
        
 
2913
        id_index is updated accordingly.
 
2914
        :return: True if we removed the row, False otherwise
 
2915
        """
 
2916
        present_in_row = False
 
2917
        entry = block[index]
 
2918
        for column in entry[1]:
 
2919
            if column[0] not in 'ar':
 
2920
                present_in_row = True
 
2921
                break
 
2922
        if not present_in_row:
 
2923
            block.pop(index)
 
2924
            self._remove_from_id_index(id_index, entry[0])
 
2925
            return True
 
2926
        return False
 
2927
 
 
2928
    def _validate(self):
 
2929
        """Check that invariants on the dirblock are correct.
 
2930
 
 
2931
        This can be useful in debugging; it shouldn't be necessary in
 
2932
        normal code.
 
2933
 
 
2934
        This must be called with a lock held.
 
2935
        """
 
2936
        # NOTE: This must always raise AssertionError not just assert,
 
2937
        # otherwise it may not behave properly under python -O
 
2938
        #
 
2939
        # TODO: All entries must have some content that's not 'a' or 'r',
 
2940
        # otherwise it could just be removed.
 
2941
        #
 
2942
        # TODO: All relocations must point directly to a real entry.
 
2943
        #
 
2944
        # TODO: No repeated keys.
 
2945
        #
 
2946
        # -- mbp 20070325
 
2947
        from pprint import pformat
 
2948
        self._read_dirblocks_if_needed()
 
2949
        if len(self._dirblocks) > 0:
 
2950
            if not self._dirblocks[0][0] == '':
 
2951
                raise AssertionError(
 
2952
                    "dirblocks don't start with root block:\n" + \
 
2953
                    pformat(self._dirblocks))
 
2954
        if len(self._dirblocks) > 1:
 
2955
            if not self._dirblocks[1][0] == '':
 
2956
                raise AssertionError(
 
2957
                    "dirblocks missing root directory:\n" + \
 
2958
                    pformat(self._dirblocks))
 
2959
        # the dirblocks are sorted by their path components, name, and dir id
 
2960
        dir_names = [d[0].split('/')
 
2961
                for d in self._dirblocks[1:]]
 
2962
        if dir_names != sorted(dir_names):
 
2963
            raise AssertionError(
 
2964
                "dir names are not in sorted order:\n" + \
 
2965
                pformat(self._dirblocks) + \
 
2966
                "\nkeys:\n" +
 
2967
                pformat(dir_names))
 
2968
        for dirblock in self._dirblocks:
 
2969
            # within each dirblock, the entries are sorted by filename and
 
2970
            # then by id.
 
2971
            for entry in dirblock[1]:
 
2972
                if dirblock[0] != entry[0][0]:
 
2973
                    raise AssertionError(
 
2974
                        "entry key for %r"
 
2975
                        "doesn't match directory name in\n%r" %
 
2976
                        (entry, pformat(dirblock)))
 
2977
            if dirblock[1] != sorted(dirblock[1]):
 
2978
                raise AssertionError(
 
2979
                    "dirblock for %r is not sorted:\n%s" % \
 
2980
                    (dirblock[0], pformat(dirblock)))
 
2981
 
 
2982
        def check_valid_parent():
 
2983
            """Check that the current entry has a valid parent.
 
2984
 
 
2985
            This makes sure that the parent has a record,
 
2986
            and that the parent isn't marked as "absent" in the
 
2987
            current tree. (It is invalid to have a non-absent file in an absent
 
2988
            directory.)
 
2989
            """
 
2990
            if entry[0][0:2] == ('', ''):
 
2991
                # There should be no parent for the root row
 
2992
                return
 
2993
            parent_entry = self._get_entry(tree_index, path_utf8=entry[0][0])
 
2994
            if parent_entry == (None, None):
 
2995
                raise AssertionError(
 
2996
                    "no parent entry for: %s in tree %s"
 
2997
                    % (this_path, tree_index))
 
2998
            if parent_entry[1][tree_index][0] != 'd':
 
2999
                raise AssertionError(
 
3000
                    "Parent entry for %s is not marked as a valid"
 
3001
                    " directory. %s" % (this_path, parent_entry,))
 
3002
 
 
3003
        # For each file id, for each tree: either
 
3004
        # the file id is not present at all; all rows with that id in the
 
3005
        # key have it marked as 'absent'
 
3006
        # OR the file id is present under exactly one name; any other entries
 
3007
        # that mention that id point to the correct name.
 
3008
        #
 
3009
        # We check this with a dict per tree pointing either to the present
 
3010
        # name, or None if absent.
 
3011
        tree_count = self._num_present_parents() + 1
 
3012
        id_path_maps = [dict() for i in range(tree_count)]
 
3013
        # Make sure that all renamed entries point to the correct location.
 
3014
        for entry in self._iter_entries():
 
3015
            file_id = entry[0][2]
 
3016
            this_path = osutils.pathjoin(entry[0][0], entry[0][1])
 
3017
            if len(entry[1]) != tree_count:
 
3018
                raise AssertionError(
 
3019
                "wrong number of entry details for row\n%s" \
 
3020
                ",\nexpected %d" % \
 
3021
                (pformat(entry), tree_count))
 
3022
            absent_positions = 0
 
3023
            for tree_index, tree_state in enumerate(entry[1]):
 
3024
                this_tree_map = id_path_maps[tree_index]
 
3025
                minikind = tree_state[0]
 
3026
                if minikind in 'ar':
 
3027
                    absent_positions += 1
 
3028
                # have we seen this id before in this column?
 
3029
                if file_id in this_tree_map:
 
3030
                    previous_path, previous_loc = this_tree_map[file_id]
 
3031
                    # any later mention of this file must be consistent with
 
3032
                    # what was said before
 
3033
                    if minikind == 'a':
 
3034
                        if previous_path is not None:
 
3035
                            raise AssertionError(
 
3036
                            "file %s is absent in row %r but also present " \
 
3037
                            "at %r"% \
 
3038
                            (file_id, entry, previous_path))
 
3039
                    elif minikind == 'r':
 
3040
                        target_location = tree_state[1]
 
3041
                        if previous_path != target_location:
 
3042
                            raise AssertionError(
 
3043
                            "file %s relocation in row %r but also at %r" \
 
3044
                            % (file_id, entry, previous_path))
 
3045
                    else:
 
3046
                        # a file, directory, etc - may have been previously
 
3047
                        # pointed to by a relocation, which must point here
 
3048
                        if previous_path != this_path:
 
3049
                            raise AssertionError(
 
3050
                                "entry %r inconsistent with previous path %r "
 
3051
                                "seen at %r" %
 
3052
                                (entry, previous_path, previous_loc))
 
3053
                        check_valid_parent()
 
3054
                else:
 
3055
                    if minikind == 'a':
 
3056
                        # absent; should not occur anywhere else
 
3057
                        this_tree_map[file_id] = None, this_path
 
3058
                    elif minikind == 'r':
 
3059
                        # relocation, must occur at expected location
 
3060
                        this_tree_map[file_id] = tree_state[1], this_path
 
3061
                    else:
 
3062
                        this_tree_map[file_id] = this_path, this_path
 
3063
                        check_valid_parent()
 
3064
            if absent_positions == tree_count:
 
3065
                raise AssertionError(
 
3066
                    "entry %r has no data for any tree." % (entry,))
 
3067
        if self._id_index is not None:
 
3068
            for file_id, entry_keys in self._id_index.iteritems():
 
3069
                for entry_key in entry_keys:
 
3070
                    if entry_key[2] != file_id:
 
3071
                        raise AssertionError(
 
3072
                            'file_id %r did not match entry key %s'
 
3073
                            % (file_id, entry_key))
 
3074
                if len(entry_keys) != len(set(entry_keys)):
 
3075
                    raise AssertionError(
 
3076
                        'id_index contained non-unique data for %s'
 
3077
                        % (entry_keys,))
 
3078
 
 
3079
    def _wipe_state(self):
 
3080
        """Forget all state information about the dirstate."""
 
3081
        self._header_state = DirState.NOT_IN_MEMORY
 
3082
        self._dirblock_state = DirState.NOT_IN_MEMORY
 
3083
        self._changes_aborted = False
 
3084
        self._parents = []
 
3085
        self._ghosts = []
 
3086
        self._dirblocks = []
 
3087
        self._id_index = None
 
3088
        self._packed_stat_index = None
 
3089
        self._end_of_header = None
 
3090
        self._cutoff_time = None
 
3091
        self._split_path_cache = {}
 
3092
 
 
3093
    def lock_read(self):
 
3094
        """Acquire a read lock on the dirstate."""
 
3095
        if self._lock_token is not None:
 
3096
            raise errors.LockContention(self._lock_token)
 
3097
        # TODO: jam 20070301 Rather than wiping completely, if the blocks are
 
3098
        #       already in memory, we could read just the header and check for
 
3099
        #       any modification. If not modified, we can just leave things
 
3100
        #       alone
 
3101
        self._lock_token = lock.ReadLock(self._filename)
 
3102
        self._lock_state = 'r'
 
3103
        self._state_file = self._lock_token.f
 
3104
        self._wipe_state()
 
3105
 
 
3106
    def lock_write(self):
 
3107
        """Acquire a write lock on the dirstate."""
 
3108
        if self._lock_token is not None:
 
3109
            raise errors.LockContention(self._lock_token)
 
3110
        # TODO: jam 20070301 Rather than wiping completely, if the blocks are
 
3111
        #       already in memory, we could read just the header and check for
 
3112
        #       any modification. If not modified, we can just leave things
 
3113
        #       alone
 
3114
        self._lock_token = lock.WriteLock(self._filename)
 
3115
        self._lock_state = 'w'
 
3116
        self._state_file = self._lock_token.f
 
3117
        self._wipe_state()
 
3118
 
 
3119
    def unlock(self):
 
3120
        """Drop any locks held on the dirstate."""
 
3121
        if self._lock_token is None:
 
3122
            raise errors.LockNotHeld(self)
 
3123
        # TODO: jam 20070301 Rather than wiping completely, if the blocks are
 
3124
        #       already in memory, we could read just the header and check for
 
3125
        #       any modification. If not modified, we can just leave things
 
3126
        #       alone
 
3127
        self._state_file = None
 
3128
        self._lock_state = None
 
3129
        self._lock_token.unlock()
 
3130
        self._lock_token = None
 
3131
        self._split_path_cache = {}
 
3132
 
 
3133
    def _requires_lock(self):
 
3134
        """Check that a lock is currently held by someone on the dirstate."""
 
3135
        if not self._lock_token:
 
3136
            raise errors.ObjectNotLocked(self)
 
3137
 
 
3138
 
 
3139
def py_update_entry(state, entry, abspath, stat_value,
 
3140
                 _stat_to_minikind=DirState._stat_to_minikind,
 
3141
                 _pack_stat=pack_stat):
 
3142
    """Update the entry based on what is actually on disk.
 
3143
 
 
3144
    This function only calculates the sha if it needs to - if the entry is
 
3145
    uncachable, or clearly different to the first parent's entry, no sha
 
3146
    is calculated, and None is returned.
 
3147
 
 
3148
    :param state: The dirstate this entry is in.
 
3149
    :param entry: This is the dirblock entry for the file in question.
 
3150
    :param abspath: The path on disk for this file.
 
3151
    :param stat_value: The stat value done on the path.
 
3152
    :return: None, or The sha1 hexdigest of the file (40 bytes) or link
 
3153
        target of a symlink.
 
3154
    """
 
3155
    try:
 
3156
        minikind = _stat_to_minikind[stat_value.st_mode & 0170000]
 
3157
    except KeyError:
 
3158
        # Unhandled kind
 
3159
        return None
 
3160
    packed_stat = _pack_stat(stat_value)
 
3161
    (saved_minikind, saved_link_or_sha1, saved_file_size,
 
3162
     saved_executable, saved_packed_stat) = entry[1][0]
 
3163
 
 
3164
    if minikind == 'd' and saved_minikind == 't':
 
3165
        minikind = 't'
 
3166
    if (minikind == saved_minikind
 
3167
        and packed_stat == saved_packed_stat):
 
3168
        # The stat hasn't changed since we saved, so we can re-use the
 
3169
        # saved sha hash.
 
3170
        if minikind == 'd':
 
3171
            return None
 
3172
 
 
3173
        # size should also be in packed_stat
 
3174
        if saved_file_size == stat_value.st_size:
 
3175
            return saved_link_or_sha1
 
3176
 
 
3177
    # If we have gotten this far, that means that we need to actually
 
3178
    # process this entry.
 
3179
    link_or_sha1 = None
 
3180
    if minikind == 'f':
 
3181
        executable = state._is_executable(stat_value.st_mode,
 
3182
                                         saved_executable)
 
3183
        if state._cutoff_time is None:
 
3184
            state._sha_cutoff_time()
 
3185
        if (stat_value.st_mtime < state._cutoff_time
 
3186
            and stat_value.st_ctime < state._cutoff_time
 
3187
            and len(entry[1]) > 1
 
3188
            and entry[1][1][0] != 'a'):
 
3189
            # Could check for size changes for further optimised
 
3190
            # avoidance of sha1's. However the most prominent case of
 
3191
            # over-shaing is during initial add, which this catches.
 
3192
            # Besides, if content filtering happens, size and sha
 
3193
            # are calculated at the same time, so checking just the size
 
3194
            # gains nothing w.r.t. performance.
 
3195
            link_or_sha1 = state._sha1_file(abspath)
 
3196
            entry[1][0] = ('f', link_or_sha1, stat_value.st_size,
 
3197
                           executable, packed_stat)
 
3198
        else:
 
3199
            entry[1][0] = ('f', '', stat_value.st_size,
 
3200
                           executable, DirState.NULLSTAT)
 
3201
    elif minikind == 'd':
 
3202
        link_or_sha1 = None
 
3203
        entry[1][0] = ('d', '', 0, False, packed_stat)
 
3204
        if saved_minikind != 'd':
 
3205
            # This changed from something into a directory. Make sure we
 
3206
            # have a directory block for it. This doesn't happen very
 
3207
            # often, so this doesn't have to be super fast.
 
3208
            block_index, entry_index, dir_present, file_present = \
 
3209
                state._get_block_entry_index(entry[0][0], entry[0][1], 0)
 
3210
            state._ensure_block(block_index, entry_index,
 
3211
                               osutils.pathjoin(entry[0][0], entry[0][1]))
 
3212
    elif minikind == 'l':
 
3213
        link_or_sha1 = state._read_link(abspath, saved_link_or_sha1)
 
3214
        if state._cutoff_time is None:
 
3215
            state._sha_cutoff_time()
 
3216
        if (stat_value.st_mtime < state._cutoff_time
 
3217
            and stat_value.st_ctime < state._cutoff_time):
 
3218
            entry[1][0] = ('l', link_or_sha1, stat_value.st_size,
 
3219
                           False, packed_stat)
 
3220
        else:
 
3221
            entry[1][0] = ('l', '', stat_value.st_size,
 
3222
                           False, DirState.NULLSTAT)
 
3223
    state._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
3224
    return link_or_sha1
 
3225
 
 
3226
 
 
3227
class ProcessEntryPython(object):
 
3228
 
 
3229
    __slots__ = ["old_dirname_to_file_id", "new_dirname_to_file_id",
 
3230
        "last_source_parent", "last_target_parent", "include_unchanged",
 
3231
        "partial", "use_filesystem_for_exec", "utf8_decode",
 
3232
        "searched_specific_files", "search_specific_files",
 
3233
        "searched_exact_paths", "search_specific_file_parents", "seen_ids",
 
3234
        "state", "source_index", "target_index", "want_unversioned", "tree"]
 
3235
 
 
3236
    def __init__(self, include_unchanged, use_filesystem_for_exec,
 
3237
        search_specific_files, state, source_index, target_index,
 
3238
        want_unversioned, tree):
 
3239
        self.old_dirname_to_file_id = {}
 
3240
        self.new_dirname_to_file_id = {}
 
3241
        # Are we doing a partial iter_changes?
 
3242
        self.partial = search_specific_files != set([''])
 
3243
        # Using a list so that we can access the values and change them in
 
3244
        # nested scope. Each one is [path, file_id, entry]
 
3245
        self.last_source_parent = [None, None]
 
3246
        self.last_target_parent = [None, None]
 
3247
        self.include_unchanged = include_unchanged
 
3248
        self.use_filesystem_for_exec = use_filesystem_for_exec
 
3249
        self.utf8_decode = cache_utf8._utf8_decode
 
3250
        # for all search_indexs in each path at or under each element of
 
3251
        # search_specific_files, if the detail is relocated: add the id, and
 
3252
        # add the relocated path as one to search if its not searched already.
 
3253
        # If the detail is not relocated, add the id.
 
3254
        self.searched_specific_files = set()
 
3255
        # When we search exact paths without expanding downwards, we record
 
3256
        # that here.
 
3257
        self.searched_exact_paths = set()
 
3258
        self.search_specific_files = search_specific_files
 
3259
        # The parents up to the root of the paths we are searching.
 
3260
        # After all normal paths are returned, these specific items are returned.
 
3261
        self.search_specific_file_parents = set()
 
3262
        # The ids we've sent out in the delta.
 
3263
        self.seen_ids = set()
 
3264
        self.state = state
 
3265
        self.source_index = source_index
 
3266
        self.target_index = target_index
 
3267
        if target_index != 0:
 
3268
            # A lot of code in here depends on target_index == 0
 
3269
            raise errors.BzrError('unsupported target index')
 
3270
        self.want_unversioned = want_unversioned
 
3271
        self.tree = tree
 
3272
 
 
3273
    def _process_entry(self, entry, path_info, pathjoin=osutils.pathjoin):
 
3274
        """Compare an entry and real disk to generate delta information.
 
3275
 
 
3276
        :param path_info: top_relpath, basename, kind, lstat, abspath for
 
3277
            the path of entry. If None, then the path is considered absent in 
 
3278
            the target (Perhaps we should pass in a concrete entry for this ?)
 
3279
            Basename is returned as a utf8 string because we expect this
 
3280
            tuple will be ignored, and don't want to take the time to
 
3281
            decode.
 
3282
        :return: (iter_changes_result, changed). If the entry has not been
 
3283
            handled then changed is None. Otherwise it is False if no content
 
3284
            or metadata changes have occurred, and True if any content or
 
3285
            metadata change has occurred. If self.include_unchanged is True then
 
3286
            if changed is not None, iter_changes_result will always be a result
 
3287
            tuple. Otherwise, iter_changes_result is None unless changed is
 
3288
            True.
 
3289
        """
 
3290
        if self.source_index is None:
 
3291
            source_details = DirState.NULL_PARENT_DETAILS
 
3292
        else:
 
3293
            source_details = entry[1][self.source_index]
 
3294
        target_details = entry[1][self.target_index]
 
3295
        target_minikind = target_details[0]
 
3296
        if path_info is not None and target_minikind in 'fdlt':
 
3297
            if not (self.target_index == 0):
 
3298
                raise AssertionError()
 
3299
            link_or_sha1 = update_entry(self.state, entry,
 
3300
                abspath=path_info[4], stat_value=path_info[3])
 
3301
            # The entry may have been modified by update_entry
 
3302
            target_details = entry[1][self.target_index]
 
3303
            target_minikind = target_details[0]
 
3304
        else:
 
3305
            link_or_sha1 = None
 
3306
        file_id = entry[0][2]
 
3307
        source_minikind = source_details[0]
 
3308
        if source_minikind in 'fdltr' and target_minikind in 'fdlt':
 
3309
            # claimed content in both: diff
 
3310
            #   r    | fdlt   |      | add source to search, add id path move and perform
 
3311
            #        |        |      | diff check on source-target
 
3312
            #   r    | fdlt   |  a   | dangling file that was present in the basis.
 
3313
            #        |        |      | ???
 
3314
            if source_minikind in 'r':
 
3315
                # add the source to the search path to find any children it
 
3316
                # has.  TODO ? : only add if it is a container ?
 
3317
                if not osutils.is_inside_any(self.searched_specific_files,
 
3318
                                             source_details[1]):
 
3319
                    self.search_specific_files.add(source_details[1])
 
3320
                # generate the old path; this is needed for stating later
 
3321
                # as well.
 
3322
                old_path = source_details[1]
 
3323
                old_dirname, old_basename = os.path.split(old_path)
 
3324
                path = pathjoin(entry[0][0], entry[0][1])
 
3325
                old_entry = self.state._get_entry(self.source_index,
 
3326
                                             path_utf8=old_path)
 
3327
                # update the source details variable to be the real
 
3328
                # location.
 
3329
                if old_entry == (None, None):
 
3330
                    raise errors.CorruptDirstate(self.state._filename,
 
3331
                        "entry '%s/%s' is considered renamed from %r"
 
3332
                        " but source does not exist\n"
 
3333
                        "entry: %s" % (entry[0][0], entry[0][1], old_path, entry))
 
3334
                source_details = old_entry[1][self.source_index]
 
3335
                source_minikind = source_details[0]
 
3336
            else:
 
3337
                old_dirname = entry[0][0]
 
3338
                old_basename = entry[0][1]
 
3339
                old_path = path = None
 
3340
            if path_info is None:
 
3341
                # the file is missing on disk, show as removed.
 
3342
                content_change = True
 
3343
                target_kind = None
 
3344
                target_exec = False
 
3345
            else:
 
3346
                # source and target are both versioned and disk file is present.
 
3347
                target_kind = path_info[2]
 
3348
                if target_kind == 'directory':
 
3349
                    if path is None:
 
3350
                        old_path = path = pathjoin(old_dirname, old_basename)
 
3351
                    self.new_dirname_to_file_id[path] = file_id
 
3352
                    if source_minikind != 'd':
 
3353
                        content_change = True
 
3354
                    else:
 
3355
                        # directories have no fingerprint
 
3356
                        content_change = False
 
3357
                    target_exec = False
 
3358
                elif target_kind == 'file':
 
3359
                    if source_minikind != 'f':
 
3360
                        content_change = True
 
3361
                    else:
 
3362
                        # Check the sha. We can't just rely on the size as
 
3363
                        # content filtering may mean differ sizes actually
 
3364
                        # map to the same content
 
3365
                        if link_or_sha1 is None:
 
3366
                            # Stat cache miss:
 
3367
                            statvalue, link_or_sha1 = \
 
3368
                                self.state._sha1_provider.stat_and_sha1(
 
3369
                                path_info[4])
 
3370
                            self.state._observed_sha1(entry, link_or_sha1,
 
3371
                                statvalue)
 
3372
                        content_change = (link_or_sha1 != source_details[1])
 
3373
                    # Target details is updated at update_entry time
 
3374
                    if self.use_filesystem_for_exec:
 
3375
                        # We don't need S_ISREG here, because we are sure
 
3376
                        # we are dealing with a file.
 
3377
                        target_exec = bool(stat.S_IEXEC & path_info[3].st_mode)
 
3378
                    else:
 
3379
                        target_exec = target_details[3]
 
3380
                elif target_kind == 'symlink':
 
3381
                    if source_minikind != 'l':
 
3382
                        content_change = True
 
3383
                    else:
 
3384
                        content_change = (link_or_sha1 != source_details[1])
 
3385
                    target_exec = False
 
3386
                elif target_kind == 'tree-reference':
 
3387
                    if source_minikind != 't':
 
3388
                        content_change = True
 
3389
                    else:
 
3390
                        content_change = False
 
3391
                    target_exec = False
 
3392
                else:
 
3393
                    if path is None:
 
3394
                        path = pathjoin(old_dirname, old_basename)
 
3395
                    raise errors.BadFileKindError(path, path_info[2])
 
3396
            if source_minikind == 'd':
 
3397
                if path is None:
 
3398
                    old_path = path = pathjoin(old_dirname, old_basename)
 
3399
                self.old_dirname_to_file_id[old_path] = file_id
 
3400
            # parent id is the entry for the path in the target tree
 
3401
            if old_basename and old_dirname == self.last_source_parent[0]:
 
3402
                source_parent_id = self.last_source_parent[1]
 
3403
            else:
 
3404
                try:
 
3405
                    source_parent_id = self.old_dirname_to_file_id[old_dirname]
 
3406
                except KeyError:
 
3407
                    source_parent_entry = self.state._get_entry(self.source_index,
 
3408
                                                           path_utf8=old_dirname)
 
3409
                    source_parent_id = source_parent_entry[0][2]
 
3410
                if source_parent_id == entry[0][2]:
 
3411
                    # This is the root, so the parent is None
 
3412
                    source_parent_id = None
 
3413
                else:
 
3414
                    self.last_source_parent[0] = old_dirname
 
3415
                    self.last_source_parent[1] = source_parent_id
 
3416
            new_dirname = entry[0][0]
 
3417
            if entry[0][1] and new_dirname == self.last_target_parent[0]:
 
3418
                target_parent_id = self.last_target_parent[1]
 
3419
            else:
 
3420
                try:
 
3421
                    target_parent_id = self.new_dirname_to_file_id[new_dirname]
 
3422
                except KeyError:
 
3423
                    # TODO: We don't always need to do the lookup, because the
 
3424
                    #       parent entry will be the same as the source entry.
 
3425
                    target_parent_entry = self.state._get_entry(self.target_index,
 
3426
                                                           path_utf8=new_dirname)
 
3427
                    if target_parent_entry == (None, None):
 
3428
                        raise AssertionError(
 
3429
                            "Could not find target parent in wt: %s\nparent of: %s"
 
3430
                            % (new_dirname, entry))
 
3431
                    target_parent_id = target_parent_entry[0][2]
 
3432
                if target_parent_id == entry[0][2]:
 
3433
                    # This is the root, so the parent is None
 
3434
                    target_parent_id = None
 
3435
                else:
 
3436
                    self.last_target_parent[0] = new_dirname
 
3437
                    self.last_target_parent[1] = target_parent_id
 
3438
 
 
3439
            source_exec = source_details[3]
 
3440
            changed = (content_change
 
3441
                or source_parent_id != target_parent_id
 
3442
                or old_basename != entry[0][1]
 
3443
                or source_exec != target_exec
 
3444
                )
 
3445
            if not changed and not self.include_unchanged:
 
3446
                return None, False
 
3447
            else:
 
3448
                if old_path is None:
 
3449
                    old_path = path = pathjoin(old_dirname, old_basename)
 
3450
                    old_path_u = self.utf8_decode(old_path)[0]
 
3451
                    path_u = old_path_u
 
3452
                else:
 
3453
                    old_path_u = self.utf8_decode(old_path)[0]
 
3454
                    if old_path == path:
 
3455
                        path_u = old_path_u
 
3456
                    else:
 
3457
                        path_u = self.utf8_decode(path)[0]
 
3458
                source_kind = DirState._minikind_to_kind[source_minikind]
 
3459
                return (entry[0][2],
 
3460
                       (old_path_u, path_u),
 
3461
                       content_change,
 
3462
                       (True, True),
 
3463
                       (source_parent_id, target_parent_id),
 
3464
                       (self.utf8_decode(old_basename)[0], self.utf8_decode(entry[0][1])[0]),
 
3465
                       (source_kind, target_kind),
 
3466
                       (source_exec, target_exec)), changed
 
3467
        elif source_minikind in 'a' and target_minikind in 'fdlt':
 
3468
            # looks like a new file
 
3469
            path = pathjoin(entry[0][0], entry[0][1])
 
3470
            # parent id is the entry for the path in the target tree
 
3471
            # TODO: these are the same for an entire directory: cache em.
 
3472
            parent_id = self.state._get_entry(self.target_index,
 
3473
                                         path_utf8=entry[0][0])[0][2]
 
3474
            if parent_id == entry[0][2]:
 
3475
                parent_id = None
 
3476
            if path_info is not None:
 
3477
                # Present on disk:
 
3478
                if self.use_filesystem_for_exec:
 
3479
                    # We need S_ISREG here, because we aren't sure if this
 
3480
                    # is a file or not.
 
3481
                    target_exec = bool(
 
3482
                        stat.S_ISREG(path_info[3].st_mode)
 
3483
                        and stat.S_IEXEC & path_info[3].st_mode)
 
3484
                else:
 
3485
                    target_exec = target_details[3]
 
3486
                return (entry[0][2],
 
3487
                       (None, self.utf8_decode(path)[0]),
 
3488
                       True,
 
3489
                       (False, True),
 
3490
                       (None, parent_id),
 
3491
                       (None, self.utf8_decode(entry[0][1])[0]),
 
3492
                       (None, path_info[2]),
 
3493
                       (None, target_exec)), True
 
3494
            else:
 
3495
                # Its a missing file, report it as such.
 
3496
                return (entry[0][2],
 
3497
                       (None, self.utf8_decode(path)[0]),
 
3498
                       False,
 
3499
                       (False, True),
 
3500
                       (None, parent_id),
 
3501
                       (None, self.utf8_decode(entry[0][1])[0]),
 
3502
                       (None, None),
 
3503
                       (None, False)), True
 
3504
        elif source_minikind in 'fdlt' and target_minikind in 'a':
 
3505
            # unversioned, possibly, or possibly not deleted: we dont care.
 
3506
            # if its still on disk, *and* theres no other entry at this
 
3507
            # path [we dont know this in this routine at the moment -
 
3508
            # perhaps we should change this - then it would be an unknown.
 
3509
            old_path = pathjoin(entry[0][0], entry[0][1])
 
3510
            # parent id is the entry for the path in the target tree
 
3511
            parent_id = self.state._get_entry(self.source_index, path_utf8=entry[0][0])[0][2]
 
3512
            if parent_id == entry[0][2]:
 
3513
                parent_id = None
 
3514
            return (entry[0][2],
 
3515
                   (self.utf8_decode(old_path)[0], None),
 
3516
                   True,
 
3517
                   (True, False),
 
3518
                   (parent_id, None),
 
3519
                   (self.utf8_decode(entry[0][1])[0], None),
 
3520
                   (DirState._minikind_to_kind[source_minikind], None),
 
3521
                   (source_details[3], None)), True
 
3522
        elif source_minikind in 'fdlt' and target_minikind in 'r':
 
3523
            # a rename; could be a true rename, or a rename inherited from
 
3524
            # a renamed parent. TODO: handle this efficiently. Its not
 
3525
            # common case to rename dirs though, so a correct but slow
 
3526
            # implementation will do.
 
3527
            if not osutils.is_inside_any(self.searched_specific_files, target_details[1]):
 
3528
                self.search_specific_files.add(target_details[1])
 
3529
        elif source_minikind in 'ra' and target_minikind in 'ra':
 
3530
            # neither of the selected trees contain this file,
 
3531
            # so skip over it. This is not currently directly tested, but
 
3532
            # is indirectly via test_too_much.TestCommands.test_conflicts.
 
3533
            pass
 
3534
        else:
 
3535
            raise AssertionError("don't know how to compare "
 
3536
                "source_minikind=%r, target_minikind=%r"
 
3537
                % (source_minikind, target_minikind))
 
3538
            ## import pdb;pdb.set_trace()
 
3539
        return None, None
 
3540
 
 
3541
    def __iter__(self):
 
3542
        return self
 
3543
 
 
3544
    def _gather_result_for_consistency(self, result):
 
3545
        """Check a result we will yield to make sure we are consistent later.
 
3546
        
 
3547
        This gathers result's parents into a set to output later.
 
3548
 
 
3549
        :param result: A result tuple.
 
3550
        """
 
3551
        if not self.partial or not result[0]:
 
3552
            return
 
3553
        self.seen_ids.add(result[0])
 
3554
        new_path = result[1][1]
 
3555
        if new_path:
 
3556
            # Not the root and not a delete: queue up the parents of the path.
 
3557
            self.search_specific_file_parents.update(
 
3558
                osutils.parent_directories(new_path.encode('utf8')))
 
3559
            # Add the root directory which parent_directories does not
 
3560
            # provide.
 
3561
            self.search_specific_file_parents.add('')
 
3562
 
 
3563
    def iter_changes(self):
 
3564
        """Iterate over the changes."""
 
3565
        utf8_decode = cache_utf8._utf8_decode
 
3566
        _cmp_by_dirs = cmp_by_dirs
 
3567
        _process_entry = self._process_entry
 
3568
        search_specific_files = self.search_specific_files
 
3569
        searched_specific_files = self.searched_specific_files
 
3570
        splitpath = osutils.splitpath
 
3571
        # sketch:
 
3572
        # compare source_index and target_index at or under each element of search_specific_files.
 
3573
        # follow the following comparison table. Note that we only want to do diff operations when
 
3574
        # the target is fdl because thats when the walkdirs logic will have exposed the pathinfo
 
3575
        # for the target.
 
3576
        # cases:
 
3577
        #
 
3578
        # Source | Target | disk | action
 
3579
        #   r    | fdlt   |      | add source to search, add id path move and perform
 
3580
        #        |        |      | diff check on source-target
 
3581
        #   r    | fdlt   |  a   | dangling file that was present in the basis.
 
3582
        #        |        |      | ???
 
3583
        #   r    |  a     |      | add source to search
 
3584
        #   r    |  a     |  a   |
 
3585
        #   r    |  r     |      | this path is present in a non-examined tree, skip.
 
3586
        #   r    |  r     |  a   | this path is present in a non-examined tree, skip.
 
3587
        #   a    | fdlt   |      | add new id
 
3588
        #   a    | fdlt   |  a   | dangling locally added file, skip
 
3589
        #   a    |  a     |      | not present in either tree, skip
 
3590
        #   a    |  a     |  a   | not present in any tree, skip
 
3591
        #   a    |  r     |      | not present in either tree at this path, skip as it
 
3592
        #        |        |      | may not be selected by the users list of paths.
 
3593
        #   a    |  r     |  a   | not present in either tree at this path, skip as it
 
3594
        #        |        |      | may not be selected by the users list of paths.
 
3595
        #  fdlt  | fdlt   |      | content in both: diff them
 
3596
        #  fdlt  | fdlt   |  a   | deleted locally, but not unversioned - show as deleted ?
 
3597
        #  fdlt  |  a     |      | unversioned: output deleted id for now
 
3598
        #  fdlt  |  a     |  a   | unversioned and deleted: output deleted id
 
3599
        #  fdlt  |  r     |      | relocated in this tree, so add target to search.
 
3600
        #        |        |      | Dont diff, we will see an r,fd; pair when we reach
 
3601
        #        |        |      | this id at the other path.
 
3602
        #  fdlt  |  r     |  a   | relocated in this tree, so add target to search.
 
3603
        #        |        |      | Dont diff, we will see an r,fd; pair when we reach
 
3604
        #        |        |      | this id at the other path.
 
3605
 
 
3606
        # TODO: jam 20070516 - Avoid the _get_entry lookup overhead by
 
3607
        #       keeping a cache of directories that we have seen.
 
3608
 
 
3609
        while search_specific_files:
 
3610
            # TODO: the pending list should be lexically sorted?  the
 
3611
            # interface doesn't require it.
 
3612
            current_root = search_specific_files.pop()
 
3613
            current_root_unicode = current_root.decode('utf8')
 
3614
            searched_specific_files.add(current_root)
 
3615
            # process the entries for this containing directory: the rest will be
 
3616
            # found by their parents recursively.
 
3617
            root_entries = self.state._entries_for_path(current_root)
 
3618
            root_abspath = self.tree.abspath(current_root_unicode)
 
3619
            try:
 
3620
                root_stat = os.lstat(root_abspath)
 
3621
            except OSError, e:
 
3622
                if e.errno == errno.ENOENT:
 
3623
                    # the path does not exist: let _process_entry know that.
 
3624
                    root_dir_info = None
 
3625
                else:
 
3626
                    # some other random error: hand it up.
 
3627
                    raise
 
3628
            else:
 
3629
                root_dir_info = ('', current_root,
 
3630
                    osutils.file_kind_from_stat_mode(root_stat.st_mode), root_stat,
 
3631
                    root_abspath)
 
3632
                if root_dir_info[2] == 'directory':
 
3633
                    if self.tree._directory_is_tree_reference(
 
3634
                        current_root.decode('utf8')):
 
3635
                        root_dir_info = root_dir_info[:2] + \
 
3636
                            ('tree-reference',) + root_dir_info[3:]
 
3637
 
 
3638
            if not root_entries and not root_dir_info:
 
3639
                # this specified path is not present at all, skip it.
 
3640
                continue
 
3641
            path_handled = False
 
3642
            for entry in root_entries:
 
3643
                result, changed = _process_entry(entry, root_dir_info)
 
3644
                if changed is not None:
 
3645
                    path_handled = True
 
3646
                    if changed:
 
3647
                        self._gather_result_for_consistency(result)
 
3648
                    if changed or self.include_unchanged:
 
3649
                        yield result
 
3650
            if self.want_unversioned and not path_handled and root_dir_info:
 
3651
                new_executable = bool(
 
3652
                    stat.S_ISREG(root_dir_info[3].st_mode)
 
3653
                    and stat.S_IEXEC & root_dir_info[3].st_mode)
 
3654
                yield (None,
 
3655
                       (None, current_root_unicode),
 
3656
                       True,
 
3657
                       (False, False),
 
3658
                       (None, None),
 
3659
                       (None, splitpath(current_root_unicode)[-1]),
 
3660
                       (None, root_dir_info[2]),
 
3661
                       (None, new_executable)
 
3662
                      )
 
3663
            initial_key = (current_root, '', '')
 
3664
            block_index, _ = self.state._find_block_index_from_key(initial_key)
 
3665
            if block_index == 0:
 
3666
                # we have processed the total root already, but because the
 
3667
                # initial key matched it we should skip it here.
 
3668
                block_index +=1
 
3669
            if root_dir_info and root_dir_info[2] == 'tree-reference':
 
3670
                current_dir_info = None
 
3671
            else:
 
3672
                dir_iterator = osutils._walkdirs_utf8(root_abspath, prefix=current_root)
 
3673
                try:
 
3674
                    current_dir_info = dir_iterator.next()
 
3675
                except OSError, e:
 
3676
                    # on win32, python2.4 has e.errno == ERROR_DIRECTORY, but
 
3677
                    # python 2.5 has e.errno == EINVAL,
 
3678
                    #            and e.winerror == ERROR_DIRECTORY
 
3679
                    e_winerror = getattr(e, 'winerror', None)
 
3680
                    win_errors = (ERROR_DIRECTORY, ERROR_PATH_NOT_FOUND)
 
3681
                    # there may be directories in the inventory even though
 
3682
                    # this path is not a file on disk: so mark it as end of
 
3683
                    # iterator
 
3684
                    if e.errno in (errno.ENOENT, errno.ENOTDIR, errno.EINVAL):
 
3685
                        current_dir_info = None
 
3686
                    elif (sys.platform == 'win32'
 
3687
                          and (e.errno in win_errors
 
3688
                               or e_winerror in win_errors)):
 
3689
                        current_dir_info = None
 
3690
                    else:
 
3691
                        raise
 
3692
                else:
 
3693
                    if current_dir_info[0][0] == '':
 
3694
                        # remove .bzr from iteration
 
3695
                        bzr_index = bisect.bisect_left(current_dir_info[1], ('.bzr',))
 
3696
                        if current_dir_info[1][bzr_index][0] != '.bzr':
 
3697
                            raise AssertionError()
 
3698
                        del current_dir_info[1][bzr_index]
 
3699
            # walk until both the directory listing and the versioned metadata
 
3700
            # are exhausted.
 
3701
            if (block_index < len(self.state._dirblocks) and
 
3702
                osutils.is_inside(current_root, self.state._dirblocks[block_index][0])):
 
3703
                current_block = self.state._dirblocks[block_index]
 
3704
            else:
 
3705
                current_block = None
 
3706
            while (current_dir_info is not None or
 
3707
                   current_block is not None):
 
3708
                if (current_dir_info and current_block
 
3709
                    and current_dir_info[0][0] != current_block[0]):
 
3710
                    if _cmp_by_dirs(current_dir_info[0][0], current_block[0]) < 0:
 
3711
                        # filesystem data refers to paths not covered by the dirblock.
 
3712
                        # this has two possibilities:
 
3713
                        # A) it is versioned but empty, so there is no block for it
 
3714
                        # B) it is not versioned.
 
3715
 
 
3716
                        # if (A) then we need to recurse into it to check for
 
3717
                        # new unknown files or directories.
 
3718
                        # if (B) then we should ignore it, because we don't
 
3719
                        # recurse into unknown directories.
 
3720
                        path_index = 0
 
3721
                        while path_index < len(current_dir_info[1]):
 
3722
                                current_path_info = current_dir_info[1][path_index]
 
3723
                                if self.want_unversioned:
 
3724
                                    if current_path_info[2] == 'directory':
 
3725
                                        if self.tree._directory_is_tree_reference(
 
3726
                                            current_path_info[0].decode('utf8')):
 
3727
                                            current_path_info = current_path_info[:2] + \
 
3728
                                                ('tree-reference',) + current_path_info[3:]
 
3729
                                    new_executable = bool(
 
3730
                                        stat.S_ISREG(current_path_info[3].st_mode)
 
3731
                                        and stat.S_IEXEC & current_path_info[3].st_mode)
 
3732
                                    yield (None,
 
3733
                                        (None, utf8_decode(current_path_info[0])[0]),
 
3734
                                        True,
 
3735
                                        (False, False),
 
3736
                                        (None, None),
 
3737
                                        (None, utf8_decode(current_path_info[1])[0]),
 
3738
                                        (None, current_path_info[2]),
 
3739
                                        (None, new_executable))
 
3740
                                # dont descend into this unversioned path if it is
 
3741
                                # a dir
 
3742
                                if current_path_info[2] in ('directory',
 
3743
                                                            'tree-reference'):
 
3744
                                    del current_dir_info[1][path_index]
 
3745
                                    path_index -= 1
 
3746
                                path_index += 1
 
3747
 
 
3748
                        # This dir info has been handled, go to the next
 
3749
                        try:
 
3750
                            current_dir_info = dir_iterator.next()
 
3751
                        except StopIteration:
 
3752
                            current_dir_info = None
 
3753
                    else:
 
3754
                        # We have a dirblock entry for this location, but there
 
3755
                        # is no filesystem path for this. This is most likely
 
3756
                        # because a directory was removed from the disk.
 
3757
                        # We don't have to report the missing directory,
 
3758
                        # because that should have already been handled, but we
 
3759
                        # need to handle all of the files that are contained
 
3760
                        # within.
 
3761
                        for current_entry in current_block[1]:
 
3762
                            # entry referring to file not present on disk.
 
3763
                            # advance the entry only, after processing.
 
3764
                            result, changed = _process_entry(current_entry, None)
 
3765
                            if changed is not None:
 
3766
                                if changed:
 
3767
                                    self._gather_result_for_consistency(result)
 
3768
                                if changed or self.include_unchanged:
 
3769
                                    yield result
 
3770
                        block_index +=1
 
3771
                        if (block_index < len(self.state._dirblocks) and
 
3772
                            osutils.is_inside(current_root,
 
3773
                                              self.state._dirblocks[block_index][0])):
 
3774
                            current_block = self.state._dirblocks[block_index]
 
3775
                        else:
 
3776
                            current_block = None
 
3777
                    continue
 
3778
                entry_index = 0
 
3779
                if current_block and entry_index < len(current_block[1]):
 
3780
                    current_entry = current_block[1][entry_index]
 
3781
                else:
 
3782
                    current_entry = None
 
3783
                advance_entry = True
 
3784
                path_index = 0
 
3785
                if current_dir_info and path_index < len(current_dir_info[1]):
 
3786
                    current_path_info = current_dir_info[1][path_index]
 
3787
                    if current_path_info[2] == 'directory':
 
3788
                        if self.tree._directory_is_tree_reference(
 
3789
                            current_path_info[0].decode('utf8')):
 
3790
                            current_path_info = current_path_info[:2] + \
 
3791
                                ('tree-reference',) + current_path_info[3:]
 
3792
                else:
 
3793
                    current_path_info = None
 
3794
                advance_path = True
 
3795
                path_handled = False
 
3796
                while (current_entry is not None or
 
3797
                    current_path_info is not None):
 
3798
                    if current_entry is None:
 
3799
                        # the check for path_handled when the path is advanced
 
3800
                        # will yield this path if needed.
 
3801
                        pass
 
3802
                    elif current_path_info is None:
 
3803
                        # no path is fine: the per entry code will handle it.
 
3804
                        result, changed = _process_entry(current_entry, current_path_info)
 
3805
                        if changed is not None:
 
3806
                            if changed:
 
3807
                                self._gather_result_for_consistency(result)
 
3808
                            if changed or self.include_unchanged:
 
3809
                                yield result
 
3810
                    elif (current_entry[0][1] != current_path_info[1]
 
3811
                          or current_entry[1][self.target_index][0] in 'ar'):
 
3812
                        # The current path on disk doesn't match the dirblock
 
3813
                        # record. Either the dirblock is marked as absent, or
 
3814
                        # the file on disk is not present at all in the
 
3815
                        # dirblock. Either way, report about the dirblock
 
3816
                        # entry, and let other code handle the filesystem one.
 
3817
 
 
3818
                        # Compare the basename for these files to determine
 
3819
                        # which comes first
 
3820
                        if current_path_info[1] < current_entry[0][1]:
 
3821
                            # extra file on disk: pass for now, but only
 
3822
                            # increment the path, not the entry
 
3823
                            advance_entry = False
 
3824
                        else:
 
3825
                            # entry referring to file not present on disk.
 
3826
                            # advance the entry only, after processing.
 
3827
                            result, changed = _process_entry(current_entry, None)
 
3828
                            if changed is not None:
 
3829
                                if changed:
 
3830
                                    self._gather_result_for_consistency(result)
 
3831
                                if changed or self.include_unchanged:
 
3832
                                    yield result
 
3833
                            advance_path = False
 
3834
                    else:
 
3835
                        result, changed = _process_entry(current_entry, current_path_info)
 
3836
                        if changed is not None:
 
3837
                            path_handled = True
 
3838
                            if changed:
 
3839
                                self._gather_result_for_consistency(result)
 
3840
                            if changed or self.include_unchanged:
 
3841
                                yield result
 
3842
                    if advance_entry and current_entry is not None:
 
3843
                        entry_index += 1
 
3844
                        if entry_index < len(current_block[1]):
 
3845
                            current_entry = current_block[1][entry_index]
 
3846
                        else:
 
3847
                            current_entry = None
 
3848
                    else:
 
3849
                        advance_entry = True # reset the advance flaga
 
3850
                    if advance_path and current_path_info is not None:
 
3851
                        if not path_handled:
 
3852
                            # unversioned in all regards
 
3853
                            if self.want_unversioned:
 
3854
                                new_executable = bool(
 
3855
                                    stat.S_ISREG(current_path_info[3].st_mode)
 
3856
                                    and stat.S_IEXEC & current_path_info[3].st_mode)
 
3857
                                try:
 
3858
                                    relpath_unicode = utf8_decode(current_path_info[0])[0]
 
3859
                                except UnicodeDecodeError:
 
3860
                                    raise errors.BadFilenameEncoding(
 
3861
                                        current_path_info[0], osutils._fs_enc)
 
3862
                                yield (None,
 
3863
                                    (None, relpath_unicode),
 
3864
                                    True,
 
3865
                                    (False, False),
 
3866
                                    (None, None),
 
3867
                                    (None, utf8_decode(current_path_info[1])[0]),
 
3868
                                    (None, current_path_info[2]),
 
3869
                                    (None, new_executable))
 
3870
                            # dont descend into this unversioned path if it is
 
3871
                            # a dir
 
3872
                            if current_path_info[2] in ('directory'):
 
3873
                                del current_dir_info[1][path_index]
 
3874
                                path_index -= 1
 
3875
                        # dont descend the disk iterator into any tree
 
3876
                        # paths.
 
3877
                        if current_path_info[2] == 'tree-reference':
 
3878
                            del current_dir_info[1][path_index]
 
3879
                            path_index -= 1
 
3880
                        path_index += 1
 
3881
                        if path_index < len(current_dir_info[1]):
 
3882
                            current_path_info = current_dir_info[1][path_index]
 
3883
                            if current_path_info[2] == 'directory':
 
3884
                                if self.tree._directory_is_tree_reference(
 
3885
                                    current_path_info[0].decode('utf8')):
 
3886
                                    current_path_info = current_path_info[:2] + \
 
3887
                                        ('tree-reference',) + current_path_info[3:]
 
3888
                        else:
 
3889
                            current_path_info = None
 
3890
                        path_handled = False
 
3891
                    else:
 
3892
                        advance_path = True # reset the advance flagg.
 
3893
                if current_block is not None:
 
3894
                    block_index += 1
 
3895
                    if (block_index < len(self.state._dirblocks) and
 
3896
                        osutils.is_inside(current_root, self.state._dirblocks[block_index][0])):
 
3897
                        current_block = self.state._dirblocks[block_index]
 
3898
                    else:
 
3899
                        current_block = None
 
3900
                if current_dir_info is not None:
 
3901
                    try:
 
3902
                        current_dir_info = dir_iterator.next()
 
3903
                    except StopIteration:
 
3904
                        current_dir_info = None
 
3905
        for result in self._iter_specific_file_parents():
 
3906
            yield result
 
3907
 
 
3908
    def _iter_specific_file_parents(self):
 
3909
        """Iter over the specific file parents."""
 
3910
        while self.search_specific_file_parents:
 
3911
            # Process the parent directories for the paths we were iterating.
 
3912
            # Even in extremely large trees this should be modest, so currently
 
3913
            # no attempt is made to optimise.
 
3914
            path_utf8 = self.search_specific_file_parents.pop()
 
3915
            if osutils.is_inside_any(self.searched_specific_files, path_utf8):
 
3916
                # We've examined this path.
 
3917
                continue
 
3918
            if path_utf8 in self.searched_exact_paths:
 
3919
                # We've examined this path.
 
3920
                continue
 
3921
            path_entries = self.state._entries_for_path(path_utf8)
 
3922
            # We need either one or two entries. If the path in
 
3923
            # self.target_index has moved (so the entry in source_index is in
 
3924
            # 'ar') then we need to also look for the entry for this path in
 
3925
            # self.source_index, to output the appropriate delete-or-rename.
 
3926
            selected_entries = []
 
3927
            found_item = False
 
3928
            for candidate_entry in path_entries:
 
3929
                # Find entries present in target at this path:
 
3930
                if candidate_entry[1][self.target_index][0] not in 'ar':
 
3931
                    found_item = True
 
3932
                    selected_entries.append(candidate_entry)
 
3933
                # Find entries present in source at this path:
 
3934
                elif (self.source_index is not None and
 
3935
                    candidate_entry[1][self.source_index][0] not in 'ar'):
 
3936
                    found_item = True
 
3937
                    if candidate_entry[1][self.target_index][0] == 'a':
 
3938
                        # Deleted, emit it here.
 
3939
                        selected_entries.append(candidate_entry)
 
3940
                    else:
 
3941
                        # renamed, emit it when we process the directory it
 
3942
                        # ended up at.
 
3943
                        self.search_specific_file_parents.add(
 
3944
                            candidate_entry[1][self.target_index][1])
 
3945
            if not found_item:
 
3946
                raise AssertionError(
 
3947
                    "Missing entry for specific path parent %r, %r" % (
 
3948
                    path_utf8, path_entries))
 
3949
            path_info = self._path_info(path_utf8, path_utf8.decode('utf8'))
 
3950
            for entry in selected_entries:
 
3951
                if entry[0][2] in self.seen_ids:
 
3952
                    continue
 
3953
                result, changed = self._process_entry(entry, path_info)
 
3954
                if changed is None:
 
3955
                    raise AssertionError(
 
3956
                        "Got entry<->path mismatch for specific path "
 
3957
                        "%r entry %r path_info %r " % (
 
3958
                        path_utf8, entry, path_info))
 
3959
                # Only include changes - we're outside the users requested
 
3960
                # expansion.
 
3961
                if changed:
 
3962
                    self._gather_result_for_consistency(result)
 
3963
                    if (result[6][0] == 'directory' and
 
3964
                        result[6][1] != 'directory'):
 
3965
                        # This stopped being a directory, the old children have
 
3966
                        # to be included.
 
3967
                        if entry[1][self.source_index][0] == 'r':
 
3968
                            # renamed, take the source path
 
3969
                            entry_path_utf8 = entry[1][self.source_index][1]
 
3970
                        else:
 
3971
                            entry_path_utf8 = path_utf8
 
3972
                        initial_key = (entry_path_utf8, '', '')
 
3973
                        block_index, _ = self.state._find_block_index_from_key(
 
3974
                            initial_key)
 
3975
                        if block_index == 0:
 
3976
                            # The children of the root are in block index 1.
 
3977
                            block_index +=1
 
3978
                        current_block = None
 
3979
                        if block_index < len(self.state._dirblocks):
 
3980
                            current_block = self.state._dirblocks[block_index]
 
3981
                            if not osutils.is_inside(
 
3982
                                entry_path_utf8, current_block[0]):
 
3983
                                # No entries for this directory at all.
 
3984
                                current_block = None
 
3985
                        if current_block is not None:
 
3986
                            for entry in current_block[1]:
 
3987
                                if entry[1][self.source_index][0] in 'ar':
 
3988
                                    # Not in the source tree, so doesn't have to be
 
3989
                                    # included.
 
3990
                                    continue
 
3991
                                # Path of the entry itself.
 
3992
 
 
3993
                                self.search_specific_file_parents.add(
 
3994
                                    osutils.pathjoin(*entry[0][:2]))
 
3995
                if changed or self.include_unchanged:
 
3996
                    yield result
 
3997
            self.searched_exact_paths.add(path_utf8)
 
3998
 
 
3999
    def _path_info(self, utf8_path, unicode_path):
 
4000
        """Generate path_info for unicode_path.
 
4001
 
 
4002
        :return: None if unicode_path does not exist, or a path_info tuple.
 
4003
        """
 
4004
        abspath = self.tree.abspath(unicode_path)
 
4005
        try:
 
4006
            stat = os.lstat(abspath)
 
4007
        except OSError, e:
 
4008
            if e.errno == errno.ENOENT:
 
4009
                # the path does not exist.
 
4010
                return None
 
4011
            else:
 
4012
                raise
 
4013
        utf8_basename = utf8_path.rsplit('/', 1)[-1]
 
4014
        dir_info = (utf8_path, utf8_basename,
 
4015
            osutils.file_kind_from_stat_mode(stat.st_mode), stat,
 
4016
            abspath)
 
4017
        if dir_info[2] == 'directory':
 
4018
            if self.tree._directory_is_tree_reference(
 
4019
                unicode_path):
 
4020
                self.root_dir_info = self.root_dir_info[:2] + \
 
4021
                    ('tree-reference',) + self.root_dir_info[3:]
 
4022
        return dir_info
 
4023
 
 
4024
 
 
4025
# Try to load the compiled form if possible
 
4026
try:
 
4027
    from bzrlib._dirstate_helpers_pyx import (
 
4028
        _read_dirblocks,
 
4029
        bisect_dirblock,
 
4030
        _bisect_path_left,
 
4031
        _bisect_path_right,
 
4032
        cmp_by_dirs,
 
4033
        ProcessEntryC as _process_entry,
 
4034
        update_entry as update_entry,
 
4035
        )
 
4036
except ImportError, e:
 
4037
    osutils.failed_to_load_extension(e)
 
4038
    from bzrlib._dirstate_helpers_py import (
 
4039
        _read_dirblocks,
 
4040
        bisect_dirblock,
 
4041
        _bisect_path_left,
 
4042
        _bisect_path_right,
 
4043
        cmp_by_dirs,
 
4044
        )
 
4045
    # FIXME: It would be nice to be able to track moved lines so that the
 
4046
    # corresponding python code can be moved to the _dirstate_helpers_py
 
4047
    # module. I don't want to break the history for this important piece of
 
4048
    # code so I left the code here -- vila 20090622
 
4049
    update_entry = py_update_entry
 
4050
    _process_entry = ProcessEntryPython