/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/dirstate.py

  • Committer: Robert Collins
  • Date: 2010-05-06 11:08:10 UTC
  • mto: This revision was merged to the branch mainline in revision 5223.
  • Revision ID: robertc@robertcollins.net-20100506110810-h3j07fh5gmw54s25
Cleaner matcher matching revised unlocking protocol.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006-2011 Canonical Ltd
 
1
# Copyright (C) 2006-2010 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
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
 
::
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
 
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
73
67
 
74
68
There may be multiple rows at the root, one per id present in the root, so the
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]: b''
82
 
    entries[0][1]: b''
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
 
   b'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
 
   b'a' is an absent entry: In that tree the id is not present at this path.
93
 
   b'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
 
   b'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
 
   b'l' is a symlink entry: As for directory, but a symlink. The fingerprint is
100
 
        the link target.
101
 
   b't' is a reference to a nested subtree; the fingerprint is the referenced
102
 
        revision.
 
69
in memory root row is now:
 
70
self._dirblocks[0] -> ('', [entry ...]),
 
71
and the entries in there are
 
72
entries[0][0]: ''
 
73
entries[0][1]: ''
 
74
entries[0][2]: file_id
 
75
entries[1][0]: The tree data for the current tree for this fileid at /
 
76
etc.
 
77
 
 
78
Kinds:
 
79
'r' is a relocated entry: This path is not present in this tree with this id,
 
80
    but the id can be found at another location. The fingerprint is used to
 
81
    point to the target location.
 
82
'a' is an absent entry: In that tree the id is not present at this path.
 
83
'd' is a directory entry: This path in this tree is a directory with the
 
84
    current file id. There is no fingerprint for directories.
 
85
'f' is a file entry: As for directory, but it's a file. The fingerprint is the
 
86
    sha1 value of the file's canonical form, i.e. after any read filters have
 
87
    been applied to the convenience form stored in the working tree.
 
88
'l' is a symlink entry: As for directory, but a symlink. The fingerprint is the
 
89
    link target.
 
90
't' is a reference to a nested subtree; the fingerprint is the referenced
 
91
    revision.
103
92
 
104
93
Ordering:
105
94
 
106
 
The entries on disk and in memory are ordered according to the following keys::
 
95
The entries on disk and in memory are ordered according to the following keys:
107
96
 
108
97
    directory, as a list of components
109
98
    filename
110
99
    file-id
111
100
 
112
101
--- Format 1 had the following different definition: ---
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
 
102
rows = dirname, NULL, basename, NULL, MINIKIND, NULL, fileid_utf8, NULL,
 
103
    WHOLE NUMBER (* size *), NULL, packed stat, NULL, sha1|symlink target,
 
104
    {PARENT ROW}
 
105
PARENT ROW = NULL, revision_utf8, NULL, MINIKIND, NULL, dirname, NULL,
 
106
    basename, NULL, WHOLE NUMBER (* size *), NULL, "y" | "n", NULL,
 
107
    SHA1
122
108
 
123
109
PARENT ROW's are emitted for every parent that is not in the ghosts details
124
110
line. That is, if the parents are foo, bar, baz, and the ghosts are bar, then
149
135
----
150
136
 
151
137
Design priorities:
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
 
138
 1) Fast end to end use for bzr's top 5 uses cases. (commmit/diff/status/merge/???)
 
139
 2) fall back current object model as needed.
 
140
 3) scale usably to the largest trees known today - say 50K entries. (mozilla
155
141
    is an example of this)
156
142
 
157
143
 
158
144
Locking:
159
 
 
160
145
 Eventually reuse dirstate objects across locks IFF the dirstate file has not
161
146
 been modified, but will require that we flush/ignore cached stat-hit data
162
147
 because we won't want to restat all files on disk just because a lock was
163
148
 acquired, yet we cannot trust the data after the previous lock was released.
164
149
 
165
 
Memory representation::
166
 
 
 
150
Memory representation:
167
151
 vector of all directories, and vector of the childen ?
168
152
   i.e.
169
153
     root_entrie = (direntry for root, [parent_direntries_for_root]),
183
167
    - What's the risk of error here? Once we have the base format being processed
184
168
      we should have a net win regardless of optimality. So we are going to
185
169
      go with what seems reasonable.
186
 
 
187
170
open questions:
188
171
 
189
172
Maybe we should do a test profile of the core structure - 10K simulated
218
201
 
219
202
"""
220
203
 
221
 
from __future__ import absolute_import
222
 
 
223
204
import bisect
 
205
import binascii
224
206
import errno
225
207
import operator
226
208
import os
227
209
from stat import S_IEXEC
228
210
import stat
 
211
import struct
229
212
import sys
230
213
import time
231
214
import zlib
232
215
 
233
 
from . import (
234
 
    inventory,
235
 
    )
236
 
from .. import (
 
216
from bzrlib import (
237
217
    cache_utf8,
238
 
    config,
239
218
    debug,
240
219
    errors,
 
220
    inventory,
241
221
    lock,
242
222
    osutils,
243
 
    static_tuple,
244
223
    trace,
245
 
    urlutils,
246
 
    )
247
 
from ..sixish import (
248
 
    range,
249
 
    text_type,
250
 
    viewitems,
251
 
    viewvalues,
252
224
    )
253
225
 
254
226
 
259
231
ERROR_DIRECTORY = 267
260
232
 
261
233
 
262
 
class DirstateCorrupt(errors.BzrError):
263
 
 
264
 
    _fmt = "The dirstate file (%(state)s) appears to be corrupt: %(msg)s"
265
 
 
266
 
    def __init__(self, state, msg):
267
 
        errors.BzrError.__init__(self)
268
 
        self.state = state
269
 
        self.msg = msg
 
234
if not getattr(struct, '_compile', None):
 
235
    # Cannot pre-compile the dirstate pack_stat
 
236
    def pack_stat(st, _encode=binascii.b2a_base64, _pack=struct.pack):
 
237
        """Convert stat values into a packed representation."""
 
238
        return _encode(_pack('>LLLLLL', st.st_size, int(st.st_mtime),
 
239
            int(st.st_ctime), st.st_dev, st.st_ino & 0xFFFFFFFF,
 
240
            st.st_mode))[:-1]
 
241
else:
 
242
    # compile the struct compiler we need, so as to only do it once
 
243
    from _struct import Struct
 
244
    _compiled_pack = Struct('>LLLLLL').pack
 
245
    def pack_stat(st, _encode=binascii.b2a_base64, _pack=_compiled_pack):
 
246
        """Convert stat values into a packed representation."""
 
247
        # jam 20060614 it isn't really worth removing more entries if we
 
248
        # are going to leave it in packed form.
 
249
        # With only st_mtime and st_mode filesize is 5.5M and read time is 275ms
 
250
        # With all entries, filesize is 5.9M and read time is maybe 280ms
 
251
        # well within the noise margin
 
252
 
 
253
        # base64 encoding always adds a final newline, so strip it off
 
254
        # The current version
 
255
        return _encode(_pack(st.st_size, int(st.st_mtime), int(st.st_ctime),
 
256
            st.st_dev, st.st_ino & 0xFFFFFFFF, st.st_mode))[:-1]
 
257
        # This is 0.060s / 1.520s faster by not encoding as much information
 
258
        # return _encode(_pack('>LL', int(st.st_mtime), st.st_mode))[:-1]
 
259
        # This is not strictly faster than _encode(_pack())[:-1]
 
260
        # return '%X.%X.%X.%X.%X.%X' % (
 
261
        #      st.st_size, int(st.st_mtime), int(st.st_ctime),
 
262
        #      st.st_dev, st.st_ino, st.st_mode)
 
263
        # Similar to the _encode(_pack('>LL'))
 
264
        # return '%X.%X' % (int(st.st_mtime), st.st_mode)
270
265
 
271
266
 
272
267
class SHA1Provider(object):
301
296
 
302
297
    def stat_and_sha1(self, abspath):
303
298
        """Return the stat and sha1 of a file given its absolute path."""
304
 
        with open(abspath, 'rb') as file_obj:
 
299
        file_obj = file(abspath, 'rb')
 
300
        try:
305
301
            statvalue = os.fstat(file_obj.fileno())
306
302
            sha1 = osutils.sha_file(file_obj)
 
303
        finally:
 
304
            file_obj.close()
307
305
        return statvalue, sha1
308
306
 
309
307
 
310
 
def is_inside(dir, fname):
311
 
    """True if fname is inside dir.
312
 
 
313
 
    The parameters should typically be passed to osutils.normpath first, so
314
 
    that . and .. and repeated slashes are eliminated, and the separators
315
 
    are canonical for the platform.
316
 
 
317
 
    The empty string as a dir name is taken as top-of-tree and matches
318
 
    everything.
319
 
 
320
 
    This is based on breezy.osutils.is_inside, which uses filesystem strings.
321
 
    """
322
 
    if dir == fname:
323
 
        return True
324
 
 
325
 
    if dir == b'':
326
 
        return True
327
 
 
328
 
    if not dir.endswith(b'/'):
329
 
        dir += b'/'
330
 
 
331
 
    return fname.startswith(dir)
332
 
 
333
 
 
334
 
def is_inside_any(dir_list, fname):
335
 
    """True if fname is inside any of given dirs."""
336
 
    for dirname in dir_list:
337
 
        if is_inside(dirname, fname):
338
 
            return True
339
 
    return False
340
 
 
341
 
 
342
308
class DirState(object):
343
309
    """Record directory and metadata state for fast access.
344
310
 
356
322
    """
357
323
 
358
324
    _kind_to_minikind = {
359
 
            'absent': b'a',
360
 
            'file': b'f',
361
 
            'directory': b'd',
362
 
            'relocated': b'r',
363
 
            'symlink': b'l',
364
 
            'tree-reference': b't',
 
325
            'absent': 'a',
 
326
            'file': 'f',
 
327
            'directory': 'd',
 
328
            'relocated': 'r',
 
329
            'symlink': 'l',
 
330
            'tree-reference': 't',
365
331
        }
366
332
    _minikind_to_kind = {
367
 
            b'a': 'absent',
368
 
            b'f': 'file',
369
 
            b'd': 'directory',
370
 
            b'l': 'symlink',
371
 
            b'r': 'relocated',
372
 
            b't': 'tree-reference',
 
333
            'a': 'absent',
 
334
            'f': 'file',
 
335
            'd': 'directory',
 
336
            'l':'symlink',
 
337
            'r': 'relocated',
 
338
            't': 'tree-reference',
373
339
        }
374
340
    _stat_to_minikind = {
375
 
        stat.S_IFDIR: b'd',
376
 
        stat.S_IFREG: b'f',
377
 
        stat.S_IFLNK: b'l',
 
341
        stat.S_IFDIR:'d',
 
342
        stat.S_IFREG:'f',
 
343
        stat.S_IFLNK:'l',
378
344
    }
379
 
    _to_yesno = {True: b'y', False: b'n'} # TODO profile the performance gain
 
345
    _to_yesno = {True:'y', False: 'n'} # TODO profile the performance gain
380
346
     # of using int conversion rather than a dict here. AND BLAME ANDREW IF
381
347
     # it is faster.
382
348
 
388
354
    NOT_IN_MEMORY = 0
389
355
    IN_MEMORY_UNMODIFIED = 1
390
356
    IN_MEMORY_MODIFIED = 2
391
 
    IN_MEMORY_HASH_MODIFIED = 3 # Only hash-cache updates
392
357
 
393
358
    # A pack_stat (the x's) that is just noise and will never match the output
394
359
    # of base64 encode.
395
 
    NULLSTAT = b'x' * 32
396
 
    NULL_PARENT_DETAILS = static_tuple.StaticTuple(b'a', b'', 0, False, b'')
397
 
 
398
 
    HEADER_FORMAT_2 = b'#bazaar dirstate flat format 2\n'
399
 
    HEADER_FORMAT_3 = b'#bazaar dirstate flat format 3\n'
400
 
 
401
 
    def __init__(self, path, sha1_provider, worth_saving_limit=0):
 
360
    NULLSTAT = 'x' * 32
 
361
    NULL_PARENT_DETAILS = ('a', '', 0, False, '')
 
362
 
 
363
    HEADER_FORMAT_2 = '#bazaar dirstate flat format 2\n'
 
364
    HEADER_FORMAT_3 = '#bazaar dirstate flat format 3\n'
 
365
 
 
366
    def __init__(self, path, sha1_provider):
402
367
        """Create a  DirState object.
403
368
 
404
369
        :param path: The path at which the dirstate file on disk should live.
405
370
        :param sha1_provider: an object meeting the SHA1Provider interface.
406
 
        :param worth_saving_limit: when the exact number of hash changed
407
 
            entries is known, only bother saving the dirstate if more than
408
 
            this count of entries have changed.
409
 
            -1 means never save hash changes, 0 means always save hash changes.
410
371
        """
411
372
        # _header_state and _dirblock_state represent the current state
412
373
        # of the dirstate metadata and the per-row data respectiely.
449
410
        # during commit.
450
411
        self._last_block_index = None
451
412
        self._last_entry_index = None
452
 
        # The set of known hash changes
453
 
        self._known_hash_changes = set()
454
 
        # How many hash changed entries can we have without saving
455
 
        self._worth_saving_limit = worth_saving_limit
456
 
        self._config_stack = config.LocationStack(urlutils.local_path_to_url(
457
 
            path))
458
413
 
459
414
    def __repr__(self):
460
415
        return "%s(%r)" % \
461
416
            (self.__class__.__name__, self._filename)
462
417
 
463
 
    def _mark_modified(self, hash_changed_entries=None, header_modified=False):
464
 
        """Mark this dirstate as modified.
465
 
 
466
 
        :param hash_changed_entries: if non-None, mark just these entries as
467
 
            having their hash modified.
468
 
        :param header_modified: mark the header modified as well, not just the
469
 
            dirblocks.
470
 
        """
471
 
        #trace.mutter_callsite(3, "modified hash entries: %s", hash_changed_entries)
472
 
        if hash_changed_entries:
473
 
            self._known_hash_changes.update([e[0] for e in hash_changed_entries])
474
 
            if self._dirblock_state in (DirState.NOT_IN_MEMORY,
475
 
                                        DirState.IN_MEMORY_UNMODIFIED):
476
 
                # If the dirstate is already marked a IN_MEMORY_MODIFIED, then
477
 
                # that takes precedence.
478
 
                self._dirblock_state = DirState.IN_MEMORY_HASH_MODIFIED
479
 
        else:
480
 
            # TODO: Since we now have a IN_MEMORY_HASH_MODIFIED state, we
481
 
            #       should fail noisily if someone tries to set
482
 
            #       IN_MEMORY_MODIFIED but we don't have a write-lock!
483
 
            # We don't know exactly what changed so disable smart saving
484
 
            self._dirblock_state = DirState.IN_MEMORY_MODIFIED
485
 
        if header_modified:
486
 
            self._header_state = DirState.IN_MEMORY_MODIFIED
487
 
 
488
 
    def _mark_unmodified(self):
489
 
        """Mark this dirstate as unmodified."""
490
 
        self._header_state = DirState.IN_MEMORY_UNMODIFIED
491
 
        self._dirblock_state = DirState.IN_MEMORY_UNMODIFIED
492
 
        self._known_hash_changes = set()
493
 
 
494
418
    def add(self, path, file_id, kind, stat, fingerprint):
495
419
        """Add a path to be tracked.
496
420
 
497
 
        :param path: The path within the dirstate - b'' is the root, 'foo' is the
 
421
        :param path: The path within the dirstate - '' is the root, 'foo' is the
498
422
            path foo within the root, 'foo/bar' is the path bar within foo
499
423
            within the root.
500
424
        :param file_id: The file id of the path being added.
505
429
            after any read filters have been applied),
506
430
            or the target of a symlink,
507
431
            or the referenced revision id for tree-references,
508
 
            or b'' for directories.
 
432
            or '' for directories.
509
433
        """
510
434
        # adding a file:
511
435
        # find the block its in.
533
457
        utf8path = (dirname + '/' + basename).strip('/').encode('utf8')
534
458
        dirname, basename = osutils.split(utf8path)
535
459
        # uses __class__ for speed; the check is needed for safety
536
 
        if file_id.__class__ is not bytes:
 
460
        if file_id.__class__ is not str:
537
461
            raise AssertionError(
538
462
                "must be a utf8 file_id not %s" % (type(file_id), ))
539
463
        # Make sure the file_id does not exist in this tree
540
464
        rename_from = None
541
465
        file_id_entry = self._get_entry(0, fileid_utf8=file_id, include_deleted=True)
542
466
        if file_id_entry != (None, None):
543
 
            if file_id_entry[1][0][0] == b'a':
 
467
            if file_id_entry[1][0][0] == 'a':
544
468
                if file_id_entry[0] != (dirname, basename, file_id):
545
469
                    # set the old name's current operation to rename
546
470
                    self.update_minimal(file_id_entry[0],
547
 
                        b'r',
548
 
                        path_utf8=b'',
549
 
                        packed_stat=b'',
 
471
                        'r',
 
472
                        path_utf8='',
 
473
                        packed_stat='',
550
474
                        fingerprint=utf8path
551
475
                    )
552
476
                    rename_from = file_id_entry[0][0:2]
555
479
                kind = DirState._minikind_to_kind[file_id_entry[1][0][0]]
556
480
                info = '%s:%s' % (kind, path)
557
481
                raise errors.DuplicateFileId(file_id, info)
558
 
        first_key = (dirname, basename, b'')
 
482
        first_key = (dirname, basename, '')
559
483
        block_index, present = self._find_block_index_from_key(first_key)
560
484
        if present:
561
485
            # check the path is not in the tree
563
487
            entry_index, _ = self._find_entry_index(first_key, block)
564
488
            while (entry_index < len(block) and
565
489
                block[entry_index][0][0:2] == first_key[0:2]):
566
 
                if block[entry_index][1][0][0] not in (b'a', b'r'):
 
490
                if block[entry_index][1][0][0] not in 'ar':
567
491
                    # this path is in the dirstate in the current tree.
568
 
                    raise Exception("adding already added path!")
 
492
                    raise Exception, "adding already added path!"
569
493
                entry_index += 1
570
494
        else:
571
495
            # The block where we want to put the file is not present. But it
589
513
        minikind = DirState._kind_to_minikind[kind]
590
514
        if rename_from is not None:
591
515
            if rename_from[0]:
592
 
                old_path_utf8 = b'%s/%s' % rename_from
 
516
                old_path_utf8 = '%s/%s' % rename_from
593
517
            else:
594
518
                old_path_utf8 = rename_from[1]
595
 
            parent_info[0] = (b'r', old_path_utf8, 0, False, b'')
 
519
            parent_info[0] = ('r', old_path_utf8, 0, False, '')
596
520
        if kind == 'file':
597
521
            entry_data = entry_key, [
598
522
                (minikind, fingerprint, size, False, packed_stat),
599
523
                ] + parent_info
600
524
        elif kind == 'directory':
601
525
            entry_data = entry_key, [
602
 
                (minikind, b'', 0, False, packed_stat),
 
526
                (minikind, '', 0, False, packed_stat),
603
527
                ] + parent_info
604
528
        elif kind == 'symlink':
605
529
            entry_data = entry_key, [
615
539
        if not present:
616
540
            block.insert(entry_index, entry_data)
617
541
        else:
618
 
            if block[entry_index][1][0][0] != b'a':
 
542
            if block[entry_index][1][0][0] != 'a':
619
543
                raise AssertionError(" %r(%r) already added" % (basename, file_id))
620
544
            block[entry_index][1][0] = entry_data[1][0]
621
545
 
622
546
        if kind == 'directory':
623
547
           # insert a new dirblock
624
548
           self._ensure_block(block_index, entry_index, utf8path)
625
 
        self._mark_modified()
 
549
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
626
550
        if self._id_index:
627
 
            self._add_to_id_index(self._id_index, entry_key)
 
551
            self._id_index.setdefault(entry_key[2], set()).add(entry_key)
628
552
 
629
553
    def _bisect(self, paths):
630
554
        """Bisect through the disk structure for specific rows.
651
575
        file_size = os.fstat(state_file.fileno()).st_size
652
576
        # We end up with 2 extra fields, we should have a trailing '\n' to
653
577
        # ensure that we read the whole record, and we should have a precursur
654
 
        # b'' which ensures that we start after the previous '\n'
 
578
        # '' which ensures that we start after the previous '\n'
655
579
        entry_field_count = self._fields_per_entry() + 1
656
580
 
657
581
        low = self._end_of_header
685
609
            if count > max_count:
686
610
                raise errors.BzrError('Too many seeks, most likely a bug.')
687
611
 
688
 
            mid = max(low, (low+high-page_size)//2)
 
612
            mid = max(low, (low+high-page_size)/2)
689
613
 
690
614
            state_file.seek(mid)
691
615
            # limit the read size, so we don't end up reading data that we have
694
618
            block = state_file.read(read_size)
695
619
 
696
620
            start = mid
697
 
            entries = block.split(b'\n')
 
621
            entries = block.split('\n')
698
622
 
699
623
            if len(entries) < 2:
700
624
                # We didn't find a '\n', so we cannot have found any records.
708
632
            # Check the first and last entries, in case they are partial, or if
709
633
            # we don't care about the rest of this page
710
634
            first_entry_num = 0
711
 
            first_fields = entries[0].split(b'\0')
 
635
            first_fields = entries[0].split('\0')
712
636
            if len(first_fields) < entry_field_count:
713
637
                # We didn't get the complete first entry
714
638
                # so move start, and grab the next, which
715
639
                # should be a full entry
716
640
                start += len(entries[0])+1
717
 
                first_fields = entries[1].split(b'\0')
 
641
                first_fields = entries[1].split('\0')
718
642
                first_entry_num = 1
719
643
 
720
644
            if len(first_fields) <= 2:
728
652
                # after this first record.
729
653
                after = start
730
654
                if first_fields[1]:
731
 
                    first_path = first_fields[1] + b'/' + first_fields[2]
 
655
                    first_path = first_fields[1] + '/' + first_fields[2]
732
656
                else:
733
657
                    first_path = first_fields[2]
734
658
                first_loc = _bisect_path_left(cur_files, first_path)
744
668
 
745
669
                # Parse the last entry
746
670
                last_entry_num = len(entries)-1
747
 
                last_fields = entries[last_entry_num].split(b'\0')
 
671
                last_fields = entries[last_entry_num].split('\0')
748
672
                if len(last_fields) < entry_field_count:
749
673
                    # The very last hunk was not complete,
750
674
                    # read the previous hunk
751
675
                    after = mid + len(block) - len(entries[-1])
752
676
                    last_entry_num -= 1
753
 
                    last_fields = entries[last_entry_num].split(b'\0')
 
677
                    last_fields = entries[last_entry_num].split('\0')
754
678
                else:
755
679
                    after = mid + len(block)
756
680
 
757
681
                if last_fields[1]:
758
 
                    last_path = last_fields[1] + b'/' + last_fields[2]
 
682
                    last_path = last_fields[1] + '/' + last_fields[2]
759
683
                else:
760
684
                    last_path = last_fields[2]
761
685
                last_loc = _bisect_path_right(post, last_path)
781
705
                    # careful if we should append rather than overwrite
782
706
                    if last_entry_num != first_entry_num:
783
707
                        paths.setdefault(last_path, []).append(last_fields)
784
 
                    for num in range(first_entry_num+1, last_entry_num):
 
708
                    for num in xrange(first_entry_num+1, last_entry_num):
785
709
                        # TODO: jam 20070223 We are already splitting here, so
786
710
                        #       shouldn't we just split the whole thing rather
787
711
                        #       than doing the split again in add_one_record?
788
 
                        fields = entries[num].split(b'\0')
 
712
                        fields = entries[num].split('\0')
789
713
                        if fields[1]:
790
 
                            path = fields[1] + b'/' + fields[2]
 
714
                            path = fields[1] + '/' + fields[2]
791
715
                        else:
792
716
                            path = fields[2]
793
717
                        paths.setdefault(path, []).append(fields)
843
767
        file_size = os.fstat(state_file.fileno()).st_size
844
768
        # We end up with 2 extra fields, we should have a trailing '\n' to
845
769
        # ensure that we read the whole record, and we should have a precursur
846
 
        # b'' which ensures that we start after the previous '\n'
 
770
        # '' which ensures that we start after the previous '\n'
847
771
        entry_field_count = self._fields_per_entry() + 1
848
772
 
849
773
        low = self._end_of_header
877
801
            if count > max_count:
878
802
                raise errors.BzrError('Too many seeks, most likely a bug.')
879
803
 
880
 
            mid = max(low, (low+high-page_size)//2)
 
804
            mid = max(low, (low+high-page_size)/2)
881
805
 
882
806
            state_file.seek(mid)
883
807
            # limit the read size, so we don't end up reading data that we have
886
810
            block = state_file.read(read_size)
887
811
 
888
812
            start = mid
889
 
            entries = block.split(b'\n')
 
813
            entries = block.split('\n')
890
814
 
891
815
            if len(entries) < 2:
892
816
                # We didn't find a '\n', so we cannot have found any records.
900
824
            # Check the first and last entries, in case they are partial, or if
901
825
            # we don't care about the rest of this page
902
826
            first_entry_num = 0
903
 
            first_fields = entries[0].split(b'\0')
 
827
            first_fields = entries[0].split('\0')
904
828
            if len(first_fields) < entry_field_count:
905
829
                # We didn't get the complete first entry
906
830
                # so move start, and grab the next, which
907
831
                # should be a full entry
908
832
                start += len(entries[0])+1
909
 
                first_fields = entries[1].split(b'\0')
 
833
                first_fields = entries[1].split('\0')
910
834
                first_entry_num = 1
911
835
 
912
836
            if len(first_fields) <= 1:
933
857
 
934
858
                # Parse the last entry
935
859
                last_entry_num = len(entries)-1
936
 
                last_fields = entries[last_entry_num].split(b'\0')
 
860
                last_fields = entries[last_entry_num].split('\0')
937
861
                if len(last_fields) < entry_field_count:
938
862
                    # The very last hunk was not complete,
939
863
                    # read the previous hunk
940
864
                    after = mid + len(block) - len(entries[-1])
941
865
                    last_entry_num -= 1
942
 
                    last_fields = entries[last_entry_num].split(b'\0')
 
866
                    last_fields = entries[last_entry_num].split('\0')
943
867
                else:
944
868
                    after = mid + len(block)
945
869
 
967
891
                    # careful if we should append rather than overwrite
968
892
                    if last_entry_num != first_entry_num:
969
893
                        paths.setdefault(last_dir, []).append(last_fields)
970
 
                    for num in range(first_entry_num+1, last_entry_num):
 
894
                    for num in xrange(first_entry_num+1, last_entry_num):
971
895
                        # TODO: jam 20070223 We are already splitting here, so
972
896
                        #       shouldn't we just split the whole thing rather
973
897
                        #       than doing the split again in add_one_record?
974
 
                        fields = entries[num].split(b'\0')
 
898
                        fields = entries[num].split('\0')
975
899
                        paths.setdefault(fields[1], []).append(fields)
976
900
 
977
901
                    for cur_dir in middle_files:
1002
926
        directories. (and renames?)
1003
927
 
1004
928
        :param paths: A sorted list of (dir, name) pairs
1005
 
             eg: [('', b'a'), ('', b'f'), ('a/b', b'c')]
 
929
             eg: [('', 'a'), ('', 'f'), ('a/b', 'c')]
1006
930
        :return: A dictionary mapping (dir, name, file_id) => [tree_info]
1007
931
        """
1008
932
        # Map from (dir, name, file_id) => [tree_info]
1019
943
            # Directories that need to be read
1020
944
            pending_dirs = set()
1021
945
            paths_to_search = set()
1022
 
            for entry_list in viewvalues(newly_found):
 
946
            for entry_list in newly_found.itervalues():
1023
947
                for dir_name_id, trees_info in entry_list:
1024
948
                    found[dir_name_id] = trees_info
1025
949
                    found_dir_names.add(dir_name_id[:2])
1026
950
                    is_dir = False
1027
951
                    for tree_info in trees_info:
1028
952
                        minikind = tree_info[0]
1029
 
                        if minikind == b'd':
 
953
                        if minikind == 'd':
1030
954
                            if is_dir:
1031
955
                                # We already processed this one as a directory,
1032
956
                                # we don't need to do the extra work again.
1036
960
                            is_dir = True
1037
961
                            if path not in processed_dirs:
1038
962
                                pending_dirs.add(path)
1039
 
                        elif minikind == b'r':
 
963
                        elif minikind == 'r':
1040
964
                            # Rename, we need to directly search the target
1041
965
                            # which is contained in the fingerprint column
1042
966
                            dir_name = osutils.split(tree_info[1])
1069
993
            return
1070
994
        # only require all dirblocks if we are doing a full-pass removal.
1071
995
        self._read_dirblocks_if_needed()
1072
 
        dead_patterns = {(b'a', b'r'), (b'a', b'a'), (b'r', b'r'), (b'r', b'a')}
 
996
        dead_patterns = set([('a', 'r'), ('a', 'a'), ('r', 'r'), ('r', 'a')])
1073
997
        def iter_entries_removable():
1074
998
            for block in self._dirblocks:
1075
999
                deleted_positions = []
1094
1018
 
1095
1019
        self._ghosts = []
1096
1020
        self._parents = [parents[0]]
1097
 
        self._mark_modified(header_modified=True)
 
1021
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
1022
        self._header_state = DirState.IN_MEMORY_MODIFIED
1098
1023
 
1099
1024
    def _empty_parent_info(self):
1100
1025
        return [DirState.NULL_PARENT_DETAILS] * (len(self._parents) -
1120
1045
        :param dirname: The utf8 dirname to ensure there is a block for.
1121
1046
        :return: The index for the block.
1122
1047
        """
1123
 
        if dirname == b'' and parent_row_index == 0 and parent_block_index == 0:
 
1048
        if dirname == '' and parent_row_index == 0 and parent_block_index == 0:
1124
1049
            # This is the signature of the root row, and the
1125
1050
            # contents-of-root row is always index 1
1126
1051
            return 1
1127
1052
        # the basename of the directory must be the end of its full name.
1128
1053
        if not (parent_block_index == -1 and
1129
 
            parent_block_index == -1 and dirname == b''):
 
1054
            parent_block_index == -1 and dirname == ''):
1130
1055
            if not dirname.endswith(
1131
1056
                    self._dirblocks[parent_block_index][1][parent_row_index][0][1]):
1132
1057
                raise AssertionError("bad dirname %r" % dirname)
1133
 
        block_index, present = self._find_block_index_from_key((dirname, b'', b''))
 
1058
        block_index, present = self._find_block_index_from_key((dirname, '', ''))
1134
1059
        if not present:
1135
1060
            ## In future, when doing partial parsing, this should load and
1136
1061
            # populate the entire block.
1147
1072
            to prevent unneeded overhead when callers have a sorted list already.
1148
1073
        :return: Nothing.
1149
1074
        """
1150
 
        if new_entries[0][0][0:2] != (b'', b''):
 
1075
        if new_entries[0][0][0:2] != ('', ''):
1151
1076
            raise AssertionError(
1152
1077
                "Missing root row %r" % (new_entries[0][0],))
1153
1078
        # The two blocks here are deliberate: the root block and the
1154
1079
        # contents-of-root block.
1155
 
        self._dirblocks = [(b'', []), (b'', [])]
 
1080
        self._dirblocks = [('', []), ('', [])]
1156
1081
        current_block = self._dirblocks[0][1]
1157
 
        current_dirname = b''
1158
 
        root_key = (b'', b'')
 
1082
        current_dirname = ''
 
1083
        root_key = ('', '')
1159
1084
        append_entry = current_block.append
1160
1085
        for entry in new_entries:
1161
1086
            if entry[0][0] != current_dirname:
1177
1102
        # The above loop leaves the "root block" entries mixed with the
1178
1103
        # "contents-of-root block". But we don't want an if check on
1179
1104
        # all entries, so instead we just fix it up here.
1180
 
        if self._dirblocks[1] != (b'', []):
 
1105
        if self._dirblocks[1] != ('', []):
1181
1106
            raise ValueError("bad dirblock start %r" % (self._dirblocks[1],))
1182
1107
        root_block = []
1183
1108
        contents_of_root_block = []
1186
1111
                root_block.append(entry)
1187
1112
            else:
1188
1113
                contents_of_root_block.append(entry)
1189
 
        self._dirblocks[0] = (b'', root_block)
1190
 
        self._dirblocks[1] = (b'', contents_of_root_block)
 
1114
        self._dirblocks[0] = ('', root_block)
 
1115
        self._dirblocks[1] = ('', contents_of_root_block)
1191
1116
 
1192
1117
    def _entries_for_path(self, path):
1193
1118
        """Return a list with all the entries that match path for all ids."""
1194
1119
        dirname, basename = os.path.split(path)
1195
 
        key = (dirname, basename, b'')
 
1120
        key = (dirname, basename, '')
1196
1121
        block_index, present = self._find_block_index_from_key(key)
1197
1122
        if not present:
1198
1123
            # the block which should contain path is absent.
1221
1146
            # minikind
1222
1147
            entire_entry[tree_offset + 0] = tree_data[0]
1223
1148
            # size
1224
 
            entire_entry[tree_offset + 2] = b'%d' % tree_data[2]
 
1149
            entire_entry[tree_offset + 2] = str(tree_data[2])
1225
1150
            # executable
1226
1151
            entire_entry[tree_offset + 3] = DirState._to_yesno[tree_data[3]]
1227
 
        return b'\0'.join(entire_entry)
 
1152
        return '\0'.join(entire_entry)
1228
1153
 
1229
1154
    def _fields_per_entry(self):
1230
1155
        """How many null separated fields should be in each entry row.
1231
1156
 
1232
 
        Each line now has an extra '\\n' field which is not used
 
1157
        Each line now has an extra '\n' field which is not used
1233
1158
        so we just skip over it
1234
 
 
1235
 
        entry size::
 
1159
        entry size:
1236
1160
            3 fields for the key
1237
1161
            + number of fields per tree_data (5) * tree count
1238
1162
            + newline
1267
1191
 
1268
1192
        :return: The block index, True if the block for the key is present.
1269
1193
        """
1270
 
        if key[0:2] == (b'', b''):
 
1194
        if key[0:2] == ('', ''):
1271
1195
            return 0, True
1272
1196
        try:
1273
1197
            if (self._last_block_index is not None and
1279
1203
                                      cache=self._split_path_cache)
1280
1204
        # _right returns one-past-where-key is so we have to subtract
1281
1205
        # one to use it. we use _right here because there are two
1282
 
        # b'' blocks - the root, and the contents of root
 
1206
        # '' blocks - the root, and the contents of root
1283
1207
        # we always have a minimum of 2 in self._dirblocks: root and
1284
 
        # root-contents, and for b'', we get 2 back, so this is
 
1208
        # root-contents, and for '', we get 2 back, so this is
1285
1209
        # simple and correct:
1286
1210
        present = (block_index < len(self._dirblocks) and
1287
1211
            self._dirblocks[block_index][0] == key[0])
1329
1253
        result = DirState.initialize(dir_state_filename,
1330
1254
            sha1_provider=sha1_provider)
1331
1255
        try:
1332
 
            with tree.lock_read():
1333
 
                try:
1334
 
                    parent_ids = tree.get_parent_ids()
1335
 
                    num_parents = len(parent_ids)
1336
 
                    parent_trees = []
1337
 
                    for parent_id in parent_ids:
1338
 
                        parent_tree = tree.branch.repository.revision_tree(parent_id)
1339
 
                        parent_trees.append((parent_id, parent_tree))
1340
 
                        parent_tree.lock_read()
1341
 
                    result.set_parent_trees(parent_trees, [])
1342
 
                    result.set_state_from_inventory(tree.root_inventory)
1343
 
                finally:
1344
 
                    for revid, parent_tree in parent_trees:
1345
 
                        parent_tree.unlock()
 
1256
            tree.lock_read()
 
1257
            try:
 
1258
                parent_ids = tree.get_parent_ids()
 
1259
                num_parents = len(parent_ids)
 
1260
                parent_trees = []
 
1261
                for parent_id in parent_ids:
 
1262
                    parent_tree = tree.branch.repository.revision_tree(parent_id)
 
1263
                    parent_trees.append((parent_id, parent_tree))
 
1264
                    parent_tree.lock_read()
 
1265
                result.set_parent_trees(parent_trees, [])
 
1266
                result.set_state_from_inventory(tree.inventory)
 
1267
            finally:
 
1268
                for revid, parent_tree in parent_trees:
 
1269
                    parent_tree.unlock()
 
1270
                tree.unlock()
1346
1271
        except:
1347
1272
            # The caller won't have a chance to unlock this, so make sure we
1348
1273
            # cleanup ourselves
1350
1275
            raise
1351
1276
        return result
1352
1277
 
1353
 
    def _check_delta_is_valid(self, delta):
1354
 
        delta = list(inventory._check_delta_unique_ids(
1355
 
                     inventory._check_delta_unique_old_paths(
1356
 
                     inventory._check_delta_unique_new_paths(
1357
 
                     inventory._check_delta_ids_match_entry(
1358
 
                     inventory._check_delta_ids_are_valid(
1359
 
                     inventory._check_delta_new_path_entry_both_or_None(delta)))))))
1360
 
        def delta_key(d):
1361
 
            (old_path, new_path, file_id, new_entry) = d
1362
 
            if old_path is None:
1363
 
                old_path = ''
1364
 
            if new_path is None:
1365
 
                new_path = ''
1366
 
            return (old_path, new_path, file_id, new_entry)
1367
 
        delta.sort(key=delta_key, reverse=True)
1368
 
        return delta
1369
 
 
1370
1278
    def update_by_delta(self, delta):
1371
1279
        """Apply an inventory delta to the dirstate for tree 0
1372
1280
 
1390
1298
        new_ids = set()
1391
1299
        # This loop transforms the delta to single atomic operations that can
1392
1300
        # be executed and validated.
1393
 
        delta = self._check_delta_is_valid(delta)
1394
 
        for old_path, new_path, file_id, inv_entry in delta:
1395
 
            if not isinstance(file_id, bytes):
1396
 
                raise AssertionError(
1397
 
                    "must be a utf8 file_id not %s" % (type(file_id), ))
 
1301
        for old_path, new_path, file_id, inv_entry in sorted(
 
1302
            inventory._check_delta_unique_old_paths(
 
1303
            inventory._check_delta_unique_new_paths(
 
1304
            inventory._check_delta_ids_match_entry(
 
1305
            inventory._check_delta_ids_are_valid(
 
1306
            inventory._check_delta_new_path_entry_both_or_None(delta))))),
 
1307
            reverse=True):
1398
1308
            if (file_id in insertions) or (file_id in removals):
1399
 
                self._raise_invalid(old_path or new_path, file_id,
 
1309
                raise errors.InconsistentDelta(old_path or new_path, file_id,
1400
1310
                    "repeated file_id")
1401
1311
            if old_path is not None:
1402
1312
                old_path = old_path.encode('utf-8')
1405
1315
                new_ids.add(file_id)
1406
1316
            if new_path is not None:
1407
1317
                if inv_entry is None:
1408
 
                    self._raise_invalid(new_path, file_id,
 
1318
                    raise errors.InconsistentDelta(new_path, file_id,
1409
1319
                        "new_path with no entry")
1410
1320
                new_path = new_path.encode('utf-8')
1411
1321
                dirname_utf8, basename = osutils.split(new_path)
1413
1323
                    parents.add((dirname_utf8, inv_entry.parent_id))
1414
1324
                key = (dirname_utf8, basename, file_id)
1415
1325
                minikind = DirState._kind_to_minikind[inv_entry.kind]
1416
 
                if minikind == b't':
1417
 
                    fingerprint = inv_entry.reference_revision or b''
 
1326
                if minikind == 't':
 
1327
                    fingerprint = inv_entry.reference_revision or ''
1418
1328
                else:
1419
 
                    fingerprint = b''
 
1329
                    fingerprint = ''
1420
1330
                insertions[file_id] = (key, minikind, inv_entry.executable,
1421
1331
                                       fingerprint, new_path)
1422
1332
            # Transform moves into delete+add pairs
1441
1351
                                               fingerprint, new_child_path)
1442
1352
        self._check_delta_ids_absent(new_ids, delta, 0)
1443
1353
        try:
1444
 
            self._apply_removals(viewitems(removals))
1445
 
            self._apply_insertions(viewvalues(insertions))
 
1354
            self._apply_removals(removals.iteritems())
 
1355
            self._apply_insertions(insertions.values())
1446
1356
            # Validate parents
1447
1357
            self._after_delta_check_parents(parents, 0)
1448
 
        except errors.BzrError as e:
 
1358
        except errors.BzrError, e:
1449
1359
            self._changes_aborted = True
1450
1360
            if 'integrity error' not in str(e):
1451
1361
                raise
1452
1362
            # _get_entry raises BzrError when a request is inconsistent; we
1453
1363
            # want such errors to be shown as InconsistentDelta - and that 
1454
1364
            # fits the behaviour we trigger.
1455
 
            raise errors.InconsistentDeltaDelta(delta,
1456
 
                "error from _get_entry. %s" % (e,))
 
1365
            raise errors.InconsistentDeltaDelta(delta, "error from _get_entry.")
1457
1366
 
1458
1367
    def _apply_removals(self, removals):
1459
1368
        for file_id, path in sorted(removals, reverse=True,
1464
1373
            try:
1465
1374
                entry = self._dirblocks[block_i][1][entry_i]
1466
1375
            except IndexError:
1467
 
                self._raise_invalid(path, file_id,
 
1376
                self._changes_aborted = True
 
1377
                raise errors.InconsistentDelta(path, file_id,
1468
1378
                    "Wrong path for old path.")
1469
 
            if not f_present or entry[1][0][0] in (b'a', b'r'):
1470
 
                self._raise_invalid(path, file_id,
 
1379
            if not f_present or entry[1][0][0] in 'ar':
 
1380
                self._changes_aborted = True
 
1381
                raise errors.InconsistentDelta(path, file_id,
1471
1382
                    "Wrong path for old path.")
1472
1383
            if file_id != entry[0][2]:
1473
 
                self._raise_invalid(path, file_id,
 
1384
                self._changes_aborted = True
 
1385
                raise errors.InconsistentDelta(path, file_id,
1474
1386
                    "Attempt to remove path has wrong id - found %r."
1475
1387
                    % entry[0][2])
1476
1388
            self._make_absent(entry)
1480
1392
            # is rare enough it shouldn't be an issue (famous last words?) RBC
1481
1393
            # 20080730.
1482
1394
            block_i, entry_i, d_present, f_present = \
1483
 
                self._get_block_entry_index(path, b'', 0)
 
1395
                self._get_block_entry_index(path, '', 0)
1484
1396
            if d_present:
1485
1397
                # The dir block is still present in the dirstate; this could
1486
1398
                # be due to it being in a parent tree, or a corrupt delta.
1487
1399
                for child_entry in self._dirblocks[block_i][1]:
1488
 
                    if child_entry[1][0][0] not in (b'r', b'a'):
1489
 
                        self._raise_invalid(path, entry[0][2],
 
1400
                    if child_entry[1][0][0] not in ('r', 'a'):
 
1401
                        self._changes_aborted = True
 
1402
                        raise errors.InconsistentDelta(path, entry[0][2],
1490
1403
                            "The file id was deleted but its children were "
1491
1404
                            "not deleted.")
1492
1405
 
1496
1409
                self.update_minimal(key, minikind, executable, fingerprint,
1497
1410
                                    path_utf8=path_utf8)
1498
1411
        except errors.NotVersionedError:
1499
 
            self._raise_invalid(path_utf8.decode('utf8'), key[2],
 
1412
            self._changes_aborted = True
 
1413
            raise errors.InconsistentDelta(path_utf8.decode('utf8'), key[2],
1500
1414
                "Missing parent")
1501
1415
 
1502
1416
    def update_basis_by_delta(self, delta, new_revid):
1510
1424
        Note that an exception during the operation of this method will leave
1511
1425
        the dirstate in a corrupt state where it should not be saved.
1512
1426
 
 
1427
        Finally, we expect all changes to be synchronising the basis tree with
 
1428
        the working tree.
 
1429
 
1513
1430
        :param new_revid: The new revision id for the trees parent.
1514
1431
        :param delta: An inventory delta (see apply_inventory_delta) describing
1515
1432
            the changes from the current left most parent revision to new_revid.
1527
1444
 
1528
1445
        self._parents[0] = new_revid
1529
1446
 
1530
 
        delta = self._check_delta_is_valid(delta)
 
1447
        delta = sorted(delta, reverse=True)
1531
1448
        adds = []
1532
1449
        changes = []
1533
1450
        deletes = []
1543
1460
        # expanding them recursively as needed.
1544
1461
        # At the same time, to reduce interface friction we convert the input
1545
1462
        # inventory entries to dirstate.
1546
 
        root_only = (b'', b'')
 
1463
        root_only = ('', '')
1547
1464
        # Accumulate parent references (path_utf8, id), to check for parentless
1548
1465
        # items or items placed under files/links/tree-references. We get
1549
1466
        # references from every item in the delta that is not a deletion and
1553
1470
        # ids.
1554
1471
        new_ids = set()
1555
1472
        for old_path, new_path, file_id, inv_entry in delta:
1556
 
            if file_id.__class__ is not bytes:
1557
 
                raise AssertionError(
1558
 
                    "must be a utf8 file_id not %s" % (type(file_id), ))
1559
1473
            if inv_entry is not None and file_id != inv_entry.file_id:
1560
 
                self._raise_invalid(new_path, file_id,
 
1474
                raise errors.InconsistentDelta(new_path, file_id,
1561
1475
                    "mismatched entry file_id %r" % inv_entry)
1562
 
            if new_path is None:
1563
 
                new_path_utf8 = None
1564
 
            else:
 
1476
            if new_path is not None:
1565
1477
                if inv_entry is None:
1566
 
                    self._raise_invalid(new_path, file_id,
 
1478
                    raise errors.InconsistentDelta(new_path, file_id,
1567
1479
                        "new_path with no entry")
1568
1480
                new_path_utf8 = encode(new_path)
1569
1481
                # note the parent for validation
1571
1483
                if basename_utf8:
1572
1484
                    parents.add((dirname_utf8, inv_entry.parent_id))
1573
1485
            if old_path is None:
1574
 
                old_path_utf8 = None
1575
 
            else:
1576
 
                old_path_utf8 = encode(old_path)
1577
 
            if old_path is None:
1578
 
                adds.append((None, new_path_utf8, file_id,
 
1486
                adds.append((None, encode(new_path), file_id,
1579
1487
                    inv_to_entry(inv_entry), True))
1580
1488
                new_ids.add(file_id)
1581
1489
            elif new_path is None:
1582
 
                deletes.append((old_path_utf8, None, file_id, None, True))
1583
 
            elif (old_path, new_path) == root_only:
1584
 
                # change things in-place
1585
 
                # Note: the case of a parent directory changing its file_id
1586
 
                #       tends to break optimizations here, because officially
1587
 
                #       the file has actually been moved, it just happens to
1588
 
                #       end up at the same path. If we can figure out how to
1589
 
                #       handle that case, we can avoid a lot of add+delete
1590
 
                #       pairs for objects that stay put.
1591
 
                # elif old_path == new_path:
1592
 
                changes.append((old_path_utf8, new_path_utf8, file_id,
1593
 
                                inv_to_entry(inv_entry)))
1594
 
            else:
 
1490
                deletes.append((encode(old_path), None, file_id, None, True))
 
1491
            elif (old_path, new_path) != root_only:
1595
1492
                # Renames:
1596
1493
                # Because renames must preserve their children we must have
1597
1494
                # processed all relocations and removes before hand. The sort
1600
1497
                # pair will result in the deleted item being reinserted, or
1601
1498
                # renamed items being reinserted twice - and possibly at the
1602
1499
                # wrong place. Splitting into a delete/add pair also simplifies
1603
 
                # the handling of entries with (b'f', ...), (b'r' ...) because
1604
 
                # the target of the b'r' is old_path here, and we add that to
 
1500
                # the handling of entries with ('f', ...), ('r' ...) because
 
1501
                # the target of the 'r' is old_path here, and we add that to
1605
1502
                # deletes, meaning that the add handler does not need to check
1606
 
                # for b'r' items on every pass.
 
1503
                # for 'r' items on every pass.
1607
1504
                self._update_basis_apply_deletes(deletes)
1608
1505
                deletes = []
1609
1506
                # Split into an add/delete pair recursively.
1610
 
                adds.append((old_path_utf8, new_path_utf8, file_id,
1611
 
                             inv_to_entry(inv_entry), False))
 
1507
                adds.append((None, new_path_utf8, file_id,
 
1508
                    inv_to_entry(inv_entry), False))
1612
1509
                # Expunge deletes that we've seen so that deleted/renamed
1613
1510
                # children of a rename directory are handled correctly.
1614
 
                new_deletes = reversed(list(
1615
 
                    self._iter_child_entries(1, old_path_utf8)))
 
1511
                new_deletes = reversed(list(self._iter_child_entries(1,
 
1512
                    encode(old_path))))
1616
1513
                # Remove the current contents of the tree at orig_path, and
1617
1514
                # reinsert at the correct new path.
1618
1515
                for entry in new_deletes:
1619
 
                    child_dirname, child_basename, child_file_id = entry[0]
1620
 
                    if child_dirname:
1621
 
                        source_path = child_dirname + b'/' + child_basename
 
1516
                    if entry[0][0]:
 
1517
                        source_path = entry[0][0] + '/' + entry[0][1]
1622
1518
                    else:
1623
 
                        source_path = child_basename
 
1519
                        source_path = entry[0][1]
1624
1520
                    if new_path_utf8:
1625
 
                        target_path = \
1626
 
                            new_path_utf8 + source_path[len(old_path_utf8):]
 
1521
                        target_path = new_path_utf8 + source_path[len(old_path):]
1627
1522
                    else:
1628
 
                        if old_path_utf8 == b'':
 
1523
                        if old_path == '':
1629
1524
                            raise AssertionError("cannot rename directory to"
1630
 
                                                 " itself")
1631
 
                        target_path = source_path[len(old_path_utf8) + 1:]
 
1525
                                " itself")
 
1526
                        target_path = source_path[len(old_path) + 1:]
1632
1527
                    adds.append((None, target_path, entry[0][2], entry[1][1], False))
1633
1528
                    deletes.append(
1634
1529
                        (source_path, target_path, entry[0][2], None, False))
1635
1530
                deletes.append(
1636
 
                    (old_path_utf8, new_path_utf8, file_id, None, False))
1637
 
 
 
1531
                    (encode(old_path), new_path, file_id, None, False))
 
1532
            else:
 
1533
                # changes to just the root should not require remove/insertion
 
1534
                # of everything.
 
1535
                changes.append((encode(old_path), encode(new_path), file_id,
 
1536
                    inv_to_entry(inv_entry)))
1638
1537
        self._check_delta_ids_absent(new_ids, delta, 1)
1639
1538
        try:
1640
1539
            # Finish expunging deletes/first half of renames.
1645
1544
            self._update_basis_apply_changes(changes)
1646
1545
            # Validate parents
1647
1546
            self._after_delta_check_parents(parents, 1)
1648
 
        except errors.BzrError as e:
 
1547
        except errors.BzrError, e:
1649
1548
            self._changes_aborted = True
1650
1549
            if 'integrity error' not in str(e):
1651
1550
                raise
1652
1551
            # _get_entry raises BzrError when a request is inconsistent; we
1653
 
            # want such errors to be shown as InconsistentDelta - and that
1654
 
            # fits the behaviour we trigger.
1655
 
            raise errors.InconsistentDeltaDelta(delta,
1656
 
                "error from _get_entry. %s" % (e,))
 
1552
            # want such errors to be shown as InconsistentDelta - and that 
 
1553
            # fits the behaviour we trigger. Partof this is driven by dirstate
 
1554
            # only supporting deltas that turn the basis into a closer fit to
 
1555
            # the active tree.
 
1556
            raise errors.InconsistentDeltaDelta(delta, "error from _get_entry.")
1657
1557
 
1658
 
        self._mark_modified(header_modified=True)
 
1558
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
1559
        self._header_state = DirState.IN_MEMORY_MODIFIED
1659
1560
        self._id_index = None
1660
1561
        return
1661
1562
 
1665
1566
            return
1666
1567
        id_index = self._get_id_index()
1667
1568
        for file_id in new_ids:
1668
 
            for key in id_index.get(file_id, ()):
 
1569
            for key in id_index.get(file_id, []):
1669
1570
                block_i, entry_i, d_present, f_present = \
1670
1571
                    self._get_block_entry_index(key[0], key[1], tree_index)
1671
1572
                if not f_present:
1675
1576
                if entry[0][2] != file_id:
1676
1577
                    # Different file_id, so not what we want.
1677
1578
                    continue
1678
 
                self._raise_invalid((b"%s/%s" % key[0:2]).decode('utf8'), file_id,
 
1579
                # NB: No changes made before this helper is called, so no need
 
1580
                # to set the _changes_aborted flag.
 
1581
                raise errors.InconsistentDelta(
 
1582
                    ("%s/%s" % key[0:2]).decode('utf8'), file_id,
1679
1583
                    "This file_id is new in the delta but already present in "
1680
1584
                    "the target")
1681
1585
 
1682
 
    def _raise_invalid(self, path, file_id, reason):
1683
 
        self._changes_aborted = True
1684
 
        raise errors.InconsistentDelta(path, file_id, reason)
1685
 
 
1686
1586
    def _update_basis_apply_adds(self, adds):
1687
1587
        """Apply a sequence of adds to tree 1 during update_basis_by_delta.
1688
1588
 
1696
1596
        """
1697
1597
        # Adds are accumulated partly from renames, so can be in any input
1698
1598
        # order - sort it.
1699
 
        # TODO: we may want to sort in dirblocks order. That way each entry
1700
 
        #       will end up in the same directory, allowing the _get_entry
1701
 
        #       fast-path for looking up 2 items in the same dir work.
1702
 
        adds.sort(key=lambda x: x[1])
 
1599
        adds.sort()
1703
1600
        # adds is now in lexographic order, which places all parents before
1704
1601
        # their children, so we can process it linearly.
1705
 
        st = static_tuple.StaticTuple
 
1602
        absent = 'ar'
1706
1603
        for old_path, new_path, file_id, new_details, real_add in adds:
1707
 
            dirname, basename = osutils.split(new_path)
1708
 
            entry_key = st(dirname, basename, file_id)
1709
 
            block_index, present = self._find_block_index_from_key(entry_key)
1710
 
            if not present:
1711
 
                # The block where we want to put the file is not present.
1712
 
                # However, it might have just been an empty directory. Look for
1713
 
                # the parent in the basis-so-far before throwing an error.
1714
 
                parent_dir, parent_base = osutils.split(dirname)
1715
 
                parent_block_idx, parent_entry_idx, _, parent_present = \
1716
 
                    self._get_block_entry_index(parent_dir, parent_base, 1)
1717
 
                if not parent_present:
1718
 
                    self._raise_invalid(new_path, file_id,
1719
 
                        "Unable to find block for this record."
1720
 
                        " Was the parent added?")
1721
 
                self._ensure_block(parent_block_idx, parent_entry_idx, dirname)
1722
 
 
1723
 
            block = self._dirblocks[block_index][1]
1724
 
            entry_index, present = self._find_entry_index(entry_key, block)
1725
 
            if real_add:
1726
 
                if old_path is not None:
1727
 
                    self._raise_invalid(new_path, file_id,
1728
 
                        'considered a real add but still had old_path at %s'
1729
 
                        % (old_path,))
1730
 
            if present:
1731
 
                entry = block[entry_index]
1732
 
                basis_kind = entry[1][1][0]
1733
 
                if basis_kind == b'a':
1734
 
                    entry[1][1] = new_details
1735
 
                elif basis_kind == b'r':
1736
 
                    raise NotImplementedError()
1737
 
                else:
1738
 
                    self._raise_invalid(new_path, file_id,
1739
 
                        "An entry was marked as a new add"
1740
 
                        " but the basis target already existed")
1741
 
            else:
1742
 
                # The exact key was not found in the block. However, we need to
1743
 
                # check if there is a key next to us that would have matched.
1744
 
                # We only need to check 2 locations, because there are only 2
1745
 
                # trees present.
1746
 
                for maybe_index in range(entry_index-1, entry_index+1):
1747
 
                    if maybe_index < 0 or maybe_index >= len(block):
1748
 
                        continue
1749
 
                    maybe_entry = block[maybe_index]
1750
 
                    if maybe_entry[0][:2] != (dirname, basename):
1751
 
                        # Just a random neighbor
1752
 
                        continue
1753
 
                    if maybe_entry[0][2] == file_id:
1754
 
                        raise AssertionError(
1755
 
                            '_find_entry_index didnt find a key match'
1756
 
                            ' but walking the data did, for %s'
1757
 
                            % (entry_key,))
1758
 
                    basis_kind = maybe_entry[1][1][0]
1759
 
                    if basis_kind not in (b'a', b'r'):
1760
 
                        self._raise_invalid(new_path, file_id,
1761
 
                            "we have an add record for path, but the path"
1762
 
                            " is already present with another file_id %s"
1763
 
                            % (maybe_entry[0][2],))
1764
 
 
1765
 
                entry = (entry_key, [DirState.NULL_PARENT_DETAILS,
1766
 
                                     new_details])
1767
 
                block.insert(entry_index, entry)
1768
 
 
1769
 
            active_kind = entry[1][0][0]
1770
 
            if active_kind == b'a':
1771
 
                # The active record shows up as absent, this could be genuine,
1772
 
                # or it could be present at some other location. We need to
1773
 
                # verify.
1774
 
                id_index = self._get_id_index()
1775
 
                # The id_index may not be perfectly accurate for tree1, because
1776
 
                # we haven't been keeping it updated. However, it should be
1777
 
                # fine for tree0, and that gives us enough info for what we
1778
 
                # need
1779
 
                keys = id_index.get(file_id, ())
1780
 
                for key in keys:
1781
 
                    block_i, entry_i, d_present, f_present = \
1782
 
                        self._get_block_entry_index(key[0], key[1], 0)
1783
 
                    if not f_present:
1784
 
                        continue
1785
 
                    active_entry = self._dirblocks[block_i][1][entry_i]
1786
 
                    if (active_entry[0][2] != file_id):
1787
 
                        # Some other file is at this path, we don't need to
1788
 
                        # link it.
1789
 
                        continue
1790
 
                    real_active_kind = active_entry[1][0][0]
1791
 
                    if real_active_kind in (b'a', b'r'):
1792
 
                        # We found a record, which was not *this* record,
1793
 
                        # which matches the file_id, but is not actually
1794
 
                        # present. Something seems *really* wrong.
1795
 
                        self._raise_invalid(new_path, file_id,
1796
 
                            "We found a tree0 entry that doesnt make sense")
1797
 
                    # Now, we've found a tree0 entry which matches the file_id
1798
 
                    # but is at a different location. So update them to be
1799
 
                    # rename records.
1800
 
                    active_dir, active_name = active_entry[0][:2]
1801
 
                    if active_dir:
1802
 
                        active_path = active_dir + b'/' + active_name
1803
 
                    else:
1804
 
                        active_path = active_name
1805
 
                    active_entry[1][1] = st(b'r', new_path, 0, False, b'')
1806
 
                    entry[1][0] = st(b'r', active_path, 0, False, b'')
1807
 
            elif active_kind == b'r':
1808
 
                raise NotImplementedError()
1809
 
 
1810
 
            new_kind = new_details[0]
1811
 
            if new_kind == b'd':
1812
 
                self._ensure_block(block_index, entry_index, new_path)
 
1604
            # the entry for this file_id must be in tree 0.
 
1605
            entry = self._get_entry(0, file_id, new_path)
 
1606
            if entry[0] is None or entry[0][2] != file_id:
 
1607
                self._changes_aborted = True
 
1608
                raise errors.InconsistentDelta(new_path, file_id,
 
1609
                    'working tree does not contain new entry')
 
1610
            if real_add and entry[1][1][0] not in absent:
 
1611
                self._changes_aborted = True
 
1612
                raise errors.InconsistentDelta(new_path, file_id,
 
1613
                    'The entry was considered to be a genuinely new record,'
 
1614
                    ' but there was already an old record for it.')
 
1615
            # We don't need to update the target of an 'r' because the handling
 
1616
            # of renames turns all 'r' situations into a delete at the original
 
1617
            # location.
 
1618
            entry[1][1] = new_details
1813
1619
 
1814
1620
    def _update_basis_apply_changes(self, changes):
1815
1621
        """Apply a sequence of changes to tree 1 during update_basis_by_delta.
1817
1623
        :param adds: A sequence of changes. Each change is a tuple:
1818
1624
            (path_utf8, path_utf8, file_id, (entry_details))
1819
1625
        """
 
1626
        absent = 'ar'
1820
1627
        for old_path, new_path, file_id, new_details in changes:
1821
1628
            # the entry for this file_id must be in tree 0.
1822
 
            entry = self._get_entry(1, file_id, new_path)
1823
 
            if entry[0] is None or entry[1][1][0] in (b'a', b'r'):
1824
 
                self._raise_invalid(new_path, file_id,
1825
 
                    'changed entry considered not present')
 
1629
            entry = self._get_entry(0, file_id, new_path)
 
1630
            if entry[0] is None or entry[0][2] != file_id:
 
1631
                self._changes_aborted = True
 
1632
                raise errors.InconsistentDelta(new_path, file_id,
 
1633
                    'working tree does not contain new entry')
 
1634
            if (entry[1][0][0] in absent or
 
1635
                entry[1][1][0] in absent):
 
1636
                self._changes_aborted = True
 
1637
                raise errors.InconsistentDelta(new_path, file_id,
 
1638
                    'changed considered absent')
1826
1639
            entry[1][1] = new_details
1827
1640
 
1828
1641
    def _update_basis_apply_deletes(self, deletes):
1840
1653
        null = DirState.NULL_PARENT_DETAILS
1841
1654
        for old_path, new_path, file_id, _, real_delete in deletes:
1842
1655
            if real_delete != (new_path is None):
1843
 
                self._raise_invalid(old_path, file_id, "bad delete delta")
 
1656
                self._changes_aborted = True
 
1657
                raise AssertionError("bad delete delta")
1844
1658
            # the entry for this file_id must be in tree 1.
1845
1659
            dirname, basename = osutils.split(old_path)
1846
1660
            block_index, entry_index, dir_present, file_present = \
1847
1661
                self._get_block_entry_index(dirname, basename, 1)
1848
1662
            if not file_present:
1849
 
                self._raise_invalid(old_path, file_id,
 
1663
                self._changes_aborted = True
 
1664
                raise errors.InconsistentDelta(old_path, file_id,
1850
1665
                    'basis tree does not contain removed entry')
1851
1666
            entry = self._dirblocks[block_index][1][entry_index]
1852
 
            # The state of the entry in the 'active' WT
1853
 
            active_kind = entry[1][0][0]
1854
1667
            if entry[0][2] != file_id:
1855
 
                self._raise_invalid(old_path, file_id,
 
1668
                self._changes_aborted = True
 
1669
                raise errors.InconsistentDelta(old_path, file_id,
1856
1670
                    'mismatched file_id in tree 1')
1857
 
            dir_block = ()
1858
 
            old_kind = entry[1][1][0]
1859
 
            if active_kind in b'ar':
1860
 
                # The active tree doesn't have this file_id.
1861
 
                # The basis tree is changing this record. If this is a
1862
 
                # rename, then we don't want the record here at all
1863
 
                # anymore. If it is just an in-place change, we want the
1864
 
                # record here, but we'll add it if we need to. So we just
1865
 
                # delete it
1866
 
                if active_kind == b'r':
1867
 
                    active_path = entry[1][0][1]
1868
 
                    active_entry = self._get_entry(0, file_id, active_path)
1869
 
                    if active_entry[1][1][0] != b'r':
1870
 
                        self._raise_invalid(old_path, file_id,
1871
 
                            "Dirstate did not have matching rename entries")
1872
 
                    elif active_entry[1][0][0] in b'ar':
1873
 
                        self._raise_invalid(old_path, file_id,
1874
 
                            "Dirstate had a rename pointing at an inactive"
1875
 
                            " tree0")
1876
 
                    active_entry[1][1] = null
 
1671
            if real_delete:
 
1672
                if entry[1][0][0] != 'a':
 
1673
                    self._changes_aborted = True
 
1674
                    raise errors.InconsistentDelta(old_path, file_id,
 
1675
                            'This was marked as a real delete, but the WT state'
 
1676
                            ' claims that it still exists and is versioned.')
1877
1677
                del self._dirblocks[block_index][1][entry_index]
1878
 
                if old_kind == b'd':
1879
 
                    # This was a directory, and the active tree says it
1880
 
                    # doesn't exist, and now the basis tree says it doesn't
1881
 
                    # exist. Remove its dirblock if present
1882
 
                    (dir_block_index,
1883
 
                     present) = self._find_block_index_from_key(
1884
 
                        (old_path, b'', b''))
1885
 
                    if present:
1886
 
                        dir_block = self._dirblocks[dir_block_index][1]
1887
 
                        if not dir_block:
1888
 
                            # This entry is empty, go ahead and just remove it
1889
 
                            del self._dirblocks[dir_block_index]
1890
1678
            else:
1891
 
                # There is still an active record, so just mark this
1892
 
                # removed.
1893
 
                entry[1][1] = null
1894
 
                block_i, entry_i, d_present, f_present = \
1895
 
                    self._get_block_entry_index(old_path, b'', 1)
1896
 
                if d_present:
1897
 
                    dir_block = self._dirblocks[block_i][1]
1898
 
            for child_entry in dir_block:
1899
 
                child_basis_kind = child_entry[1][1][0]
1900
 
                if child_basis_kind not in b'ar':
1901
 
                    self._raise_invalid(old_path, file_id,
1902
 
                        "The file id was deleted but its children were "
1903
 
                        "not deleted.")
 
1679
                if entry[1][0][0] == 'a':
 
1680
                    self._changes_aborted = True
 
1681
                    raise errors.InconsistentDelta(old_path, file_id,
 
1682
                        'The entry was considered a rename, but the source path'
 
1683
                        ' is marked as absent.')
 
1684
                    # For whatever reason, we were asked to rename an entry
 
1685
                    # that was originally marked as deleted. This could be
 
1686
                    # because we are renaming the parent directory, and the WT
 
1687
                    # current state has the file marked as deleted.
 
1688
                elif entry[1][0][0] == 'r':
 
1689
                    # implement the rename
 
1690
                    del self._dirblocks[block_index][1][entry_index]
 
1691
                else:
 
1692
                    # it is being resurrected here, so blank it out temporarily.
 
1693
                    self._dirblocks[block_index][1][entry_index][1][1] = null
1904
1694
 
1905
1695
    def _after_delta_check_parents(self, parents, index):
1906
1696
        """Check that parents required by the delta are all intact.
1915
1705
            # has the right file id.
1916
1706
            entry = self._get_entry(index, file_id, dirname_utf8)
1917
1707
            if entry[1] is None:
1918
 
                self._raise_invalid(dirname_utf8.decode('utf8'),
 
1708
                self._changes_aborted = True
 
1709
                raise errors.InconsistentDelta(dirname_utf8.decode('utf8'),
1919
1710
                    file_id, "This parent is not present.")
1920
1711
            # Parents of things must be directories
1921
 
            if entry[1][index][0] != b'd':
1922
 
                self._raise_invalid(dirname_utf8.decode('utf8'),
 
1712
            if entry[1][index][0] != 'd':
 
1713
                self._changes_aborted = True
 
1714
                raise errors.InconsistentDelta(dirname_utf8.decode('utf8'),
1923
1715
                    file_id, "This parent is not a directory.")
1924
1716
 
1925
1717
    def _observed_sha1(self, entry, sha1, stat_value,
1926
 
        _stat_to_minikind=_stat_to_minikind):
 
1718
        _stat_to_minikind=_stat_to_minikind, _pack_stat=pack_stat):
1927
1719
        """Note the sha1 of a file.
1928
1720
 
1929
1721
        :param entry: The entry the sha1 is for.
1931
1723
        :param stat_value: The os.lstat for the file.
1932
1724
        """
1933
1725
        try:
1934
 
            minikind = _stat_to_minikind[stat_value.st_mode & 0o170000]
 
1726
            minikind = _stat_to_minikind[stat_value.st_mode & 0170000]
1935
1727
        except KeyError:
1936
1728
            # Unhandled kind
1937
1729
            return None
1938
 
        if minikind == b'f':
 
1730
        packed_stat = _pack_stat(stat_value)
 
1731
        if minikind == 'f':
1939
1732
            if self._cutoff_time is None:
1940
1733
                self._sha_cutoff_time()
1941
1734
            if (stat_value.st_mtime < self._cutoff_time
1942
1735
                and stat_value.st_ctime < self._cutoff_time):
1943
 
                entry[1][0] = (b'f', sha1, stat_value.st_size, entry[1][0][3],
1944
 
                               pack_stat(stat_value))
1945
 
                self._mark_modified([entry])
 
1736
                entry[1][0] = ('f', sha1, entry[1][0][2], entry[1][0][3],
 
1737
                    packed_stat)
 
1738
                self._dirblock_state = DirState.IN_MEMORY_MODIFIED
1946
1739
 
1947
1740
    def _sha_cutoff_time(self):
1948
1741
        """Return cutoff time.
1985
1778
        #       higher level, because there either won't be anything on disk,
1986
1779
        #       or the thing on disk will be a file.
1987
1780
        fs_encoding = osutils._fs_enc
1988
 
        if isinstance(abspath, text_type):
 
1781
        if isinstance(abspath, unicode):
1989
1782
            # abspath is defined as the path to pass to lstat. readlink is
1990
1783
            # buggy in python < 2.6 (it doesn't encode unicode path into FS
1991
1784
            # encoding), so we need to encode ourselves knowing that unicode
1992
1785
            # paths are produced by UnicodeDirReader on purpose.
1993
1786
            abspath = abspath.encode(fs_encoding)
1994
1787
        target = os.readlink(abspath)
1995
 
        if fs_encoding not in ('utf-8', 'ascii'):
 
1788
        if fs_encoding not in ('UTF-8', 'US-ASCII', 'ANSI_X3.4-1968'):
1996
1789
            # Change encoding if needed
1997
1790
            target = target.decode(fs_encoding).encode('UTF-8')
1998
1791
        return target
2006
1799
        """Serialise the entire dirstate to a sequence of lines."""
2007
1800
        if (self._header_state == DirState.IN_MEMORY_UNMODIFIED and
2008
1801
            self._dirblock_state == DirState.IN_MEMORY_UNMODIFIED):
2009
 
            # read what's on disk.
 
1802
            # read whats on disk.
2010
1803
            self._state_file.seek(0)
2011
1804
            return self._state_file.readlines()
2012
1805
        lines = []
2013
1806
        lines.append(self._get_parents_line(self.get_parent_ids()))
2014
1807
        lines.append(self._get_ghosts_line(self._ghosts))
2015
 
        lines.extend(self._iter_entry_lines())
 
1808
        # append the root line which is special cased
 
1809
        lines.extend(map(self._entry_to_line, self._iter_entries()))
2016
1810
        return self._get_output_lines(lines)
2017
1811
 
2018
1812
    def _get_ghosts_line(self, ghost_ids):
2019
1813
        """Create a line for the state file for ghost information."""
2020
 
        return b'\0'.join([b'%d' % len(ghost_ids)] + ghost_ids)
 
1814
        return '\0'.join([str(len(ghost_ids))] + ghost_ids)
2021
1815
 
2022
1816
    def _get_parents_line(self, parent_ids):
2023
1817
        """Create a line for the state file for parents information."""
2024
 
        return b'\0'.join([b'%d' % len(parent_ids)] + parent_ids)
2025
 
 
2026
 
    def _iter_entry_lines(self):
2027
 
        """Create lines for entries."""
2028
 
        return map(self._entry_to_line, self._iter_entries())
 
1818
        return '\0'.join([str(len(parent_ids))] + parent_ids)
2029
1819
 
2030
1820
    def _get_fields_to_entry(self):
2031
1821
        """Get a function which converts entry fields into a entry record.
2045
1835
                        fields[3],                # minikind
2046
1836
                        fields[4],                # fingerprint
2047
1837
                        _int(fields[5]),          # size
2048
 
                        fields[6] == b'y',         # executable
 
1838
                        fields[6] == 'y',         # executable
2049
1839
                        fields[7],                # packed_stat or revision_id
2050
1840
                    )])
2051
1841
            return fields_to_entry_0_parents
2057
1847
                        fields[3],                # minikind
2058
1848
                        fields[4],                # fingerprint
2059
1849
                        _int(fields[5]),          # size
2060
 
                        fields[6] == b'y',         # executable
 
1850
                        fields[6] == 'y',         # executable
2061
1851
                        fields[7],                # packed_stat or revision_id
2062
1852
                    ),
2063
1853
                    ( # Parent 1
2064
1854
                        fields[8],                # minikind
2065
1855
                        fields[9],                # fingerprint
2066
1856
                        _int(fields[10]),         # size
2067
 
                        fields[11] == b'y',        # executable
 
1857
                        fields[11] == 'y',        # executable
2068
1858
                        fields[12],               # packed_stat or revision_id
2069
1859
                    ),
2070
1860
                    ])
2077
1867
                        fields[3],                # minikind
2078
1868
                        fields[4],                # fingerprint
2079
1869
                        _int(fields[5]),          # size
2080
 
                        fields[6] == b'y',         # executable
 
1870
                        fields[6] == 'y',         # executable
2081
1871
                        fields[7],                # packed_stat or revision_id
2082
1872
                    ),
2083
1873
                    ( # Parent 1
2084
1874
                        fields[8],                # minikind
2085
1875
                        fields[9],                # fingerprint
2086
1876
                        _int(fields[10]),         # size
2087
 
                        fields[11] == b'y',        # executable
 
1877
                        fields[11] == 'y',        # executable
2088
1878
                        fields[12],               # packed_stat or revision_id
2089
1879
                    ),
2090
1880
                    ( # Parent 2
2091
1881
                        fields[13],               # minikind
2092
1882
                        fields[14],               # fingerprint
2093
1883
                        _int(fields[15]),         # size
2094
 
                        fields[16] == b'y',        # executable
 
1884
                        fields[16] == 'y',        # executable
2095
1885
                        fields[17],               # packed_stat or revision_id
2096
1886
                    ),
2097
1887
                    ])
2102
1892
                trees = [(fields[cur],                # minikind
2103
1893
                          fields[cur+1],              # fingerprint
2104
1894
                          _int(fields[cur+2]),        # size
2105
 
                          fields[cur+3] == b'y',       # executable
 
1895
                          fields[cur+3] == 'y',       # executable
2106
1896
                          fields[cur+4],              # stat or revision_id
2107
 
                         ) for cur in range(3, len(fields)-1, 5)]
 
1897
                         ) for cur in xrange(3, len(fields)-1, 5)]
2108
1898
                return path_name_file_id_key, trees
2109
1899
            return fields_to_entry_n_parents
2110
1900
 
2134
1924
            tree present there.
2135
1925
        """
2136
1926
        self._read_dirblocks_if_needed()
2137
 
        key = dirname, basename, b''
 
1927
        key = dirname, basename, ''
2138
1928
        block_index, present = self._find_block_index_from_key(key)
2139
1929
        if not present:
2140
1930
            # no such directory - return the dir index and 0 for the row.
2144
1934
        # linear search through entries at this path to find the one
2145
1935
        # requested.
2146
1936
        while entry_index < len(block) and block[entry_index][0][1] == basename:
2147
 
            if block[entry_index][1][tree_index][0] not in (b'a', b'r'):
 
1937
            if block[entry_index][1][tree_index][0] not in 'ar':
2148
1938
                # neither absent or relocated
2149
1939
                return block_index, entry_index, True, True
2150
1940
            entry_index += 1
2151
1941
        return block_index, entry_index, True, False
2152
1942
 
2153
 
    def _get_entry(self, tree_index, fileid_utf8=None, path_utf8=None,
2154
 
                   include_deleted=False):
 
1943
    def _get_entry(self, tree_index, fileid_utf8=None, path_utf8=None, include_deleted=False):
2155
1944
        """Get the dirstate entry for path in tree tree_index.
2156
1945
 
2157
1946
        If either file_id or path is supplied, it is used as the key to lookup.
2172
1961
        """
2173
1962
        self._read_dirblocks_if_needed()
2174
1963
        if path_utf8 is not None:
2175
 
            if not isinstance(path_utf8, bytes):
2176
 
                raise errors.BzrError('path_utf8 is not bytes: %s %r'
 
1964
            if type(path_utf8) is not str:
 
1965
                raise errors.BzrError('path_utf8 is not a str: %s %r'
2177
1966
                    % (type(path_utf8), path_utf8))
2178
1967
            # path lookups are faster
2179
1968
            dirname, basename = osutils.split(path_utf8)
2182
1971
            if not file_present:
2183
1972
                return None, None
2184
1973
            entry = self._dirblocks[block_index][1][entry_index]
2185
 
            if not (entry[0][2] and entry[1][tree_index][0] not in (b'a', b'r')):
 
1974
            if not (entry[0][2] and entry[1][tree_index][0] not in ('a', 'r')):
2186
1975
                raise AssertionError('unversioned entry?')
2187
1976
            if fileid_utf8:
2188
1977
                if entry[0][2] != fileid_utf8:
2191
1980
                                          ' tree_index, file_id and path')
2192
1981
            return entry
2193
1982
        else:
2194
 
            possible_keys = self._get_id_index().get(fileid_utf8, ())
 
1983
            possible_keys = self._get_id_index().get(fileid_utf8, None)
2195
1984
            if not possible_keys:
2196
1985
                return None, None
2197
1986
            for key in possible_keys:
2210
1999
                    entry = self._dirblocks[block_index][1][entry_index]
2211
2000
                    # TODO: We might want to assert that entry[0][2] ==
2212
2001
                    #       fileid_utf8.
2213
 
                    # GZ 2017-06-09: Hoist set of minkinds somewhere
2214
 
                    if entry[1][tree_index][0] in {b'f', b'd', b'l', b't'}:
 
2002
                    if entry[1][tree_index][0] in 'fdlt':
2215
2003
                        # this is the result we are looking for: the
2216
2004
                        # real home of this file_id in this tree.
2217
2005
                        return entry
2218
 
                    if entry[1][tree_index][0] == b'a':
 
2006
                    if entry[1][tree_index][0] == 'a':
2219
2007
                        # there is no home for this entry in this tree
2220
2008
                        if include_deleted:
2221
2009
                            return entry
2222
2010
                        return None, None
2223
 
                    if entry[1][tree_index][0] != b'r':
 
2011
                    if entry[1][tree_index][0] != 'r':
2224
2012
                        raise AssertionError(
2225
2013
                            "entry %r has invalid minikind %r for tree %r" \
2226
2014
                            % (entry,
2252
2040
            sha1_provider = DefaultSHA1Provider()
2253
2041
        result = cls(path, sha1_provider)
2254
2042
        # root dir and root dir contents with no children.
2255
 
        empty_tree_dirblocks = [(b'', []), (b'', [])]
 
2043
        empty_tree_dirblocks = [('', []), ('', [])]
2256
2044
        # a new root directory, with a NULLSTAT.
2257
2045
        empty_tree_dirblocks[0][1].append(
2258
 
            ((b'', b'', inventory.ROOT_ID), [
2259
 
                (b'd', b'', 0, False, DirState.NULLSTAT),
 
2046
            (('', '', inventory.ROOT_ID), [
 
2047
                ('d', '', 0, False, DirState.NULLSTAT),
2260
2048
            ]))
2261
2049
        result.lock_write()
2262
2050
        try:
2280
2068
        minikind = DirState._kind_to_minikind[kind]
2281
2069
        tree_data = inv_entry.revision
2282
2070
        if kind == 'directory':
2283
 
            fingerprint = b''
 
2071
            fingerprint = ''
2284
2072
            size = 0
2285
2073
            executable = False
2286
2074
        elif kind == 'symlink':
2287
2075
            if inv_entry.symlink_target is None:
2288
 
                fingerprint = b''
 
2076
                fingerprint = ''
2289
2077
            else:
2290
2078
                fingerprint = inv_entry.symlink_target.encode('utf8')
2291
2079
            size = 0
2292
2080
            executable = False
2293
2081
        elif kind == 'file':
2294
 
            fingerprint = inv_entry.text_sha1 or b''
 
2082
            fingerprint = inv_entry.text_sha1 or ''
2295
2083
            size = inv_entry.text_size or 0
2296
2084
            executable = inv_entry.executable
2297
2085
        elif kind == 'tree-reference':
2298
 
            fingerprint = inv_entry.reference_revision or b''
 
2086
            fingerprint = inv_entry.reference_revision or ''
2299
2087
            size = 0
2300
2088
            executable = False
2301
2089
        else:
2302
2090
            raise Exception("can't pack %s" % inv_entry)
2303
 
        return static_tuple.StaticTuple(minikind, fingerprint, size,
2304
 
                                        executable, tree_data)
 
2091
        return (minikind, fingerprint, size, executable, tree_data)
2305
2092
 
2306
2093
    def _iter_child_entries(self, tree_index, path_utf8):
2307
2094
        """Iterate over all the entries that are children of path_utf.
2308
2095
 
2309
 
        This only returns entries that are present (not in b'a', b'r') in
 
2096
        This only returns entries that are present (not in 'a', 'r') in
2310
2097
        tree_index. tree_index data is not refreshed, so if tree 0 is used,
2311
2098
        results may differ from that obtained if paths were statted to
2312
2099
        determine what ones were directories.
2316
2103
        """
2317
2104
        pending_dirs = []
2318
2105
        next_pending_dirs = [path_utf8]
2319
 
        absent = (b'a', b'r')
 
2106
        absent = 'ar'
2320
2107
        while next_pending_dirs:
2321
2108
            pending_dirs = next_pending_dirs
2322
2109
            next_pending_dirs = []
2323
2110
            for path in pending_dirs:
2324
2111
                block_index, present = self._find_block_index_from_key(
2325
 
                    (path, b'', b''))
 
2112
                    (path, '', ''))
2326
2113
                if block_index == 0:
2327
2114
                    block_index = 1
2328
2115
                    if len(self._dirblocks) == 1:
2337
2124
                    kind = entry[1][tree_index][0]
2338
2125
                    if kind not in absent:
2339
2126
                        yield entry
2340
 
                    if kind == b'd':
 
2127
                    if kind == 'd':
2341
2128
                        if entry[0][0]:
2342
 
                            path = entry[0][0] + b'/' + entry[0][1]
 
2129
                            path = entry[0][0] + '/' + entry[0][1]
2343
2130
                        else:
2344
2131
                            path = entry[0][1]
2345
2132
                        next_pending_dirs.append(path)
2348
2135
        """Iterate over all the entries in the dirstate.
2349
2136
 
2350
2137
        Each yelt item is an entry in the standard format described in the
2351
 
        docstring of breezy.dirstate.
 
2138
        docstring of bzrlib.dirstate.
2352
2139
        """
2353
2140
        self._read_dirblocks_if_needed()
2354
2141
        for directory in self._dirblocks:
2356
2143
                yield entry
2357
2144
 
2358
2145
    def _get_id_index(self):
2359
 
        """Get an id index of self._dirblocks.
2360
 
 
2361
 
        This maps from file_id => [(directory, name, file_id)] entries where
2362
 
        that file_id appears in one of the trees.
2363
 
        """
 
2146
        """Get an id index of self._dirblocks."""
2364
2147
        if self._id_index is None:
2365
2148
            id_index = {}
2366
2149
            for key, tree_details in self._iter_entries():
2367
 
                self._add_to_id_index(id_index, key)
 
2150
                id_index.setdefault(key[2], set()).add(key)
2368
2151
            self._id_index = id_index
2369
2152
        return self._id_index
2370
2153
 
2371
 
    def _add_to_id_index(self, id_index, entry_key):
2372
 
        """Add this entry to the _id_index mapping."""
2373
 
        # This code used to use a set for every entry in the id_index. However,
2374
 
        # it is *rare* to have more than one entry. So a set is a large
2375
 
        # overkill. And even when we do, we won't ever have more than the
2376
 
        # number of parent trees. Which is still a small number (rarely >2). As
2377
 
        # such, we use a simple tuple, and do our own uniqueness checks. While
2378
 
        # the 'in' check is O(N) since N is nicely bounded it shouldn't ever
2379
 
        # cause quadratic failure.
2380
 
        file_id = entry_key[2]
2381
 
        entry_key = static_tuple.StaticTuple.from_sequence(entry_key)
2382
 
        if file_id not in id_index:
2383
 
            id_index[file_id] = static_tuple.StaticTuple(entry_key,)
2384
 
        else:
2385
 
            entry_keys = id_index[file_id]
2386
 
            if entry_key not in entry_keys:
2387
 
                id_index[file_id] = entry_keys + (entry_key,)
2388
 
 
2389
 
    def _remove_from_id_index(self, id_index, entry_key):
2390
 
        """Remove this entry from the _id_index mapping.
2391
 
 
2392
 
        It is an programming error to call this when the entry_key is not
2393
 
        already present.
2394
 
        """
2395
 
        file_id = entry_key[2]
2396
 
        entry_keys = list(id_index[file_id])
2397
 
        entry_keys.remove(entry_key)
2398
 
        id_index[file_id] = static_tuple.StaticTuple.from_sequence(entry_keys)
2399
 
 
2400
2154
    def _get_output_lines(self, lines):
2401
2155
        """Format lines for final output.
2402
2156
 
2404
2158
            path lines.
2405
2159
        """
2406
2160
        output_lines = [DirState.HEADER_FORMAT_3]
2407
 
        lines.append(b'') # a final newline
2408
 
        inventory_text = b'\0\n\0'.join(lines)
2409
 
        output_lines.append(b'crc32: %d\n' % (zlib.crc32(inventory_text),))
 
2161
        lines.append('') # a final newline
 
2162
        inventory_text = '\0\n\0'.join(lines)
 
2163
        output_lines.append('crc32: %s\n' % (zlib.crc32(inventory_text),))
2410
2164
        # -3, 1 for num parents, 1 for ghosts, 1 for final newline
2411
2165
        num_entries = len(lines)-3
2412
 
        output_lines.append(b'num_entries: %d\n' % (num_entries,))
 
2166
        output_lines.append('num_entries: %s\n' % (num_entries,))
2413
2167
        output_lines.append(inventory_text)
2414
2168
        return output_lines
2415
2169
 
2416
2170
    def _make_deleted_row(self, fileid_utf8, parents):
2417
2171
        """Return a deleted row for fileid_utf8."""
2418
 
        return (b'/', b'RECYCLED.BIN', b'file', fileid_utf8, 0, DirState.NULLSTAT,
2419
 
            b''), parents
 
2172
        return ('/', 'RECYCLED.BIN', 'file', fileid_utf8, 0, DirState.NULLSTAT,
 
2173
            ''), parents
2420
2174
 
2421
2175
    def _num_present_parents(self):
2422
2176
        """The number of parent entries in each record row."""
2423
2177
        return len(self._parents) - len(self._ghosts)
2424
2178
 
2425
 
    @classmethod
2426
 
    def on_file(cls, path, sha1_provider=None, worth_saving_limit=0):
 
2179
    @staticmethod
 
2180
    def on_file(path, sha1_provider=None):
2427
2181
        """Construct a DirState on the file at path "path".
2428
2182
 
2429
2183
        :param path: The path at which the dirstate file on disk should live.
2430
2184
        :param sha1_provider: an object meeting the SHA1Provider interface.
2431
2185
            If None, a DefaultSHA1Provider is used.
2432
 
        :param worth_saving_limit: when the exact number of hash changed
2433
 
            entries is known, only bother saving the dirstate if more than
2434
 
            this count of entries have changed. -1 means never save.
2435
2186
        :return: An unlocked DirState object, associated with the given path.
2436
2187
        """
2437
2188
        if sha1_provider is None:
2438
2189
            sha1_provider = DefaultSHA1Provider()
2439
 
        result = cls(path, sha1_provider,
2440
 
                     worth_saving_limit=worth_saving_limit)
 
2190
        result = DirState(path, sha1_provider)
2441
2191
        return result
2442
2192
 
2443
2193
    def _read_dirblocks_if_needed(self):
2461
2211
        """
2462
2212
        self._read_prelude()
2463
2213
        parent_line = self._state_file.readline()
2464
 
        info = parent_line.split(b'\0')
 
2214
        info = parent_line.split('\0')
2465
2215
        num_parents = int(info[0])
2466
2216
        self._parents = info[1:-1]
2467
2217
        ghost_line = self._state_file.readline()
2468
 
        info = ghost_line.split(b'\0')
 
2218
        info = ghost_line.split('\0')
2469
2219
        num_ghosts = int(info[1])
2470
2220
        self._ghosts = info[2:-1]
2471
2221
        self._header_state = DirState.IN_MEMORY_UNMODIFIED
2493
2243
            raise errors.BzrError(
2494
2244
                'invalid header line: %r' % (header,))
2495
2245
        crc_line = self._state_file.readline()
2496
 
        if not crc_line.startswith(b'crc32: '):
 
2246
        if not crc_line.startswith('crc32: '):
2497
2247
            raise errors.BzrError('missing crc32 checksum: %r' % crc_line)
2498
 
        self.crc_expected = int(crc_line[len(b'crc32: '):-1])
 
2248
        self.crc_expected = int(crc_line[len('crc32: '):-1])
2499
2249
        num_entries_line = self._state_file.readline()
2500
 
        if not num_entries_line.startswith(b'num_entries: '):
 
2250
        if not num_entries_line.startswith('num_entries: '):
2501
2251
            raise errors.BzrError('missing num_entries line')
2502
 
        self._num_entries = int(num_entries_line[len(b'num_entries: '):-1])
 
2252
        self._num_entries = int(num_entries_line[len('num_entries: '):-1])
2503
2253
 
2504
 
    def sha1_from_stat(self, path, stat_result):
 
2254
    def sha1_from_stat(self, path, stat_result, _pack_stat=pack_stat):
2505
2255
        """Find a sha1 given a stat lookup."""
2506
 
        return self._get_packed_stat_index().get(pack_stat(stat_result), None)
 
2256
        return self._get_packed_stat_index().get(_pack_stat(stat_result), None)
2507
2257
 
2508
2258
    def _get_packed_stat_index(self):
2509
2259
        """Get a packed_stat index of self._dirblocks."""
2510
2260
        if self._packed_stat_index is None:
2511
2261
            index = {}
2512
2262
            for key, tree_details in self._iter_entries():
2513
 
                if tree_details[0][0] == b'f':
 
2263
                if tree_details[0][0] == 'f':
2514
2264
                    index[tree_details[0][4]] = tree_details[0][1]
2515
2265
            self._packed_stat_index = index
2516
2266
        return self._packed_stat_index
2535
2285
            trace.mutter('Not saving DirState because '
2536
2286
                    '_changes_aborted is set.')
2537
2287
            return
2538
 
        # TODO: Since we now distinguish IN_MEMORY_MODIFIED from
2539
 
        #       IN_MEMORY_HASH_MODIFIED, we should only fail quietly if we fail
2540
 
        #       to save an IN_MEMORY_HASH_MODIFIED, and fail *noisily* if we
2541
 
        #       fail to save IN_MEMORY_MODIFIED
2542
 
        if not self._worth_saving():
2543
 
            return
 
2288
        if (self._header_state == DirState.IN_MEMORY_MODIFIED or
 
2289
            self._dirblock_state == DirState.IN_MEMORY_MODIFIED):
2544
2290
 
2545
 
        grabbed_write_lock = False
2546
 
        if self._lock_state != 'w':
2547
 
            grabbed_write_lock, new_lock = self._lock_token.temporary_write_lock()
2548
 
            # Switch over to the new lock, as the old one may be closed.
2549
 
            # TODO: jam 20070315 We should validate the disk file has
2550
 
            #       not changed contents, since temporary_write_lock may
2551
 
            #       not be an atomic operation.
2552
 
            self._lock_token = new_lock
2553
 
            self._state_file = new_lock.f
2554
 
            if not grabbed_write_lock:
2555
 
                # We couldn't grab a write lock, so we switch back to a read one
2556
 
                return
2557
 
        try:
2558
 
            lines = self.get_lines()
2559
 
            self._state_file.seek(0)
2560
 
            self._state_file.writelines(lines)
2561
 
            self._state_file.truncate()
2562
 
            self._state_file.flush()
2563
 
            self._maybe_fdatasync()
2564
 
            self._mark_unmodified()
2565
 
        finally:
2566
 
            if grabbed_write_lock:
2567
 
                self._lock_token = self._lock_token.restore_read_lock()
2568
 
                self._state_file = self._lock_token.f
 
2291
            grabbed_write_lock = False
 
2292
            if self._lock_state != 'w':
 
2293
                grabbed_write_lock, new_lock = self._lock_token.temporary_write_lock()
 
2294
                # Switch over to the new lock, as the old one may be closed.
2569
2295
                # TODO: jam 20070315 We should validate the disk file has
2570
 
                #       not changed contents. Since restore_read_lock may
 
2296
                #       not changed contents. Since temporary_write_lock may
2571
2297
                #       not be an atomic operation.
2572
 
 
2573
 
    def _maybe_fdatasync(self):
2574
 
        """Flush to disk if possible and if not configured off."""
2575
 
        if self._config_stack.get('dirstate.fdatasync'):
2576
 
            osutils.fdatasync(self._state_file.fileno())
2577
 
 
2578
 
    def _worth_saving(self):
2579
 
        """Is it worth saving the dirstate or not?"""
2580
 
        if (self._header_state == DirState.IN_MEMORY_MODIFIED
2581
 
            or self._dirblock_state == DirState.IN_MEMORY_MODIFIED):
2582
 
            return True
2583
 
        if self._dirblock_state == DirState.IN_MEMORY_HASH_MODIFIED:
2584
 
            if self._worth_saving_limit == -1:
2585
 
                # We never save hash changes when the limit is -1
2586
 
                return False
2587
 
            # If we're using smart saving and only a small number of
2588
 
            # entries have changed their hash, don't bother saving. John has
2589
 
            # suggested using a heuristic here based on the size of the
2590
 
            # changed files and/or tree. For now, we go with a configurable
2591
 
            # number of changes, keeping the calculation time
2592
 
            # as low overhead as possible. (This also keeps all existing
2593
 
            # tests passing as the default is 0, i.e. always save.)
2594
 
            if len(self._known_hash_changes) >= self._worth_saving_limit:
2595
 
                return True
2596
 
        return False
 
2298
                self._lock_token = new_lock
 
2299
                self._state_file = new_lock.f
 
2300
                if not grabbed_write_lock:
 
2301
                    # We couldn't grab a write lock, so we switch back to a read one
 
2302
                    return
 
2303
            try:
 
2304
                self._state_file.seek(0)
 
2305
                self._state_file.writelines(self.get_lines())
 
2306
                self._state_file.truncate()
 
2307
                self._state_file.flush()
 
2308
                self._header_state = DirState.IN_MEMORY_UNMODIFIED
 
2309
                self._dirblock_state = DirState.IN_MEMORY_UNMODIFIED
 
2310
            finally:
 
2311
                if grabbed_write_lock:
 
2312
                    self._lock_token = self._lock_token.restore_read_lock()
 
2313
                    self._state_file = self._lock_token.f
 
2314
                    # TODO: jam 20070315 We should validate the disk file has
 
2315
                    #       not changed contents. Since restore_read_lock may
 
2316
                    #       not be an atomic operation.
2597
2317
 
2598
2318
    def _set_data(self, parent_ids, dirblocks):
2599
2319
        """Set the full dirstate data in memory.
2608
2328
        """
2609
2329
        # our memory copy is now authoritative.
2610
2330
        self._dirblocks = dirblocks
2611
 
        self._mark_modified(header_modified=True)
 
2331
        self._header_state = DirState.IN_MEMORY_MODIFIED
 
2332
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
2612
2333
        self._parents = list(parent_ids)
2613
2334
        self._id_index = None
2614
2335
        self._packed_stat_index = None
2616
2337
    def set_path_id(self, path, new_id):
2617
2338
        """Change the id of path to new_id in the current working tree.
2618
2339
 
2619
 
        :param path: The path inside the tree to set - b'' is the root, 'foo'
 
2340
        :param path: The path inside the tree to set - '' is the root, 'foo'
2620
2341
            is the path foo in the root.
2621
2342
        :param new_id: The new id to assign to the path. This must be a utf8
2622
2343
            file id (not unicode, and not None).
2630
2351
        if entry[0][2] == new_id:
2631
2352
            # Nothing to change.
2632
2353
            return
2633
 
        if new_id.__class__ != bytes:
2634
 
            raise AssertionError(
2635
 
                "must be a utf8 file_id not %s" % (type(new_id), ))
2636
2354
        # mark the old path absent, and insert a new root path
2637
2355
        self._make_absent(entry)
2638
 
        self.update_minimal((b'', b'', new_id), b'd',
2639
 
            path_utf8=b'', packed_stat=entry[1][0][4])
2640
 
        self._mark_modified()
 
2356
        self.update_minimal(('', '', new_id), 'd',
 
2357
            path_utf8='', packed_stat=entry[1][0][4])
 
2358
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
2641
2359
 
2642
2360
    def set_parent_trees(self, trees, ghosts):
2643
2361
        """Set the parent trees for the dirstate.
2688
2406
        parent_trees = [tree for rev_id, tree in trees if rev_id not in ghosts]
2689
2407
        # how many trees do we end up with
2690
2408
        parent_count = len(parent_trees)
2691
 
        st = static_tuple.StaticTuple
2692
2409
 
2693
2410
        # one: the current tree
2694
2411
        for entry in self._iter_entries():
2695
2412
            # skip entries not in the current tree
2696
 
            if entry[1][0][0] in (b'a', b'r'): # absent, relocated
 
2413
            if entry[1][0][0] in 'ar': # absent, relocated
2697
2414
                continue
2698
2415
            by_path[entry[0]] = [entry[1][0]] + \
2699
2416
                [DirState.NULL_PARENT_DETAILS] * parent_count
2700
 
            # TODO: Possibly inline this, since we know it isn't present yet
2701
 
            #       id_index[entry[0][2]] = (entry[0],)
2702
 
            self._add_to_id_index(id_index, entry[0])
 
2417
            id_index[entry[0][2]] = set([entry[0]])
2703
2418
 
2704
2419
        # now the parent trees:
2705
2420
        for tree_index, tree in enumerate(parent_trees):
2711
2426
            # the suffix is from tree_index+1:parent_count+1.
2712
2427
            new_location_suffix = [DirState.NULL_PARENT_DETAILS] * (parent_count - tree_index)
2713
2428
            # now stitch in all the entries from this tree
2714
 
            last_dirname = None
2715
 
            for path, entry in tree.iter_entries_by_dir():
 
2429
            for path, entry in tree.inventory.iter_entries_by_dir():
2716
2430
                # here we process each trees details for each item in the tree.
2717
2431
                # we first update any existing entries for the id at other paths,
2718
2432
                # then we either create or update the entry for the id at the
2725
2439
                file_id = entry.file_id
2726
2440
                path_utf8 = path.encode('utf8')
2727
2441
                dirname, basename = osutils.split(path_utf8)
2728
 
                if dirname == last_dirname:
2729
 
                    # Try to re-use objects as much as possible
2730
 
                    dirname = last_dirname
2731
 
                else:
2732
 
                    last_dirname = dirname
2733
 
                new_entry_key = st(dirname, basename, file_id)
 
2442
                new_entry_key = (dirname, basename, file_id)
2734
2443
                # tree index consistency: All other paths for this id in this tree
2735
2444
                # index must point to the correct path.
2736
 
                entry_keys = id_index.get(file_id, ())
2737
 
                for entry_key in entry_keys:
 
2445
                for entry_key in id_index.setdefault(file_id, set()):
2738
2446
                    # TODO:PROFILING: It might be faster to just update
2739
2447
                    # rather than checking if we need to, and then overwrite
2740
2448
                    # the one we are located at.
2743
2451
                        # other trees, so put absent pointers there
2744
2452
                        # This is the vertical axis in the matrix, all pointing
2745
2453
                        # to the real path.
2746
 
                        by_path[entry_key][tree_index] = st(b'r', path_utf8, 0,
2747
 
                                                            False, b'')
2748
 
                # by path consistency: Insert into an existing path record
2749
 
                # (trivial), or add a new one with relocation pointers for the
2750
 
                # other tree indexes.
2751
 
                if new_entry_key in entry_keys:
2752
 
                    # there is already an entry where this data belongs, just
2753
 
                    # insert it.
 
2454
                        by_path[entry_key][tree_index] = ('r', path_utf8, 0, False, '')
 
2455
                # by path consistency: Insert into an existing path record (trivial), or
 
2456
                # add a new one with relocation pointers for the other tree indexes.
 
2457
                if new_entry_key in id_index[file_id]:
 
2458
                    # there is already an entry where this data belongs, just insert it.
2754
2459
                    by_path[new_entry_key][tree_index] = \
2755
2460
                        self._inv_entry_to_details(entry)
2756
2461
                else:
2758
2463
                    # mapping from path,id. We need to look up the correct path
2759
2464
                    # for the indexes from 0 to tree_index -1
2760
2465
                    new_details = []
2761
 
                    for lookup_index in range(tree_index):
 
2466
                    for lookup_index in xrange(tree_index):
2762
2467
                        # boundary case: this is the first occurence of file_id
2763
 
                        # so there are no id_indexes, possibly take this out of
 
2468
                        # so there are no id_indexs, possibly take this out of
2764
2469
                        # the loop?
2765
 
                        if not len(entry_keys):
 
2470
                        if not len(id_index[file_id]):
2766
2471
                            new_details.append(DirState.NULL_PARENT_DETAILS)
2767
2472
                        else:
2768
2473
                            # grab any one entry, use it to find the right path.
2769
 
                            a_key = next(iter(entry_keys))
2770
 
                            if by_path[a_key][lookup_index][0] in (b'r', b'a'):
2771
 
                                # its a pointer or missing statement, use it as
2772
 
                                # is.
 
2474
                            # TODO: optimise this to reduce memory use in highly
 
2475
                            # fragmented situations by reusing the relocation
 
2476
                            # records.
 
2477
                            a_key = iter(id_index[file_id]).next()
 
2478
                            if by_path[a_key][lookup_index][0] in ('r', 'a'):
 
2479
                                # its a pointer or missing statement, use it as is.
2773
2480
                                new_details.append(by_path[a_key][lookup_index])
2774
2481
                            else:
2775
2482
                                # we have the right key, make a pointer to it.
2776
 
                                real_path = (b'/'.join(a_key[0:2])).strip(b'/')
2777
 
                                new_details.append(st(b'r', real_path, 0, False,
2778
 
                                                      b''))
 
2483
                                real_path = ('/'.join(a_key[0:2])).strip('/')
 
2484
                                new_details.append(('r', real_path, 0, False, ''))
2779
2485
                    new_details.append(self._inv_entry_to_details(entry))
2780
2486
                    new_details.extend(new_location_suffix)
2781
2487
                    by_path[new_entry_key] = new_details
2782
 
                    self._add_to_id_index(id_index, new_entry_key)
 
2488
                    id_index[file_id].add(new_entry_key)
2783
2489
        # --- end generation of full tree mappings
2784
2490
 
2785
2491
        # sort and output all the entries
2786
 
        new_entries = self._sort_entries(viewitems(by_path))
 
2492
        new_entries = self._sort_entries(by_path.items())
2787
2493
        self._entries_to_current_state(new_entries)
2788
2494
        self._parents = [rev_id for rev_id, tree in trees]
2789
2495
        self._ghosts = list(ghosts)
2790
 
        self._mark_modified(header_modified=True)
 
2496
        self._header_state = DirState.IN_MEMORY_MODIFIED
 
2497
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
2791
2498
        self._id_index = id_index
2792
2499
 
2793
2500
    def _sort_entries(self, entry_list):
2797
2504
        try to keep everything in sorted blocks all the time, but sometimes
2798
2505
        it's easier to sort after the fact.
2799
2506
        """
2800
 
        # When sorting, we usually have 10x more entries than directories. (69k
2801
 
        # total entries, 4k directories). So cache the results of splitting.
2802
 
        # Saving time and objects. Also, use StaticTuple to avoid putting all
2803
 
        # of these object into python's garbage collector.
2804
 
        split_dirs = {}
2805
 
        def _key(entry, _split_dirs=split_dirs, _st=static_tuple.StaticTuple):
 
2507
        def _key(entry):
2806
2508
            # sort by: directory parts, file name, file id
2807
 
            dirpath, fname, file_id = entry[0]
2808
 
            try:
2809
 
                split = _split_dirs[dirpath]
2810
 
            except KeyError:
2811
 
                split = _st.from_sequence(dirpath.split(b'/'))
2812
 
                _split_dirs[dirpath] = split
2813
 
            return _st(split, fname, file_id)
 
2509
            return entry[0][0].split('/'), entry[0][1], entry[0][2]
2814
2510
        return sorted(entry_list, key=_key)
2815
2511
 
2816
2512
    def set_state_from_inventory(self, new_inv):
2846
2542
        # underlying dirstate.
2847
2543
        old_iterator = iter(list(self._iter_entries()))
2848
2544
        # both must have roots so this is safe:
2849
 
        current_new = next(new_iterator)
2850
 
        current_old = next(old_iterator)
 
2545
        current_new = new_iterator.next()
 
2546
        current_old = old_iterator.next()
2851
2547
        def advance(iterator):
2852
2548
            try:
2853
 
                return next(iterator)
 
2549
                return iterator.next()
2854
2550
            except StopIteration:
2855
2551
                return None
2856
2552
        while current_new or current_old:
2857
2553
            # skip entries in old that are not really there
2858
 
            if current_old and current_old[1][0][0] in (b'a', b'r'):
 
2554
            if current_old and current_old[1][0][0] in 'ar':
2859
2555
                # relocated or absent
2860
2556
                current_old = advance(old_iterator)
2861
2557
                continue
2867
2563
                new_entry_key = (new_dirname, new_basename, new_id)
2868
2564
                current_new_minikind = \
2869
2565
                    DirState._kind_to_minikind[current_new[1].kind]
2870
 
                if current_new_minikind == b't':
2871
 
                    fingerprint = current_new[1].reference_revision or b''
 
2566
                if current_new_minikind == 't':
 
2567
                    fingerprint = current_new[1].reference_revision or ''
2872
2568
                else:
2873
2569
                    # We normally only insert or remove records, or update
2874
2570
                    # them when it has significantly changed.  Then we want to
2875
2571
                    # erase its fingerprint.  Unaffected records should
2876
2572
                    # normally not be updated at all.
2877
 
                    fingerprint = b''
 
2573
                    fingerprint = ''
2878
2574
            else:
2879
2575
                # for safety disable variables
2880
2576
                new_path_utf8 = new_dirname = new_basename = new_id = \
2919
2615
                # both sides are dealt with, move on
2920
2616
                current_old = advance(old_iterator)
2921
2617
                current_new = advance(new_iterator)
2922
 
            elif (lt_by_dirs(new_dirname, current_old[0][0])
 
2618
            elif (cmp_by_dirs(new_dirname, current_old[0][0]) < 0
2923
2619
                  or (new_dirname == current_old[0][0]
2924
2620
                      and new_entry_key[1:] < current_old[0][1:])):
2925
2621
                # new comes before:
2941
2637
                        current_old[0][1].decode('utf8'))
2942
2638
                self._make_absent(current_old)
2943
2639
                current_old = advance(old_iterator)
2944
 
        self._mark_modified()
 
2640
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
2945
2641
        self._id_index = None
2946
2642
        self._packed_stat_index = None
2947
2643
        if tracing:
2948
2644
            trace.mutter("set_state_from_inventory complete.")
2949
2645
 
2950
 
    def set_state_from_scratch(self, working_inv, parent_trees, parent_ghosts):
2951
 
        """Wipe the currently stored state and set it to something new.
2952
 
 
2953
 
        This is a hard-reset for the data we are working with.
2954
 
        """
2955
 
        # Technically, we really want a write lock, but until we write, we
2956
 
        # don't really need it.
2957
 
        self._requires_lock()
2958
 
        # root dir and root dir contents with no children. We have to have a
2959
 
        # root for set_state_from_inventory to work correctly.
2960
 
        empty_root = ((b'', b'', inventory.ROOT_ID),
2961
 
                      [(b'd', b'', 0, False, DirState.NULLSTAT)])
2962
 
        empty_tree_dirblocks = [(b'', [empty_root]), (b'', [])]
2963
 
        self._set_data([], empty_tree_dirblocks)
2964
 
        self.set_state_from_inventory(working_inv)
2965
 
        self.set_parent_trees(parent_trees, parent_ghosts)
2966
 
 
2967
2646
    def _make_absent(self, current_old):
2968
2647
        """Mark current_old - an entry - as absent for tree 0.
2969
2648
 
2976
2655
        all_remaining_keys = set()
2977
2656
        # Dont check the working tree, because it's going.
2978
2657
        for details in current_old[1][1:]:
2979
 
            if details[0] not in (b'a', b'r'): # absent, relocated
 
2658
            if details[0] not in 'ar': # absent, relocated
2980
2659
                all_remaining_keys.add(current_old[0])
2981
 
            elif details[0] == b'r': # relocated
 
2660
            elif details[0] == 'r': # relocated
2982
2661
                # record the key for the real path.
2983
2662
                all_remaining_keys.add(tuple(osutils.split(details[1])) + (current_old[0][2],))
2984
2663
            # absent rows are not present at any path.
2994
2673
            block[1].pop(entry_index)
2995
2674
            # if we have an id_index in use, remove this key from it for this id.
2996
2675
            if self._id_index is not None:
2997
 
                self._remove_from_id_index(self._id_index, current_old[0])
 
2676
                self._id_index[current_old[0][2]].remove(current_old[0])
2998
2677
        # update all remaining keys for this id to record it as absent. The
2999
2678
        # existing details may either be the record we are marking as deleted
3000
2679
        # (if there were other trees with the id present at this path), or may
3010
2689
                raise AssertionError('could not find entry for %s' % (update_key,))
3011
2690
            update_tree_details = self._dirblocks[update_block_index][1][update_entry_index][1]
3012
2691
            # it must not be absent at the moment
3013
 
            if update_tree_details[0][0] == b'a': # absent
 
2692
            if update_tree_details[0][0] == 'a': # absent
3014
2693
                raise AssertionError('bad row %r' % (update_tree_details,))
3015
2694
            update_tree_details[0] = DirState.NULL_PARENT_DETAILS
3016
 
        self._mark_modified()
 
2695
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
3017
2696
        return last_reference
3018
2697
 
3019
 
    def update_minimal(self, key, minikind, executable=False, fingerprint=b'',
 
2698
    def update_minimal(self, key, minikind, executable=False, fingerprint='',
3020
2699
        packed_stat=None, size=0, path_utf8=None, fullscan=False):
3021
2700
        """Update an entry to the state in tree 0.
3022
2701
 
3025
2704
        updated as well.
3026
2705
 
3027
2706
        :param key: (dir, name, file_id) for the new entry
3028
 
        :param minikind: The type for the entry (b'f' == 'file', b'd' ==
 
2707
        :param minikind: The type for the entry ('f' == 'file', 'd' ==
3029
2708
                'directory'), etc.
3030
2709
        :param executable: Should the executable bit be set?
3031
2710
        :param fingerprint: Simple fingerprint for new entry: canonical-form
3044
2723
        block = self._find_block(key)[1]
3045
2724
        if packed_stat is None:
3046
2725
            packed_stat = DirState.NULLSTAT
3047
 
        # XXX: Some callers pass b'' as the packed_stat, and it seems to be
 
2726
        # XXX: Some callers pass '' as the packed_stat, and it seems to be
3048
2727
        # sometimes present in the dirstate - this seems oddly inconsistent.
3049
2728
        # mbp 20071008
3050
2729
        entry_index, present = self._find_entry_index(key, block)
3053
2732
        if not present:
3054
2733
            # New record. Check there isn't a entry at this path already.
3055
2734
            if not fullscan:
3056
 
                low_index, _ = self._find_entry_index(key[0:2] + (b'',), block)
 
2735
                low_index, _ = self._find_entry_index(key[0:2] + ('',), block)
3057
2736
                while low_index < len(block):
3058
2737
                    entry = block[low_index]
3059
2738
                    if entry[0][0:2] == key[0:2]:
3060
 
                        if entry[1][0][0] not in (b'a', b'r'):
 
2739
                        if entry[1][0][0] not in 'ar':
3061
2740
                            # This entry has the same path (but a different id) as
3062
2741
                            # the new entry we're adding, and is present in ths
3063
2742
                            # tree.
3064
 
                            self._raise_invalid(
3065
 
                                (b"%s/%s" % key[0:2]).decode('utf8'), key[2],
 
2743
                            raise errors.InconsistentDelta(
 
2744
                                ("%s/%s" % key[0:2]).decode('utf8'), key[2],
3066
2745
                                "Attempt to add item at path already occupied by "
3067
2746
                                "id %r" % entry[0][2])
3068
2747
                        low_index += 1
3069
2748
                    else:
3070
2749
                        break
3071
2750
            # new entry, synthesis cross reference here,
3072
 
            existing_keys = id_index.get(key[2], ())
 
2751
            existing_keys = id_index.setdefault(key[2], set())
3073
2752
            if not existing_keys:
3074
2753
                # not currently in the state, simplest case
3075
2754
                new_entry = key, [new_details] + self._empty_parent_info()
3105
2784
                    # entry, if not already examined, is skipped over by that
3106
2785
                    # loop.
3107
2786
                    other_entry = other_block[other_entry_index]
3108
 
                    other_entry[1][0] = (b'r', path_utf8, 0, False, b'')
3109
 
                    if self._maybe_remove_row(other_block, other_entry_index,
3110
 
                                              id_index):
3111
 
                        # If the row holding this was removed, we need to
3112
 
                        # recompute where this entry goes
3113
 
                        entry_index, _ = self._find_entry_index(key, block)
 
2787
                    other_entry[1][0] = ('r', path_utf8, 0, False, '')
 
2788
                    self._maybe_remove_row(other_block, other_entry_index,
 
2789
                        id_index)
3114
2790
 
3115
2791
                # This loop:
3116
2792
                # adds a tuple to the new details for each column
3118
2794
                #  - or by creating a new pointer to the right row inside that column
3119
2795
                num_present_parents = self._num_present_parents()
3120
2796
                if num_present_parents:
3121
 
                    # TODO: This re-evaluates the existing_keys set, do we need
3122
 
                    #       to do that ourselves?
3123
2797
                    other_key = list(existing_keys)[0]
3124
 
                for lookup_index in range(1, num_present_parents + 1):
 
2798
                for lookup_index in xrange(1, num_present_parents + 1):
3125
2799
                    # grab any one entry, use it to find the right path.
3126
2800
                    # TODO: optimise this to reduce memory use in highly
3127
2801
                    # fragmented situations by reusing the relocation
3135
2809
                    if not present:
3136
2810
                        raise AssertionError('update_minimal: could not find entry for %s' % (other_key,))
3137
2811
                    update_details = self._dirblocks[update_block_index][1][update_entry_index][1][lookup_index]
3138
 
                    if update_details[0] in (b'a', b'r'): # relocated, absent
 
2812
                    if update_details[0] in 'ar': # relocated, absent
3139
2813
                        # its a pointer or absent in lookup_index's tree, use
3140
2814
                        # it as is.
3141
2815
                        new_entry[1].append(update_details)
3142
2816
                    else:
3143
2817
                        # we have the right key, make a pointer to it.
3144
2818
                        pointer_path = osutils.pathjoin(*other_key[0:2])
3145
 
                        new_entry[1].append((b'r', pointer_path, 0, False, b''))
 
2819
                        new_entry[1].append(('r', pointer_path, 0, False, ''))
3146
2820
            block.insert(entry_index, new_entry)
3147
 
            self._add_to_id_index(id_index, key)
 
2821
            existing_keys.add(key)
3148
2822
        else:
3149
2823
            # Does the new state matter?
3150
2824
            block[entry_index][1][0] = new_details
3159
2833
            # converted to relocated.
3160
2834
            if path_utf8 is None:
3161
2835
                raise AssertionError('no path')
3162
 
            existing_keys = id_index.get(key[2], ())
3163
 
            if key not in existing_keys:
3164
 
                raise AssertionError('We found the entry in the blocks, but'
3165
 
                    ' the key is not in the id_index.'
3166
 
                    ' key: %s, existing_keys: %s' % (key, existing_keys))
3167
 
            for entry_key in existing_keys:
 
2836
            for entry_key in id_index.setdefault(key[2], set()):
3168
2837
                # TODO:PROFILING: It might be faster to just update
3169
2838
                # rather than checking if we need to, and then overwrite
3170
2839
                # the one we are located at.
3180
2849
                    if not present:
3181
2850
                        raise AssertionError('not present: %r', entry_key)
3182
2851
                    self._dirblocks[block_index][1][entry_index][1][0] = \
3183
 
                        (b'r', path_utf8, 0, False, b'')
 
2852
                        ('r', path_utf8, 0, False, '')
3184
2853
        # add a containing dirblock if needed.
3185
 
        if new_details[0] == b'd':
3186
 
            # GZ 2017-06-09: Using pathjoin why?
3187
 
            subdir_key = (osutils.pathjoin(*key[0:2]), b'', b'')
 
2854
        if new_details[0] == 'd':
 
2855
            subdir_key = (osutils.pathjoin(*key[0:2]), '', '')
3188
2856
            block_index, present = self._find_block_index_from_key(subdir_key)
3189
2857
            if not present:
3190
2858
                self._dirblocks.insert(block_index, (subdir_key[0], []))
3191
2859
 
3192
 
        self._mark_modified()
 
2860
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
3193
2861
 
3194
2862
    def _maybe_remove_row(self, block, index, id_index):
3195
2863
        """Remove index if it is absent or relocated across the row.
3196
2864
        
3197
2865
        id_index is updated accordingly.
3198
 
        :return: True if we removed the row, False otherwise
3199
2866
        """
3200
2867
        present_in_row = False
3201
2868
        entry = block[index]
3202
2869
        for column in entry[1]:
3203
 
            if column[0] not in (b'a', b'r'):
 
2870
            if column[0] not in 'ar':
3204
2871
                present_in_row = True
3205
2872
                break
3206
2873
        if not present_in_row:
3207
2874
            block.pop(index)
3208
 
            self._remove_from_id_index(id_index, entry[0])
3209
 
            return True
3210
 
        return False
 
2875
            id_index[entry[0][2]].remove(entry[0])
3211
2876
 
3212
2877
    def _validate(self):
3213
2878
        """Check that invariants on the dirblock are correct.
3220
2885
        # NOTE: This must always raise AssertionError not just assert,
3221
2886
        # otherwise it may not behave properly under python -O
3222
2887
        #
3223
 
        # TODO: All entries must have some content that's not b'a' or b'r',
 
2888
        # TODO: All entries must have some content that's not 'a' or 'r',
3224
2889
        # otherwise it could just be removed.
3225
2890
        #
3226
2891
        # TODO: All relocations must point directly to a real entry.
3231
2896
        from pprint import pformat
3232
2897
        self._read_dirblocks_if_needed()
3233
2898
        if len(self._dirblocks) > 0:
3234
 
            if not self._dirblocks[0][0] == b'':
 
2899
            if not self._dirblocks[0][0] == '':
3235
2900
                raise AssertionError(
3236
2901
                    "dirblocks don't start with root block:\n" + \
3237
2902
                    pformat(self._dirblocks))
3238
2903
        if len(self._dirblocks) > 1:
3239
 
            if not self._dirblocks[1][0] == b'':
 
2904
            if not self._dirblocks[1][0] == '':
3240
2905
                raise AssertionError(
3241
2906
                    "dirblocks missing root directory:\n" + \
3242
2907
                    pformat(self._dirblocks))
3243
2908
        # the dirblocks are sorted by their path components, name, and dir id
3244
 
        dir_names = [d[0].split(b'/')
 
2909
        dir_names = [d[0].split('/')
3245
2910
                for d in self._dirblocks[1:]]
3246
2911
        if dir_names != sorted(dir_names):
3247
2912
            raise AssertionError(
3271
2936
            current tree. (It is invalid to have a non-absent file in an absent
3272
2937
            directory.)
3273
2938
            """
3274
 
            if entry[0][0:2] == (b'', b''):
 
2939
            if entry[0][0:2] == ('', ''):
3275
2940
                # There should be no parent for the root row
3276
2941
                return
3277
2942
            parent_entry = self._get_entry(tree_index, path_utf8=entry[0][0])
3279
2944
                raise AssertionError(
3280
2945
                    "no parent entry for: %s in tree %s"
3281
2946
                    % (this_path, tree_index))
3282
 
            if parent_entry[1][tree_index][0] != b'd':
 
2947
            if parent_entry[1][tree_index][0] != 'd':
3283
2948
                raise AssertionError(
3284
2949
                    "Parent entry for %s is not marked as a valid"
3285
2950
                    " directory. %s" % (this_path, parent_entry,))
3293
2958
        # We check this with a dict per tree pointing either to the present
3294
2959
        # name, or None if absent.
3295
2960
        tree_count = self._num_present_parents() + 1
3296
 
        id_path_maps = [{} for _ in range(tree_count)]
 
2961
        id_path_maps = [dict() for i in range(tree_count)]
3297
2962
        # Make sure that all renamed entries point to the correct location.
3298
2963
        for entry in self._iter_entries():
3299
2964
            file_id = entry[0][2]
3307
2972
            for tree_index, tree_state in enumerate(entry[1]):
3308
2973
                this_tree_map = id_path_maps[tree_index]
3309
2974
                minikind = tree_state[0]
3310
 
                if minikind in (b'a', b'r'):
 
2975
                if minikind in 'ar':
3311
2976
                    absent_positions += 1
3312
2977
                # have we seen this id before in this column?
3313
2978
                if file_id in this_tree_map:
3314
2979
                    previous_path, previous_loc = this_tree_map[file_id]
3315
2980
                    # any later mention of this file must be consistent with
3316
2981
                    # what was said before
3317
 
                    if minikind == b'a':
 
2982
                    if minikind == 'a':
3318
2983
                        if previous_path is not None:
3319
2984
                            raise AssertionError(
3320
2985
                            "file %s is absent in row %r but also present " \
3321
2986
                            "at %r"% \
3322
 
                            (file_id.decode('utf-8'), entry, previous_path))
3323
 
                    elif minikind == b'r':
 
2987
                            (file_id, entry, previous_path))
 
2988
                    elif minikind == 'r':
3324
2989
                        target_location = tree_state[1]
3325
2990
                        if previous_path != target_location:
3326
2991
                            raise AssertionError(
3336
3001
                                (entry, previous_path, previous_loc))
3337
3002
                        check_valid_parent()
3338
3003
                else:
3339
 
                    if minikind == b'a':
 
3004
                    if minikind == 'a':
3340
3005
                        # absent; should not occur anywhere else
3341
3006
                        this_tree_map[file_id] = None, this_path
3342
 
                    elif minikind == b'r':
 
3007
                    elif minikind == 'r':
3343
3008
                        # relocation, must occur at expected location
3344
3009
                        this_tree_map[file_id] = tree_state[1], this_path
3345
3010
                    else:
3349
3014
                raise AssertionError(
3350
3015
                    "entry %r has no data for any tree." % (entry,))
3351
3016
        if self._id_index is not None:
3352
 
            for file_id, entry_keys in viewitems(self._id_index):
 
3017
            for file_id, entry_keys in self._id_index.iteritems():
3353
3018
                for entry_key in entry_keys:
3354
 
                    # Check that the entry in the map is pointing to the same
3355
 
                    # file_id
3356
3019
                    if entry_key[2] != file_id:
3357
3020
                        raise AssertionError(
3358
3021
                            'file_id %r did not match entry key %s'
3359
3022
                            % (file_id, entry_key))
3360
 
                    # And that from this entry key, we can look up the original
3361
 
                    # record
3362
 
                    block_index, present = self._find_block_index_from_key(entry_key)
3363
 
                    if not present:
3364
 
                        raise AssertionError('missing block for entry key: %r', entry_key)
3365
 
                    entry_index, present = self._find_entry_index(entry_key, self._dirblocks[block_index][1])
3366
 
                    if not present:
3367
 
                        raise AssertionError('missing entry for key: %r', entry_key)
3368
 
                if len(entry_keys) != len(set(entry_keys)):
3369
 
                    raise AssertionError(
3370
 
                        'id_index contained non-unique data for %s'
3371
 
                        % (entry_keys,))
3372
3023
 
3373
3024
    def _wipe_state(self):
3374
3025
        """Forget all state information about the dirstate."""
3396
3047
        self._lock_state = 'r'
3397
3048
        self._state_file = self._lock_token.f
3398
3049
        self._wipe_state()
3399
 
        return lock.LogicalLockResult(self.unlock)
3400
3050
 
3401
3051
    def lock_write(self):
3402
3052
        """Acquire a write lock on the dirstate."""
3410
3060
        self._lock_state = 'w'
3411
3061
        self._state_file = self._lock_token.f
3412
3062
        self._wipe_state()
3413
 
        return lock.LogicalLockResult(self.unlock, self._lock_token)
3414
3063
 
3415
3064
    def unlock(self):
3416
3065
        """Drop any locks held on the dirstate."""
3433
3082
 
3434
3083
 
3435
3084
def py_update_entry(state, entry, abspath, stat_value,
3436
 
                    _stat_to_minikind=DirState._stat_to_minikind):
 
3085
                 _stat_to_minikind=DirState._stat_to_minikind,
 
3086
                 _pack_stat=pack_stat):
3437
3087
    """Update the entry based on what is actually on disk.
3438
3088
 
3439
3089
    This function only calculates the sha if it needs to - if the entry is
3448
3098
        target of a symlink.
3449
3099
    """
3450
3100
    try:
3451
 
        minikind = _stat_to_minikind[stat_value.st_mode & 0o170000]
 
3101
        minikind = _stat_to_minikind[stat_value.st_mode & 0170000]
3452
3102
    except KeyError:
3453
3103
        # Unhandled kind
3454
3104
        return None
3455
 
    packed_stat = pack_stat(stat_value)
 
3105
    packed_stat = _pack_stat(stat_value)
3456
3106
    (saved_minikind, saved_link_or_sha1, saved_file_size,
3457
3107
     saved_executable, saved_packed_stat) = entry[1][0]
3458
 
    if not isinstance(saved_minikind, bytes):
3459
 
        raise TypeError(saved_minikind)
3460
3108
 
3461
 
    if minikind == b'd' and saved_minikind == b't':
3462
 
        minikind = b't'
 
3109
    if minikind == 'd' and saved_minikind == 't':
 
3110
        minikind = 't'
3463
3111
    if (minikind == saved_minikind
3464
3112
        and packed_stat == saved_packed_stat):
3465
3113
        # The stat hasn't changed since we saved, so we can re-use the
3466
3114
        # saved sha hash.
3467
 
        if minikind == b'd':
 
3115
        if minikind == 'd':
3468
3116
            return None
3469
3117
 
3470
3118
        # size should also be in packed_stat
3474
3122
    # If we have gotten this far, that means that we need to actually
3475
3123
    # process this entry.
3476
3124
    link_or_sha1 = None
3477
 
    worth_saving = True
3478
 
    if minikind == b'f':
 
3125
    if minikind == 'f':
3479
3126
        executable = state._is_executable(stat_value.st_mode,
3480
3127
                                         saved_executable)
3481
3128
        if state._cutoff_time is None:
3483
3130
        if (stat_value.st_mtime < state._cutoff_time
3484
3131
            and stat_value.st_ctime < state._cutoff_time
3485
3132
            and len(entry[1]) > 1
3486
 
            and entry[1][1][0] != b'a'):
 
3133
            and entry[1][1][0] != 'a'):
3487
3134
            # Could check for size changes for further optimised
3488
3135
            # avoidance of sha1's. However the most prominent case of
3489
3136
            # over-shaing is during initial add, which this catches.
3491
3138
            # are calculated at the same time, so checking just the size
3492
3139
            # gains nothing w.r.t. performance.
3493
3140
            link_or_sha1 = state._sha1_file(abspath)
3494
 
            entry[1][0] = (b'f', link_or_sha1, stat_value.st_size,
 
3141
            entry[1][0] = ('f', link_or_sha1, stat_value.st_size,
3495
3142
                           executable, packed_stat)
3496
3143
        else:
3497
 
            entry[1][0] = (b'f', b'', stat_value.st_size,
 
3144
            entry[1][0] = ('f', '', stat_value.st_size,
3498
3145
                           executable, DirState.NULLSTAT)
3499
 
            worth_saving = False
3500
 
    elif minikind == b'd':
 
3146
    elif minikind == 'd':
3501
3147
        link_or_sha1 = None
3502
 
        entry[1][0] = (b'd', b'', 0, False, packed_stat)
3503
 
        if saved_minikind != b'd':
 
3148
        entry[1][0] = ('d', '', 0, False, packed_stat)
 
3149
        if saved_minikind != 'd':
3504
3150
            # This changed from something into a directory. Make sure we
3505
3151
            # have a directory block for it. This doesn't happen very
3506
3152
            # often, so this doesn't have to be super fast.
3508
3154
                state._get_block_entry_index(entry[0][0], entry[0][1], 0)
3509
3155
            state._ensure_block(block_index, entry_index,
3510
3156
                               osutils.pathjoin(entry[0][0], entry[0][1]))
3511
 
        else:
3512
 
            worth_saving = False
3513
 
    elif minikind == b'l':
3514
 
        if saved_minikind == b'l':
3515
 
            worth_saving = False
 
3157
    elif minikind == 'l':
3516
3158
        link_or_sha1 = state._read_link(abspath, saved_link_or_sha1)
3517
3159
        if state._cutoff_time is None:
3518
3160
            state._sha_cutoff_time()
3519
3161
        if (stat_value.st_mtime < state._cutoff_time
3520
3162
            and stat_value.st_ctime < state._cutoff_time):
3521
 
            entry[1][0] = (b'l', link_or_sha1, stat_value.st_size,
 
3163
            entry[1][0] = ('l', link_or_sha1, stat_value.st_size,
3522
3164
                           False, packed_stat)
3523
3165
        else:
3524
 
            entry[1][0] = (b'l', b'', stat_value.st_size,
 
3166
            entry[1][0] = ('l', '', stat_value.st_size,
3525
3167
                           False, DirState.NULLSTAT)
3526
 
    if worth_saving:
3527
 
        state._mark_modified([entry])
 
3168
    state._dirblock_state = DirState.IN_MEMORY_MODIFIED
3528
3169
    return link_or_sha1
3529
3170
 
3530
3171
 
3543
3184
        self.old_dirname_to_file_id = {}
3544
3185
        self.new_dirname_to_file_id = {}
3545
3186
        # Are we doing a partial iter_changes?
3546
 
        self.partial = search_specific_files != {''}
 
3187
        self.partial = search_specific_files != set([''])
3547
3188
        # Using a list so that we can access the values and change them in
3548
3189
        # nested scope. Each one is [path, file_id, entry]
3549
3190
        self.last_source_parent = [None, None]
3595
3236
            source_details = DirState.NULL_PARENT_DETAILS
3596
3237
        else:
3597
3238
            source_details = entry[1][self.source_index]
3598
 
        # GZ 2017-06-09: Eck, more sets.
3599
 
        _fdltr = {b'f', b'd', b'l', b't', b'r'}
3600
 
        _fdlt = {b'f', b'd', b'l', b't'}
3601
 
        _ra = (b'r', b'a')
3602
3239
        target_details = entry[1][self.target_index]
3603
3240
        target_minikind = target_details[0]
3604
 
        if path_info is not None and target_minikind in _fdlt:
 
3241
        if path_info is not None and target_minikind in 'fdlt':
3605
3242
            if not (self.target_index == 0):
3606
3243
                raise AssertionError()
3607
3244
            link_or_sha1 = update_entry(self.state, entry,
3613
3250
            link_or_sha1 = None
3614
3251
        file_id = entry[0][2]
3615
3252
        source_minikind = source_details[0]
3616
 
        if source_minikind in _fdltr and target_minikind in _fdlt:
 
3253
        if source_minikind in 'fdltr' and target_minikind in 'fdlt':
3617
3254
            # claimed content in both: diff
3618
3255
            #   r    | fdlt   |      | add source to search, add id path move and perform
3619
3256
            #        |        |      | diff check on source-target
3620
3257
            #   r    | fdlt   |  a   | dangling file that was present in the basis.
3621
3258
            #        |        |      | ???
3622
 
            if source_minikind == b'r':
 
3259
            if source_minikind in 'r':
3623
3260
                # add the source to the search path to find any children it
3624
3261
                # has.  TODO ? : only add if it is a container ?
3625
 
                if not is_inside_any(self.searched_specific_files,
 
3262
                if not osutils.is_inside_any(self.searched_specific_files,
3626
3263
                                             source_details[1]):
3627
3264
                    self.search_specific_files.add(source_details[1])
3628
3265
                # generate the old path; this is needed for stating later
3635
3272
                # update the source details variable to be the real
3636
3273
                # location.
3637
3274
                if old_entry == (None, None):
3638
 
                    raise DirstateCorrupt(self.state._filename,
 
3275
                    raise errors.CorruptDirstate(self.state._filename,
3639
3276
                        "entry '%s/%s' is considered renamed from %r"
3640
3277
                        " but source does not exist\n"
3641
3278
                        "entry: %s" % (entry[0][0], entry[0][1], old_path, entry))
3657
3294
                    if path is None:
3658
3295
                        old_path = path = pathjoin(old_dirname, old_basename)
3659
3296
                    self.new_dirname_to_file_id[path] = file_id
3660
 
                    if source_minikind != b'd':
 
3297
                    if source_minikind != 'd':
3661
3298
                        content_change = True
3662
3299
                    else:
3663
3300
                        # directories have no fingerprint
3664
3301
                        content_change = False
3665
3302
                    target_exec = False
3666
3303
                elif target_kind == 'file':
3667
 
                    if source_minikind != b'f':
 
3304
                    if source_minikind != 'f':
3668
3305
                        content_change = True
3669
3306
                    else:
3670
3307
                        # Check the sha. We can't just rely on the size as
3686
3323
                    else:
3687
3324
                        target_exec = target_details[3]
3688
3325
                elif target_kind == 'symlink':
3689
 
                    if source_minikind != b'l':
 
3326
                    if source_minikind != 'l':
3690
3327
                        content_change = True
3691
3328
                    else:
3692
3329
                        content_change = (link_or_sha1 != source_details[1])
3693
3330
                    target_exec = False
3694
3331
                elif target_kind == 'tree-reference':
3695
 
                    if source_minikind != b't':
 
3332
                    if source_minikind != 't':
3696
3333
                        content_change = True
3697
3334
                    else:
3698
3335
                        content_change = False
3701
3338
                    if path is None:
3702
3339
                        path = pathjoin(old_dirname, old_basename)
3703
3340
                    raise errors.BadFileKindError(path, path_info[2])
3704
 
            if source_minikind == b'd':
 
3341
            if source_minikind == 'd':
3705
3342
                if path is None:
3706
3343
                    old_path = path = pathjoin(old_dirname, old_basename)
3707
3344
                self.old_dirname_to_file_id[old_path] = file_id
3772
3409
                       (self.utf8_decode(old_basename)[0], self.utf8_decode(entry[0][1])[0]),
3773
3410
                       (source_kind, target_kind),
3774
3411
                       (source_exec, target_exec)), changed
3775
 
        elif source_minikind in b'a' and target_minikind in _fdlt:
 
3412
        elif source_minikind in 'a' and target_minikind in 'fdlt':
3776
3413
            # looks like a new file
3777
3414
            path = pathjoin(entry[0][0], entry[0][1])
3778
3415
            # parent id is the entry for the path in the target tree
3809
3446
                       (None, self.utf8_decode(entry[0][1])[0]),
3810
3447
                       (None, None),
3811
3448
                       (None, False)), True
3812
 
        elif source_minikind in _fdlt and target_minikind in b'a':
 
3449
        elif source_minikind in 'fdlt' and target_minikind in 'a':
3813
3450
            # unversioned, possibly, or possibly not deleted: we dont care.
3814
3451
            # if its still on disk, *and* theres no other entry at this
3815
3452
            # path [we dont know this in this routine at the moment -
3827
3464
                   (self.utf8_decode(entry[0][1])[0], None),
3828
3465
                   (DirState._minikind_to_kind[source_minikind], None),
3829
3466
                   (source_details[3], None)), True
3830
 
        elif source_minikind in _fdlt and target_minikind in b'r':
 
3467
        elif source_minikind in 'fdlt' and target_minikind in 'r':
3831
3468
            # a rename; could be a true rename, or a rename inherited from
3832
3469
            # a renamed parent. TODO: handle this efficiently. Its not
3833
3470
            # common case to rename dirs though, so a correct but slow
3834
3471
            # implementation will do.
3835
 
            if not is_inside_any(self.searched_specific_files, target_details[1]):
 
3472
            if not osutils.is_inside_any(self.searched_specific_files, target_details[1]):
3836
3473
                self.search_specific_files.add(target_details[1])
3837
 
        elif source_minikind in _ra and target_minikind in _ra:
 
3474
        elif source_minikind in 'ra' and target_minikind in 'ra':
3838
3475
            # neither of the selected trees contain this file,
3839
3476
            # so skip over it. This is not currently directly tested, but
3840
3477
            # is indirectly via test_too_much.TestCommands.test_conflicts.
3843
3480
            raise AssertionError("don't know how to compare "
3844
3481
                "source_minikind=%r, target_minikind=%r"
3845
3482
                % (source_minikind, target_minikind))
 
3483
            ## import pdb;pdb.set_trace()
3846
3484
        return None, None
3847
3485
 
3848
3486
    def __iter__(self):
3862
3500
        if new_path:
3863
3501
            # Not the root and not a delete: queue up the parents of the path.
3864
3502
            self.search_specific_file_parents.update(
3865
 
                p.encode('utf8') for p in osutils.parent_directories(new_path))
 
3503
                osutils.parent_directories(new_path.encode('utf8')))
3866
3504
            # Add the root directory which parent_directories does not
3867
3505
            # provide.
3868
 
            self.search_specific_file_parents.add(b'')
 
3506
            self.search_specific_file_parents.add('')
3869
3507
 
3870
3508
    def iter_changes(self):
3871
3509
        """Iterate over the changes."""
3872
3510
        utf8_decode = cache_utf8._utf8_decode
3873
 
        _lt_by_dirs = lt_by_dirs
 
3511
        _cmp_by_dirs = cmp_by_dirs
3874
3512
        _process_entry = self._process_entry
3875
3513
        search_specific_files = self.search_specific_files
3876
3514
        searched_specific_files = self.searched_specific_files
3925
3563
            root_abspath = self.tree.abspath(current_root_unicode)
3926
3564
            try:
3927
3565
                root_stat = os.lstat(root_abspath)
3928
 
            except OSError as e:
 
3566
            except OSError, e:
3929
3567
                if e.errno == errno.ENOENT:
3930
3568
                    # the path does not exist: let _process_entry know that.
3931
3569
                    root_dir_info = None
3933
3571
                    # some other random error: hand it up.
3934
3572
                    raise
3935
3573
            else:
3936
 
                root_dir_info = (b'', current_root,
 
3574
                root_dir_info = ('', current_root,
3937
3575
                    osutils.file_kind_from_stat_mode(root_stat.st_mode), root_stat,
3938
3576
                    root_abspath)
3939
3577
                if root_dir_info[2] == 'directory':
3967
3605
                       (None, root_dir_info[2]),
3968
3606
                       (None, new_executable)
3969
3607
                      )
3970
 
            initial_key = (current_root, b'', b'')
 
3608
            initial_key = (current_root, '', '')
3971
3609
            block_index, _ = self.state._find_block_index_from_key(initial_key)
3972
3610
            if block_index == 0:
3973
3611
                # we have processed the total root already, but because the
3978
3616
            else:
3979
3617
                dir_iterator = osutils._walkdirs_utf8(root_abspath, prefix=current_root)
3980
3618
                try:
3981
 
                    current_dir_info = next(dir_iterator)
3982
 
                except OSError as e:
 
3619
                    current_dir_info = dir_iterator.next()
 
3620
                except OSError, e:
3983
3621
                    # on win32, python2.4 has e.errno == ERROR_DIRECTORY, but
3984
3622
                    # python 2.5 has e.errno == EINVAL,
3985
3623
                    #            and e.winerror == ERROR_DIRECTORY
3997
3635
                    else:
3998
3636
                        raise
3999
3637
                else:
4000
 
                    if current_dir_info[0][0] == b'':
 
3638
                    if current_dir_info[0][0] == '':
4001
3639
                        # remove .bzr from iteration
4002
 
                        bzr_index = bisect.bisect_left(current_dir_info[1], (b'.bzr',))
4003
 
                        if current_dir_info[1][bzr_index][0] != b'.bzr':
 
3640
                        bzr_index = bisect.bisect_left(current_dir_info[1], ('.bzr',))
 
3641
                        if current_dir_info[1][bzr_index][0] != '.bzr':
4004
3642
                            raise AssertionError()
4005
3643
                        del current_dir_info[1][bzr_index]
4006
3644
            # walk until both the directory listing and the versioned metadata
4007
3645
            # are exhausted.
4008
3646
            if (block_index < len(self.state._dirblocks) and
4009
 
                is_inside(current_root, self.state._dirblocks[block_index][0])):
 
3647
                osutils.is_inside(current_root, self.state._dirblocks[block_index][0])):
4010
3648
                current_block = self.state._dirblocks[block_index]
4011
3649
            else:
4012
3650
                current_block = None
4014
3652
                   current_block is not None):
4015
3653
                if (current_dir_info and current_block
4016
3654
                    and current_dir_info[0][0] != current_block[0]):
4017
 
                    if _lt_by_dirs(current_dir_info[0][0], current_block[0]):
 
3655
                    if _cmp_by_dirs(current_dir_info[0][0], current_block[0]) < 0:
4018
3656
                        # filesystem data refers to paths not covered by the dirblock.
4019
3657
                        # this has two possibilities:
4020
3658
                        # A) it is versioned but empty, so there is no block for it
4054
3692
 
4055
3693
                        # This dir info has been handled, go to the next
4056
3694
                        try:
4057
 
                            current_dir_info = next(dir_iterator)
 
3695
                            current_dir_info = dir_iterator.next()
4058
3696
                        except StopIteration:
4059
3697
                            current_dir_info = None
4060
3698
                    else:
4076
3714
                                    yield result
4077
3715
                        block_index +=1
4078
3716
                        if (block_index < len(self.state._dirblocks) and
4079
 
                            is_inside(current_root,
 
3717
                            osutils.is_inside(current_root,
4080
3718
                                              self.state._dirblocks[block_index][0])):
4081
3719
                            current_block = self.state._dirblocks[block_index]
4082
3720
                        else:
4115
3753
                            if changed or self.include_unchanged:
4116
3754
                                yield result
4117
3755
                    elif (current_entry[0][1] != current_path_info[1]
4118
 
                          or current_entry[1][self.target_index][0] in (b'a', b'r')):
 
3756
                          or current_entry[1][self.target_index][0] in 'ar'):
4119
3757
                        # The current path on disk doesn't match the dirblock
4120
3758
                        # record. Either the dirblock is marked as absent, or
4121
3759
                        # the file on disk is not present at all in the
4200
3838
                if current_block is not None:
4201
3839
                    block_index += 1
4202
3840
                    if (block_index < len(self.state._dirblocks) and
4203
 
                        is_inside(current_root, self.state._dirblocks[block_index][0])):
 
3841
                        osutils.is_inside(current_root, self.state._dirblocks[block_index][0])):
4204
3842
                        current_block = self.state._dirblocks[block_index]
4205
3843
                    else:
4206
3844
                        current_block = None
4207
3845
                if current_dir_info is not None:
4208
3846
                    try:
4209
 
                        current_dir_info = next(dir_iterator)
 
3847
                        current_dir_info = dir_iterator.next()
4210
3848
                    except StopIteration:
4211
3849
                        current_dir_info = None
4212
3850
        for result in self._iter_specific_file_parents():
4219
3857
            # Even in extremely large trees this should be modest, so currently
4220
3858
            # no attempt is made to optimise.
4221
3859
            path_utf8 = self.search_specific_file_parents.pop()
4222
 
            if is_inside_any(self.searched_specific_files, path_utf8):
 
3860
            if osutils.is_inside_any(self.searched_specific_files, path_utf8):
4223
3861
                # We've examined this path.
4224
3862
                continue
4225
3863
            if path_utf8 in self.searched_exact_paths:
4234
3872
            found_item = False
4235
3873
            for candidate_entry in path_entries:
4236
3874
                # Find entries present in target at this path:
4237
 
                if candidate_entry[1][self.target_index][0] not in (b'a', b'r'):
 
3875
                if candidate_entry[1][self.target_index][0] not in 'ar':
4238
3876
                    found_item = True
4239
3877
                    selected_entries.append(candidate_entry)
4240
3878
                # Find entries present in source at this path:
4241
3879
                elif (self.source_index is not None and
4242
 
                    candidate_entry[1][self.source_index][0] not in (b'a', b'r')):
 
3880
                    candidate_entry[1][self.source_index][0] not in 'ar'):
4243
3881
                    found_item = True
4244
 
                    if candidate_entry[1][self.target_index][0] == b'a':
 
3882
                    if candidate_entry[1][self.target_index][0] == 'a':
4245
3883
                        # Deleted, emit it here.
4246
3884
                        selected_entries.append(candidate_entry)
4247
3885
                    else:
4271
3909
                        result[6][1] != 'directory'):
4272
3910
                        # This stopped being a directory, the old children have
4273
3911
                        # to be included.
4274
 
                        if entry[1][self.source_index][0] == b'r':
 
3912
                        if entry[1][self.source_index][0] == 'r':
4275
3913
                            # renamed, take the source path
4276
3914
                            entry_path_utf8 = entry[1][self.source_index][1]
4277
3915
                        else:
4278
3916
                            entry_path_utf8 = path_utf8
4279
 
                        initial_key = (entry_path_utf8, b'', b'')
 
3917
                        initial_key = (entry_path_utf8, '', '')
4280
3918
                        block_index, _ = self.state._find_block_index_from_key(
4281
3919
                            initial_key)
4282
3920
                        if block_index == 0:
4285
3923
                        current_block = None
4286
3924
                        if block_index < len(self.state._dirblocks):
4287
3925
                            current_block = self.state._dirblocks[block_index]
4288
 
                            if not is_inside(
 
3926
                            if not osutils.is_inside(
4289
3927
                                entry_path_utf8, current_block[0]):
4290
3928
                                # No entries for this directory at all.
4291
3929
                                current_block = None
4292
3930
                        if current_block is not None:
4293
3931
                            for entry in current_block[1]:
4294
 
                                if entry[1][self.source_index][0] in (b'a', b'r'):
 
3932
                                if entry[1][self.source_index][0] in 'ar':
4295
3933
                                    # Not in the source tree, so doesn't have to be
4296
3934
                                    # included.
4297
3935
                                    continue
4311
3949
        abspath = self.tree.abspath(unicode_path)
4312
3950
        try:
4313
3951
            stat = os.lstat(abspath)
4314
 
        except OSError as e:
 
3952
        except OSError, e:
4315
3953
            if e.errno == errno.ENOENT:
4316
3954
                # the path does not exist.
4317
3955
                return None
4318
3956
            else:
4319
3957
                raise
4320
 
        utf8_basename = utf8_path.rsplit(b'/', 1)[-1]
 
3958
        utf8_basename = utf8_path.rsplit('/', 1)[-1]
4321
3959
        dir_info = (utf8_path, utf8_basename,
4322
3960
            osutils.file_kind_from_stat_mode(stat.st_mode), stat,
4323
3961
            abspath)
4331
3969
 
4332
3970
# Try to load the compiled form if possible
4333
3971
try:
4334
 
    from ._dirstate_helpers_pyx import (
 
3972
    from bzrlib._dirstate_helpers_pyx import (
4335
3973
        _read_dirblocks,
4336
3974
        bisect_dirblock,
4337
3975
        _bisect_path_left,
4338
3976
        _bisect_path_right,
4339
 
        lt_by_dirs,
4340
 
        pack_stat,
 
3977
        cmp_by_dirs,
4341
3978
        ProcessEntryC as _process_entry,
4342
3979
        update_entry as update_entry,
4343
3980
        )
4344
 
except ImportError as e:
 
3981
except ImportError, e:
4345
3982
    osutils.failed_to_load_extension(e)
4346
 
    from ._dirstate_helpers_py import (
 
3983
    from bzrlib._dirstate_helpers_py import (
4347
3984
        _read_dirblocks,
4348
3985
        bisect_dirblock,
4349
3986
        _bisect_path_left,
4350
3987
        _bisect_path_right,
4351
 
        lt_by_dirs,
4352
 
        pack_stat,
 
3988
        cmp_by_dirs,
4353
3989
        )
4354
3990
    # FIXME: It would be nice to be able to track moved lines so that the
4355
3991
    # corresponding python code can be moved to the _dirstate_helpers_py