~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/dirstate.py

(jelmer) Support upgrading between the 2a and development-colo formats.
 (Jelmer Vernooij)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006, 2007, 2008 Canonical Ltd
 
1
# Copyright (C) 2006-2011 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
17
"""DirState objects record the state of a directory and its bzr metadata.
18
18
 
20
20
lines by NL. The field delimiters are ommitted in the grammar, line delimiters
21
21
are not - this is done for clarity of reading. All string data is in utf8.
22
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
 
23
::
 
24
 
 
25
    MINIKIND = "f" | "d" | "l" | "a" | "r" | "t";
 
26
    NL = "\\n";
 
27
    NULL = "\\0";
 
28
    WHOLE_NUMBER = {digit}, digit;
 
29
    BOOLEAN = "y" | "n";
 
30
    REVISION_ID = a non-empty utf8 string;
 
31
    
 
32
    dirstate format = header line, full checksum, row count, parent details,
 
33
     ghost_details, entries;
 
34
    header line = "#bazaar dirstate flat format 3", NL;
 
35
    full checksum = "crc32: ", ["-"], WHOLE_NUMBER, NL;
 
36
    row count = "num_entries: ", WHOLE_NUMBER, NL;
 
37
    parent_details = WHOLE NUMBER, {REVISION_ID}* NL;
 
38
    ghost_details = WHOLE NUMBER, {REVISION_ID}*, NL;
 
39
    entries = {entry};
 
40
    entry = entry_key, current_entry_details, {parent_entry_details};
 
41
    entry_key = dirname,  basename, fileid;
 
42
    current_entry_details = common_entry_details, working_entry_details;
 
43
    parent_entry_details = common_entry_details, history_entry_details;
 
44
    common_entry_details = MINIKIND, fingerprint, size, executable
 
45
    working_entry_details = packed_stat
 
46
    history_entry_details = REVISION_ID;
 
47
    executable = BOOLEAN;
 
48
    size = WHOLE_NUMBER;
 
49
    fingerprint = a nonempty utf8 sequence with meaning defined by minikind.
 
50
 
 
51
Given this definition, the following is useful to know::
 
52
 
 
53
    entry (aka row) - all the data for a given key.
 
54
    entry[0]: The key (dirname, basename, fileid)
 
55
    entry[0][0]: dirname
 
56
    entry[0][1]: basename
 
57
    entry[0][2]: fileid
 
58
    entry[1]: The tree(s) data for this path and id combination.
 
59
    entry[1][0]: The current tree
 
60
    entry[1][1]: The second tree
 
61
 
 
62
For an entry for a tree, we have (using tree 0 - current tree) to demonstrate::
 
63
 
 
64
    entry[1][0][0]: minikind
 
65
    entry[1][0][1]: fingerprint
 
66
    entry[1][0][2]: size
 
67
    entry[1][0][3]: executable
 
68
    entry[1][0][4]: packed_stat
 
69
 
 
70
OR (for non tree-0)::
 
71
 
 
72
    entry[1][1][4]: revision_id
67
73
 
68
74
There may be multiple rows at the root, one per id present in the root, so the
69
 
in memory root row is now:
70
 
self._dirblocks[0] -> ('', [entry ...]),
71
 
and the entries in there are
72
 
entries[0][0]: ''
73
 
entries[0][1]: ''
74
 
entries[0][2]: file_id
75
 
entries[1][0]: The tree data for the current tree for this fileid at /
76
 
etc.
77
 
 
78
 
Kinds:
79
 
'r' is a relocated entry: This path is not present in this tree with this id,
80
 
    but the id can be found at another location. The fingerprint is used to
81
 
    point to the target location.
82
 
'a' is an absent entry: In that tree the id is not present at this path.
83
 
'd' is a directory entry: This path in this tree is a directory with the
84
 
    current file id. There is no fingerprint for directories.
85
 
'f' is a file entry: As for directory, but its a file. The fingerprint is a
86
 
    sha1 value.
87
 
'l' is a symlink entry: As for directory, but a symlink. The fingerprint is the
88
 
    link target.
89
 
't' is a reference to a nested subtree; the fingerprint is the referenced
90
 
    revision.
 
75
in memory root row is now::
 
76
 
 
77
    self._dirblocks[0] -> ('', [entry ...]),
 
78
 
 
79
and the entries in there are::
 
80
 
 
81
    entries[0][0]: ''
 
82
    entries[0][1]: ''
 
83
    entries[0][2]: file_id
 
84
    entries[1][0]: The tree data for the current tree for this fileid at /
 
85
    etc.
 
86
 
 
87
Kinds::
 
88
 
 
89
    'r' is a relocated entry: This path is not present in this tree with this
 
90
        id, but the id can be found at another location. The fingerprint is
 
91
        used to point to the target location.
 
92
    'a' is an absent entry: In that tree the id is not present at this path.
 
93
    'd' is a directory entry: This path in this tree is a directory with the
 
94
        current file id. There is no fingerprint for directories.
 
95
    'f' is a file entry: As for directory, but it's a file. The fingerprint is
 
96
        the sha1 value of the file's canonical form, i.e. after any read
 
97
        filters have been applied to the convenience form stored in the working
 
98
        tree.
 
99
    'l' is a symlink entry: As for directory, but a symlink. The fingerprint is
 
100
        the link target.
 
101
    't' is a reference to a nested subtree; the fingerprint is the referenced
 
102
        revision.
91
103
 
92
104
Ordering:
93
105
 
94
 
The entries on disk and in memory are ordered according to the following keys:
 
106
The entries on disk and in memory are ordered according to the following keys::
95
107
 
96
108
    directory, as a list of components
97
109
    filename
98
110
    file-id
99
111
 
100
112
--- Format 1 had the following different definition: ---
101
 
rows = dirname, NULL, basename, NULL, MINIKIND, NULL, fileid_utf8, NULL,
102
 
    WHOLE NUMBER (* size *), NULL, packed stat, NULL, sha1|symlink target, 
103
 
    {PARENT ROW}
104
 
PARENT ROW = NULL, revision_utf8, NULL, MINIKIND, NULL, dirname, NULL,
105
 
    basename, NULL, WHOLE NUMBER (* size *), NULL, "y" | "n", NULL,
106
 
    SHA1
 
113
 
 
114
::
 
115
 
 
116
    rows = dirname, NULL, basename, NULL, MINIKIND, NULL, fileid_utf8, NULL,
 
117
        WHOLE NUMBER (* size *), NULL, packed stat, NULL, sha1|symlink target,
 
118
        {PARENT ROW}
 
119
    PARENT ROW = NULL, revision_utf8, NULL, MINIKIND, NULL, dirname, NULL,
 
120
        basename, NULL, WHOLE NUMBER (* size *), NULL, "y" | "n", NULL,
 
121
        SHA1
107
122
 
108
123
PARENT ROW's are emitted for every parent that is not in the ghosts details
109
124
line. That is, if the parents are foo, bar, baz, and the ghosts are bar, then
130
145
operations for the less common but still occurs a lot status/diff/commit
131
146
on specific files). Operations on specific files involve a scan for all
132
147
the children of a path, *in every involved tree*, which the current
133
 
format did not accommodate. 
 
148
format did not accommodate.
134
149
----
135
150
 
136
151
Design priorities:
137
 
 1) Fast end to end use for bzr's top 5 uses cases. (commmit/diff/status/merge/???)
138
 
 2) fall back current object model as needed.
139
 
 3) scale usably to the largest trees known today - say 50K entries. (mozilla
 
152
 1. Fast end to end use for bzr's top 5 uses cases. (commmit/diff/status/merge/???)
 
153
 2. fall back current object model as needed.
 
154
 3. scale usably to the largest trees known today - say 50K entries. (mozilla
140
155
    is an example of this)
141
156
 
142
157
 
143
158
Locking:
 
159
 
144
160
 Eventually reuse dirstate objects across locks IFF the dirstate file has not
145
161
 been modified, but will require that we flush/ignore cached stat-hit data
146
162
 because we won't want to restat all files on disk just because a lock was
147
163
 acquired, yet we cannot trust the data after the previous lock was released.
148
164
 
149
 
Memory representation:
 
165
Memory representation::
 
166
 
150
167
 vector of all directories, and vector of the childen ?
151
 
   i.e. 
152
 
     root_entrie = (direntry for root, [parent_direntries_for_root]), 
 
168
   i.e.
 
169
     root_entrie = (direntry for root, [parent_direntries_for_root]),
153
170
     dirblocks = [
154
171
     ('', ['data for achild', 'data for bchild', 'data for cchild'])
155
172
     ('dir', ['achild', 'cchild', 'echild'])
158
175
    - in-order for serialisation - this is 'dirblock' grouping.
159
176
    - insertion of a file '/a' affects only the '/' child-vector, that is, to
160
177
      insert 10K elements from scratch does not generates O(N^2) memoves of a
161
 
      single vector, rather each individual, which tends to be limited to a 
162
 
      manageable number. Will scale badly on trees with 10K entries in a 
 
178
      single vector, rather each individual, which tends to be limited to a
 
179
      manageable number. Will scale badly on trees with 10K entries in a
163
180
      single directory. compare with Inventory.InventoryDirectory which has
164
181
      a dictionary for the children. No bisect capability, can only probe for
165
182
      exact matches, or grab all elements and sort.
166
183
    - What's the risk of error here? Once we have the base format being processed
167
 
      we should have a net win regardless of optimality. So we are going to 
 
184
      we should have a net win regardless of optimality. So we are going to
168
185
      go with what seems reasonable.
 
186
 
169
187
open questions:
170
188
 
171
189
Maybe we should do a test profile of the core structure - 10K simulated
186
204
the file on disk, and then immediately discard, the overhead of object creation
187
205
becomes a significant cost.
188
206
 
189
 
Figures: Creating a tuple from from 3 elements was profiled at 0.0625
 
207
Figures: Creating a tuple from 3 elements was profiled at 0.0625
190
208
microseconds, whereas creating a object which is subclassed from tuple was
191
209
0.500 microseconds, and creating an object with 3 elements and slots was 3
192
210
microseconds long. 0.1 milliseconds is 100 microseconds, and ideally we'll get
201
219
"""
202
220
 
203
221
import bisect
204
 
import binascii
205
222
import errno
 
223
import operator
206
224
import os
207
225
from stat import S_IEXEC
208
226
import stat
209
 
import struct
210
227
import sys
211
228
import time
212
229
import zlib
213
230
 
214
231
from bzrlib import (
215
232
    cache_utf8,
 
233
    config,
216
234
    debug,
217
235
    errors,
218
236
    inventory,
219
237
    lock,
220
238
    osutils,
 
239
    static_tuple,
221
240
    trace,
 
241
    urlutils,
222
242
    )
223
243
 
224
244
 
225
 
def pack_stat(st, _encode=binascii.b2a_base64, _pack=struct.pack):
226
 
    """Convert stat values into a packed representation."""
227
 
    # jam 20060614 it isn't really worth removing more entries if we
228
 
    # are going to leave it in packed form.
229
 
    # With only st_mtime and st_mode filesize is 5.5M and read time is 275ms
230
 
    # With all entries, filesize is 5.9M and read time is maybe 280ms
231
 
    # well within the noise margin
232
 
 
233
 
    # base64 encoding always adds a final newline, so strip it off
234
 
    # The current version
235
 
    return _encode(_pack('>LLLLLL'
236
 
        , st.st_size, int(st.st_mtime), int(st.st_ctime)
237
 
        , st.st_dev, st.st_ino & 0xFFFFFFFF, st.st_mode))[:-1]
238
 
    # This is 0.060s / 1.520s faster by not encoding as much information
239
 
    # return _encode(_pack('>LL', int(st.st_mtime), st.st_mode))[:-1]
240
 
    # This is not strictly faster than _encode(_pack())[:-1]
241
 
    # return '%X.%X.%X.%X.%X.%X' % (
242
 
    #      st.st_size, int(st.st_mtime), int(st.st_ctime),
243
 
    #      st.st_dev, st.st_ino, st.st_mode)
244
 
    # Similar to the _encode(_pack('>LL'))
245
 
    # return '%X.%X' % (int(st.st_mtime), st.st_mode)
 
245
# This is the Windows equivalent of ENOTDIR
 
246
# It is defined in pywin32.winerror, but we don't want a strong dependency for
 
247
# just an error code.
 
248
ERROR_PATH_NOT_FOUND = 3
 
249
ERROR_DIRECTORY = 267
 
250
 
 
251
 
 
252
class SHA1Provider(object):
 
253
    """An interface for getting sha1s of a file."""
 
254
 
 
255
    def sha1(self, abspath):
 
256
        """Return the sha1 of a file given its absolute path.
 
257
 
 
258
        :param abspath:  May be a filesystem encoded absolute path
 
259
             or a unicode path.
 
260
        """
 
261
        raise NotImplementedError(self.sha1)
 
262
 
 
263
    def stat_and_sha1(self, abspath):
 
264
        """Return the stat and sha1 of a file given its absolute path.
 
265
        
 
266
        :param abspath:  May be a filesystem encoded absolute path
 
267
             or a unicode path.
 
268
 
 
269
        Note: the stat should be the stat of the physical file
 
270
        while the sha may be the sha of its canonical content.
 
271
        """
 
272
        raise NotImplementedError(self.stat_and_sha1)
 
273
 
 
274
 
 
275
class DefaultSHA1Provider(SHA1Provider):
 
276
    """A SHA1Provider that reads directly from the filesystem."""
 
277
 
 
278
    def sha1(self, abspath):
 
279
        """Return the sha1 of a file given its absolute path."""
 
280
        return osutils.sha_file_by_name(abspath)
 
281
 
 
282
    def stat_and_sha1(self, abspath):
 
283
        """Return the stat and sha1 of a file given its absolute path."""
 
284
        file_obj = file(abspath, 'rb')
 
285
        try:
 
286
            statvalue = os.fstat(file_obj.fileno())
 
287
            sha1 = osutils.sha_file(file_obj)
 
288
        finally:
 
289
            file_obj.close()
 
290
        return statvalue, sha1
246
291
 
247
292
 
248
293
class DirState(object):
294
339
    NOT_IN_MEMORY = 0
295
340
    IN_MEMORY_UNMODIFIED = 1
296
341
    IN_MEMORY_MODIFIED = 2
 
342
    IN_MEMORY_HASH_MODIFIED = 3 # Only hash-cache updates
297
343
 
298
344
    # A pack_stat (the x's) that is just noise and will never match the output
299
345
    # of base64 encode.
300
346
    NULLSTAT = 'x' * 32
301
 
    NULL_PARENT_DETAILS = ('a', '', 0, False, '')
 
347
    NULL_PARENT_DETAILS = static_tuple.StaticTuple('a', '', 0, False, '')
302
348
 
303
349
    HEADER_FORMAT_2 = '#bazaar dirstate flat format 2\n'
304
350
    HEADER_FORMAT_3 = '#bazaar dirstate flat format 3\n'
305
351
 
306
 
    def __init__(self, path):
 
352
    def __init__(self, path, sha1_provider, worth_saving_limit=0):
307
353
        """Create a  DirState object.
308
354
 
309
355
        :param path: The path at which the dirstate file on disk should live.
 
356
        :param sha1_provider: an object meeting the SHA1Provider interface.
 
357
        :param worth_saving_limit: when the exact number of hash changed
 
358
            entries is known, only bother saving the dirstate if more than
 
359
            this count of entries have changed.
 
360
            -1 means never save hash changes, 0 means always save hash changes.
310
361
        """
311
362
        # _header_state and _dirblock_state represent the current state
312
363
        # of the dirstate metadata and the per-row data respectiely.
314
365
        # IN_MEMORY_UNMODIFIED indicates that what we have in memory
315
366
        #   is the same as is on disk
316
367
        # IN_MEMORY_MODIFIED indicates that we have a modified version
317
 
        #   of what is on disk. 
 
368
        #   of what is on disk.
318
369
        # In future we will add more granularity, for instance _dirblock_state
319
370
        # will probably support partially-in-memory as a separate variable,
320
371
        # allowing for partially-in-memory unmodified and partially-in-memory
321
372
        # modified states.
322
373
        self._header_state = DirState.NOT_IN_MEMORY
323
374
        self._dirblock_state = DirState.NOT_IN_MEMORY
324
 
        # If true, an error has been detected while updating the dirstate, and 
 
375
        # If true, an error has been detected while updating the dirstate, and
325
376
        # for safety we're not going to commit to disk.
326
377
        self._changes_aborted = False
327
378
        self._dirblocks = []
338
389
        self._cutoff_time = None
339
390
        self._split_path_cache = {}
340
391
        self._bisect_page_size = DirState.BISECT_PAGE_SIZE
 
392
        self._sha1_provider = sha1_provider
341
393
        if 'hashcache' in debug.debug_flags:
342
394
            self._sha1_file = self._sha1_file_and_mutter
343
395
        else:
344
 
            self._sha1_file = osutils.sha_file_by_name
 
396
            self._sha1_file = self._sha1_provider.sha1
345
397
        # These two attributes provide a simple cache for lookups into the
346
398
        # dirstate in-memory vectors. By probing respectively for the last
347
399
        # block, and for the next entry, we save nearly 2 bisections per path
348
400
        # during commit.
349
401
        self._last_block_index = None
350
402
        self._last_entry_index = None
 
403
        # The set of known hash changes
 
404
        self._known_hash_changes = set()
 
405
        # How many hash changed entries can we have without saving
 
406
        self._worth_saving_limit = worth_saving_limit
 
407
        self._config_stack = config.LocationStack(urlutils.local_path_to_url(
 
408
            path))
351
409
 
352
410
    def __repr__(self):
353
411
        return "%s(%r)" % \
354
412
            (self.__class__.__name__, self._filename)
355
413
 
 
414
    def _mark_modified(self, hash_changed_entries=None, header_modified=False):
 
415
        """Mark this dirstate as modified.
 
416
 
 
417
        :param hash_changed_entries: if non-None, mark just these entries as
 
418
            having their hash modified.
 
419
        :param header_modified: mark the header modified as well, not just the
 
420
            dirblocks.
 
421
        """
 
422
        #trace.mutter_callsite(3, "modified hash entries: %s", hash_changed_entries)
 
423
        if hash_changed_entries:
 
424
            self._known_hash_changes.update([e[0] for e in hash_changed_entries])
 
425
            if self._dirblock_state in (DirState.NOT_IN_MEMORY,
 
426
                                        DirState.IN_MEMORY_UNMODIFIED):
 
427
                # If the dirstate is already marked a IN_MEMORY_MODIFIED, then
 
428
                # that takes precedence.
 
429
                self._dirblock_state = DirState.IN_MEMORY_HASH_MODIFIED
 
430
        else:
 
431
            # TODO: Since we now have a IN_MEMORY_HASH_MODIFIED state, we
 
432
            #       should fail noisily if someone tries to set
 
433
            #       IN_MEMORY_MODIFIED but we don't have a write-lock!
 
434
            # We don't know exactly what changed so disable smart saving
 
435
            self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
436
        if header_modified:
 
437
            self._header_state = DirState.IN_MEMORY_MODIFIED
 
438
 
 
439
    def _mark_unmodified(self):
 
440
        """Mark this dirstate as unmodified."""
 
441
        self._header_state = DirState.IN_MEMORY_UNMODIFIED
 
442
        self._dirblock_state = DirState.IN_MEMORY_UNMODIFIED
 
443
        self._known_hash_changes = set()
 
444
 
356
445
    def add(self, path, file_id, kind, stat, fingerprint):
357
446
        """Add a path to be tracked.
358
447
 
359
448
        :param path: The path within the dirstate - '' is the root, 'foo' is the
360
 
            path foo within the root, 'foo/bar' is the path bar within foo 
 
449
            path foo within the root, 'foo/bar' is the path bar within foo
361
450
            within the root.
362
451
        :param file_id: The file id of the path being added.
363
 
        :param kind: The kind of the path, as a string like 'file', 
 
452
        :param kind: The kind of the path, as a string like 'file',
364
453
            'directory', etc.
365
454
        :param stat: The output of os.lstat for the path.
366
 
        :param fingerprint: The sha value of the file,
 
455
        :param fingerprint: The sha value of the file's canonical form (i.e.
 
456
            after any read filters have been applied),
367
457
            or the target of a symlink,
368
458
            or the referenced revision id for tree-references,
369
459
            or '' for directories.
370
460
        """
371
461
        # adding a file:
372
 
        # find the block its in. 
 
462
        # find the block its in.
373
463
        # find the location in the block.
374
464
        # check its not there
375
465
        # add it.
388
478
        # in the parent, or according to the special treatment for the root
389
479
        if basename == '.' or basename == '..':
390
480
            raise errors.InvalidEntryName(path)
391
 
        # now that we've normalised, we need the correct utf8 path and 
 
481
        # now that we've normalised, we need the correct utf8 path and
392
482
        # dirname and basename elements. This single encode and split should be
393
483
        # faster than three separate encodes.
394
484
        utf8path = (dirname + '/' + basename).strip('/').encode('utf8')
395
485
        dirname, basename = osutils.split(utf8path)
396
 
        assert file_id.__class__ == str, \
397
 
            "must be a utf8 file_id not %s" % (type(file_id))
 
486
        # uses __class__ for speed; the check is needed for safety
 
487
        if file_id.__class__ is not str:
 
488
            raise AssertionError(
 
489
                "must be a utf8 file_id not %s" % (type(file_id), ))
398
490
        # Make sure the file_id does not exist in this tree
399
 
        file_id_entry = self._get_entry(0, fileid_utf8=file_id)
 
491
        rename_from = None
 
492
        file_id_entry = self._get_entry(0, fileid_utf8=file_id, include_deleted=True)
400
493
        if file_id_entry != (None, None):
401
 
            path = osutils.pathjoin(file_id_entry[0][0], file_id_entry[0][1])
402
 
            kind = DirState._minikind_to_kind[file_id_entry[1][0][0]]
403
 
            info = '%s:%s' % (kind, path)
404
 
            raise errors.DuplicateFileId(file_id, info)
 
494
            if file_id_entry[1][0][0] == 'a':
 
495
                if file_id_entry[0] != (dirname, basename, file_id):
 
496
                    # set the old name's current operation to rename
 
497
                    self.update_minimal(file_id_entry[0],
 
498
                        'r',
 
499
                        path_utf8='',
 
500
                        packed_stat='',
 
501
                        fingerprint=utf8path
 
502
                    )
 
503
                    rename_from = file_id_entry[0][0:2]
 
504
            else:
 
505
                path = osutils.pathjoin(file_id_entry[0][0], file_id_entry[0][1])
 
506
                kind = DirState._minikind_to_kind[file_id_entry[1][0][0]]
 
507
                info = '%s:%s' % (kind, path)
 
508
                raise errors.DuplicateFileId(file_id, info)
405
509
        first_key = (dirname, basename, '')
406
510
        block_index, present = self._find_block_index_from_key(first_key)
407
511
        if present:
408
512
            # check the path is not in the tree
409
513
            block = self._dirblocks[block_index][1]
410
514
            entry_index, _ = self._find_entry_index(first_key, block)
411
 
            while (entry_index < len(block) and 
 
515
            while (entry_index < len(block) and
412
516
                block[entry_index][0][0:2] == first_key[0:2]):
413
517
                if block[entry_index][1][0][0] not in 'ar':
414
518
                    # this path is in the dirstate in the current tree.
434
538
            packed_stat = pack_stat(stat)
435
539
        parent_info = self._empty_parent_info()
436
540
        minikind = DirState._kind_to_minikind[kind]
 
541
        if rename_from is not None:
 
542
            if rename_from[0]:
 
543
                old_path_utf8 = '%s/%s' % rename_from
 
544
            else:
 
545
                old_path_utf8 = rename_from[1]
 
546
            parent_info[0] = ('r', old_path_utf8, 0, False, '')
437
547
        if kind == 'file':
438
548
            entry_data = entry_key, [
439
549
                (minikind, fingerprint, size, False, packed_stat),
456
566
        if not present:
457
567
            block.insert(entry_index, entry_data)
458
568
        else:
459
 
            assert block[entry_index][1][0][0] == 'a', " %r(%r) already added" % (basename, file_id)
 
569
            if block[entry_index][1][0][0] != 'a':
 
570
                raise AssertionError(" %r(%r) already added" % (basename, file_id))
460
571
            block[entry_index][1][0] = entry_data[1][0]
461
572
 
462
573
        if kind == 'directory':
463
574
           # insert a new dirblock
464
575
           self._ensure_block(block_index, entry_index, utf8path)
465
 
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
576
        self._mark_modified()
466
577
        if self._id_index:
467
 
            self._id_index.setdefault(entry_key[2], set()).add(entry_key)
 
578
            self._add_to_id_index(self._id_index, entry_key)
468
579
 
469
580
    def _bisect(self, paths):
470
581
        """Bisect through the disk structure for specific rows.
481
592
        # If _dirblock_state was in memory, we should just return info from
482
593
        # there, this function is only meant to handle when we want to read
483
594
        # part of the disk.
484
 
        assert self._dirblock_state == DirState.NOT_IN_MEMORY
 
595
        if self._dirblock_state != DirState.NOT_IN_MEMORY:
 
596
            raise AssertionError("bad dirblock state %r" % self._dirblock_state)
485
597
 
486
598
        # The disk representation is generally info + '\0\n\0' at the end. But
487
599
        # for bisecting, it is easier to treat this as '\0' + info + '\0\n'
673
785
        # If _dirblock_state was in memory, we should just return info from
674
786
        # there, this function is only meant to handle when we want to read
675
787
        # part of the disk.
676
 
        assert self._dirblock_state == DirState.NOT_IN_MEMORY
677
 
 
 
788
        if self._dirblock_state != DirState.NOT_IN_MEMORY:
 
789
            raise AssertionError("bad dirblock state %r" % self._dirblock_state)
678
790
        # The disk representation is generally info + '\0\n\0' at the end. But
679
791
        # for bisecting, it is easier to treat this as '\0' + info + '\0\n'
680
792
        # Because it means we can sync on the '\n'
896
1008
 
897
1009
    def _discard_merge_parents(self):
898
1010
        """Discard any parents trees beyond the first.
899
 
        
 
1011
 
900
1012
        Note that if this fails the dirstate is corrupted.
901
1013
 
902
1014
        After this function returns the dirstate contains 2 trees, neither of
933
1045
 
934
1046
        self._ghosts = []
935
1047
        self._parents = [parents[0]]
936
 
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
937
 
        self._header_state = DirState.IN_MEMORY_MODIFIED
 
1048
        self._mark_modified(header_modified=True)
938
1049
 
939
1050
    def _empty_parent_info(self):
940
1051
        return [DirState.NULL_PARENT_DETAILS] * (len(self._parents) -
967
1078
        # the basename of the directory must be the end of its full name.
968
1079
        if not (parent_block_index == -1 and
969
1080
            parent_block_index == -1 and dirname == ''):
970
 
            assert dirname.endswith(
971
 
                self._dirblocks[parent_block_index][1][parent_row_index][0][1])
 
1081
            if not dirname.endswith(
 
1082
                    self._dirblocks[parent_block_index][1][parent_row_index][0][1]):
 
1083
                raise AssertionError("bad dirname %r" % dirname)
972
1084
        block_index, present = self._find_block_index_from_key((dirname, '', ''))
973
1085
        if not present:
974
 
            ## In future, when doing partial parsing, this should load and 
 
1086
            ## In future, when doing partial parsing, this should load and
975
1087
            # populate the entire block.
976
1088
            self._dirblocks.insert(block_index, (dirname, []))
977
1089
        return block_index
986
1098
            to prevent unneeded overhead when callers have a sorted list already.
987
1099
        :return: Nothing.
988
1100
        """
989
 
        assert new_entries[0][0][0:2] == ('', ''), \
990
 
            "Missing root row %r" % (new_entries[0][0],)
991
 
        # The two blocks here are deliberate: the root block and the 
 
1101
        if new_entries[0][0][0:2] != ('', ''):
 
1102
            raise AssertionError(
 
1103
                "Missing root row %r" % (new_entries[0][0],))
 
1104
        # The two blocks here are deliberate: the root block and the
992
1105
        # contents-of-root block.
993
1106
        self._dirblocks = [('', []), ('', [])]
994
1107
        current_block = self._dirblocks[0][1]
1015
1128
        # The above loop leaves the "root block" entries mixed with the
1016
1129
        # "contents-of-root block". But we don't want an if check on
1017
1130
        # all entries, so instead we just fix it up here.
1018
 
        assert self._dirblocks[1] == ('', [])
 
1131
        if self._dirblocks[1] != ('', []):
 
1132
            raise ValueError("bad dirblock start %r" % (self._dirblocks[1],))
1019
1133
        root_block = []
1020
1134
        contents_of_root_block = []
1021
1135
        for entry in self._dirblocks[0][1]:
1026
1140
        self._dirblocks[0] = ('', root_block)
1027
1141
        self._dirblocks[1] = ('', contents_of_root_block)
1028
1142
 
 
1143
    def _entries_for_path(self, path):
 
1144
        """Return a list with all the entries that match path for all ids."""
 
1145
        dirname, basename = os.path.split(path)
 
1146
        key = (dirname, basename, '')
 
1147
        block_index, present = self._find_block_index_from_key(key)
 
1148
        if not present:
 
1149
            # the block which should contain path is absent.
 
1150
            return []
 
1151
        result = []
 
1152
        block = self._dirblocks[block_index][1]
 
1153
        entry_index, _ = self._find_entry_index(key, block)
 
1154
        # we may need to look at multiple entries at this path: walk while the specific_files match.
 
1155
        while (entry_index < len(block) and
 
1156
            block[entry_index][0][0:2] == key[0:2]):
 
1157
            result.append(block[entry_index])
 
1158
            entry_index += 1
 
1159
        return result
 
1160
 
1029
1161
    def _entry_to_line(self, entry):
1030
1162
        """Serialize entry to a NULL delimited line ready for _get_output_lines.
1031
1163
 
1048
1180
    def _fields_per_entry(self):
1049
1181
        """How many null separated fields should be in each entry row.
1050
1182
 
1051
 
        Each line now has an extra '\n' field which is not used
 
1183
        Each line now has an extra '\\n' field which is not used
1052
1184
        so we just skip over it
1053
 
        entry size:
 
1185
 
 
1186
        entry size::
1054
1187
            3 fields for the key
1055
1188
            + number of fields per tree_data (5) * tree count
1056
1189
            + newline
1099
1232
        # one to use it. we use _right here because there are two
1100
1233
        # '' blocks - the root, and the contents of root
1101
1234
        # we always have a minimum of 2 in self._dirblocks: root and
1102
 
        # root-contents, and for '', we get 2 back, so this is 
 
1235
        # root-contents, and for '', we get 2 back, so this is
1103
1236
        # simple and correct:
1104
1237
        present = (block_index < len(self._dirblocks) and
1105
1238
            self._dirblocks[block_index][0] == key[0])
1134
1267
        return entry_index, present
1135
1268
 
1136
1269
    @staticmethod
1137
 
    def from_tree(tree, dir_state_filename):
 
1270
    def from_tree(tree, dir_state_filename, sha1_provider=None):
1138
1271
        """Create a dirstate from a bzr Tree.
1139
1272
 
1140
1273
        :param tree: The tree which should provide parent information and
1141
1274
            inventory ids.
 
1275
        :param sha1_provider: an object meeting the SHA1Provider interface.
 
1276
            If None, a DefaultSHA1Provider is used.
1142
1277
        :return: a DirState object which is currently locked for writing.
1143
1278
            (it was locked by DirState.initialize)
1144
1279
        """
1145
 
        result = DirState.initialize(dir_state_filename)
 
1280
        result = DirState.initialize(dir_state_filename,
 
1281
            sha1_provider=sha1_provider)
1146
1282
        try:
1147
1283
            tree.lock_read()
1148
1284
            try:
1166
1302
            raise
1167
1303
        return result
1168
1304
 
 
1305
    def _check_delta_is_valid(self, delta):
 
1306
        return list(inventory._check_delta_unique_ids(
 
1307
                    inventory._check_delta_unique_old_paths(
 
1308
                    inventory._check_delta_unique_new_paths(
 
1309
                    inventory._check_delta_ids_match_entry(
 
1310
                    inventory._check_delta_ids_are_valid(
 
1311
                    inventory._check_delta_new_path_entry_both_or_None(delta)))))))
 
1312
 
1169
1313
    def update_by_delta(self, delta):
1170
1314
        """Apply an inventory delta to the dirstate for tree 0
1171
1315
 
 
1316
        This is the workhorse for apply_inventory_delta in dirstate based
 
1317
        trees.
 
1318
 
1172
1319
        :param delta: An inventory delta.  See Inventory.apply_delta for
1173
1320
            details.
1174
1321
        """
1175
1322
        self._read_dirblocks_if_needed()
 
1323
        encode = cache_utf8.encode
1176
1324
        insertions = {}
1177
1325
        removals = {}
1178
 
        for old_path, new_path, file_id, inv_entry in sorted(delta,
1179
 
                                                             reverse=True):
1180
 
            assert file_id not in insertions
1181
 
            assert file_id not in removals
 
1326
        # Accumulate parent references (path_utf8, id), to check for parentless
 
1327
        # items or items placed under files/links/tree-references. We get
 
1328
        # references from every item in the delta that is not a deletion and
 
1329
        # is not itself the root.
 
1330
        parents = set()
 
1331
        # Added ids must not be in the dirstate already. This set holds those
 
1332
        # ids.
 
1333
        new_ids = set()
 
1334
        # This loop transforms the delta to single atomic operations that can
 
1335
        # be executed and validated.
 
1336
        delta = sorted(self._check_delta_is_valid(delta), reverse=True)
 
1337
        for old_path, new_path, file_id, inv_entry in delta:
 
1338
            if (file_id in insertions) or (file_id in removals):
 
1339
                self._raise_invalid(old_path or new_path, file_id,
 
1340
                    "repeated file_id")
1182
1341
            if old_path is not None:
1183
1342
                old_path = old_path.encode('utf-8')
1184
1343
                removals[file_id] = old_path
 
1344
            else:
 
1345
                new_ids.add(file_id)
1185
1346
            if new_path is not None:
 
1347
                if inv_entry is None:
 
1348
                    self._raise_invalid(new_path, file_id,
 
1349
                        "new_path with no entry")
1186
1350
                new_path = new_path.encode('utf-8')
1187
 
                dirname, basename = osutils.split(new_path)
1188
 
                key = (dirname, basename, file_id)
 
1351
                dirname_utf8, basename = osutils.split(new_path)
 
1352
                if basename:
 
1353
                    parents.add((dirname_utf8, inv_entry.parent_id))
 
1354
                key = (dirname_utf8, basename, file_id)
1189
1355
                minikind = DirState._kind_to_minikind[inv_entry.kind]
1190
1356
                if minikind == 't':
1191
 
                    fingerprint = inv_entry.reference_revision
 
1357
                    fingerprint = inv_entry.reference_revision or ''
1192
1358
                else:
1193
1359
                    fingerprint = ''
1194
1360
                insertions[file_id] = (key, minikind, inv_entry.executable,
1195
1361
                                       fingerprint, new_path)
 
1362
            # Transform moves into delete+add pairs
1196
1363
            if None not in (old_path, new_path):
1197
1364
                for child in self._iter_child_entries(0, old_path):
1198
1365
                    if child[0][2] in insertions or child[0][2] in removals:
1202
1369
                    minikind = child[1][0][0]
1203
1370
                    fingerprint = child[1][0][4]
1204
1371
                    executable = child[1][0][3]
1205
 
                    old_child_path = osutils.pathjoin(child[0][0],
1206
 
                                                      child[0][1])
 
1372
                    old_child_path = osutils.pathjoin(child_dirname,
 
1373
                                                      child_basename)
1207
1374
                    removals[child[0][2]] = old_child_path
1208
1375
                    child_suffix = child_dirname[len(old_path):]
1209
1376
                    new_child_dirname = (new_path + child_suffix)
1210
1377
                    key = (new_child_dirname, child_basename, child[0][2])
1211
 
                    new_child_path = os.path.join(new_child_dirname,
1212
 
                                                  child_basename)
 
1378
                    new_child_path = osutils.pathjoin(new_child_dirname,
 
1379
                                                      child_basename)
1213
1380
                    insertions[child[0][2]] = (key, minikind, executable,
1214
1381
                                               fingerprint, new_child_path)
1215
 
        self._apply_removals(removals.values())
1216
 
        self._apply_insertions(insertions.values())
 
1382
        self._check_delta_ids_absent(new_ids, delta, 0)
 
1383
        try:
 
1384
            self._apply_removals(removals.iteritems())
 
1385
            self._apply_insertions(insertions.values())
 
1386
            # Validate parents
 
1387
            self._after_delta_check_parents(parents, 0)
 
1388
        except errors.BzrError, e:
 
1389
            self._changes_aborted = True
 
1390
            if 'integrity error' not in str(e):
 
1391
                raise
 
1392
            # _get_entry raises BzrError when a request is inconsistent; we
 
1393
            # want such errors to be shown as InconsistentDelta - and that 
 
1394
            # fits the behaviour we trigger.
 
1395
            raise errors.InconsistentDeltaDelta(delta,
 
1396
                "error from _get_entry. %s" % (e,))
1217
1397
 
1218
1398
    def _apply_removals(self, removals):
1219
 
        for path in sorted(removals, reverse=True):
 
1399
        for file_id, path in sorted(removals, reverse=True,
 
1400
            key=operator.itemgetter(1)):
1220
1401
            dirname, basename = osutils.split(path)
1221
1402
            block_i, entry_i, d_present, f_present = \
1222
1403
                self._get_block_entry_index(dirname, basename, 0)
1223
 
            entry = self._dirblocks[block_i][1][entry_i]
 
1404
            try:
 
1405
                entry = self._dirblocks[block_i][1][entry_i]
 
1406
            except IndexError:
 
1407
                self._raise_invalid(path, file_id,
 
1408
                    "Wrong path for old path.")
 
1409
            if not f_present or entry[1][0][0] in 'ar':
 
1410
                self._raise_invalid(path, file_id,
 
1411
                    "Wrong path for old path.")
 
1412
            if file_id != entry[0][2]:
 
1413
                self._raise_invalid(path, file_id,
 
1414
                    "Attempt to remove path has wrong id - found %r."
 
1415
                    % entry[0][2])
1224
1416
            self._make_absent(entry)
 
1417
            # See if we have a malformed delta: deleting a directory must not
 
1418
            # leave crud behind. This increases the number of bisects needed
 
1419
            # substantially, but deletion or renames of large numbers of paths
 
1420
            # is rare enough it shouldn't be an issue (famous last words?) RBC
 
1421
            # 20080730.
 
1422
            block_i, entry_i, d_present, f_present = \
 
1423
                self._get_block_entry_index(path, '', 0)
 
1424
            if d_present:
 
1425
                # The dir block is still present in the dirstate; this could
 
1426
                # be due to it being in a parent tree, or a corrupt delta.
 
1427
                for child_entry in self._dirblocks[block_i][1]:
 
1428
                    if child_entry[1][0][0] not in ('r', 'a'):
 
1429
                        self._raise_invalid(path, entry[0][2],
 
1430
                            "The file id was deleted but its children were "
 
1431
                            "not deleted.")
1225
1432
 
1226
1433
    def _apply_insertions(self, adds):
1227
 
        for key, minikind, executable, fingerprint, path_utf8 in sorted(adds):
1228
 
            self.update_minimal(key, minikind, executable, fingerprint,
1229
 
                                path_utf8=path_utf8)
 
1434
        try:
 
1435
            for key, minikind, executable, fingerprint, path_utf8 in sorted(adds):
 
1436
                self.update_minimal(key, minikind, executable, fingerprint,
 
1437
                                    path_utf8=path_utf8)
 
1438
        except errors.NotVersionedError:
 
1439
            self._raise_invalid(path_utf8.decode('utf8'), key[2],
 
1440
                "Missing parent")
1230
1441
 
1231
1442
    def update_basis_by_delta(self, delta, new_revid):
1232
1443
        """Update the parents of this tree after a commit.
1239
1450
        Note that an exception during the operation of this method will leave
1240
1451
        the dirstate in a corrupt state where it should not be saved.
1241
1452
 
1242
 
        Finally, we expect all changes to be synchronising the basis tree with
1243
 
        the working tree.
1244
 
 
1245
1453
        :param new_revid: The new revision id for the trees parent.
1246
1454
        :param delta: An inventory delta (see apply_inventory_delta) describing
1247
1455
            the changes from the current left most parent revision to new_revid.
1259
1467
 
1260
1468
        self._parents[0] = new_revid
1261
1469
 
1262
 
        delta = sorted(delta, reverse=True)
 
1470
        delta = sorted(self._check_delta_is_valid(delta), reverse=True)
1263
1471
        adds = []
1264
1472
        changes = []
1265
1473
        deletes = []
1276
1484
        # At the same time, to reduce interface friction we convert the input
1277
1485
        # inventory entries to dirstate.
1278
1486
        root_only = ('', '')
 
1487
        # Accumulate parent references (path_utf8, id), to check for parentless
 
1488
        # items or items placed under files/links/tree-references. We get
 
1489
        # references from every item in the delta that is not a deletion and
 
1490
        # is not itself the root.
 
1491
        parents = set()
 
1492
        # Added ids must not be in the dirstate already. This set holds those
 
1493
        # ids.
 
1494
        new_ids = set()
1279
1495
        for old_path, new_path, file_id, inv_entry in delta:
1280
 
            if old_path is None:
1281
 
                adds.append((None, encode(new_path), file_id,
 
1496
            if inv_entry is not None and file_id != inv_entry.file_id:
 
1497
                self._raise_invalid(new_path, file_id,
 
1498
                    "mismatched entry file_id %r" % inv_entry)
 
1499
            if new_path is None:
 
1500
                new_path_utf8 = None
 
1501
            else:
 
1502
                if inv_entry is None:
 
1503
                    self._raise_invalid(new_path, file_id,
 
1504
                        "new_path with no entry")
 
1505
                new_path_utf8 = encode(new_path)
 
1506
                # note the parent for validation
 
1507
                dirname_utf8, basename_utf8 = osutils.split(new_path_utf8)
 
1508
                if basename_utf8:
 
1509
                    parents.add((dirname_utf8, inv_entry.parent_id))
 
1510
            if old_path is None:
 
1511
                old_path_utf8 = None
 
1512
            else:
 
1513
                old_path_utf8 = encode(old_path)
 
1514
            if old_path is None:
 
1515
                adds.append((None, new_path_utf8, file_id,
1282
1516
                    inv_to_entry(inv_entry), True))
 
1517
                new_ids.add(file_id)
1283
1518
            elif new_path is None:
1284
 
                deletes.append((encode(old_path), None, file_id, None, True))
1285
 
            elif (old_path, new_path) != root_only:
 
1519
                deletes.append((old_path_utf8, None, file_id, None, True))
 
1520
            elif (old_path, new_path) == root_only:
 
1521
                # change things in-place
 
1522
                # Note: the case of a parent directory changing its file_id
 
1523
                #       tends to break optimizations here, because officially
 
1524
                #       the file has actually been moved, it just happens to
 
1525
                #       end up at the same path. If we can figure out how to
 
1526
                #       handle that case, we can avoid a lot of add+delete
 
1527
                #       pairs for objects that stay put.
 
1528
                # elif old_path == new_path:
 
1529
                changes.append((old_path_utf8, new_path_utf8, file_id,
 
1530
                                inv_to_entry(inv_entry)))
 
1531
            else:
1286
1532
                # Renames:
1287
1533
                # Because renames must preserve their children we must have
1288
1534
                # processed all relocations and removes before hand. The sort
1297
1543
                # for 'r' items on every pass.
1298
1544
                self._update_basis_apply_deletes(deletes)
1299
1545
                deletes = []
1300
 
                new_path_utf8 = encode(new_path)
1301
1546
                # Split into an add/delete pair recursively.
1302
 
                adds.append((None, new_path_utf8, file_id,
1303
 
                    inv_to_entry(inv_entry), False))
 
1547
                adds.append((old_path_utf8, new_path_utf8, file_id,
 
1548
                             inv_to_entry(inv_entry), False))
1304
1549
                # Expunge deletes that we've seen so that deleted/renamed
1305
1550
                # children of a rename directory are handled correctly.
1306
 
                new_deletes = reversed(list(self._iter_child_entries(1,
1307
 
                    encode(old_path))))
 
1551
                new_deletes = reversed(list(
 
1552
                    self._iter_child_entries(1, old_path_utf8)))
1308
1553
                # Remove the current contents of the tree at orig_path, and
1309
1554
                # reinsert at the correct new path.
1310
1555
                for entry in new_deletes:
1311
 
                    if entry[0][0]:
1312
 
                        source_path = entry[0][0] + '/' + entry[0][1]
 
1556
                    child_dirname, child_basename, child_file_id = entry[0]
 
1557
                    if child_dirname:
 
1558
                        source_path = child_dirname + '/' + child_basename
1313
1559
                    else:
1314
 
                        source_path = entry[0][1]
 
1560
                        source_path = child_basename
1315
1561
                    if new_path_utf8:
1316
1562
                        target_path = new_path_utf8 + source_path[len(old_path):]
1317
1563
                    else:
1318
 
                        assert len(old_path) > 0, ("cannot rename directory to"
1319
 
                                                   " itself")
 
1564
                        if old_path == '':
 
1565
                            raise AssertionError("cannot rename directory to"
 
1566
                                                 " itself")
1320
1567
                        target_path = source_path[len(old_path) + 1:]
1321
1568
                    adds.append((None, target_path, entry[0][2], entry[1][1], False))
1322
1569
                    deletes.append(
1323
1570
                        (source_path, target_path, entry[0][2], None, False))
1324
 
                deletes.append(
1325
 
                    (encode(old_path), new_path, file_id, None, False))
1326
 
            else:
1327
 
                # changes to just the root should not require remove/insertion
1328
 
                # of everything.
1329
 
                changes.append((encode(old_path), encode(new_path), file_id,
1330
 
                    inv_to_entry(inv_entry)))
1331
 
 
1332
 
        # Finish expunging deletes/first half of renames.
1333
 
        self._update_basis_apply_deletes(deletes)
1334
 
        # Reinstate second half of renames and new paths.
1335
 
        self._update_basis_apply_adds(adds)
1336
 
        # Apply in-situ changes.
1337
 
        self._update_basis_apply_changes(changes)
1338
 
 
1339
 
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
1340
 
        self._header_state = DirState.IN_MEMORY_MODIFIED
 
1571
                deletes.append((old_path_utf8, new_path, file_id, None, False))
 
1572
        self._check_delta_ids_absent(new_ids, delta, 1)
 
1573
        try:
 
1574
            # Finish expunging deletes/first half of renames.
 
1575
            self._update_basis_apply_deletes(deletes)
 
1576
            # Reinstate second half of renames and new paths.
 
1577
            self._update_basis_apply_adds(adds)
 
1578
            # Apply in-situ changes.
 
1579
            self._update_basis_apply_changes(changes)
 
1580
            # Validate parents
 
1581
            self._after_delta_check_parents(parents, 1)
 
1582
        except errors.BzrError, e:
 
1583
            self._changes_aborted = True
 
1584
            if 'integrity error' not in str(e):
 
1585
                raise
 
1586
            # _get_entry raises BzrError when a request is inconsistent; we
 
1587
            # want such errors to be shown as InconsistentDelta - and that
 
1588
            # fits the behaviour we trigger.
 
1589
            raise errors.InconsistentDeltaDelta(delta,
 
1590
                "error from _get_entry. %s" % (e,))
 
1591
 
 
1592
        self._mark_modified(header_modified=True)
1341
1593
        self._id_index = None
1342
1594
        return
1343
1595
 
 
1596
    def _check_delta_ids_absent(self, new_ids, delta, tree_index):
 
1597
        """Check that none of the file_ids in new_ids are present in a tree."""
 
1598
        if not new_ids:
 
1599
            return
 
1600
        id_index = self._get_id_index()
 
1601
        for file_id in new_ids:
 
1602
            for key in id_index.get(file_id, ()):
 
1603
                block_i, entry_i, d_present, f_present = \
 
1604
                    self._get_block_entry_index(key[0], key[1], tree_index)
 
1605
                if not f_present:
 
1606
                    # In a different tree
 
1607
                    continue
 
1608
                entry = self._dirblocks[block_i][1][entry_i]
 
1609
                if entry[0][2] != file_id:
 
1610
                    # Different file_id, so not what we want.
 
1611
                    continue
 
1612
                self._raise_invalid(("%s/%s" % key[0:2]).decode('utf8'), file_id,
 
1613
                    "This file_id is new in the delta but already present in "
 
1614
                    "the target")
 
1615
 
 
1616
    def _raise_invalid(self, path, file_id, reason):
 
1617
        self._changes_aborted = True
 
1618
        raise errors.InconsistentDelta(path, file_id, reason)
 
1619
 
1344
1620
    def _update_basis_apply_adds(self, adds):
1345
1621
        """Apply a sequence of adds to tree 1 during update_basis_by_delta.
1346
1622
 
1354
1630
        """
1355
1631
        # Adds are accumulated partly from renames, so can be in any input
1356
1632
        # order - sort it.
1357
 
        adds.sort()
 
1633
        # TODO: we may want to sort in dirblocks order. That way each entry
 
1634
        #       will end up in the same directory, allowing the _get_entry
 
1635
        #       fast-path for looking up 2 items in the same dir work.
 
1636
        adds.sort(key=lambda x: x[1])
1358
1637
        # adds is now in lexographic order, which places all parents before
1359
1638
        # their children, so we can process it linearly.
1360
1639
        absent = 'ar'
 
1640
        st = static_tuple.StaticTuple
1361
1641
        for old_path, new_path, file_id, new_details, real_add in adds:
1362
 
            assert old_path is None
1363
 
            # the entry for this file_id must be in tree 0.
1364
 
            entry = self._get_entry(0, file_id, new_path)
1365
 
            if entry[0] is None or entry[0][2] != file_id:
1366
 
                self._changes_aborted = True
1367
 
                raise errors.InconsistentDelta(new_path, file_id,
1368
 
                    'working tree does not contain new entry')
1369
 
            if real_add and entry[1][1][0] not in absent:
1370
 
                self._changes_aborted = True
1371
 
                raise errors.InconsistentDelta(new_path, file_id,
1372
 
                    'The entry was considered to be a genuinely new record,'
1373
 
                    ' but there was already an old record for it.')
1374
 
            # We don't need to update the target of an 'r' because the handling
1375
 
            # of renames turns all 'r' situations into a delete at the original
1376
 
            # location.
1377
 
            entry[1][1] = new_details
 
1642
            dirname, basename = osutils.split(new_path)
 
1643
            entry_key = st(dirname, basename, file_id)
 
1644
            block_index, present = self._find_block_index_from_key(entry_key)
 
1645
            if not present:
 
1646
                self._raise_invalid(new_path, file_id,
 
1647
                    "Unable to find block for this record."
 
1648
                    " Was the parent added?")
 
1649
            block = self._dirblocks[block_index][1]
 
1650
            entry_index, present = self._find_entry_index(entry_key, block)
 
1651
            if real_add:
 
1652
                if old_path is not None:
 
1653
                    self._raise_invalid(new_path, file_id,
 
1654
                        'considered a real add but still had old_path at %s'
 
1655
                        % (old_path,))
 
1656
            if present:
 
1657
                entry = block[entry_index]
 
1658
                basis_kind = entry[1][1][0]
 
1659
                if basis_kind == 'a':
 
1660
                    entry[1][1] = new_details
 
1661
                elif basis_kind == 'r':
 
1662
                    raise NotImplementedError()
 
1663
                else:
 
1664
                    self._raise_invalid(new_path, file_id,
 
1665
                        "An entry was marked as a new add"
 
1666
                        " but the basis target already existed")
 
1667
            else:
 
1668
                # The exact key was not found in the block. However, we need to
 
1669
                # check if there is a key next to us that would have matched.
 
1670
                # We only need to check 2 locations, because there are only 2
 
1671
                # trees present.
 
1672
                for maybe_index in range(entry_index-1, entry_index+1):
 
1673
                    if maybe_index < 0 or maybe_index >= len(block):
 
1674
                        continue
 
1675
                    maybe_entry = block[maybe_index]
 
1676
                    if maybe_entry[0][:2] != (dirname, basename):
 
1677
                        # Just a random neighbor
 
1678
                        continue
 
1679
                    if maybe_entry[0][2] == file_id:
 
1680
                        raise AssertionError(
 
1681
                            '_find_entry_index didnt find a key match'
 
1682
                            ' but walking the data did, for %s'
 
1683
                            % (entry_key,))
 
1684
                    basis_kind = maybe_entry[1][1][0]
 
1685
                    if basis_kind not in 'ar':
 
1686
                        self._raise_invalid(new_path, file_id,
 
1687
                            "we have an add record for path, but the path"
 
1688
                            " is already present with another file_id %s"
 
1689
                            % (maybe_entry[0][2],))
 
1690
 
 
1691
                entry = (entry_key, [DirState.NULL_PARENT_DETAILS,
 
1692
                                     new_details])
 
1693
                block.insert(entry_index, entry)
 
1694
 
 
1695
            active_kind = entry[1][0][0]
 
1696
            if active_kind == 'a':
 
1697
                # The active record shows up as absent, this could be genuine,
 
1698
                # or it could be present at some other location. We need to
 
1699
                # verify.
 
1700
                id_index = self._get_id_index()
 
1701
                # The id_index may not be perfectly accurate for tree1, because
 
1702
                # we haven't been keeping it updated. However, it should be
 
1703
                # fine for tree0, and that gives us enough info for what we
 
1704
                # need
 
1705
                keys = id_index.get(file_id, ())
 
1706
                for key in keys:
 
1707
                    block_i, entry_i, d_present, f_present = \
 
1708
                        self._get_block_entry_index(key[0], key[1], 0)
 
1709
                    if not f_present:
 
1710
                        continue
 
1711
                    active_entry = self._dirblocks[block_i][1][entry_i]
 
1712
                    if (active_entry[0][2] != file_id):
 
1713
                        # Some other file is at this path, we don't need to
 
1714
                        # link it.
 
1715
                        continue
 
1716
                    real_active_kind = active_entry[1][0][0]
 
1717
                    if real_active_kind in 'ar':
 
1718
                        # We found a record, which was not *this* record,
 
1719
                        # which matches the file_id, but is not actually
 
1720
                        # present. Something seems *really* wrong.
 
1721
                        self._raise_invalid(new_path, file_id,
 
1722
                            "We found a tree0 entry that doesnt make sense")
 
1723
                    # Now, we've found a tree0 entry which matches the file_id
 
1724
                    # but is at a different location. So update them to be
 
1725
                    # rename records.
 
1726
                    active_dir, active_name = active_entry[0][:2]
 
1727
                    if active_dir:
 
1728
                        active_path = active_dir + '/' + active_name
 
1729
                    else:
 
1730
                        active_path = active_name
 
1731
                    active_entry[1][1] = st('r', new_path, 0, False, '')
 
1732
                    entry[1][0] = st('r', active_path, 0, False, '')
 
1733
            elif active_kind == 'r':
 
1734
                raise NotImplementedError()
 
1735
 
 
1736
            new_kind = new_details[0]
 
1737
            if new_kind == 'd':
 
1738
                self._ensure_block(block_index, entry_index, new_path)
1378
1739
 
1379
1740
    def _update_basis_apply_changes(self, changes):
1380
1741
        """Apply a sequence of changes to tree 1 during update_basis_by_delta.
1384
1745
        """
1385
1746
        absent = 'ar'
1386
1747
        for old_path, new_path, file_id, new_details in changes:
1387
 
            assert old_path == new_path
1388
1748
            # the entry for this file_id must be in tree 0.
1389
 
            entry = self._get_entry(0, file_id, new_path)
1390
 
            if entry[0] is None or entry[0][2] != file_id:
1391
 
                self._changes_aborted = True
1392
 
                raise errors.InconsistentDelta(new_path, file_id,
1393
 
                    'working tree does not contain new entry')
1394
 
            if (entry[1][0][0] in absent or
1395
 
                entry[1][1][0] in absent):
1396
 
                self._changes_aborted = True
1397
 
                raise errors.InconsistentDelta(new_path, file_id,
1398
 
                    'changed considered absent')
 
1749
            entry = self._get_entry(1, file_id, new_path)
 
1750
            if entry[0] is None or entry[1][1][0] in 'ar':
 
1751
                self._raise_invalid(new_path, file_id,
 
1752
                    'changed entry considered not present')
1399
1753
            entry[1][1] = new_details
1400
1754
 
1401
1755
    def _update_basis_apply_deletes(self, deletes):
1412
1766
        """
1413
1767
        null = DirState.NULL_PARENT_DETAILS
1414
1768
        for old_path, new_path, file_id, _, real_delete in deletes:
1415
 
            if real_delete:
1416
 
                assert new_path is None
1417
 
            else:
1418
 
                assert new_path is not None
 
1769
            if real_delete != (new_path is None):
 
1770
                self._raise_invalid(old_path, file_id, "bad delete delta")
1419
1771
            # the entry for this file_id must be in tree 1.
1420
1772
            dirname, basename = osutils.split(old_path)
1421
1773
            block_index, entry_index, dir_present, file_present = \
1422
1774
                self._get_block_entry_index(dirname, basename, 1)
1423
1775
            if not file_present:
1424
 
                self._changes_aborted = True
1425
 
                raise errors.InconsistentDelta(old_path, file_id,
 
1776
                self._raise_invalid(old_path, file_id,
1426
1777
                    'basis tree does not contain removed entry')
1427
1778
            entry = self._dirblocks[block_index][1][entry_index]
 
1779
            # The state of the entry in the 'active' WT
 
1780
            active_kind = entry[1][0][0]
1428
1781
            if entry[0][2] != file_id:
1429
 
                self._changes_aborted = True
1430
 
                raise errors.InconsistentDelta(old_path, file_id,
 
1782
                self._raise_invalid(old_path, file_id,
1431
1783
                    'mismatched file_id in tree 1')
1432
 
            if real_delete:
1433
 
                if entry[1][0][0] != 'a':
1434
 
                    self._changes_aborted = True
1435
 
                    raise errors.InconsistentDelta(old_path, file_id,
1436
 
                            'This was marked as a real delete, but the WT state'
1437
 
                            ' claims that it still exists and is versioned.')
 
1784
            dir_block = ()
 
1785
            old_kind = entry[1][1][0]
 
1786
            if active_kind in 'ar':
 
1787
                # The active tree doesn't have this file_id.
 
1788
                # The basis tree is changing this record. If this is a
 
1789
                # rename, then we don't want the record here at all
 
1790
                # anymore. If it is just an in-place change, we want the
 
1791
                # record here, but we'll add it if we need to. So we just
 
1792
                # delete it
 
1793
                if active_kind == 'r':
 
1794
                    active_path = entry[1][0][1]
 
1795
                    active_entry = self._get_entry(0, file_id, active_path)
 
1796
                    if active_entry[1][1][0] != 'r':
 
1797
                        self._raise_invalid(old_path, file_id,
 
1798
                            "Dirstate did not have matching rename entries")
 
1799
                    elif active_entry[1][0][0] in 'ar':
 
1800
                        self._raise_invalid(old_path, file_id,
 
1801
                            "Dirstate had a rename pointing at an inactive"
 
1802
                            " tree0")
 
1803
                    active_entry[1][1] = null
1438
1804
                del self._dirblocks[block_index][1][entry_index]
 
1805
                if old_kind == 'd':
 
1806
                    # This was a directory, and the active tree says it
 
1807
                    # doesn't exist, and now the basis tree says it doesn't
 
1808
                    # exist. Remove its dirblock if present
 
1809
                    (dir_block_index,
 
1810
                     present) = self._find_block_index_from_key(
 
1811
                        (old_path, '', ''))
 
1812
                    if present:
 
1813
                        dir_block = self._dirblocks[dir_block_index][1]
 
1814
                        if not dir_block:
 
1815
                            # This entry is empty, go ahead and just remove it
 
1816
                            del self._dirblocks[dir_block_index]
1439
1817
            else:
1440
 
                if entry[1][0][0] == 'a':
1441
 
                    self._changes_aborted = True
1442
 
                    raise errors.InconsistentDelta(old_path, file_id,
1443
 
                        'The entry was considered a rename, but the source path'
1444
 
                        ' is marked as absent.')
1445
 
                    # For whatever reason, we were asked to rename an entry
1446
 
                    # that was originally marked as deleted. This could be
1447
 
                    # because we are renaming the parent directory, and the WT
1448
 
                    # current state has the file marked as deleted.
1449
 
                elif entry[1][0][0] == 'r':
1450
 
                    # implement the rename
1451
 
                    del self._dirblocks[block_index][1][entry_index]
1452
 
                else:
1453
 
                    # it is being resurrected here, so blank it out temporarily.
1454
 
                    self._dirblocks[block_index][1][entry_index][1][1] = null
1455
 
 
1456
 
    def update_entry(self, entry, abspath, stat_value,
1457
 
                     _stat_to_minikind=_stat_to_minikind,
1458
 
                     _pack_stat=pack_stat):
1459
 
        """Update the entry based on what is actually on disk.
1460
 
 
1461
 
        :param entry: This is the dirblock entry for the file in question.
1462
 
        :param abspath: The path on disk for this file.
1463
 
        :param stat_value: (optional) if we already have done a stat on the
1464
 
            file, re-use it.
1465
 
        :return: The sha1 hexdigest of the file (40 bytes) or link target of a
1466
 
                symlink.
 
1818
                # There is still an active record, so just mark this
 
1819
                # removed.
 
1820
                entry[1][1] = null
 
1821
                block_i, entry_i, d_present, f_present = \
 
1822
                    self._get_block_entry_index(old_path, '', 1)
 
1823
                if d_present:
 
1824
                    dir_block = self._dirblocks[block_i][1]
 
1825
            for child_entry in dir_block:
 
1826
                child_basis_kind = child_entry[1][1][0]
 
1827
                if child_basis_kind not in 'ar':
 
1828
                    self._raise_invalid(old_path, file_id,
 
1829
                        "The file id was deleted but its children were "
 
1830
                        "not deleted.")
 
1831
 
 
1832
    def _after_delta_check_parents(self, parents, index):
 
1833
        """Check that parents required by the delta are all intact.
 
1834
        
 
1835
        :param parents: An iterable of (path_utf8, file_id) tuples which are
 
1836
            required to be present in tree 'index' at path_utf8 with id file_id
 
1837
            and be a directory.
 
1838
        :param index: The column in the dirstate to check for parents in.
 
1839
        """
 
1840
        for dirname_utf8, file_id in parents:
 
1841
            # Get the entry - the ensures that file_id, dirname_utf8 exists and
 
1842
            # has the right file id.
 
1843
            entry = self._get_entry(index, file_id, dirname_utf8)
 
1844
            if entry[1] is None:
 
1845
                self._raise_invalid(dirname_utf8.decode('utf8'),
 
1846
                    file_id, "This parent is not present.")
 
1847
            # Parents of things must be directories
 
1848
            if entry[1][index][0] != 'd':
 
1849
                self._raise_invalid(dirname_utf8.decode('utf8'),
 
1850
                    file_id, "This parent is not a directory.")
 
1851
 
 
1852
    def _observed_sha1(self, entry, sha1, stat_value,
 
1853
        _stat_to_minikind=_stat_to_minikind):
 
1854
        """Note the sha1 of a file.
 
1855
 
 
1856
        :param entry: The entry the sha1 is for.
 
1857
        :param sha1: The observed sha1.
 
1858
        :param stat_value: The os.lstat for the file.
1467
1859
        """
1468
1860
        try:
1469
1861
            minikind = _stat_to_minikind[stat_value.st_mode & 0170000]
1470
1862
        except KeyError:
1471
1863
            # Unhandled kind
1472
1864
            return None
1473
 
        packed_stat = _pack_stat(stat_value)
1474
 
        (saved_minikind, saved_link_or_sha1, saved_file_size,
1475
 
         saved_executable, saved_packed_stat) = entry[1][0]
1476
 
 
1477
 
        if (minikind == saved_minikind
1478
 
            and packed_stat == saved_packed_stat):
1479
 
            # The stat hasn't changed since we saved, so we can re-use the
1480
 
            # saved sha hash.
1481
 
            if minikind == 'd':
1482
 
                return None
1483
 
 
1484
 
            # size should also be in packed_stat
1485
 
            if saved_file_size == stat_value.st_size:
1486
 
                return saved_link_or_sha1
1487
 
 
1488
 
        # If we have gotten this far, that means that we need to actually
1489
 
        # process this entry.
1490
 
        link_or_sha1 = None
1491
1865
        if minikind == 'f':
1492
 
            link_or_sha1 = self._sha1_file(abspath)
1493
 
            executable = self._is_executable(stat_value.st_mode,
1494
 
                                             saved_executable)
1495
 
            if self._cutoff_time is None:
1496
 
                self._sha_cutoff_time()
1497
 
            if (stat_value.st_mtime < self._cutoff_time
1498
 
                and stat_value.st_ctime < self._cutoff_time):
1499
 
                entry[1][0] = ('f', link_or_sha1, stat_value.st_size,
1500
 
                               executable, packed_stat)
1501
 
            else:
1502
 
                entry[1][0] = ('f', '', stat_value.st_size,
1503
 
                               executable, DirState.NULLSTAT)
1504
 
        elif minikind == 'd':
1505
 
            link_or_sha1 = None
1506
 
            entry[1][0] = ('d', '', 0, False, packed_stat)
1507
 
            if saved_minikind != 'd':
1508
 
                # This changed from something into a directory. Make sure we
1509
 
                # have a directory block for it. This doesn't happen very
1510
 
                # often, so this doesn't have to be super fast.
1511
 
                block_index, entry_index, dir_present, file_present = \
1512
 
                    self._get_block_entry_index(entry[0][0], entry[0][1], 0)
1513
 
                self._ensure_block(block_index, entry_index,
1514
 
                                   osutils.pathjoin(entry[0][0], entry[0][1]))
1515
 
        elif minikind == 'l':
1516
 
            link_or_sha1 = self._read_link(abspath, saved_link_or_sha1)
1517
 
            if self._cutoff_time is None:
1518
 
                self._sha_cutoff_time()
1519
 
            if (stat_value.st_mtime < self._cutoff_time
1520
 
                and stat_value.st_ctime < self._cutoff_time):
1521
 
                entry[1][0] = ('l', link_or_sha1, stat_value.st_size,
1522
 
                               False, packed_stat)
1523
 
            else:
1524
 
                entry[1][0] = ('l', '', stat_value.st_size,
1525
 
                               False, DirState.NULLSTAT)
1526
 
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
1527
 
        return link_or_sha1
 
1866
            if self._cutoff_time is None:
 
1867
                self._sha_cutoff_time()
 
1868
            if (stat_value.st_mtime < self._cutoff_time
 
1869
                and stat_value.st_ctime < self._cutoff_time):
 
1870
                entry[1][0] = ('f', sha1, stat_value.st_size, entry[1][0][3],
 
1871
                               pack_stat(stat_value))
 
1872
                self._mark_modified([entry])
1528
1873
 
1529
1874
    def _sha_cutoff_time(self):
1530
1875
        """Return cutoff time.
1547
1892
        # when -Dhashcache is turned on, this is monkey-patched in to log
1548
1893
        # file reads
1549
1894
        trace.mutter("dirstate sha1 " + abspath)
1550
 
        return osutils.sha_file_by_name(abspath)
 
1895
        return self._sha1_provider.sha1(abspath)
1551
1896
 
1552
1897
    def _is_executable(self, mode, old_executable):
1553
1898
        """Is this file executable?"""
1566
1911
        #       already in memory. However, this really needs to be done at a
1567
1912
        #       higher level, because there either won't be anything on disk,
1568
1913
        #       or the thing on disk will be a file.
1569
 
        return os.readlink(abspath)
 
1914
        fs_encoding = osutils._fs_enc
 
1915
        if isinstance(abspath, unicode):
 
1916
            # abspath is defined as the path to pass to lstat. readlink is
 
1917
            # buggy in python < 2.6 (it doesn't encode unicode path into FS
 
1918
            # encoding), so we need to encode ourselves knowing that unicode
 
1919
            # paths are produced by UnicodeDirReader on purpose.
 
1920
            abspath = abspath.encode(fs_encoding)
 
1921
        target = os.readlink(abspath)
 
1922
        if fs_encoding not in ('UTF-8', 'US-ASCII', 'ANSI_X3.4-1968'):
 
1923
            # Change encoding if needed
 
1924
            target = target.decode(fs_encoding).encode('UTF-8')
 
1925
        return target
1570
1926
 
1571
1927
    def get_ghosts(self):
1572
1928
        """Return a list of the parent tree revision ids that are ghosts."""
1577
1933
        """Serialise the entire dirstate to a sequence of lines."""
1578
1934
        if (self._header_state == DirState.IN_MEMORY_UNMODIFIED and
1579
1935
            self._dirblock_state == DirState.IN_MEMORY_UNMODIFIED):
1580
 
            # read whats on disk.
 
1936
            # read what's on disk.
1581
1937
            self._state_file.seek(0)
1582
1938
            return self._state_file.readlines()
1583
1939
        lines = []
1584
1940
        lines.append(self._get_parents_line(self.get_parent_ids()))
1585
1941
        lines.append(self._get_ghosts_line(self._ghosts))
1586
 
        # append the root line which is special cased
1587
 
        lines.extend(map(self._entry_to_line, self._iter_entries()))
 
1942
        lines.extend(self._get_entry_lines())
1588
1943
        return self._get_output_lines(lines)
1589
1944
 
1590
1945
    def _get_ghosts_line(self, ghost_ids):
1595
1950
        """Create a line for the state file for parents information."""
1596
1951
        return '\0'.join([str(len(parent_ids))] + parent_ids)
1597
1952
 
 
1953
    def _get_entry_lines(self):
 
1954
        """Create lines for entries."""
 
1955
        return map(self._entry_to_line, self._iter_entries())
 
1956
 
1598
1957
    def _get_fields_to_entry(self):
1599
1958
        """Get a function which converts entry fields into a entry record.
1600
1959
 
1718
2077
            entry_index += 1
1719
2078
        return block_index, entry_index, True, False
1720
2079
 
1721
 
    def _get_entry(self, tree_index, fileid_utf8=None, path_utf8=None):
 
2080
    def _get_entry(self, tree_index, fileid_utf8=None, path_utf8=None,
 
2081
                   include_deleted=False):
1722
2082
        """Get the dirstate entry for path in tree tree_index.
1723
2083
 
1724
2084
        If either file_id or path is supplied, it is used as the key to lookup.
1732
2092
            trees.
1733
2093
        :param fileid_utf8: A utf8 file_id to look up.
1734
2094
        :param path_utf8: An utf8 path to be looked up.
 
2095
        :param include_deleted: If True, and performing a lookup via
 
2096
            fileid_utf8 rather than path_utf8, return an entry for deleted
 
2097
            (absent) paths.
1735
2098
        :return: The dirstate entry tuple for path, or (None, None)
1736
2099
        """
1737
2100
        self._read_dirblocks_if_needed()
1738
2101
        if path_utf8 is not None:
1739
 
            assert path_utf8.__class__ == str, ('path_utf8 is not a str: %s %s'
1740
 
                % (type(path_utf8), path_utf8))
 
2102
            if type(path_utf8) is not str:
 
2103
                raise errors.BzrError('path_utf8 is not a str: %s %r'
 
2104
                    % (type(path_utf8), path_utf8))
1741
2105
            # path lookups are faster
1742
2106
            dirname, basename = osutils.split(path_utf8)
1743
2107
            block_index, entry_index, dir_present, file_present = \
1745
2109
            if not file_present:
1746
2110
                return None, None
1747
2111
            entry = self._dirblocks[block_index][1][entry_index]
1748
 
            assert entry[0][2] and entry[1][tree_index][0] not in ('a', 'r'), 'unversioned entry?!?!'
 
2112
            if not (entry[0][2] and entry[1][tree_index][0] not in ('a', 'r')):
 
2113
                raise AssertionError('unversioned entry?')
1749
2114
            if fileid_utf8:
1750
2115
                if entry[0][2] != fileid_utf8:
1751
2116
                    self._changes_aborted = True
1753
2118
                                          ' tree_index, file_id and path')
1754
2119
            return entry
1755
2120
        else:
1756
 
            assert fileid_utf8 is not None
1757
 
            possible_keys = self._get_id_index().get(fileid_utf8, None)
 
2121
            possible_keys = self._get_id_index().get(fileid_utf8, ())
1758
2122
            if not possible_keys:
1759
2123
                return None, None
1760
2124
            for key in possible_keys:
1771
2135
                entry_index, present = self._find_entry_index(key, block)
1772
2136
                if present:
1773
2137
                    entry = self._dirblocks[block_index][1][entry_index]
 
2138
                    # TODO: We might want to assert that entry[0][2] ==
 
2139
                    #       fileid_utf8.
1774
2140
                    if entry[1][tree_index][0] in 'fdlt':
1775
 
                        # this is the result we are looking for: the  
 
2141
                        # this is the result we are looking for: the
1776
2142
                        # real home of this file_id in this tree.
1777
2143
                        return entry
1778
2144
                    if entry[1][tree_index][0] == 'a':
1779
2145
                        # there is no home for this entry in this tree
 
2146
                        if include_deleted:
 
2147
                            return entry
1780
2148
                        return None, None
1781
 
                    assert entry[1][tree_index][0] == 'r', \
1782
 
                        "entry %r has invalid minikind %r for tree %r" \
1783
 
                        % (entry,
1784
 
                           entry[1][tree_index][0],
1785
 
                           tree_index)
 
2149
                    if entry[1][tree_index][0] != 'r':
 
2150
                        raise AssertionError(
 
2151
                            "entry %r has invalid minikind %r for tree %r" \
 
2152
                            % (entry,
 
2153
                               entry[1][tree_index][0],
 
2154
                               tree_index))
1786
2155
                    real_path = entry[1][tree_index][1]
1787
2156
                    return self._get_entry(tree_index, fileid_utf8=fileid_utf8,
1788
2157
                        path_utf8=real_path)
1789
2158
            return None, None
1790
2159
 
1791
2160
    @classmethod
1792
 
    def initialize(cls, path):
 
2161
    def initialize(cls, path, sha1_provider=None):
1793
2162
        """Create a new dirstate on path.
1794
2163
 
1795
2164
        The new dirstate will be an empty tree - that is it has no parents,
1796
2165
        and only a root node - which has id ROOT_ID.
1797
2166
 
1798
2167
        :param path: The name of the file for the dirstate.
 
2168
        :param sha1_provider: an object meeting the SHA1Provider interface.
 
2169
            If None, a DefaultSHA1Provider is used.
1799
2170
        :return: A write-locked DirState object.
1800
2171
        """
1801
2172
        # This constructs a new DirState object on a path, sets the _state_file
1803
2174
        # stock empty dirstate information - a root with ROOT_ID, no children,
1804
2175
        # and no parents. Finally it calls save() to ensure that this data will
1805
2176
        # persist.
1806
 
        result = cls(path)
 
2177
        if sha1_provider is None:
 
2178
            sha1_provider = DefaultSHA1Provider()
 
2179
        result = cls(path, sha1_provider)
1807
2180
        # root dir and root dir contents with no children.
1808
2181
        empty_tree_dirblocks = [('', []), ('', [])]
1809
2182
        # a new root directory, with a NULLSTAT.
1820
2193
            raise
1821
2194
        return result
1822
2195
 
1823
 
    def _inv_entry_to_details(self, inv_entry):
 
2196
    @staticmethod
 
2197
    def _inv_entry_to_details(inv_entry):
1824
2198
        """Convert an inventory entry (from a revision tree) to state details.
1825
2199
 
1826
2200
        :param inv_entry: An inventory entry whose sha1 and link targets can be
1831
2205
        kind = inv_entry.kind
1832
2206
        minikind = DirState._kind_to_minikind[kind]
1833
2207
        tree_data = inv_entry.revision
1834
 
        assert tree_data, 'empty revision for the inv_entry %s.' % \
1835
 
            inv_entry.file_id
1836
2208
        if kind == 'directory':
1837
2209
            fingerprint = ''
1838
2210
            size = 0
1839
2211
            executable = False
1840
2212
        elif kind == 'symlink':
1841
 
            fingerprint = inv_entry.symlink_target or ''
 
2213
            if inv_entry.symlink_target is None:
 
2214
                fingerprint = ''
 
2215
            else:
 
2216
                fingerprint = inv_entry.symlink_target.encode('utf8')
1842
2217
            size = 0
1843
2218
            executable = False
1844
2219
        elif kind == 'file':
1851
2226
            executable = False
1852
2227
        else:
1853
2228
            raise Exception("can't pack %s" % inv_entry)
1854
 
        return (minikind, fingerprint, size, executable, tree_data)
 
2229
        return static_tuple.StaticTuple(minikind, fingerprint, size,
 
2230
                                        executable, tree_data)
1855
2231
 
1856
2232
    def _iter_child_entries(self, tree_index, path_utf8):
1857
2233
        """Iterate over all the entries that are children of path_utf.
1858
2234
 
1859
 
        This only returns entries that are present (not in 'a', 'r') in 
 
2235
        This only returns entries that are present (not in 'a', 'r') in
1860
2236
        tree_index. tree_index data is not refreshed, so if tree 0 is used,
1861
2237
        results may differ from that obtained if paths were statted to
1862
2238
        determine what ones were directories.
1893
2269
                        else:
1894
2270
                            path = entry[0][1]
1895
2271
                        next_pending_dirs.append(path)
1896
 
    
 
2272
 
1897
2273
    def _iter_entries(self):
1898
2274
        """Iterate over all the entries in the dirstate.
1899
2275
 
1906
2282
                yield entry
1907
2283
 
1908
2284
    def _get_id_index(self):
1909
 
        """Get an id index of self._dirblocks."""
 
2285
        """Get an id index of self._dirblocks.
 
2286
 
 
2287
        This maps from file_id => [(directory, name, file_id)] entries where
 
2288
        that file_id appears in one of the trees.
 
2289
        """
1910
2290
        if self._id_index is None:
1911
2291
            id_index = {}
1912
2292
            for key, tree_details in self._iter_entries():
1913
 
                id_index.setdefault(key[2], set()).add(key)
 
2293
                self._add_to_id_index(id_index, key)
1914
2294
            self._id_index = id_index
1915
2295
        return self._id_index
1916
2296
 
 
2297
    def _add_to_id_index(self, id_index, entry_key):
 
2298
        """Add this entry to the _id_index mapping."""
 
2299
        # This code used to use a set for every entry in the id_index. However,
 
2300
        # it is *rare* to have more than one entry. So a set is a large
 
2301
        # overkill. And even when we do, we won't ever have more than the
 
2302
        # number of parent trees. Which is still a small number (rarely >2). As
 
2303
        # such, we use a simple tuple, and do our own uniqueness checks. While
 
2304
        # the 'in' check is O(N) since N is nicely bounded it shouldn't ever
 
2305
        # cause quadratic failure.
 
2306
        file_id = entry_key[2]
 
2307
        entry_key = static_tuple.StaticTuple.from_sequence(entry_key)
 
2308
        if file_id not in id_index:
 
2309
            id_index[file_id] = static_tuple.StaticTuple(entry_key,)
 
2310
        else:
 
2311
            entry_keys = id_index[file_id]
 
2312
            if entry_key not in entry_keys:
 
2313
                id_index[file_id] = entry_keys + (entry_key,)
 
2314
 
 
2315
    def _remove_from_id_index(self, id_index, entry_key):
 
2316
        """Remove this entry from the _id_index mapping.
 
2317
 
 
2318
        It is an programming error to call this when the entry_key is not
 
2319
        already present.
 
2320
        """
 
2321
        file_id = entry_key[2]
 
2322
        entry_keys = list(id_index[file_id])
 
2323
        entry_keys.remove(entry_key)
 
2324
        id_index[file_id] = static_tuple.StaticTuple.from_sequence(entry_keys)
 
2325
 
1917
2326
    def _get_output_lines(self, lines):
1918
2327
        """Format lines for final output.
1919
2328
 
1939
2348
        """The number of parent entries in each record row."""
1940
2349
        return len(self._parents) - len(self._ghosts)
1941
2350
 
1942
 
    @staticmethod
1943
 
    def on_file(path):
1944
 
        """Construct a DirState on the file at path path.
 
2351
    @classmethod
 
2352
    def on_file(cls, path, sha1_provider=None, worth_saving_limit=0):
 
2353
        """Construct a DirState on the file at path "path".
1945
2354
 
 
2355
        :param path: The path at which the dirstate file on disk should live.
 
2356
        :param sha1_provider: an object meeting the SHA1Provider interface.
 
2357
            If None, a DefaultSHA1Provider is used.
 
2358
        :param worth_saving_limit: when the exact number of hash changed
 
2359
            entries is known, only bother saving the dirstate if more than
 
2360
            this count of entries have changed. -1 means never save.
1946
2361
        :return: An unlocked DirState object, associated with the given path.
1947
2362
        """
1948
 
        result = DirState(path)
 
2363
        if sha1_provider is None:
 
2364
            sha1_provider = DefaultSHA1Provider()
 
2365
        result = cls(path, sha1_provider,
 
2366
                     worth_saving_limit=worth_saving_limit)
1949
2367
        return result
1950
2368
 
1951
2369
    def _read_dirblocks_if_needed(self):
1952
2370
        """Read in all the dirblocks from the file if they are not in memory.
1953
 
        
 
2371
 
1954
2372
        This populates self._dirblocks, and sets self._dirblock_state to
1955
2373
        IN_MEMORY_UNMODIFIED. It is not currently ready for incremental block
1956
2374
        loading.
1971
2389
        parent_line = self._state_file.readline()
1972
2390
        info = parent_line.split('\0')
1973
2391
        num_parents = int(info[0])
1974
 
        assert num_parents == len(info)-2, 'incorrect parent info line'
1975
2392
        self._parents = info[1:-1]
1976
 
 
1977
2393
        ghost_line = self._state_file.readline()
1978
2394
        info = ghost_line.split('\0')
1979
2395
        num_ghosts = int(info[1])
1980
 
        assert num_ghosts == len(info)-3, 'incorrect ghost info line'
1981
2396
        self._ghosts = info[2:-1]
1982
2397
        self._header_state = DirState.IN_MEMORY_UNMODIFIED
1983
2398
        self._end_of_header = self._state_file.tell()
2000
2415
        and their ids. Followed by a newline.
2001
2416
        """
2002
2417
        header = self._state_file.readline()
2003
 
        assert header == DirState.HEADER_FORMAT_3, \
2004
 
            'invalid header line: %r' % (header,)
 
2418
        if header != DirState.HEADER_FORMAT_3:
 
2419
            raise errors.BzrError(
 
2420
                'invalid header line: %r' % (header,))
2005
2421
        crc_line = self._state_file.readline()
2006
 
        assert crc_line.startswith('crc32: '), 'missing crc32 checksum'
 
2422
        if not crc_line.startswith('crc32: '):
 
2423
            raise errors.BzrError('missing crc32 checksum: %r' % crc_line)
2007
2424
        self.crc_expected = int(crc_line[len('crc32: '):-1])
2008
2425
        num_entries_line = self._state_file.readline()
2009
 
        assert num_entries_line.startswith('num_entries: '), 'missing num_entries line'
 
2426
        if not num_entries_line.startswith('num_entries: '):
 
2427
            raise errors.BzrError('missing num_entries line')
2010
2428
        self._num_entries = int(num_entries_line[len('num_entries: '):-1])
2011
2429
 
2012
 
    def sha1_from_stat(self, path, stat_result, _pack_stat=pack_stat):
 
2430
    def sha1_from_stat(self, path, stat_result):
2013
2431
        """Find a sha1 given a stat lookup."""
2014
 
        return self._get_packed_stat_index().get(_pack_stat(stat_result), None)
 
2432
        return self._get_packed_stat_index().get(pack_stat(stat_result), None)
2015
2433
 
2016
2434
    def _get_packed_stat_index(self):
2017
2435
        """Get a packed_stat index of self._dirblocks."""
2043
2461
            trace.mutter('Not saving DirState because '
2044
2462
                    '_changes_aborted is set.')
2045
2463
            return
2046
 
        if (self._header_state == DirState.IN_MEMORY_MODIFIED or
2047
 
            self._dirblock_state == DirState.IN_MEMORY_MODIFIED):
 
2464
        # TODO: Since we now distinguish IN_MEMORY_MODIFIED from
 
2465
        #       IN_MEMORY_HASH_MODIFIED, we should only fail quietly if we fail
 
2466
        #       to save an IN_MEMORY_HASH_MODIFIED, and fail *noisily* if we
 
2467
        #       fail to save IN_MEMORY_MODIFIED
 
2468
        if not self._worth_saving():
 
2469
            return
2048
2470
 
2049
 
            grabbed_write_lock = False
2050
 
            if self._lock_state != 'w':
2051
 
                grabbed_write_lock, new_lock = self._lock_token.temporary_write_lock()
2052
 
                # Switch over to the new lock, as the old one may be closed.
 
2471
        grabbed_write_lock = False
 
2472
        if self._lock_state != 'w':
 
2473
            grabbed_write_lock, new_lock = self._lock_token.temporary_write_lock()
 
2474
            # Switch over to the new lock, as the old one may be closed.
 
2475
            # TODO: jam 20070315 We should validate the disk file has
 
2476
            #       not changed contents, since temporary_write_lock may
 
2477
            #       not be an atomic operation.
 
2478
            self._lock_token = new_lock
 
2479
            self._state_file = new_lock.f
 
2480
            if not grabbed_write_lock:
 
2481
                # We couldn't grab a write lock, so we switch back to a read one
 
2482
                return
 
2483
        try:
 
2484
            lines = self.get_lines()
 
2485
            self._state_file.seek(0)
 
2486
            self._state_file.writelines(lines)
 
2487
            self._state_file.truncate()
 
2488
            self._state_file.flush()
 
2489
            self._maybe_fdatasync()
 
2490
            self._mark_unmodified()
 
2491
        finally:
 
2492
            if grabbed_write_lock:
 
2493
                self._lock_token = self._lock_token.restore_read_lock()
 
2494
                self._state_file = self._lock_token.f
2053
2495
                # TODO: jam 20070315 We should validate the disk file has
2054
 
                #       not changed contents. Since temporary_write_lock may
2055
 
                #       not be an atomic operation.
2056
 
                self._lock_token = new_lock
2057
 
                self._state_file = new_lock.f
2058
 
                if not grabbed_write_lock:
2059
 
                    # We couldn't grab a write lock, so we switch back to a read one
2060
 
                    return
2061
 
            try:
2062
 
                self._state_file.seek(0)
2063
 
                self._state_file.writelines(self.get_lines())
2064
 
                self._state_file.truncate()
2065
 
                self._state_file.flush()
2066
 
                self._header_state = DirState.IN_MEMORY_UNMODIFIED
2067
 
                self._dirblock_state = DirState.IN_MEMORY_UNMODIFIED
2068
 
            finally:
2069
 
                if grabbed_write_lock:
2070
 
                    self._lock_token = self._lock_token.restore_read_lock()
2071
 
                    self._state_file = self._lock_token.f
2072
 
                    # TODO: jam 20070315 We should validate the disk file has
2073
 
                    #       not changed contents. Since restore_read_lock may
2074
 
                    #       not be an atomic operation.
 
2496
                #       not changed contents. Since restore_read_lock may
 
2497
                #       not be an atomic operation.                
 
2498
 
 
2499
    def _maybe_fdatasync(self):
 
2500
        """Flush to disk if possible and if not configured off."""
 
2501
        if self._config_stack.get('dirstate.fdatasync'):
 
2502
            osutils.fdatasync(self._state_file.fileno())
 
2503
 
 
2504
    def _worth_saving(self):
 
2505
        """Is it worth saving the dirstate or not?"""
 
2506
        if (self._header_state == DirState.IN_MEMORY_MODIFIED
 
2507
            or self._dirblock_state == DirState.IN_MEMORY_MODIFIED):
 
2508
            return True
 
2509
        if self._dirblock_state == DirState.IN_MEMORY_HASH_MODIFIED:
 
2510
            if self._worth_saving_limit == -1:
 
2511
                # We never save hash changes when the limit is -1
 
2512
                return False
 
2513
            # If we're using smart saving and only a small number of
 
2514
            # entries have changed their hash, don't bother saving. John has
 
2515
            # suggested using a heuristic here based on the size of the
 
2516
            # changed files and/or tree. For now, we go with a configurable
 
2517
            # number of changes, keeping the calculation time
 
2518
            # as low overhead as possible. (This also keeps all existing
 
2519
            # tests passing as the default is 0, i.e. always save.)
 
2520
            if len(self._known_hash_changes) >= self._worth_saving_limit:
 
2521
                return True
 
2522
        return False
2075
2523
 
2076
2524
    def _set_data(self, parent_ids, dirblocks):
2077
2525
        """Set the full dirstate data in memory.
2081
2529
 
2082
2530
        :param parent_ids: A list of parent tree revision ids.
2083
2531
        :param dirblocks: A list containing one tuple for each directory in the
2084
 
            tree. Each tuple contains the directory path and a list of entries 
 
2532
            tree. Each tuple contains the directory path and a list of entries
2085
2533
            found in that directory.
2086
2534
        """
2087
2535
        # our memory copy is now authoritative.
2088
2536
        self._dirblocks = dirblocks
2089
 
        self._header_state = DirState.IN_MEMORY_MODIFIED
2090
 
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
2537
        self._mark_modified(header_modified=True)
2091
2538
        self._parents = list(parent_ids)
2092
2539
        self._id_index = None
2093
2540
        self._packed_stat_index = None
2100
2547
        :param new_id: The new id to assign to the path. This must be a utf8
2101
2548
            file id (not unicode, and not None).
2102
2549
        """
2103
 
        assert new_id.__class__ == str, \
2104
 
            "path_id %r is not a plain string" % (new_id,)
2105
2550
        self._read_dirblocks_if_needed()
2106
2551
        if len(path):
2107
2552
            # TODO: logic not written
2115
2560
        self._make_absent(entry)
2116
2561
        self.update_minimal(('', '', new_id), 'd',
2117
2562
            path_utf8='', packed_stat=entry[1][0][4])
2118
 
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
2563
        self._mark_modified()
 
2564
        # XXX: This was added by Ian, we need to make sure there
 
2565
        #      are tests for it, because it isn't in bzr.dev TRUNK
 
2566
        #      It looks like the only place it is called is in setting the root
 
2567
        #      id of the tree. So probably we never had an _id_index when we
 
2568
        #      don't even have a root yet.
2119
2569
        if self._id_index is not None:
2120
 
            self._id_index.setdefault(new_id, set()).add(entry[0])
 
2570
            self._add_to_id_index(self._id_index, entry[0])
2121
2571
 
2122
2572
    def set_parent_trees(self, trees, ghosts):
2123
2573
        """Set the parent trees for the dirstate.
2124
2574
 
2125
2575
        :param trees: A list of revision_id, tree tuples. tree must be provided
2126
 
            even if the revision_id refers to a ghost: supply an empty tree in 
 
2576
            even if the revision_id refers to a ghost: supply an empty tree in
2127
2577
            this case.
2128
2578
        :param ghosts: A list of the revision_ids that are ghosts at the time
2129
2579
            of setting.
2130
 
        """ 
2131
 
        # TODO: generate a list of parent indexes to preserve to save 
 
2580
        """
 
2581
        # TODO: generate a list of parent indexes to preserve to save
2132
2582
        # processing specific parent trees. In the common case one tree will
2133
2583
        # be preserved - the left most parent.
2134
2584
        # TODO: if the parent tree is a dirstate, we might want to walk them
2139
2589
        # map and then walk the new parent trees only, mapping them into the
2140
2590
        # dirstate. Walk the dirstate at the same time to remove unreferenced
2141
2591
        # entries.
2142
 
        # for now: 
2143
 
        # sketch: loop over all entries in the dirstate, cherry picking 
 
2592
        # for now:
 
2593
        # sketch: loop over all entries in the dirstate, cherry picking
2144
2594
        # entries from the parent trees, if they are not ghost trees.
2145
2595
        # after we finish walking the dirstate, all entries not in the dirstate
2146
2596
        # are deletes, so we want to append them to the end as per the design
2151
2601
        #   links. We dont't trivially use the inventory from other trees
2152
2602
        #   because this leads to either double touching, or to accessing
2153
2603
        #   missing keys,
2154
 
        # - find other keys containing a path 
2155
 
        # We accumulate each entry via this dictionary, including the root 
 
2604
        # - find other keys containing a path
 
2605
        # We accumulate each entry via this dictionary, including the root
2156
2606
        by_path = {}
2157
2607
        id_index = {}
2158
2608
        # we could do parallel iterators, but because file id data may be
2162
2612
        # parent, but for now the common cases are adding a new parent (merge),
2163
2613
        # and replacing completely (commit), and commit is more common: so
2164
2614
        # optimise merge later.
2165
 
        
 
2615
 
2166
2616
        # ---- start generation of full tree mapping data
2167
2617
        # what trees should we use?
2168
2618
        parent_trees = [tree for rev_id, tree in trees if rev_id not in ghosts]
2169
 
        # how many trees do we end up with 
 
2619
        # how many trees do we end up with
2170
2620
        parent_count = len(parent_trees)
 
2621
        st = static_tuple.StaticTuple
2171
2622
 
2172
2623
        # one: the current tree
2173
2624
        for entry in self._iter_entries():
2176
2627
                continue
2177
2628
            by_path[entry[0]] = [entry[1][0]] + \
2178
2629
                [DirState.NULL_PARENT_DETAILS] * parent_count
2179
 
            id_index[entry[0][2]] = set([entry[0]])
2180
 
        
 
2630
            # TODO: Possibly inline this, since we know it isn't present yet
 
2631
            #       id_index[entry[0][2]] = (entry[0],)
 
2632
            self._add_to_id_index(id_index, entry[0])
 
2633
 
2181
2634
        # now the parent trees:
2182
2635
        for tree_index, tree in enumerate(parent_trees):
2183
2636
            # the index is off by one, adjust it.
2188
2641
            # the suffix is from tree_index+1:parent_count+1.
2189
2642
            new_location_suffix = [DirState.NULL_PARENT_DETAILS] * (parent_count - tree_index)
2190
2643
            # now stitch in all the entries from this tree
2191
 
            for path, entry in tree.inventory.iter_entries_by_dir():
 
2644
            last_dirname = None
 
2645
            for path, entry in tree.iter_entries_by_dir():
2192
2646
                # here we process each trees details for each item in the tree.
2193
2647
                # we first update any existing entries for the id at other paths,
2194
2648
                # then we either create or update the entry for the id at the
2197
2651
                # avoid checking all known paths for the id when generating a
2198
2652
                # new entry at this path: by adding the id->path mapping last,
2199
2653
                # all the mappings are valid and have correct relocation
2200
 
                # records where needed. 
 
2654
                # records where needed.
2201
2655
                file_id = entry.file_id
2202
2656
                path_utf8 = path.encode('utf8')
2203
2657
                dirname, basename = osutils.split(path_utf8)
2204
 
                new_entry_key = (dirname, basename, file_id)
 
2658
                if dirname == last_dirname:
 
2659
                    # Try to re-use objects as much as possible
 
2660
                    dirname = last_dirname
 
2661
                else:
 
2662
                    last_dirname = dirname
 
2663
                new_entry_key = st(dirname, basename, file_id)
2205
2664
                # tree index consistency: All other paths for this id in this tree
2206
2665
                # index must point to the correct path.
2207
 
                for entry_key in id_index.setdefault(file_id, set()):
 
2666
                entry_keys = id_index.get(file_id, ())
 
2667
                for entry_key in entry_keys:
2208
2668
                    # TODO:PROFILING: It might be faster to just update
2209
2669
                    # rather than checking if we need to, and then overwrite
2210
2670
                    # the one we are located at.
2213
2673
                        # other trees, so put absent pointers there
2214
2674
                        # This is the vertical axis in the matrix, all pointing
2215
2675
                        # to the real path.
2216
 
                        by_path[entry_key][tree_index] = ('r', path_utf8, 0, False, '')
2217
 
                # by path consistency: Insert into an existing path record (trivial), or 
2218
 
                # add a new one with relocation pointers for the other tree indexes.
2219
 
                if new_entry_key in id_index[file_id]:
2220
 
                    # there is already an entry where this data belongs, just insert it.
 
2676
                        by_path[entry_key][tree_index] = st('r', path_utf8, 0,
 
2677
                                                            False, '')
 
2678
                # by path consistency: Insert into an existing path record
 
2679
                # (trivial), or add a new one with relocation pointers for the
 
2680
                # other tree indexes.
 
2681
                if new_entry_key in entry_keys:
 
2682
                    # there is already an entry where this data belongs, just
 
2683
                    # insert it.
2221
2684
                    by_path[new_entry_key][tree_index] = \
2222
2685
                        self._inv_entry_to_details(entry)
2223
2686
                else:
2227
2690
                    new_details = []
2228
2691
                    for lookup_index in xrange(tree_index):
2229
2692
                        # boundary case: this is the first occurence of file_id
2230
 
                        # so there are no id_indexs, possibly take this out of
 
2693
                        # so there are no id_indexes, possibly take this out of
2231
2694
                        # the loop?
2232
 
                        if not len(id_index[file_id]):
 
2695
                        if not len(entry_keys):
2233
2696
                            new_details.append(DirState.NULL_PARENT_DETAILS)
2234
2697
                        else:
2235
2698
                            # grab any one entry, use it to find the right path.
2236
 
                            # TODO: optimise this to reduce memory use in highly 
2237
 
                            # fragmented situations by reusing the relocation
2238
 
                            # records.
2239
 
                            a_key = iter(id_index[file_id]).next()
 
2699
                            a_key = iter(entry_keys).next()
2240
2700
                            if by_path[a_key][lookup_index][0] in ('r', 'a'):
2241
 
                                # its a pointer or missing statement, use it as is.
 
2701
                                # its a pointer or missing statement, use it as
 
2702
                                # is.
2242
2703
                                new_details.append(by_path[a_key][lookup_index])
2243
2704
                            else:
2244
2705
                                # we have the right key, make a pointer to it.
2245
2706
                                real_path = ('/'.join(a_key[0:2])).strip('/')
2246
 
                                new_details.append(('r', real_path, 0, False, ''))
 
2707
                                new_details.append(st('r', real_path, 0, False,
 
2708
                                                      ''))
2247
2709
                    new_details.append(self._inv_entry_to_details(entry))
2248
2710
                    new_details.extend(new_location_suffix)
2249
2711
                    by_path[new_entry_key] = new_details
2250
 
                    id_index[file_id].add(new_entry_key)
 
2712
                    self._add_to_id_index(id_index, new_entry_key)
2251
2713
        # --- end generation of full tree mappings
2252
2714
 
2253
2715
        # sort and output all the entries
2255
2717
        self._entries_to_current_state(new_entries)
2256
2718
        self._parents = [rev_id for rev_id, tree in trees]
2257
2719
        self._ghosts = list(ghosts)
2258
 
        self._header_state = DirState.IN_MEMORY_MODIFIED
2259
 
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
2720
        self._mark_modified(header_modified=True)
2260
2721
        self._id_index = id_index
2261
2722
 
2262
2723
    def _sort_entries(self, entry_list):
2266
2727
        try to keep everything in sorted blocks all the time, but sometimes
2267
2728
        it's easier to sort after the fact.
2268
2729
        """
2269
 
        def _key(entry):
 
2730
        # When sorting, we usually have 10x more entries than directories. (69k
 
2731
        # total entries, 4k directories). So cache the results of splitting.
 
2732
        # Saving time and objects. Also, use StaticTuple to avoid putting all
 
2733
        # of these object into python's garbage collector.
 
2734
        split_dirs = {}
 
2735
        def _key(entry, _split_dirs=split_dirs, _st=static_tuple.StaticTuple):
2270
2736
            # sort by: directory parts, file name, file id
2271
 
            return entry[0][0].split('/'), entry[0][1], entry[0][2]
 
2737
            dirpath, fname, file_id = entry[0]
 
2738
            try:
 
2739
                split = _split_dirs[dirpath]
 
2740
            except KeyError:
 
2741
                split = _st.from_sequence(dirpath.split('/'))
 
2742
                _split_dirs[dirpath] = split
 
2743
            return _st(split, fname, file_id)
2272
2744
        return sorted(entry_list, key=_key)
2273
2745
 
2274
2746
    def set_state_from_inventory(self, new_inv):
2275
 
        """Set new_inv as the current state. 
 
2747
        """Set new_inv as the current state.
2276
2748
 
2277
2749
        This API is called by tree transform, and will usually occur with
2278
2750
        existing parent trees.
2282
2754
        if 'evil' in debug.debug_flags:
2283
2755
            trace.mutter_callsite(1,
2284
2756
                "set_state_from_inventory called; please mutate the tree instead")
 
2757
        tracing = 'dirstate' in debug.debug_flags
 
2758
        if tracing:
 
2759
            trace.mutter("set_state_from_inventory trace:")
2285
2760
        self._read_dirblocks_if_needed()
2286
2761
        # sketch:
2287
 
        # Two iterators: current data and new data, both in dirblock order. 
 
2762
        # Two iterators: current data and new data, both in dirblock order.
2288
2763
        # We zip them together, which tells about entries that are new in the
2289
2764
        # inventory, or removed in the inventory, or present in both and
2290
 
        # possibly changed.  
 
2765
        # possibly changed.
2291
2766
        #
2292
2767
        # You might think we could just synthesize a new dirstate directly
2293
2768
        # since we're processing it in the right order.  However, we need to
2296
2771
        new_iterator = new_inv.iter_entries_by_dir()
2297
2772
        # we will be modifying the dirstate, so we need a stable iterator. In
2298
2773
        # future we might write one, for now we just clone the state into a
2299
 
        # list - which is a shallow copy.
 
2774
        # list using a copy so that we see every original item and don't have
 
2775
        # to adjust the position when items are inserted or deleted in the
 
2776
        # underlying dirstate.
2300
2777
        old_iterator = iter(list(self._iter_entries()))
2301
2778
        # both must have roots so this is safe:
2302
2779
        current_new = new_iterator.next()
2336
2813
            # we make both end conditions explicit
2337
2814
            if not current_old:
2338
2815
                # old is finished: insert current_new into the state.
 
2816
                if tracing:
 
2817
                    trace.mutter("Appending from new '%s'.",
 
2818
                        new_path_utf8.decode('utf8'))
2339
2819
                self.update_minimal(new_entry_key, current_new_minikind,
2340
2820
                    executable=current_new[1].executable,
2341
 
                    path_utf8=new_path_utf8, fingerprint=fingerprint)
 
2821
                    path_utf8=new_path_utf8, fingerprint=fingerprint,
 
2822
                    fullscan=True)
2342
2823
                current_new = advance(new_iterator)
2343
2824
            elif not current_new:
2344
2825
                # new is finished
 
2826
                if tracing:
 
2827
                    trace.mutter("Truncating from old '%s/%s'.",
 
2828
                        current_old[0][0].decode('utf8'),
 
2829
                        current_old[0][1].decode('utf8'))
2345
2830
                self._make_absent(current_old)
2346
2831
                current_old = advance(old_iterator)
2347
2832
            elif new_entry_key == current_old[0]:
2354
2839
                # kind has changed.
2355
2840
                if (current_old[1][0][3] != current_new[1].executable or
2356
2841
                    current_old[1][0][0] != current_new_minikind):
 
2842
                    if tracing:
 
2843
                        trace.mutter("Updating in-place change '%s'.",
 
2844
                            new_path_utf8.decode('utf8'))
2357
2845
                    self.update_minimal(current_old[0], current_new_minikind,
2358
2846
                        executable=current_new[1].executable,
2359
 
                        path_utf8=new_path_utf8, fingerprint=fingerprint)
 
2847
                        path_utf8=new_path_utf8, fingerprint=fingerprint,
 
2848
                        fullscan=True)
2360
2849
                # both sides are dealt with, move on
2361
2850
                current_old = advance(old_iterator)
2362
2851
                current_new = advance(new_iterator)
2365
2854
                      and new_entry_key[1:] < current_old[0][1:])):
2366
2855
                # new comes before:
2367
2856
                # add a entry for this and advance new
 
2857
                if tracing:
 
2858
                    trace.mutter("Inserting from new '%s'.",
 
2859
                        new_path_utf8.decode('utf8'))
2368
2860
                self.update_minimal(new_entry_key, current_new_minikind,
2369
2861
                    executable=current_new[1].executable,
2370
 
                    path_utf8=new_path_utf8, fingerprint=fingerprint)
 
2862
                    path_utf8=new_path_utf8, fingerprint=fingerprint,
 
2863
                    fullscan=True)
2371
2864
                current_new = advance(new_iterator)
2372
2865
            else:
2373
2866
                # we've advanced past the place where the old key would be,
2374
2867
                # without seeing it in the new list.  so it must be gone.
 
2868
                if tracing:
 
2869
                    trace.mutter("Deleting from old '%s/%s'.",
 
2870
                        current_old[0][0].decode('utf8'),
 
2871
                        current_old[0][1].decode('utf8'))
2375
2872
                self._make_absent(current_old)
2376
2873
                current_old = advance(old_iterator)
2377
 
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
2874
        self._mark_modified()
2378
2875
        self._id_index = None
2379
2876
        self._packed_stat_index = None
 
2877
        if tracing:
 
2878
            trace.mutter("set_state_from_inventory complete.")
 
2879
 
 
2880
    def set_state_from_scratch(self, working_inv, parent_trees, parent_ghosts):
 
2881
        """Wipe the currently stored state and set it to something new.
 
2882
 
 
2883
        This is a hard-reset for the data we are working with.
 
2884
        """
 
2885
        # Technically, we really want a write lock, but until we write, we
 
2886
        # don't really need it.
 
2887
        self._requires_lock()
 
2888
        # root dir and root dir contents with no children. We have to have a
 
2889
        # root for set_state_from_inventory to work correctly.
 
2890
        empty_root = (('', '', inventory.ROOT_ID),
 
2891
                      [('d', '', 0, False, DirState.NULLSTAT)])
 
2892
        empty_tree_dirblocks = [('', [empty_root]), ('', [])]
 
2893
        self._set_data([], empty_tree_dirblocks)
 
2894
        self.set_state_from_inventory(working_inv)
 
2895
        self.set_parent_trees(parent_trees, parent_ghosts)
2380
2896
 
2381
2897
    def _make_absent(self, current_old):
2382
2898
        """Mark current_old - an entry - as absent for tree 0.
2403
2919
            # Remove it, its meaningless.
2404
2920
            block = self._find_block(current_old[0])
2405
2921
            entry_index, present = self._find_entry_index(current_old[0], block[1])
2406
 
            assert present, 'could not find entry for %s' % (current_old,)
 
2922
            if not present:
 
2923
                raise AssertionError('could not find entry for %s' % (current_old,))
2407
2924
            block[1].pop(entry_index)
2408
2925
            # if we have an id_index in use, remove this key from it for this id.
2409
2926
            if self._id_index is not None:
2410
 
                self._id_index[current_old[0][2]].remove(current_old[0])
 
2927
                self._remove_from_id_index(self._id_index, current_old[0])
2411
2928
        # update all remaining keys for this id to record it as absent. The
2412
2929
        # existing details may either be the record we are marking as deleted
2413
2930
        # (if there were other trees with the id present at this path), or may
2415
2932
        for update_key in all_remaining_keys:
2416
2933
            update_block_index, present = \
2417
2934
                self._find_block_index_from_key(update_key)
2418
 
            assert present, 'could not find block for %s' % (update_key,)
 
2935
            if not present:
 
2936
                raise AssertionError('could not find block for %s' % (update_key,))
2419
2937
            update_entry_index, present = \
2420
2938
                self._find_entry_index(update_key, self._dirblocks[update_block_index][1])
2421
 
            assert present, 'could not find entry for %s' % (update_key,)
 
2939
            if not present:
 
2940
                raise AssertionError('could not find entry for %s' % (update_key,))
2422
2941
            update_tree_details = self._dirblocks[update_block_index][1][update_entry_index][1]
2423
2942
            # it must not be absent at the moment
2424
 
            assert update_tree_details[0][0] != 'a' # absent
 
2943
            if update_tree_details[0][0] == 'a': # absent
 
2944
                raise AssertionError('bad row %r' % (update_tree_details,))
2425
2945
            update_tree_details[0] = DirState.NULL_PARENT_DETAILS
2426
 
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
2946
        self._mark_modified()
2427
2947
        return last_reference
2428
2948
 
2429
2949
    def update_minimal(self, key, minikind, executable=False, fingerprint='',
2430
 
                       packed_stat=None, size=0, path_utf8=None):
 
2950
        packed_stat=None, size=0, path_utf8=None, fullscan=False):
2431
2951
        """Update an entry to the state in tree 0.
2432
2952
 
2433
2953
        This will either create a new entry at 'key' or update an existing one.
2438
2958
        :param minikind: The type for the entry ('f' == 'file', 'd' ==
2439
2959
                'directory'), etc.
2440
2960
        :param executable: Should the executable bit be set?
2441
 
        :param fingerprint: Simple fingerprint for new entry: sha1 for files, 
2442
 
            referenced revision id for subtrees, etc.
 
2961
        :param fingerprint: Simple fingerprint for new entry: canonical-form
 
2962
            sha1 for files, referenced revision id for subtrees, etc.
2443
2963
        :param packed_stat: Packed stat value for new entry.
2444
2964
        :param size: Size information for new entry
2445
2965
        :param path_utf8: key[0] + '/' + key[1], just passed in to avoid doing
2446
2966
                extra computation.
 
2967
        :param fullscan: If True then a complete scan of the dirstate is being
 
2968
            done and checking for duplicate rows should not be done. This
 
2969
            should only be set by set_state_from_inventory and similar methods.
2447
2970
 
2448
2971
        If packed_stat and fingerprint are not given, they're invalidated in
2449
2972
        the entry.
2458
2981
        new_details = (minikind, fingerprint, size, executable, packed_stat)
2459
2982
        id_index = self._get_id_index()
2460
2983
        if not present:
 
2984
            # New record. Check there isn't a entry at this path already.
 
2985
            if not fullscan:
 
2986
                low_index, _ = self._find_entry_index(key[0:2] + ('',), block)
 
2987
                while low_index < len(block):
 
2988
                    entry = block[low_index]
 
2989
                    if entry[0][0:2] == key[0:2]:
 
2990
                        if entry[1][0][0] not in 'ar':
 
2991
                            # This entry has the same path (but a different id) as
 
2992
                            # the new entry we're adding, and is present in ths
 
2993
                            # tree.
 
2994
                            self._raise_invalid(
 
2995
                                ("%s/%s" % key[0:2]).decode('utf8'), key[2],
 
2996
                                "Attempt to add item at path already occupied by "
 
2997
                                "id %r" % entry[0][2])
 
2998
                        low_index += 1
 
2999
                    else:
 
3000
                        break
2461
3001
            # new entry, synthesis cross reference here,
2462
 
            existing_keys = id_index.setdefault(key[2], set())
 
3002
            existing_keys = id_index.get(key[2], ())
2463
3003
            if not existing_keys:
2464
3004
                # not currently in the state, simplest case
2465
3005
                new_entry = key, [new_details] + self._empty_parent_info()
2468
3008
                # grab one of them and use it to generate parent
2469
3009
                # relocation/absent entries.
2470
3010
                new_entry = key, [new_details]
2471
 
                for other_key in existing_keys:
 
3011
                # existing_keys can be changed as we iterate.
 
3012
                for other_key in tuple(existing_keys):
2472
3013
                    # change the record at other to be a pointer to this new
2473
3014
                    # record. The loop looks similar to the change to
2474
3015
                    # relocations when updating an existing record but its not:
2475
3016
                    # the test for existing kinds is different: this can be
2476
3017
                    # factored out to a helper though.
2477
 
                    other_block_index, present = self._find_block_index_from_key(other_key)
2478
 
                    assert present, 'could not find block for %s' % (other_key,)
2479
 
                    other_entry_index, present = self._find_entry_index(other_key,
2480
 
                                            self._dirblocks[other_block_index][1])
2481
 
                    assert present, 'could not find entry for %s' % (other_key,)
2482
 
                    assert path_utf8 is not None
2483
 
                    self._dirblocks[other_block_index][1][other_entry_index][1][0] = \
2484
 
                        ('r', path_utf8, 0, False, '')
 
3018
                    other_block_index, present = self._find_block_index_from_key(
 
3019
                        other_key)
 
3020
                    if not present:
 
3021
                        raise AssertionError('could not find block for %s' % (
 
3022
                            other_key,))
 
3023
                    other_block = self._dirblocks[other_block_index][1]
 
3024
                    other_entry_index, present = self._find_entry_index(
 
3025
                        other_key, other_block)
 
3026
                    if not present:
 
3027
                        raise AssertionError(
 
3028
                            'update_minimal: could not find other entry for %s'
 
3029
                            % (other_key,))
 
3030
                    if path_utf8 is None:
 
3031
                        raise AssertionError('no path')
 
3032
                    # Turn this other location into a reference to the new
 
3033
                    # location. This also updates the aliased iterator
 
3034
                    # (current_old in set_state_from_inventory) so that the old
 
3035
                    # entry, if not already examined, is skipped over by that
 
3036
                    # loop.
 
3037
                    other_entry = other_block[other_entry_index]
 
3038
                    other_entry[1][0] = ('r', path_utf8, 0, False, '')
 
3039
                    if self._maybe_remove_row(other_block, other_entry_index,
 
3040
                                              id_index):
 
3041
                        # If the row holding this was removed, we need to
 
3042
                        # recompute where this entry goes
 
3043
                        entry_index, _ = self._find_entry_index(key, block)
2485
3044
 
 
3045
                # This loop:
 
3046
                # adds a tuple to the new details for each column
 
3047
                #  - either by copying an existing relocation pointer inside that column
 
3048
                #  - or by creating a new pointer to the right row inside that column
2486
3049
                num_present_parents = self._num_present_parents()
 
3050
                if num_present_parents:
 
3051
                    # TODO: This re-evaluates the existing_keys set, do we need
 
3052
                    #       to do that ourselves?
 
3053
                    other_key = list(existing_keys)[0]
2487
3054
                for lookup_index in xrange(1, num_present_parents + 1):
2488
3055
                    # grab any one entry, use it to find the right path.
2489
 
                    # TODO: optimise this to reduce memory use in highly 
 
3056
                    # TODO: optimise this to reduce memory use in highly
2490
3057
                    # fragmented situations by reusing the relocation
2491
3058
                    # records.
2492
3059
                    update_block_index, present = \
2493
3060
                        self._find_block_index_from_key(other_key)
2494
 
                    assert present, 'could not find block for %s' % (other_key,)
 
3061
                    if not present:
 
3062
                        raise AssertionError('could not find block for %s' % (other_key,))
2495
3063
                    update_entry_index, present = \
2496
3064
                        self._find_entry_index(other_key, self._dirblocks[update_block_index][1])
2497
 
                    assert present, 'could not find entry for %s' % (other_key,)
 
3065
                    if not present:
 
3066
                        raise AssertionError('update_minimal: could not find entry for %s' % (other_key,))
2498
3067
                    update_details = self._dirblocks[update_block_index][1][update_entry_index][1][lookup_index]
2499
3068
                    if update_details[0] in 'ar': # relocated, absent
2500
3069
                        # its a pointer or absent in lookup_index's tree, use
2505
3074
                        pointer_path = osutils.pathjoin(*other_key[0:2])
2506
3075
                        new_entry[1].append(('r', pointer_path, 0, False, ''))
2507
3076
            block.insert(entry_index, new_entry)
2508
 
            existing_keys.add(key)
 
3077
            self._add_to_id_index(id_index, key)
2509
3078
        else:
2510
 
            # Does the new state matter? 
 
3079
            # Does the new state matter?
2511
3080
            block[entry_index][1][0] = new_details
2512
3081
            # parents cannot be affected by what we do.
2513
 
            # other occurences of this id can be found 
 
3082
            # other occurences of this id can be found
2514
3083
            # from the id index.
2515
3084
            # ---
2516
3085
            # tree index consistency: All other paths for this id in this tree
2518
3087
            # we may have passed entries in the state with this file id already
2519
3088
            # that were absent - where parent entries are - and they need to be
2520
3089
            # converted to relocated.
2521
 
            assert path_utf8 is not None
2522
 
            for entry_key in id_index.setdefault(key[2], set()):
 
3090
            if path_utf8 is None:
 
3091
                raise AssertionError('no path')
 
3092
            existing_keys = id_index.get(key[2], ())
 
3093
            if key not in existing_keys:
 
3094
                raise AssertionError('We found the entry in the blocks, but'
 
3095
                    ' the key is not in the id_index.'
 
3096
                    ' key: %s, existing_keys: %s' % (key, existing_keys))
 
3097
            for entry_key in existing_keys:
2523
3098
                # TODO:PROFILING: It might be faster to just update
2524
3099
                # rather than checking if we need to, and then overwrite
2525
3100
                # the one we are located at.
2529
3104
                    # This is the vertical axis in the matrix, all pointing
2530
3105
                    # to the real path.
2531
3106
                    block_index, present = self._find_block_index_from_key(entry_key)
2532
 
                    assert present
 
3107
                    if not present:
 
3108
                        raise AssertionError('not present: %r', entry_key)
2533
3109
                    entry_index, present = self._find_entry_index(entry_key, self._dirblocks[block_index][1])
2534
 
                    assert present
 
3110
                    if not present:
 
3111
                        raise AssertionError('not present: %r', entry_key)
2535
3112
                    self._dirblocks[block_index][1][entry_index][1][0] = \
2536
3113
                        ('r', path_utf8, 0, False, '')
2537
3114
        # add a containing dirblock if needed.
2541
3118
            if not present:
2542
3119
                self._dirblocks.insert(block_index, (subdir_key[0], []))
2543
3120
 
2544
 
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
3121
        self._mark_modified()
 
3122
 
 
3123
    def _maybe_remove_row(self, block, index, id_index):
 
3124
        """Remove index if it is absent or relocated across the row.
 
3125
        
 
3126
        id_index is updated accordingly.
 
3127
        :return: True if we removed the row, False otherwise
 
3128
        """
 
3129
        present_in_row = False
 
3130
        entry = block[index]
 
3131
        for column in entry[1]:
 
3132
            if column[0] not in 'ar':
 
3133
                present_in_row = True
 
3134
                break
 
3135
        if not present_in_row:
 
3136
            block.pop(index)
 
3137
            self._remove_from_id_index(id_index, entry[0])
 
3138
            return True
 
3139
        return False
2545
3140
 
2546
3141
    def _validate(self):
2547
3142
        """Check that invariants on the dirblock are correct.
2548
3143
 
2549
 
        This can be useful in debugging; it shouldn't be necessary in 
 
3144
        This can be useful in debugging; it shouldn't be necessary in
2550
3145
        normal code.
2551
3146
 
2552
3147
        This must be called with a lock held.
2568
3163
            if not self._dirblocks[0][0] == '':
2569
3164
                raise AssertionError(
2570
3165
                    "dirblocks don't start with root block:\n" + \
2571
 
                    pformat(dirblocks))
 
3166
                    pformat(self._dirblocks))
2572
3167
        if len(self._dirblocks) > 1:
2573
3168
            if not self._dirblocks[1][0] == '':
2574
3169
                raise AssertionError(
2575
3170
                    "dirblocks missing root directory:\n" + \
2576
 
                    pformat(dirblocks))
 
3171
                    pformat(self._dirblocks))
2577
3172
        # the dirblocks are sorted by their path components, name, and dir id
2578
3173
        dir_names = [d[0].split('/')
2579
3174
                for d in self._dirblocks[1:]]
2621
3216
        # For each file id, for each tree: either
2622
3217
        # the file id is not present at all; all rows with that id in the
2623
3218
        # key have it marked as 'absent'
2624
 
        # OR the file id is present under exactly one name; any other entries 
 
3219
        # OR the file id is present under exactly one name; any other entries
2625
3220
        # that mention that id point to the correct name.
2626
3221
        #
2627
3222
        # We check this with a dict per tree pointing either to the present
2674
3269
                        # absent; should not occur anywhere else
2675
3270
                        this_tree_map[file_id] = None, this_path
2676
3271
                    elif minikind == 'r':
2677
 
                        # relocation, must occur at expected location 
 
3272
                        # relocation, must occur at expected location
2678
3273
                        this_tree_map[file_id] = tree_state[1], this_path
2679
3274
                    else:
2680
3275
                        this_tree_map[file_id] = this_path, this_path
2682
3277
            if absent_positions == tree_count:
2683
3278
                raise AssertionError(
2684
3279
                    "entry %r has no data for any tree." % (entry,))
 
3280
        if self._id_index is not None:
 
3281
            for file_id, entry_keys in self._id_index.iteritems():
 
3282
                for entry_key in entry_keys:
 
3283
                    if entry_key[2] != file_id:
 
3284
                        raise AssertionError(
 
3285
                            'file_id %r did not match entry key %s'
 
3286
                            % (file_id, entry_key))
 
3287
                if len(entry_keys) != len(set(entry_keys)):
 
3288
                    raise AssertionError(
 
3289
                        'id_index contained non-unique data for %s'
 
3290
                        % (entry_keys,))
2685
3291
 
2686
3292
    def _wipe_state(self):
2687
3293
        """Forget all state information about the dirstate."""
2743
3349
            raise errors.ObjectNotLocked(self)
2744
3350
 
2745
3351
 
 
3352
def py_update_entry(state, entry, abspath, stat_value,
 
3353
                 _stat_to_minikind=DirState._stat_to_minikind):
 
3354
    """Update the entry based on what is actually on disk.
 
3355
 
 
3356
    This function only calculates the sha if it needs to - if the entry is
 
3357
    uncachable, or clearly different to the first parent's entry, no sha
 
3358
    is calculated, and None is returned.
 
3359
 
 
3360
    :param state: The dirstate this entry is in.
 
3361
    :param entry: This is the dirblock entry for the file in question.
 
3362
    :param abspath: The path on disk for this file.
 
3363
    :param stat_value: The stat value done on the path.
 
3364
    :return: None, or The sha1 hexdigest of the file (40 bytes) or link
 
3365
        target of a symlink.
 
3366
    """
 
3367
    try:
 
3368
        minikind = _stat_to_minikind[stat_value.st_mode & 0170000]
 
3369
    except KeyError:
 
3370
        # Unhandled kind
 
3371
        return None
 
3372
    packed_stat = pack_stat(stat_value)
 
3373
    (saved_minikind, saved_link_or_sha1, saved_file_size,
 
3374
     saved_executable, saved_packed_stat) = entry[1][0]
 
3375
 
 
3376
    if minikind == 'd' and saved_minikind == 't':
 
3377
        minikind = 't'
 
3378
    if (minikind == saved_minikind
 
3379
        and packed_stat == saved_packed_stat):
 
3380
        # The stat hasn't changed since we saved, so we can re-use the
 
3381
        # saved sha hash.
 
3382
        if minikind == 'd':
 
3383
            return None
 
3384
 
 
3385
        # size should also be in packed_stat
 
3386
        if saved_file_size == stat_value.st_size:
 
3387
            return saved_link_or_sha1
 
3388
 
 
3389
    # If we have gotten this far, that means that we need to actually
 
3390
    # process this entry.
 
3391
    link_or_sha1 = None
 
3392
    worth_saving = True
 
3393
    if minikind == 'f':
 
3394
        executable = state._is_executable(stat_value.st_mode,
 
3395
                                         saved_executable)
 
3396
        if state._cutoff_time is None:
 
3397
            state._sha_cutoff_time()
 
3398
        if (stat_value.st_mtime < state._cutoff_time
 
3399
            and stat_value.st_ctime < state._cutoff_time
 
3400
            and len(entry[1]) > 1
 
3401
            and entry[1][1][0] != 'a'):
 
3402
            # Could check for size changes for further optimised
 
3403
            # avoidance of sha1's. However the most prominent case of
 
3404
            # over-shaing is during initial add, which this catches.
 
3405
            # Besides, if content filtering happens, size and sha
 
3406
            # are calculated at the same time, so checking just the size
 
3407
            # gains nothing w.r.t. performance.
 
3408
            link_or_sha1 = state._sha1_file(abspath)
 
3409
            entry[1][0] = ('f', link_or_sha1, stat_value.st_size,
 
3410
                           executable, packed_stat)
 
3411
        else:
 
3412
            entry[1][0] = ('f', '', stat_value.st_size,
 
3413
                           executable, DirState.NULLSTAT)
 
3414
            worth_saving = False
 
3415
    elif minikind == 'd':
 
3416
        link_or_sha1 = None
 
3417
        entry[1][0] = ('d', '', 0, False, packed_stat)
 
3418
        if saved_minikind != 'd':
 
3419
            # This changed from something into a directory. Make sure we
 
3420
            # have a directory block for it. This doesn't happen very
 
3421
            # often, so this doesn't have to be super fast.
 
3422
            block_index, entry_index, dir_present, file_present = \
 
3423
                state._get_block_entry_index(entry[0][0], entry[0][1], 0)
 
3424
            state._ensure_block(block_index, entry_index,
 
3425
                               osutils.pathjoin(entry[0][0], entry[0][1]))
 
3426
        else:
 
3427
            worth_saving = False
 
3428
    elif minikind == 'l':
 
3429
        if saved_minikind == 'l':
 
3430
            worth_saving = False
 
3431
        link_or_sha1 = state._read_link(abspath, saved_link_or_sha1)
 
3432
        if state._cutoff_time is None:
 
3433
            state._sha_cutoff_time()
 
3434
        if (stat_value.st_mtime < state._cutoff_time
 
3435
            and stat_value.st_ctime < state._cutoff_time):
 
3436
            entry[1][0] = ('l', link_or_sha1, stat_value.st_size,
 
3437
                           False, packed_stat)
 
3438
        else:
 
3439
            entry[1][0] = ('l', '', stat_value.st_size,
 
3440
                           False, DirState.NULLSTAT)
 
3441
    if worth_saving:
 
3442
        state._mark_modified([entry])
 
3443
    return link_or_sha1
 
3444
 
 
3445
 
 
3446
class ProcessEntryPython(object):
 
3447
 
 
3448
    __slots__ = ["old_dirname_to_file_id", "new_dirname_to_file_id",
 
3449
        "last_source_parent", "last_target_parent", "include_unchanged",
 
3450
        "partial", "use_filesystem_for_exec", "utf8_decode",
 
3451
        "searched_specific_files", "search_specific_files",
 
3452
        "searched_exact_paths", "search_specific_file_parents", "seen_ids",
 
3453
        "state", "source_index", "target_index", "want_unversioned", "tree"]
 
3454
 
 
3455
    def __init__(self, include_unchanged, use_filesystem_for_exec,
 
3456
        search_specific_files, state, source_index, target_index,
 
3457
        want_unversioned, tree):
 
3458
        self.old_dirname_to_file_id = {}
 
3459
        self.new_dirname_to_file_id = {}
 
3460
        # Are we doing a partial iter_changes?
 
3461
        self.partial = search_specific_files != set([''])
 
3462
        # Using a list so that we can access the values and change them in
 
3463
        # nested scope. Each one is [path, file_id, entry]
 
3464
        self.last_source_parent = [None, None]
 
3465
        self.last_target_parent = [None, None]
 
3466
        self.include_unchanged = include_unchanged
 
3467
        self.use_filesystem_for_exec = use_filesystem_for_exec
 
3468
        self.utf8_decode = cache_utf8._utf8_decode
 
3469
        # for all search_indexs in each path at or under each element of
 
3470
        # search_specific_files, if the detail is relocated: add the id, and
 
3471
        # add the relocated path as one to search if its not searched already.
 
3472
        # If the detail is not relocated, add the id.
 
3473
        self.searched_specific_files = set()
 
3474
        # When we search exact paths without expanding downwards, we record
 
3475
        # that here.
 
3476
        self.searched_exact_paths = set()
 
3477
        self.search_specific_files = search_specific_files
 
3478
        # The parents up to the root of the paths we are searching.
 
3479
        # After all normal paths are returned, these specific items are returned.
 
3480
        self.search_specific_file_parents = set()
 
3481
        # The ids we've sent out in the delta.
 
3482
        self.seen_ids = set()
 
3483
        self.state = state
 
3484
        self.source_index = source_index
 
3485
        self.target_index = target_index
 
3486
        if target_index != 0:
 
3487
            # A lot of code in here depends on target_index == 0
 
3488
            raise errors.BzrError('unsupported target index')
 
3489
        self.want_unversioned = want_unversioned
 
3490
        self.tree = tree
 
3491
 
 
3492
    def _process_entry(self, entry, path_info, pathjoin=osutils.pathjoin):
 
3493
        """Compare an entry and real disk to generate delta information.
 
3494
 
 
3495
        :param path_info: top_relpath, basename, kind, lstat, abspath for
 
3496
            the path of entry. If None, then the path is considered absent in 
 
3497
            the target (Perhaps we should pass in a concrete entry for this ?)
 
3498
            Basename is returned as a utf8 string because we expect this
 
3499
            tuple will be ignored, and don't want to take the time to
 
3500
            decode.
 
3501
        :return: (iter_changes_result, changed). If the entry has not been
 
3502
            handled then changed is None. Otherwise it is False if no content
 
3503
            or metadata changes have occurred, and True if any content or
 
3504
            metadata change has occurred. If self.include_unchanged is True then
 
3505
            if changed is not None, iter_changes_result will always be a result
 
3506
            tuple. Otherwise, iter_changes_result is None unless changed is
 
3507
            True.
 
3508
        """
 
3509
        if self.source_index is None:
 
3510
            source_details = DirState.NULL_PARENT_DETAILS
 
3511
        else:
 
3512
            source_details = entry[1][self.source_index]
 
3513
        target_details = entry[1][self.target_index]
 
3514
        target_minikind = target_details[0]
 
3515
        if path_info is not None and target_minikind in 'fdlt':
 
3516
            if not (self.target_index == 0):
 
3517
                raise AssertionError()
 
3518
            link_or_sha1 = update_entry(self.state, entry,
 
3519
                abspath=path_info[4], stat_value=path_info[3])
 
3520
            # The entry may have been modified by update_entry
 
3521
            target_details = entry[1][self.target_index]
 
3522
            target_minikind = target_details[0]
 
3523
        else:
 
3524
            link_or_sha1 = None
 
3525
        file_id = entry[0][2]
 
3526
        source_minikind = source_details[0]
 
3527
        if source_minikind in 'fdltr' and target_minikind in 'fdlt':
 
3528
            # claimed content in both: diff
 
3529
            #   r    | fdlt   |      | add source to search, add id path move and perform
 
3530
            #        |        |      | diff check on source-target
 
3531
            #   r    | fdlt   |  a   | dangling file that was present in the basis.
 
3532
            #        |        |      | ???
 
3533
            if source_minikind in 'r':
 
3534
                # add the source to the search path to find any children it
 
3535
                # has.  TODO ? : only add if it is a container ?
 
3536
                if not osutils.is_inside_any(self.searched_specific_files,
 
3537
                                             source_details[1]):
 
3538
                    self.search_specific_files.add(source_details[1])
 
3539
                # generate the old path; this is needed for stating later
 
3540
                # as well.
 
3541
                old_path = source_details[1]
 
3542
                old_dirname, old_basename = os.path.split(old_path)
 
3543
                path = pathjoin(entry[0][0], entry[0][1])
 
3544
                old_entry = self.state._get_entry(self.source_index,
 
3545
                                             path_utf8=old_path)
 
3546
                # update the source details variable to be the real
 
3547
                # location.
 
3548
                if old_entry == (None, None):
 
3549
                    raise errors.CorruptDirstate(self.state._filename,
 
3550
                        "entry '%s/%s' is considered renamed from %r"
 
3551
                        " but source does not exist\n"
 
3552
                        "entry: %s" % (entry[0][0], entry[0][1], old_path, entry))
 
3553
                source_details = old_entry[1][self.source_index]
 
3554
                source_minikind = source_details[0]
 
3555
            else:
 
3556
                old_dirname = entry[0][0]
 
3557
                old_basename = entry[0][1]
 
3558
                old_path = path = None
 
3559
            if path_info is None:
 
3560
                # the file is missing on disk, show as removed.
 
3561
                content_change = True
 
3562
                target_kind = None
 
3563
                target_exec = False
 
3564
            else:
 
3565
                # source and target are both versioned and disk file is present.
 
3566
                target_kind = path_info[2]
 
3567
                if target_kind == 'directory':
 
3568
                    if path is None:
 
3569
                        old_path = path = pathjoin(old_dirname, old_basename)
 
3570
                    self.new_dirname_to_file_id[path] = file_id
 
3571
                    if source_minikind != 'd':
 
3572
                        content_change = True
 
3573
                    else:
 
3574
                        # directories have no fingerprint
 
3575
                        content_change = False
 
3576
                    target_exec = False
 
3577
                elif target_kind == 'file':
 
3578
                    if source_minikind != 'f':
 
3579
                        content_change = True
 
3580
                    else:
 
3581
                        # Check the sha. We can't just rely on the size as
 
3582
                        # content filtering may mean differ sizes actually
 
3583
                        # map to the same content
 
3584
                        if link_or_sha1 is None:
 
3585
                            # Stat cache miss:
 
3586
                            statvalue, link_or_sha1 = \
 
3587
                                self.state._sha1_provider.stat_and_sha1(
 
3588
                                path_info[4])
 
3589
                            self.state._observed_sha1(entry, link_or_sha1,
 
3590
                                statvalue)
 
3591
                        content_change = (link_or_sha1 != source_details[1])
 
3592
                    # Target details is updated at update_entry time
 
3593
                    if self.use_filesystem_for_exec:
 
3594
                        # We don't need S_ISREG here, because we are sure
 
3595
                        # we are dealing with a file.
 
3596
                        target_exec = bool(stat.S_IEXEC & path_info[3].st_mode)
 
3597
                    else:
 
3598
                        target_exec = target_details[3]
 
3599
                elif target_kind == 'symlink':
 
3600
                    if source_minikind != 'l':
 
3601
                        content_change = True
 
3602
                    else:
 
3603
                        content_change = (link_or_sha1 != source_details[1])
 
3604
                    target_exec = False
 
3605
                elif target_kind == 'tree-reference':
 
3606
                    if source_minikind != 't':
 
3607
                        content_change = True
 
3608
                    else:
 
3609
                        content_change = False
 
3610
                    target_exec = False
 
3611
                else:
 
3612
                    if path is None:
 
3613
                        path = pathjoin(old_dirname, old_basename)
 
3614
                    raise errors.BadFileKindError(path, path_info[2])
 
3615
            if source_minikind == 'd':
 
3616
                if path is None:
 
3617
                    old_path = path = pathjoin(old_dirname, old_basename)
 
3618
                self.old_dirname_to_file_id[old_path] = file_id
 
3619
            # parent id is the entry for the path in the target tree
 
3620
            if old_basename and old_dirname == self.last_source_parent[0]:
 
3621
                source_parent_id = self.last_source_parent[1]
 
3622
            else:
 
3623
                try:
 
3624
                    source_parent_id = self.old_dirname_to_file_id[old_dirname]
 
3625
                except KeyError:
 
3626
                    source_parent_entry = self.state._get_entry(self.source_index,
 
3627
                                                           path_utf8=old_dirname)
 
3628
                    source_parent_id = source_parent_entry[0][2]
 
3629
                if source_parent_id == entry[0][2]:
 
3630
                    # This is the root, so the parent is None
 
3631
                    source_parent_id = None
 
3632
                else:
 
3633
                    self.last_source_parent[0] = old_dirname
 
3634
                    self.last_source_parent[1] = source_parent_id
 
3635
            new_dirname = entry[0][0]
 
3636
            if entry[0][1] and new_dirname == self.last_target_parent[0]:
 
3637
                target_parent_id = self.last_target_parent[1]
 
3638
            else:
 
3639
                try:
 
3640
                    target_parent_id = self.new_dirname_to_file_id[new_dirname]
 
3641
                except KeyError:
 
3642
                    # TODO: We don't always need to do the lookup, because the
 
3643
                    #       parent entry will be the same as the source entry.
 
3644
                    target_parent_entry = self.state._get_entry(self.target_index,
 
3645
                                                           path_utf8=new_dirname)
 
3646
                    if target_parent_entry == (None, None):
 
3647
                        raise AssertionError(
 
3648
                            "Could not find target parent in wt: %s\nparent of: %s"
 
3649
                            % (new_dirname, entry))
 
3650
                    target_parent_id = target_parent_entry[0][2]
 
3651
                if target_parent_id == entry[0][2]:
 
3652
                    # This is the root, so the parent is None
 
3653
                    target_parent_id = None
 
3654
                else:
 
3655
                    self.last_target_parent[0] = new_dirname
 
3656
                    self.last_target_parent[1] = target_parent_id
 
3657
 
 
3658
            source_exec = source_details[3]
 
3659
            changed = (content_change
 
3660
                or source_parent_id != target_parent_id
 
3661
                or old_basename != entry[0][1]
 
3662
                or source_exec != target_exec
 
3663
                )
 
3664
            if not changed and not self.include_unchanged:
 
3665
                return None, False
 
3666
            else:
 
3667
                if old_path is None:
 
3668
                    old_path = path = pathjoin(old_dirname, old_basename)
 
3669
                    old_path_u = self.utf8_decode(old_path)[0]
 
3670
                    path_u = old_path_u
 
3671
                else:
 
3672
                    old_path_u = self.utf8_decode(old_path)[0]
 
3673
                    if old_path == path:
 
3674
                        path_u = old_path_u
 
3675
                    else:
 
3676
                        path_u = self.utf8_decode(path)[0]
 
3677
                source_kind = DirState._minikind_to_kind[source_minikind]
 
3678
                return (entry[0][2],
 
3679
                       (old_path_u, path_u),
 
3680
                       content_change,
 
3681
                       (True, True),
 
3682
                       (source_parent_id, target_parent_id),
 
3683
                       (self.utf8_decode(old_basename)[0], self.utf8_decode(entry[0][1])[0]),
 
3684
                       (source_kind, target_kind),
 
3685
                       (source_exec, target_exec)), changed
 
3686
        elif source_minikind in 'a' and target_minikind in 'fdlt':
 
3687
            # looks like a new file
 
3688
            path = pathjoin(entry[0][0], entry[0][1])
 
3689
            # parent id is the entry for the path in the target tree
 
3690
            # TODO: these are the same for an entire directory: cache em.
 
3691
            parent_id = self.state._get_entry(self.target_index,
 
3692
                                         path_utf8=entry[0][0])[0][2]
 
3693
            if parent_id == entry[0][2]:
 
3694
                parent_id = None
 
3695
            if path_info is not None:
 
3696
                # Present on disk:
 
3697
                if self.use_filesystem_for_exec:
 
3698
                    # We need S_ISREG here, because we aren't sure if this
 
3699
                    # is a file or not.
 
3700
                    target_exec = bool(
 
3701
                        stat.S_ISREG(path_info[3].st_mode)
 
3702
                        and stat.S_IEXEC & path_info[3].st_mode)
 
3703
                else:
 
3704
                    target_exec = target_details[3]
 
3705
                return (entry[0][2],
 
3706
                       (None, self.utf8_decode(path)[0]),
 
3707
                       True,
 
3708
                       (False, True),
 
3709
                       (None, parent_id),
 
3710
                       (None, self.utf8_decode(entry[0][1])[0]),
 
3711
                       (None, path_info[2]),
 
3712
                       (None, target_exec)), True
 
3713
            else:
 
3714
                # Its a missing file, report it as such.
 
3715
                return (entry[0][2],
 
3716
                       (None, self.utf8_decode(path)[0]),
 
3717
                       False,
 
3718
                       (False, True),
 
3719
                       (None, parent_id),
 
3720
                       (None, self.utf8_decode(entry[0][1])[0]),
 
3721
                       (None, None),
 
3722
                       (None, False)), True
 
3723
        elif source_minikind in 'fdlt' and target_minikind in 'a':
 
3724
            # unversioned, possibly, or possibly not deleted: we dont care.
 
3725
            # if its still on disk, *and* theres no other entry at this
 
3726
            # path [we dont know this in this routine at the moment -
 
3727
            # perhaps we should change this - then it would be an unknown.
 
3728
            old_path = pathjoin(entry[0][0], entry[0][1])
 
3729
            # parent id is the entry for the path in the target tree
 
3730
            parent_id = self.state._get_entry(self.source_index, path_utf8=entry[0][0])[0][2]
 
3731
            if parent_id == entry[0][2]:
 
3732
                parent_id = None
 
3733
            return (entry[0][2],
 
3734
                   (self.utf8_decode(old_path)[0], None),
 
3735
                   True,
 
3736
                   (True, False),
 
3737
                   (parent_id, None),
 
3738
                   (self.utf8_decode(entry[0][1])[0], None),
 
3739
                   (DirState._minikind_to_kind[source_minikind], None),
 
3740
                   (source_details[3], None)), True
 
3741
        elif source_minikind in 'fdlt' and target_minikind in 'r':
 
3742
            # a rename; could be a true rename, or a rename inherited from
 
3743
            # a renamed parent. TODO: handle this efficiently. Its not
 
3744
            # common case to rename dirs though, so a correct but slow
 
3745
            # implementation will do.
 
3746
            if not osutils.is_inside_any(self.searched_specific_files, target_details[1]):
 
3747
                self.search_specific_files.add(target_details[1])
 
3748
        elif source_minikind in 'ra' and target_minikind in 'ra':
 
3749
            # neither of the selected trees contain this file,
 
3750
            # so skip over it. This is not currently directly tested, but
 
3751
            # is indirectly via test_too_much.TestCommands.test_conflicts.
 
3752
            pass
 
3753
        else:
 
3754
            raise AssertionError("don't know how to compare "
 
3755
                "source_minikind=%r, target_minikind=%r"
 
3756
                % (source_minikind, target_minikind))
 
3757
        return None, None
 
3758
 
 
3759
    def __iter__(self):
 
3760
        return self
 
3761
 
 
3762
    def _gather_result_for_consistency(self, result):
 
3763
        """Check a result we will yield to make sure we are consistent later.
 
3764
        
 
3765
        This gathers result's parents into a set to output later.
 
3766
 
 
3767
        :param result: A result tuple.
 
3768
        """
 
3769
        if not self.partial or not result[0]:
 
3770
            return
 
3771
        self.seen_ids.add(result[0])
 
3772
        new_path = result[1][1]
 
3773
        if new_path:
 
3774
            # Not the root and not a delete: queue up the parents of the path.
 
3775
            self.search_specific_file_parents.update(
 
3776
                osutils.parent_directories(new_path.encode('utf8')))
 
3777
            # Add the root directory which parent_directories does not
 
3778
            # provide.
 
3779
            self.search_specific_file_parents.add('')
 
3780
 
 
3781
    def iter_changes(self):
 
3782
        """Iterate over the changes."""
 
3783
        utf8_decode = cache_utf8._utf8_decode
 
3784
        _cmp_by_dirs = cmp_by_dirs
 
3785
        _process_entry = self._process_entry
 
3786
        search_specific_files = self.search_specific_files
 
3787
        searched_specific_files = self.searched_specific_files
 
3788
        splitpath = osutils.splitpath
 
3789
        # sketch:
 
3790
        # compare source_index and target_index at or under each element of search_specific_files.
 
3791
        # follow the following comparison table. Note that we only want to do diff operations when
 
3792
        # the target is fdl because thats when the walkdirs logic will have exposed the pathinfo
 
3793
        # for the target.
 
3794
        # cases:
 
3795
        #
 
3796
        # Source | Target | disk | action
 
3797
        #   r    | fdlt   |      | add source to search, add id path move and perform
 
3798
        #        |        |      | diff check on source-target
 
3799
        #   r    | fdlt   |  a   | dangling file that was present in the basis.
 
3800
        #        |        |      | ???
 
3801
        #   r    |  a     |      | add source to search
 
3802
        #   r    |  a     |  a   |
 
3803
        #   r    |  r     |      | this path is present in a non-examined tree, skip.
 
3804
        #   r    |  r     |  a   | this path is present in a non-examined tree, skip.
 
3805
        #   a    | fdlt   |      | add new id
 
3806
        #   a    | fdlt   |  a   | dangling locally added file, skip
 
3807
        #   a    |  a     |      | not present in either tree, skip
 
3808
        #   a    |  a     |  a   | not present in any tree, skip
 
3809
        #   a    |  r     |      | not present in either tree at this path, skip as it
 
3810
        #        |        |      | may not be selected by the users list of paths.
 
3811
        #   a    |  r     |  a   | not present in either tree at this path, skip as it
 
3812
        #        |        |      | may not be selected by the users list of paths.
 
3813
        #  fdlt  | fdlt   |      | content in both: diff them
 
3814
        #  fdlt  | fdlt   |  a   | deleted locally, but not unversioned - show as deleted ?
 
3815
        #  fdlt  |  a     |      | unversioned: output deleted id for now
 
3816
        #  fdlt  |  a     |  a   | unversioned and deleted: output deleted id
 
3817
        #  fdlt  |  r     |      | relocated in this tree, so add target to search.
 
3818
        #        |        |      | Dont diff, we will see an r,fd; pair when we reach
 
3819
        #        |        |      | this id at the other path.
 
3820
        #  fdlt  |  r     |  a   | relocated in this tree, so add target to search.
 
3821
        #        |        |      | Dont diff, we will see an r,fd; pair when we reach
 
3822
        #        |        |      | this id at the other path.
 
3823
 
 
3824
        # TODO: jam 20070516 - Avoid the _get_entry lookup overhead by
 
3825
        #       keeping a cache of directories that we have seen.
 
3826
 
 
3827
        while search_specific_files:
 
3828
            # TODO: the pending list should be lexically sorted?  the
 
3829
            # interface doesn't require it.
 
3830
            current_root = search_specific_files.pop()
 
3831
            current_root_unicode = current_root.decode('utf8')
 
3832
            searched_specific_files.add(current_root)
 
3833
            # process the entries for this containing directory: the rest will be
 
3834
            # found by their parents recursively.
 
3835
            root_entries = self.state._entries_for_path(current_root)
 
3836
            root_abspath = self.tree.abspath(current_root_unicode)
 
3837
            try:
 
3838
                root_stat = os.lstat(root_abspath)
 
3839
            except OSError, e:
 
3840
                if e.errno == errno.ENOENT:
 
3841
                    # the path does not exist: let _process_entry know that.
 
3842
                    root_dir_info = None
 
3843
                else:
 
3844
                    # some other random error: hand it up.
 
3845
                    raise
 
3846
            else:
 
3847
                root_dir_info = ('', current_root,
 
3848
                    osutils.file_kind_from_stat_mode(root_stat.st_mode), root_stat,
 
3849
                    root_abspath)
 
3850
                if root_dir_info[2] == 'directory':
 
3851
                    if self.tree._directory_is_tree_reference(
 
3852
                        current_root.decode('utf8')):
 
3853
                        root_dir_info = root_dir_info[:2] + \
 
3854
                            ('tree-reference',) + root_dir_info[3:]
 
3855
 
 
3856
            if not root_entries and not root_dir_info:
 
3857
                # this specified path is not present at all, skip it.
 
3858
                continue
 
3859
            path_handled = False
 
3860
            for entry in root_entries:
 
3861
                result, changed = _process_entry(entry, root_dir_info)
 
3862
                if changed is not None:
 
3863
                    path_handled = True
 
3864
                    if changed:
 
3865
                        self._gather_result_for_consistency(result)
 
3866
                    if changed or self.include_unchanged:
 
3867
                        yield result
 
3868
            if self.want_unversioned and not path_handled and root_dir_info:
 
3869
                new_executable = bool(
 
3870
                    stat.S_ISREG(root_dir_info[3].st_mode)
 
3871
                    and stat.S_IEXEC & root_dir_info[3].st_mode)
 
3872
                yield (None,
 
3873
                       (None, current_root_unicode),
 
3874
                       True,
 
3875
                       (False, False),
 
3876
                       (None, None),
 
3877
                       (None, splitpath(current_root_unicode)[-1]),
 
3878
                       (None, root_dir_info[2]),
 
3879
                       (None, new_executable)
 
3880
                      )
 
3881
            initial_key = (current_root, '', '')
 
3882
            block_index, _ = self.state._find_block_index_from_key(initial_key)
 
3883
            if block_index == 0:
 
3884
                # we have processed the total root already, but because the
 
3885
                # initial key matched it we should skip it here.
 
3886
                block_index +=1
 
3887
            if root_dir_info and root_dir_info[2] == 'tree-reference':
 
3888
                current_dir_info = None
 
3889
            else:
 
3890
                dir_iterator = osutils._walkdirs_utf8(root_abspath, prefix=current_root)
 
3891
                try:
 
3892
                    current_dir_info = dir_iterator.next()
 
3893
                except OSError, e:
 
3894
                    # on win32, python2.4 has e.errno == ERROR_DIRECTORY, but
 
3895
                    # python 2.5 has e.errno == EINVAL,
 
3896
                    #            and e.winerror == ERROR_DIRECTORY
 
3897
                    e_winerror = getattr(e, 'winerror', None)
 
3898
                    win_errors = (ERROR_DIRECTORY, ERROR_PATH_NOT_FOUND)
 
3899
                    # there may be directories in the inventory even though
 
3900
                    # this path is not a file on disk: so mark it as end of
 
3901
                    # iterator
 
3902
                    if e.errno in (errno.ENOENT, errno.ENOTDIR, errno.EINVAL):
 
3903
                        current_dir_info = None
 
3904
                    elif (sys.platform == 'win32'
 
3905
                          and (e.errno in win_errors
 
3906
                               or e_winerror in win_errors)):
 
3907
                        current_dir_info = None
 
3908
                    else:
 
3909
                        raise
 
3910
                else:
 
3911
                    if current_dir_info[0][0] == '':
 
3912
                        # remove .bzr from iteration
 
3913
                        bzr_index = bisect.bisect_left(current_dir_info[1], ('.bzr',))
 
3914
                        if current_dir_info[1][bzr_index][0] != '.bzr':
 
3915
                            raise AssertionError()
 
3916
                        del current_dir_info[1][bzr_index]
 
3917
            # walk until both the directory listing and the versioned metadata
 
3918
            # are exhausted.
 
3919
            if (block_index < len(self.state._dirblocks) and
 
3920
                osutils.is_inside(current_root, self.state._dirblocks[block_index][0])):
 
3921
                current_block = self.state._dirblocks[block_index]
 
3922
            else:
 
3923
                current_block = None
 
3924
            while (current_dir_info is not None or
 
3925
                   current_block is not None):
 
3926
                if (current_dir_info and current_block
 
3927
                    and current_dir_info[0][0] != current_block[0]):
 
3928
                    if _cmp_by_dirs(current_dir_info[0][0], current_block[0]) < 0:
 
3929
                        # filesystem data refers to paths not covered by the dirblock.
 
3930
                        # this has two possibilities:
 
3931
                        # A) it is versioned but empty, so there is no block for it
 
3932
                        # B) it is not versioned.
 
3933
 
 
3934
                        # if (A) then we need to recurse into it to check for
 
3935
                        # new unknown files or directories.
 
3936
                        # if (B) then we should ignore it, because we don't
 
3937
                        # recurse into unknown directories.
 
3938
                        path_index = 0
 
3939
                        while path_index < len(current_dir_info[1]):
 
3940
                                current_path_info = current_dir_info[1][path_index]
 
3941
                                if self.want_unversioned:
 
3942
                                    if current_path_info[2] == 'directory':
 
3943
                                        if self.tree._directory_is_tree_reference(
 
3944
                                            current_path_info[0].decode('utf8')):
 
3945
                                            current_path_info = current_path_info[:2] + \
 
3946
                                                ('tree-reference',) + current_path_info[3:]
 
3947
                                    new_executable = bool(
 
3948
                                        stat.S_ISREG(current_path_info[3].st_mode)
 
3949
                                        and stat.S_IEXEC & current_path_info[3].st_mode)
 
3950
                                    yield (None,
 
3951
                                        (None, utf8_decode(current_path_info[0])[0]),
 
3952
                                        True,
 
3953
                                        (False, False),
 
3954
                                        (None, None),
 
3955
                                        (None, utf8_decode(current_path_info[1])[0]),
 
3956
                                        (None, current_path_info[2]),
 
3957
                                        (None, new_executable))
 
3958
                                # dont descend into this unversioned path if it is
 
3959
                                # a dir
 
3960
                                if current_path_info[2] in ('directory',
 
3961
                                                            'tree-reference'):
 
3962
                                    del current_dir_info[1][path_index]
 
3963
                                    path_index -= 1
 
3964
                                path_index += 1
 
3965
 
 
3966
                        # This dir info has been handled, go to the next
 
3967
                        try:
 
3968
                            current_dir_info = dir_iterator.next()
 
3969
                        except StopIteration:
 
3970
                            current_dir_info = None
 
3971
                    else:
 
3972
                        # We have a dirblock entry for this location, but there
 
3973
                        # is no filesystem path for this. This is most likely
 
3974
                        # because a directory was removed from the disk.
 
3975
                        # We don't have to report the missing directory,
 
3976
                        # because that should have already been handled, but we
 
3977
                        # need to handle all of the files that are contained
 
3978
                        # within.
 
3979
                        for current_entry in current_block[1]:
 
3980
                            # entry referring to file not present on disk.
 
3981
                            # advance the entry only, after processing.
 
3982
                            result, changed = _process_entry(current_entry, None)
 
3983
                            if changed is not None:
 
3984
                                if changed:
 
3985
                                    self._gather_result_for_consistency(result)
 
3986
                                if changed or self.include_unchanged:
 
3987
                                    yield result
 
3988
                        block_index +=1
 
3989
                        if (block_index < len(self.state._dirblocks) and
 
3990
                            osutils.is_inside(current_root,
 
3991
                                              self.state._dirblocks[block_index][0])):
 
3992
                            current_block = self.state._dirblocks[block_index]
 
3993
                        else:
 
3994
                            current_block = None
 
3995
                    continue
 
3996
                entry_index = 0
 
3997
                if current_block and entry_index < len(current_block[1]):
 
3998
                    current_entry = current_block[1][entry_index]
 
3999
                else:
 
4000
                    current_entry = None
 
4001
                advance_entry = True
 
4002
                path_index = 0
 
4003
                if current_dir_info and path_index < len(current_dir_info[1]):
 
4004
                    current_path_info = current_dir_info[1][path_index]
 
4005
                    if current_path_info[2] == 'directory':
 
4006
                        if self.tree._directory_is_tree_reference(
 
4007
                            current_path_info[0].decode('utf8')):
 
4008
                            current_path_info = current_path_info[:2] + \
 
4009
                                ('tree-reference',) + current_path_info[3:]
 
4010
                else:
 
4011
                    current_path_info = None
 
4012
                advance_path = True
 
4013
                path_handled = False
 
4014
                while (current_entry is not None or
 
4015
                    current_path_info is not None):
 
4016
                    if current_entry is None:
 
4017
                        # the check for path_handled when the path is advanced
 
4018
                        # will yield this path if needed.
 
4019
                        pass
 
4020
                    elif current_path_info is None:
 
4021
                        # no path is fine: the per entry code will handle it.
 
4022
                        result, changed = _process_entry(current_entry, current_path_info)
 
4023
                        if changed is not None:
 
4024
                            if changed:
 
4025
                                self._gather_result_for_consistency(result)
 
4026
                            if changed or self.include_unchanged:
 
4027
                                yield result
 
4028
                    elif (current_entry[0][1] != current_path_info[1]
 
4029
                          or current_entry[1][self.target_index][0] in 'ar'):
 
4030
                        # The current path on disk doesn't match the dirblock
 
4031
                        # record. Either the dirblock is marked as absent, or
 
4032
                        # the file on disk is not present at all in the
 
4033
                        # dirblock. Either way, report about the dirblock
 
4034
                        # entry, and let other code handle the filesystem one.
 
4035
 
 
4036
                        # Compare the basename for these files to determine
 
4037
                        # which comes first
 
4038
                        if current_path_info[1] < current_entry[0][1]:
 
4039
                            # extra file on disk: pass for now, but only
 
4040
                            # increment the path, not the entry
 
4041
                            advance_entry = False
 
4042
                        else:
 
4043
                            # entry referring to file not present on disk.
 
4044
                            # advance the entry only, after processing.
 
4045
                            result, changed = _process_entry(current_entry, None)
 
4046
                            if changed is not None:
 
4047
                                if changed:
 
4048
                                    self._gather_result_for_consistency(result)
 
4049
                                if changed or self.include_unchanged:
 
4050
                                    yield result
 
4051
                            advance_path = False
 
4052
                    else:
 
4053
                        result, changed = _process_entry(current_entry, current_path_info)
 
4054
                        if changed is not None:
 
4055
                            path_handled = True
 
4056
                            if changed:
 
4057
                                self._gather_result_for_consistency(result)
 
4058
                            if changed or self.include_unchanged:
 
4059
                                yield result
 
4060
                    if advance_entry and current_entry is not None:
 
4061
                        entry_index += 1
 
4062
                        if entry_index < len(current_block[1]):
 
4063
                            current_entry = current_block[1][entry_index]
 
4064
                        else:
 
4065
                            current_entry = None
 
4066
                    else:
 
4067
                        advance_entry = True # reset the advance flaga
 
4068
                    if advance_path and current_path_info is not None:
 
4069
                        if not path_handled:
 
4070
                            # unversioned in all regards
 
4071
                            if self.want_unversioned:
 
4072
                                new_executable = bool(
 
4073
                                    stat.S_ISREG(current_path_info[3].st_mode)
 
4074
                                    and stat.S_IEXEC & current_path_info[3].st_mode)
 
4075
                                try:
 
4076
                                    relpath_unicode = utf8_decode(current_path_info[0])[0]
 
4077
                                except UnicodeDecodeError:
 
4078
                                    raise errors.BadFilenameEncoding(
 
4079
                                        current_path_info[0], osutils._fs_enc)
 
4080
                                yield (None,
 
4081
                                    (None, relpath_unicode),
 
4082
                                    True,
 
4083
                                    (False, False),
 
4084
                                    (None, None),
 
4085
                                    (None, utf8_decode(current_path_info[1])[0]),
 
4086
                                    (None, current_path_info[2]),
 
4087
                                    (None, new_executable))
 
4088
                            # dont descend into this unversioned path if it is
 
4089
                            # a dir
 
4090
                            if current_path_info[2] in ('directory'):
 
4091
                                del current_dir_info[1][path_index]
 
4092
                                path_index -= 1
 
4093
                        # dont descend the disk iterator into any tree
 
4094
                        # paths.
 
4095
                        if current_path_info[2] == 'tree-reference':
 
4096
                            del current_dir_info[1][path_index]
 
4097
                            path_index -= 1
 
4098
                        path_index += 1
 
4099
                        if path_index < len(current_dir_info[1]):
 
4100
                            current_path_info = current_dir_info[1][path_index]
 
4101
                            if current_path_info[2] == 'directory':
 
4102
                                if self.tree._directory_is_tree_reference(
 
4103
                                    current_path_info[0].decode('utf8')):
 
4104
                                    current_path_info = current_path_info[:2] + \
 
4105
                                        ('tree-reference',) + current_path_info[3:]
 
4106
                        else:
 
4107
                            current_path_info = None
 
4108
                        path_handled = False
 
4109
                    else:
 
4110
                        advance_path = True # reset the advance flagg.
 
4111
                if current_block is not None:
 
4112
                    block_index += 1
 
4113
                    if (block_index < len(self.state._dirblocks) and
 
4114
                        osutils.is_inside(current_root, self.state._dirblocks[block_index][0])):
 
4115
                        current_block = self.state._dirblocks[block_index]
 
4116
                    else:
 
4117
                        current_block = None
 
4118
                if current_dir_info is not None:
 
4119
                    try:
 
4120
                        current_dir_info = dir_iterator.next()
 
4121
                    except StopIteration:
 
4122
                        current_dir_info = None
 
4123
        for result in self._iter_specific_file_parents():
 
4124
            yield result
 
4125
 
 
4126
    def _iter_specific_file_parents(self):
 
4127
        """Iter over the specific file parents."""
 
4128
        while self.search_specific_file_parents:
 
4129
            # Process the parent directories for the paths we were iterating.
 
4130
            # Even in extremely large trees this should be modest, so currently
 
4131
            # no attempt is made to optimise.
 
4132
            path_utf8 = self.search_specific_file_parents.pop()
 
4133
            if osutils.is_inside_any(self.searched_specific_files, path_utf8):
 
4134
                # We've examined this path.
 
4135
                continue
 
4136
            if path_utf8 in self.searched_exact_paths:
 
4137
                # We've examined this path.
 
4138
                continue
 
4139
            path_entries = self.state._entries_for_path(path_utf8)
 
4140
            # We need either one or two entries. If the path in
 
4141
            # self.target_index has moved (so the entry in source_index is in
 
4142
            # 'ar') then we need to also look for the entry for this path in
 
4143
            # self.source_index, to output the appropriate delete-or-rename.
 
4144
            selected_entries = []
 
4145
            found_item = False
 
4146
            for candidate_entry in path_entries:
 
4147
                # Find entries present in target at this path:
 
4148
                if candidate_entry[1][self.target_index][0] not in 'ar':
 
4149
                    found_item = True
 
4150
                    selected_entries.append(candidate_entry)
 
4151
                # Find entries present in source at this path:
 
4152
                elif (self.source_index is not None and
 
4153
                    candidate_entry[1][self.source_index][0] not in 'ar'):
 
4154
                    found_item = True
 
4155
                    if candidate_entry[1][self.target_index][0] == 'a':
 
4156
                        # Deleted, emit it here.
 
4157
                        selected_entries.append(candidate_entry)
 
4158
                    else:
 
4159
                        # renamed, emit it when we process the directory it
 
4160
                        # ended up at.
 
4161
                        self.search_specific_file_parents.add(
 
4162
                            candidate_entry[1][self.target_index][1])
 
4163
            if not found_item:
 
4164
                raise AssertionError(
 
4165
                    "Missing entry for specific path parent %r, %r" % (
 
4166
                    path_utf8, path_entries))
 
4167
            path_info = self._path_info(path_utf8, path_utf8.decode('utf8'))
 
4168
            for entry in selected_entries:
 
4169
                if entry[0][2] in self.seen_ids:
 
4170
                    continue
 
4171
                result, changed = self._process_entry(entry, path_info)
 
4172
                if changed is None:
 
4173
                    raise AssertionError(
 
4174
                        "Got entry<->path mismatch for specific path "
 
4175
                        "%r entry %r path_info %r " % (
 
4176
                        path_utf8, entry, path_info))
 
4177
                # Only include changes - we're outside the users requested
 
4178
                # expansion.
 
4179
                if changed:
 
4180
                    self._gather_result_for_consistency(result)
 
4181
                    if (result[6][0] == 'directory' and
 
4182
                        result[6][1] != 'directory'):
 
4183
                        # This stopped being a directory, the old children have
 
4184
                        # to be included.
 
4185
                        if entry[1][self.source_index][0] == 'r':
 
4186
                            # renamed, take the source path
 
4187
                            entry_path_utf8 = entry[1][self.source_index][1]
 
4188
                        else:
 
4189
                            entry_path_utf8 = path_utf8
 
4190
                        initial_key = (entry_path_utf8, '', '')
 
4191
                        block_index, _ = self.state._find_block_index_from_key(
 
4192
                            initial_key)
 
4193
                        if block_index == 0:
 
4194
                            # The children of the root are in block index 1.
 
4195
                            block_index +=1
 
4196
                        current_block = None
 
4197
                        if block_index < len(self.state._dirblocks):
 
4198
                            current_block = self.state._dirblocks[block_index]
 
4199
                            if not osutils.is_inside(
 
4200
                                entry_path_utf8, current_block[0]):
 
4201
                                # No entries for this directory at all.
 
4202
                                current_block = None
 
4203
                        if current_block is not None:
 
4204
                            for entry in current_block[1]:
 
4205
                                if entry[1][self.source_index][0] in 'ar':
 
4206
                                    # Not in the source tree, so doesn't have to be
 
4207
                                    # included.
 
4208
                                    continue
 
4209
                                # Path of the entry itself.
 
4210
 
 
4211
                                self.search_specific_file_parents.add(
 
4212
                                    osutils.pathjoin(*entry[0][:2]))
 
4213
                if changed or self.include_unchanged:
 
4214
                    yield result
 
4215
            self.searched_exact_paths.add(path_utf8)
 
4216
 
 
4217
    def _path_info(self, utf8_path, unicode_path):
 
4218
        """Generate path_info for unicode_path.
 
4219
 
 
4220
        :return: None if unicode_path does not exist, or a path_info tuple.
 
4221
        """
 
4222
        abspath = self.tree.abspath(unicode_path)
 
4223
        try:
 
4224
            stat = os.lstat(abspath)
 
4225
        except OSError, e:
 
4226
            if e.errno == errno.ENOENT:
 
4227
                # the path does not exist.
 
4228
                return None
 
4229
            else:
 
4230
                raise
 
4231
        utf8_basename = utf8_path.rsplit('/', 1)[-1]
 
4232
        dir_info = (utf8_path, utf8_basename,
 
4233
            osutils.file_kind_from_stat_mode(stat.st_mode), stat,
 
4234
            abspath)
 
4235
        if dir_info[2] == 'directory':
 
4236
            if self.tree._directory_is_tree_reference(
 
4237
                unicode_path):
 
4238
                self.root_dir_info = self.root_dir_info[:2] + \
 
4239
                    ('tree-reference',) + self.root_dir_info[3:]
 
4240
        return dir_info
 
4241
 
 
4242
 
2746
4243
# Try to load the compiled form if possible
2747
4244
try:
2748
 
    from bzrlib._dirstate_helpers_c import (
2749
 
        _read_dirblocks_c as _read_dirblocks,
2750
 
        bisect_dirblock_c as bisect_dirblock,
2751
 
        _bisect_path_left_c as _bisect_path_left,
2752
 
        _bisect_path_right_c as _bisect_path_right,
2753
 
        cmp_by_dirs_c as cmp_by_dirs,
 
4245
    from bzrlib._dirstate_helpers_pyx import (
 
4246
        _read_dirblocks,
 
4247
        bisect_dirblock,
 
4248
        _bisect_path_left,
 
4249
        _bisect_path_right,
 
4250
        cmp_by_dirs,
 
4251
        pack_stat,
 
4252
        ProcessEntryC as _process_entry,
 
4253
        update_entry as update_entry,
2754
4254
        )
2755
 
except ImportError:
 
4255
except ImportError, e:
 
4256
    osutils.failed_to_load_extension(e)
2756
4257
    from bzrlib._dirstate_helpers_py import (
2757
 
        _read_dirblocks_py as _read_dirblocks,
2758
 
        bisect_dirblock_py as bisect_dirblock,
2759
 
        _bisect_path_left_py as _bisect_path_left,
2760
 
        _bisect_path_right_py as _bisect_path_right,
2761
 
        cmp_by_dirs_py as cmp_by_dirs,
 
4258
        _read_dirblocks,
 
4259
        bisect_dirblock,
 
4260
        _bisect_path_left,
 
4261
        _bisect_path_right,
 
4262
        cmp_by_dirs,
 
4263
        pack_stat,
2762
4264
        )
 
4265
    # FIXME: It would be nice to be able to track moved lines so that the
 
4266
    # corresponding python code can be moved to the _dirstate_helpers_py
 
4267
    # module. I don't want to break the history for this important piece of
 
4268
    # code so I left the code here -- vila 20090622
 
4269
    update_entry = py_update_entry
 
4270
    _process_entry = ProcessEntryPython