/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]: ''
82
 
    entries[0][1]: ''
83
 
    entries[0][2]: file_id
84
 
    entries[1][0]: The tree data for the current tree for this fileid at /
85
 
    etc.
86
 
 
87
 
Kinds::
88
 
 
89
 
    'r' is a relocated entry: This path is not present in this tree with this
90
 
        id, but the id can be found at another location. The fingerprint is
91
 
        used to point to the target location.
92
 
    'a' is an absent entry: In that tree the id is not present at this path.
93
 
    'd' is a directory entry: This path in this tree is a directory with the
94
 
        current file id. There is no fingerprint for directories.
95
 
    'f' is a file entry: As for directory, but it's a file. The fingerprint is
96
 
        the sha1 value of the file's canonical form, i.e. after any read
97
 
        filters have been applied to the convenience form stored in the working
98
 
        tree.
99
 
    'l' is a symlink entry: As for directory, but a symlink. The fingerprint is
100
 
        the link target.
101
 
    't' is a reference to a nested subtree; the fingerprint is the referenced
102
 
        revision.
 
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
 
324
322
    """
325
323
 
326
324
    _kind_to_minikind = {
327
 
            'absent': b'a',
328
 
            'file': b'f',
329
 
            'directory': b'd',
330
 
            'relocated': b'r',
331
 
            'symlink': b'l',
332
 
            'tree-reference': b't',
 
325
            'absent': 'a',
 
326
            'file': 'f',
 
327
            'directory': 'd',
 
328
            'relocated': 'r',
 
329
            'symlink': 'l',
 
330
            'tree-reference': 't',
333
331
        }
334
332
    _minikind_to_kind = {
335
 
            b'a': 'absent',
336
 
            b'f': 'file',
337
 
            b'd': 'directory',
338
 
            b'l': 'symlink',
339
 
            b'r': 'relocated',
340
 
            b't': 'tree-reference',
 
333
            'a': 'absent',
 
334
            'f': 'file',
 
335
            'd': 'directory',
 
336
            'l':'symlink',
 
337
            'r': 'relocated',
 
338
            't': 'tree-reference',
341
339
        }
342
340
    _stat_to_minikind = {
343
 
        stat.S_IFDIR: b'd',
344
 
        stat.S_IFREG: b'f',
345
 
        stat.S_IFLNK: b'l',
 
341
        stat.S_IFDIR:'d',
 
342
        stat.S_IFREG:'f',
 
343
        stat.S_IFLNK:'l',
346
344
    }
347
 
    _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
348
346
     # of using int conversion rather than a dict here. AND BLAME ANDREW IF
349
347
     # it is faster.
350
348
 
356
354
    NOT_IN_MEMORY = 0
357
355
    IN_MEMORY_UNMODIFIED = 1
358
356
    IN_MEMORY_MODIFIED = 2
359
 
    IN_MEMORY_HASH_MODIFIED = 3 # Only hash-cache updates
360
357
 
361
358
    # A pack_stat (the x's) that is just noise and will never match the output
362
359
    # of base64 encode.
363
 
    NULLSTAT = b'x' * 32
364
 
    NULL_PARENT_DETAILS = static_tuple.StaticTuple(b'a', b'', 0, False, b'')
365
 
 
366
 
    HEADER_FORMAT_2 = b'#bazaar dirstate flat format 2\n'
367
 
    HEADER_FORMAT_3 = b'#bazaar dirstate flat format 3\n'
368
 
 
369
 
    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):
370
367
        """Create a  DirState object.
371
368
 
372
369
        :param path: The path at which the dirstate file on disk should live.
373
370
        :param sha1_provider: an object meeting the SHA1Provider interface.
374
 
        :param worth_saving_limit: when the exact number of hash changed
375
 
            entries is known, only bother saving the dirstate if more than
376
 
            this count of entries have changed.
377
 
            -1 means never save hash changes, 0 means always save hash changes.
378
371
        """
379
372
        # _header_state and _dirblock_state represent the current state
380
373
        # of the dirstate metadata and the per-row data respectiely.
417
410
        # during commit.
418
411
        self._last_block_index = None
419
412
        self._last_entry_index = None
420
 
        # The set of known hash changes
421
 
        self._known_hash_changes = set()
422
 
        # How many hash changed entries can we have without saving
423
 
        self._worth_saving_limit = worth_saving_limit
424
 
        self._config_stack = config.LocationStack(urlutils.local_path_to_url(
425
 
            path))
426
413
 
427
414
    def __repr__(self):
428
415
        return "%s(%r)" % \
429
416
            (self.__class__.__name__, self._filename)
430
417
 
431
 
    def _mark_modified(self, hash_changed_entries=None, header_modified=False):
432
 
        """Mark this dirstate as modified.
433
 
 
434
 
        :param hash_changed_entries: if non-None, mark just these entries as
435
 
            having their hash modified.
436
 
        :param header_modified: mark the header modified as well, not just the
437
 
            dirblocks.
438
 
        """
439
 
        #trace.mutter_callsite(3, "modified hash entries: %s", hash_changed_entries)
440
 
        if hash_changed_entries:
441
 
            self._known_hash_changes.update([e[0] for e in hash_changed_entries])
442
 
            if self._dirblock_state in (DirState.NOT_IN_MEMORY,
443
 
                                        DirState.IN_MEMORY_UNMODIFIED):
444
 
                # If the dirstate is already marked a IN_MEMORY_MODIFIED, then
445
 
                # that takes precedence.
446
 
                self._dirblock_state = DirState.IN_MEMORY_HASH_MODIFIED
447
 
        else:
448
 
            # TODO: Since we now have a IN_MEMORY_HASH_MODIFIED state, we
449
 
            #       should fail noisily if someone tries to set
450
 
            #       IN_MEMORY_MODIFIED but we don't have a write-lock!
451
 
            # We don't know exactly what changed so disable smart saving
452
 
            self._dirblock_state = DirState.IN_MEMORY_MODIFIED
453
 
        if header_modified:
454
 
            self._header_state = DirState.IN_MEMORY_MODIFIED
455
 
 
456
 
    def _mark_unmodified(self):
457
 
        """Mark this dirstate as unmodified."""
458
 
        self._header_state = DirState.IN_MEMORY_UNMODIFIED
459
 
        self._dirblock_state = DirState.IN_MEMORY_UNMODIFIED
460
 
        self._known_hash_changes = set()
461
 
 
462
418
    def add(self, path, file_id, kind, stat, fingerprint):
463
419
        """Add a path to be tracked.
464
420
 
501
457
        utf8path = (dirname + '/' + basename).strip('/').encode('utf8')
502
458
        dirname, basename = osutils.split(utf8path)
503
459
        # uses __class__ for speed; the check is needed for safety
504
 
        if file_id.__class__ is not bytes:
 
460
        if file_id.__class__ is not str:
505
461
            raise AssertionError(
506
462
                "must be a utf8 file_id not %s" % (type(file_id), ))
507
463
        # Make sure the file_id does not exist in this tree
508
464
        rename_from = None
509
465
        file_id_entry = self._get_entry(0, fileid_utf8=file_id, include_deleted=True)
510
466
        if file_id_entry != (None, None):
511
 
            if file_id_entry[1][0][0] == b'a':
 
467
            if file_id_entry[1][0][0] == 'a':
512
468
                if file_id_entry[0] != (dirname, basename, file_id):
513
469
                    # set the old name's current operation to rename
514
470
                    self.update_minimal(file_id_entry[0],
531
487
            entry_index, _ = self._find_entry_index(first_key, block)
532
488
            while (entry_index < len(block) and
533
489
                block[entry_index][0][0:2] == first_key[0:2]):
534
 
                if block[entry_index][1][0][0] not in (b'a', b'r'):
 
490
                if block[entry_index][1][0][0] not in 'ar':
535
491
                    # this path is in the dirstate in the current tree.
536
 
                    raise Exception("adding already added path!")
 
492
                    raise Exception, "adding already added path!"
537
493
                entry_index += 1
538
494
        else:
539
495
            # The block where we want to put the file is not present. But it
560
516
                old_path_utf8 = '%s/%s' % rename_from
561
517
            else:
562
518
                old_path_utf8 = rename_from[1]
563
 
            parent_info[0] = (b'r', old_path_utf8, 0, False, b'')
 
519
            parent_info[0] = ('r', old_path_utf8, 0, False, '')
564
520
        if kind == 'file':
565
521
            entry_data = entry_key, [
566
522
                (minikind, fingerprint, size, False, packed_stat),
567
523
                ] + parent_info
568
524
        elif kind == 'directory':
569
525
            entry_data = entry_key, [
570
 
                (minikind, b'', 0, False, packed_stat),
 
526
                (minikind, '', 0, False, packed_stat),
571
527
                ] + parent_info
572
528
        elif kind == 'symlink':
573
529
            entry_data = entry_key, [
583
539
        if not present:
584
540
            block.insert(entry_index, entry_data)
585
541
        else:
586
 
            if block[entry_index][1][0][0] != b'a':
 
542
            if block[entry_index][1][0][0] != 'a':
587
543
                raise AssertionError(" %r(%r) already added" % (basename, file_id))
588
544
            block[entry_index][1][0] = entry_data[1][0]
589
545
 
590
546
        if kind == 'directory':
591
547
           # insert a new dirblock
592
548
           self._ensure_block(block_index, entry_index, utf8path)
593
 
        self._mark_modified()
 
549
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
594
550
        if self._id_index:
595
 
            self._add_to_id_index(self._id_index, entry_key)
 
551
            self._id_index.setdefault(entry_key[2], set()).add(entry_key)
596
552
 
597
553
    def _bisect(self, paths):
598
554
        """Bisect through the disk structure for specific rows.
662
618
            block = state_file.read(read_size)
663
619
 
664
620
            start = mid
665
 
            entries = block.split(b'\n')
 
621
            entries = block.split('\n')
666
622
 
667
623
            if len(entries) < 2:
668
624
                # We didn't find a '\n', so we cannot have found any records.
676
632
            # Check the first and last entries, in case they are partial, or if
677
633
            # we don't care about the rest of this page
678
634
            first_entry_num = 0
679
 
            first_fields = entries[0].split(b'\0')
 
635
            first_fields = entries[0].split('\0')
680
636
            if len(first_fields) < entry_field_count:
681
637
                # We didn't get the complete first entry
682
638
                # so move start, and grab the next, which
683
639
                # should be a full entry
684
640
                start += len(entries[0])+1
685
 
                first_fields = entries[1].split(b'\0')
 
641
                first_fields = entries[1].split('\0')
686
642
                first_entry_num = 1
687
643
 
688
644
            if len(first_fields) <= 2:
696
652
                # after this first record.
697
653
                after = start
698
654
                if first_fields[1]:
699
 
                    first_path = first_fields[1] + b'/' + first_fields[2]
 
655
                    first_path = first_fields[1] + '/' + first_fields[2]
700
656
                else:
701
657
                    first_path = first_fields[2]
702
658
                first_loc = _bisect_path_left(cur_files, first_path)
712
668
 
713
669
                # Parse the last entry
714
670
                last_entry_num = len(entries)-1
715
 
                last_fields = entries[last_entry_num].split(b'\0')
 
671
                last_fields = entries[last_entry_num].split('\0')
716
672
                if len(last_fields) < entry_field_count:
717
673
                    # The very last hunk was not complete,
718
674
                    # read the previous hunk
719
675
                    after = mid + len(block) - len(entries[-1])
720
676
                    last_entry_num -= 1
721
 
                    last_fields = entries[last_entry_num].split(b'\0')
 
677
                    last_fields = entries[last_entry_num].split('\0')
722
678
                else:
723
679
                    after = mid + len(block)
724
680
 
725
681
                if last_fields[1]:
726
 
                    last_path = last_fields[1] + b'/' + last_fields[2]
 
682
                    last_path = last_fields[1] + '/' + last_fields[2]
727
683
                else:
728
684
                    last_path = last_fields[2]
729
685
                last_loc = _bisect_path_right(post, last_path)
749
705
                    # careful if we should append rather than overwrite
750
706
                    if last_entry_num != first_entry_num:
751
707
                        paths.setdefault(last_path, []).append(last_fields)
752
 
                    for num in range(first_entry_num+1, last_entry_num):
 
708
                    for num in xrange(first_entry_num+1, last_entry_num):
753
709
                        # TODO: jam 20070223 We are already splitting here, so
754
710
                        #       shouldn't we just split the whole thing rather
755
711
                        #       than doing the split again in add_one_record?
756
 
                        fields = entries[num].split(b'\0')
 
712
                        fields = entries[num].split('\0')
757
713
                        if fields[1]:
758
 
                            path = fields[1] + b'/' + fields[2]
 
714
                            path = fields[1] + '/' + fields[2]
759
715
                        else:
760
716
                            path = fields[2]
761
717
                        paths.setdefault(path, []).append(fields)
854
810
            block = state_file.read(read_size)
855
811
 
856
812
            start = mid
857
 
            entries = block.split(b'\n')
 
813
            entries = block.split('\n')
858
814
 
859
815
            if len(entries) < 2:
860
816
                # We didn't find a '\n', so we cannot have found any records.
868
824
            # Check the first and last entries, in case they are partial, or if
869
825
            # we don't care about the rest of this page
870
826
            first_entry_num = 0
871
 
            first_fields = entries[0].split(b'\0')
 
827
            first_fields = entries[0].split('\0')
872
828
            if len(first_fields) < entry_field_count:
873
829
                # We didn't get the complete first entry
874
830
                # so move start, and grab the next, which
875
831
                # should be a full entry
876
832
                start += len(entries[0])+1
877
 
                first_fields = entries[1].split(b'\0')
 
833
                first_fields = entries[1].split('\0')
878
834
                first_entry_num = 1
879
835
 
880
836
            if len(first_fields) <= 1:
901
857
 
902
858
                # Parse the last entry
903
859
                last_entry_num = len(entries)-1
904
 
                last_fields = entries[last_entry_num].split(b'\0')
 
860
                last_fields = entries[last_entry_num].split('\0')
905
861
                if len(last_fields) < entry_field_count:
906
862
                    # The very last hunk was not complete,
907
863
                    # read the previous hunk
908
864
                    after = mid + len(block) - len(entries[-1])
909
865
                    last_entry_num -= 1
910
 
                    last_fields = entries[last_entry_num].split(b'\0')
 
866
                    last_fields = entries[last_entry_num].split('\0')
911
867
                else:
912
868
                    after = mid + len(block)
913
869
 
935
891
                    # careful if we should append rather than overwrite
936
892
                    if last_entry_num != first_entry_num:
937
893
                        paths.setdefault(last_dir, []).append(last_fields)
938
 
                    for num in range(first_entry_num+1, last_entry_num):
 
894
                    for num in xrange(first_entry_num+1, last_entry_num):
939
895
                        # TODO: jam 20070223 We are already splitting here, so
940
896
                        #       shouldn't we just split the whole thing rather
941
897
                        #       than doing the split again in add_one_record?
942
 
                        fields = entries[num].split(b'\0')
 
898
                        fields = entries[num].split('\0')
943
899
                        paths.setdefault(fields[1], []).append(fields)
944
900
 
945
901
                    for cur_dir in middle_files:
987
943
            # Directories that need to be read
988
944
            pending_dirs = set()
989
945
            paths_to_search = set()
990
 
            for entry_list in viewvalues(newly_found):
 
946
            for entry_list in newly_found.itervalues():
991
947
                for dir_name_id, trees_info in entry_list:
992
948
                    found[dir_name_id] = trees_info
993
949
                    found_dir_names.add(dir_name_id[:2])
994
950
                    is_dir = False
995
951
                    for tree_info in trees_info:
996
952
                        minikind = tree_info[0]
997
 
                        if minikind == b'd':
 
953
                        if minikind == 'd':
998
954
                            if is_dir:
999
955
                                # We already processed this one as a directory,
1000
956
                                # we don't need to do the extra work again.
1004
960
                            is_dir = True
1005
961
                            if path not in processed_dirs:
1006
962
                                pending_dirs.add(path)
1007
 
                        elif minikind == b'r':
 
963
                        elif minikind == 'r':
1008
964
                            # Rename, we need to directly search the target
1009
965
                            # which is contained in the fingerprint column
1010
966
                            dir_name = osutils.split(tree_info[1])
1037
993
            return
1038
994
        # only require all dirblocks if we are doing a full-pass removal.
1039
995
        self._read_dirblocks_if_needed()
1040
 
        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')])
1041
997
        def iter_entries_removable():
1042
998
            for block in self._dirblocks:
1043
999
                deleted_positions = []
1062
1018
 
1063
1019
        self._ghosts = []
1064
1020
        self._parents = [parents[0]]
1065
 
        self._mark_modified(header_modified=True)
 
1021
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
1022
        self._header_state = DirState.IN_MEMORY_MODIFIED
1066
1023
 
1067
1024
    def _empty_parent_info(self):
1068
1025
        return [DirState.NULL_PARENT_DETAILS] * (len(self._parents) -
1088
1045
        :param dirname: The utf8 dirname to ensure there is a block for.
1089
1046
        :return: The index for the block.
1090
1047
        """
1091
 
        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:
1092
1049
            # This is the signature of the root row, and the
1093
1050
            # contents-of-root row is always index 1
1094
1051
            return 1
1095
1052
        # the basename of the directory must be the end of its full name.
1096
1053
        if not (parent_block_index == -1 and
1097
 
            parent_block_index == -1 and dirname == b''):
 
1054
            parent_block_index == -1 and dirname == ''):
1098
1055
            if not dirname.endswith(
1099
1056
                    self._dirblocks[parent_block_index][1][parent_row_index][0][1]):
1100
1057
                raise AssertionError("bad dirname %r" % dirname)
1101
 
        block_index, present = self._find_block_index_from_key((dirname, b'', b''))
 
1058
        block_index, present = self._find_block_index_from_key((dirname, '', ''))
1102
1059
        if not present:
1103
1060
            ## In future, when doing partial parsing, this should load and
1104
1061
            # populate the entire block.
1115
1072
            to prevent unneeded overhead when callers have a sorted list already.
1116
1073
        :return: Nothing.
1117
1074
        """
1118
 
        if new_entries[0][0][0:2] != (b'', b''):
 
1075
        if new_entries[0][0][0:2] != ('', ''):
1119
1076
            raise AssertionError(
1120
1077
                "Missing root row %r" % (new_entries[0][0],))
1121
1078
        # The two blocks here are deliberate: the root block and the
1122
1079
        # contents-of-root block.
1123
 
        self._dirblocks = [(b'', []), (b'', [])]
 
1080
        self._dirblocks = [('', []), ('', [])]
1124
1081
        current_block = self._dirblocks[0][1]
1125
 
        current_dirname = b''
1126
 
        root_key = (b'', b'')
 
1082
        current_dirname = ''
 
1083
        root_key = ('', '')
1127
1084
        append_entry = current_block.append
1128
1085
        for entry in new_entries:
1129
1086
            if entry[0][0] != current_dirname:
1145
1102
        # The above loop leaves the "root block" entries mixed with the
1146
1103
        # "contents-of-root block". But we don't want an if check on
1147
1104
        # all entries, so instead we just fix it up here.
1148
 
        if self._dirblocks[1] != (b'', []):
 
1105
        if self._dirblocks[1] != ('', []):
1149
1106
            raise ValueError("bad dirblock start %r" % (self._dirblocks[1],))
1150
1107
        root_block = []
1151
1108
        contents_of_root_block = []
1154
1111
                root_block.append(entry)
1155
1112
            else:
1156
1113
                contents_of_root_block.append(entry)
1157
 
        self._dirblocks[0] = (b'', root_block)
1158
 
        self._dirblocks[1] = (b'', contents_of_root_block)
 
1114
        self._dirblocks[0] = ('', root_block)
 
1115
        self._dirblocks[1] = ('', contents_of_root_block)
1159
1116
 
1160
1117
    def _entries_for_path(self, path):
1161
1118
        """Return a list with all the entries that match path for all ids."""
1162
1119
        dirname, basename = os.path.split(path)
1163
 
        key = (dirname, basename, b'')
 
1120
        key = (dirname, basename, '')
1164
1121
        block_index, present = self._find_block_index_from_key(key)
1165
1122
        if not present:
1166
1123
            # the block which should contain path is absent.
1189
1146
            # minikind
1190
1147
            entire_entry[tree_offset + 0] = tree_data[0]
1191
1148
            # size
1192
 
            entire_entry[tree_offset + 2] = b'%d' % tree_data[2]
 
1149
            entire_entry[tree_offset + 2] = str(tree_data[2])
1193
1150
            # executable
1194
1151
            entire_entry[tree_offset + 3] = DirState._to_yesno[tree_data[3]]
1195
 
        return b'\0'.join(entire_entry)
 
1152
        return '\0'.join(entire_entry)
1196
1153
 
1197
1154
    def _fields_per_entry(self):
1198
1155
        """How many null separated fields should be in each entry row.
1199
1156
 
1200
 
        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
1201
1158
        so we just skip over it
1202
 
 
1203
 
        entry size::
 
1159
        entry size:
1204
1160
            3 fields for the key
1205
1161
            + number of fields per tree_data (5) * tree count
1206
1162
            + newline
1235
1191
 
1236
1192
        :return: The block index, True if the block for the key is present.
1237
1193
        """
1238
 
        if key[0:2] == (b'', b''):
 
1194
        if key[0:2] == ('', ''):
1239
1195
            return 0, True
1240
1196
        try:
1241
1197
            if (self._last_block_index is not None and
1297
1253
        result = DirState.initialize(dir_state_filename,
1298
1254
            sha1_provider=sha1_provider)
1299
1255
        try:
1300
 
            with tree.lock_read():
1301
 
                try:
1302
 
                    parent_ids = tree.get_parent_ids()
1303
 
                    num_parents = len(parent_ids)
1304
 
                    parent_trees = []
1305
 
                    for parent_id in parent_ids:
1306
 
                        parent_tree = tree.branch.repository.revision_tree(parent_id)
1307
 
                        parent_trees.append((parent_id, parent_tree))
1308
 
                        parent_tree.lock_read()
1309
 
                    result.set_parent_trees(parent_trees, [])
1310
 
                    result.set_state_from_inventory(tree.root_inventory)
1311
 
                finally:
1312
 
                    for revid, parent_tree in parent_trees:
1313
 
                        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()
1314
1271
        except:
1315
1272
            # The caller won't have a chance to unlock this, so make sure we
1316
1273
            # cleanup ourselves
1318
1275
            raise
1319
1276
        return result
1320
1277
 
1321
 
    def _check_delta_is_valid(self, delta):
1322
 
        delta = list(inventory._check_delta_unique_ids(
1323
 
                     inventory._check_delta_unique_old_paths(
1324
 
                     inventory._check_delta_unique_new_paths(
1325
 
                     inventory._check_delta_ids_match_entry(
1326
 
                     inventory._check_delta_ids_are_valid(
1327
 
                     inventory._check_delta_new_path_entry_both_or_None(delta)))))))
1328
 
        def delta_key(d):
1329
 
            (old_path, new_path, file_id, new_entry) = d
1330
 
            if old_path is None:
1331
 
                old_path = ''
1332
 
            if new_path is None:
1333
 
                new_path = ''
1334
 
            return (old_path, new_path, file_id, new_entry)
1335
 
        delta.sort(key=delta_key, reverse=True)
1336
 
        return delta
1337
 
 
1338
1278
    def update_by_delta(self, delta):
1339
1279
        """Apply an inventory delta to the dirstate for tree 0
1340
1280
 
1358
1298
        new_ids = set()
1359
1299
        # This loop transforms the delta to single atomic operations that can
1360
1300
        # be executed and validated.
1361
 
        delta = self._check_delta_is_valid(delta)
1362
 
        for old_path, new_path, file_id, inv_entry in delta:
1363
 
            if not isinstance(file_id, bytes):
1364
 
                raise AssertionError(
1365
 
                    "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):
1366
1308
            if (file_id in insertions) or (file_id in removals):
1367
 
                self._raise_invalid(old_path or new_path, file_id,
 
1309
                raise errors.InconsistentDelta(old_path or new_path, file_id,
1368
1310
                    "repeated file_id")
1369
1311
            if old_path is not None:
1370
1312
                old_path = old_path.encode('utf-8')
1373
1315
                new_ids.add(file_id)
1374
1316
            if new_path is not None:
1375
1317
                if inv_entry is None:
1376
 
                    self._raise_invalid(new_path, file_id,
 
1318
                    raise errors.InconsistentDelta(new_path, file_id,
1377
1319
                        "new_path with no entry")
1378
1320
                new_path = new_path.encode('utf-8')
1379
1321
                dirname_utf8, basename = osutils.split(new_path)
1381
1323
                    parents.add((dirname_utf8, inv_entry.parent_id))
1382
1324
                key = (dirname_utf8, basename, file_id)
1383
1325
                minikind = DirState._kind_to_minikind[inv_entry.kind]
1384
 
                if minikind == b't':
1385
 
                    fingerprint = inv_entry.reference_revision or b''
 
1326
                if minikind == 't':
 
1327
                    fingerprint = inv_entry.reference_revision or ''
1386
1328
                else:
1387
 
                    fingerprint = b''
 
1329
                    fingerprint = ''
1388
1330
                insertions[file_id] = (key, minikind, inv_entry.executable,
1389
1331
                                       fingerprint, new_path)
1390
1332
            # Transform moves into delete+add pairs
1409
1351
                                               fingerprint, new_child_path)
1410
1352
        self._check_delta_ids_absent(new_ids, delta, 0)
1411
1353
        try:
1412
 
            self._apply_removals(viewitems(removals))
1413
 
            self._apply_insertions(viewvalues(insertions))
 
1354
            self._apply_removals(removals.iteritems())
 
1355
            self._apply_insertions(insertions.values())
1414
1356
            # Validate parents
1415
1357
            self._after_delta_check_parents(parents, 0)
1416
 
        except errors.BzrError as e:
 
1358
        except errors.BzrError, e:
1417
1359
            self._changes_aborted = True
1418
1360
            if 'integrity error' not in str(e):
1419
1361
                raise
1420
1362
            # _get_entry raises BzrError when a request is inconsistent; we
1421
1363
            # want such errors to be shown as InconsistentDelta - and that 
1422
1364
            # fits the behaviour we trigger.
1423
 
            raise errors.InconsistentDeltaDelta(delta,
1424
 
                "error from _get_entry. %s" % (e,))
 
1365
            raise errors.InconsistentDeltaDelta(delta, "error from _get_entry.")
1425
1366
 
1426
1367
    def _apply_removals(self, removals):
1427
1368
        for file_id, path in sorted(removals, reverse=True,
1432
1373
            try:
1433
1374
                entry = self._dirblocks[block_i][1][entry_i]
1434
1375
            except IndexError:
1435
 
                self._raise_invalid(path, file_id,
 
1376
                self._changes_aborted = True
 
1377
                raise errors.InconsistentDelta(path, file_id,
1436
1378
                    "Wrong path for old path.")
1437
 
            if not f_present or entry[1][0][0] in (b'a', b'r'):
1438
 
                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,
1439
1382
                    "Wrong path for old path.")
1440
1383
            if file_id != entry[0][2]:
1441
 
                self._raise_invalid(path, file_id,
 
1384
                self._changes_aborted = True
 
1385
                raise errors.InconsistentDelta(path, file_id,
1442
1386
                    "Attempt to remove path has wrong id - found %r."
1443
1387
                    % entry[0][2])
1444
1388
            self._make_absent(entry)
1448
1392
            # is rare enough it shouldn't be an issue (famous last words?) RBC
1449
1393
            # 20080730.
1450
1394
            block_i, entry_i, d_present, f_present = \
1451
 
                self._get_block_entry_index(path, b'', 0)
 
1395
                self._get_block_entry_index(path, '', 0)
1452
1396
            if d_present:
1453
1397
                # The dir block is still present in the dirstate; this could
1454
1398
                # be due to it being in a parent tree, or a corrupt delta.
1455
1399
                for child_entry in self._dirblocks[block_i][1]:
1456
 
                    if child_entry[1][0][0] not in (b'r', b'a'):
1457
 
                        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],
1458
1403
                            "The file id was deleted but its children were "
1459
1404
                            "not deleted.")
1460
1405
 
1464
1409
                self.update_minimal(key, minikind, executable, fingerprint,
1465
1410
                                    path_utf8=path_utf8)
1466
1411
        except errors.NotVersionedError:
1467
 
            self._raise_invalid(path_utf8.decode('utf8'), key[2],
 
1412
            self._changes_aborted = True
 
1413
            raise errors.InconsistentDelta(path_utf8.decode('utf8'), key[2],
1468
1414
                "Missing parent")
1469
1415
 
1470
1416
    def update_basis_by_delta(self, delta, new_revid):
1478
1424
        Note that an exception during the operation of this method will leave
1479
1425
        the dirstate in a corrupt state where it should not be saved.
1480
1426
 
 
1427
        Finally, we expect all changes to be synchronising the basis tree with
 
1428
        the working tree.
 
1429
 
1481
1430
        :param new_revid: The new revision id for the trees parent.
1482
1431
        :param delta: An inventory delta (see apply_inventory_delta) describing
1483
1432
            the changes from the current left most parent revision to new_revid.
1495
1444
 
1496
1445
        self._parents[0] = new_revid
1497
1446
 
1498
 
        delta = self._check_delta_is_valid(delta)
 
1447
        delta = sorted(delta, reverse=True)
1499
1448
        adds = []
1500
1449
        changes = []
1501
1450
        deletes = []
1511
1460
        # expanding them recursively as needed.
1512
1461
        # At the same time, to reduce interface friction we convert the input
1513
1462
        # inventory entries to dirstate.
1514
 
        root_only = (b'', b'')
 
1463
        root_only = ('', '')
1515
1464
        # Accumulate parent references (path_utf8, id), to check for parentless
1516
1465
        # items or items placed under files/links/tree-references. We get
1517
1466
        # references from every item in the delta that is not a deletion and
1521
1470
        # ids.
1522
1471
        new_ids = set()
1523
1472
        for old_path, new_path, file_id, inv_entry in delta:
1524
 
            if file_id.__class__ is not bytes:
1525
 
                raise AssertionError(
1526
 
                    "must be a utf8 file_id not %s" % (type(file_id), ))
1527
1473
            if inv_entry is not None and file_id != inv_entry.file_id:
1528
 
                self._raise_invalid(new_path, file_id,
 
1474
                raise errors.InconsistentDelta(new_path, file_id,
1529
1475
                    "mismatched entry file_id %r" % inv_entry)
1530
 
            if new_path is None:
1531
 
                new_path_utf8 = None
1532
 
            else:
 
1476
            if new_path is not None:
1533
1477
                if inv_entry is None:
1534
 
                    self._raise_invalid(new_path, file_id,
 
1478
                    raise errors.InconsistentDelta(new_path, file_id,
1535
1479
                        "new_path with no entry")
1536
1480
                new_path_utf8 = encode(new_path)
1537
1481
                # note the parent for validation
1539
1483
                if basename_utf8:
1540
1484
                    parents.add((dirname_utf8, inv_entry.parent_id))
1541
1485
            if old_path is None:
1542
 
                old_path_utf8 = None
1543
 
            else:
1544
 
                old_path_utf8 = encode(old_path)
1545
 
            if old_path is None:
1546
 
                adds.append((None, new_path_utf8, file_id,
 
1486
                adds.append((None, encode(new_path), file_id,
1547
1487
                    inv_to_entry(inv_entry), True))
1548
1488
                new_ids.add(file_id)
1549
1489
            elif new_path is None:
1550
 
                deletes.append((old_path_utf8, None, file_id, None, True))
1551
 
            elif (old_path, new_path) == root_only:
1552
 
                # change things in-place
1553
 
                # Note: the case of a parent directory changing its file_id
1554
 
                #       tends to break optimizations here, because officially
1555
 
                #       the file has actually been moved, it just happens to
1556
 
                #       end up at the same path. If we can figure out how to
1557
 
                #       handle that case, we can avoid a lot of add+delete
1558
 
                #       pairs for objects that stay put.
1559
 
                # elif old_path == new_path:
1560
 
                changes.append((old_path_utf8, new_path_utf8, file_id,
1561
 
                                inv_to_entry(inv_entry)))
1562
 
            else:
 
1490
                deletes.append((encode(old_path), None, file_id, None, True))
 
1491
            elif (old_path, new_path) != root_only:
1563
1492
                # Renames:
1564
1493
                # Because renames must preserve their children we must have
1565
1494
                # processed all relocations and removes before hand. The sort
1575
1504
                self._update_basis_apply_deletes(deletes)
1576
1505
                deletes = []
1577
1506
                # Split into an add/delete pair recursively.
1578
 
                adds.append((old_path_utf8, new_path_utf8, file_id,
1579
 
                             inv_to_entry(inv_entry), False))
 
1507
                adds.append((None, new_path_utf8, file_id,
 
1508
                    inv_to_entry(inv_entry), False))
1580
1509
                # Expunge deletes that we've seen so that deleted/renamed
1581
1510
                # children of a rename directory are handled correctly.
1582
 
                new_deletes = reversed(list(
1583
 
                    self._iter_child_entries(1, old_path_utf8)))
 
1511
                new_deletes = reversed(list(self._iter_child_entries(1,
 
1512
                    encode(old_path))))
1584
1513
                # Remove the current contents of the tree at orig_path, and
1585
1514
                # reinsert at the correct new path.
1586
1515
                for entry in new_deletes:
1587
 
                    child_dirname, child_basename, child_file_id = entry[0]
1588
 
                    if child_dirname:
1589
 
                        source_path = child_dirname + b'/' + child_basename
 
1516
                    if entry[0][0]:
 
1517
                        source_path = entry[0][0] + '/' + entry[0][1]
1590
1518
                    else:
1591
 
                        source_path = child_basename
 
1519
                        source_path = entry[0][1]
1592
1520
                    if new_path_utf8:
1593
 
                        target_path = \
1594
 
                            new_path_utf8 + source_path[len(old_path_utf8):]
 
1521
                        target_path = new_path_utf8 + source_path[len(old_path):]
1595
1522
                    else:
1596
 
                        if old_path_utf8 == b'':
 
1523
                        if old_path == '':
1597
1524
                            raise AssertionError("cannot rename directory to"
1598
 
                                                 " itself")
1599
 
                        target_path = source_path[len(old_path_utf8) + 1:]
 
1525
                                " itself")
 
1526
                        target_path = source_path[len(old_path) + 1:]
1600
1527
                    adds.append((None, target_path, entry[0][2], entry[1][1], False))
1601
1528
                    deletes.append(
1602
1529
                        (source_path, target_path, entry[0][2], None, False))
1603
1530
                deletes.append(
1604
 
                    (old_path_utf8, new_path_utf8, file_id, None, False))
1605
 
 
 
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)))
1606
1537
        self._check_delta_ids_absent(new_ids, delta, 1)
1607
1538
        try:
1608
1539
            # Finish expunging deletes/first half of renames.
1613
1544
            self._update_basis_apply_changes(changes)
1614
1545
            # Validate parents
1615
1546
            self._after_delta_check_parents(parents, 1)
1616
 
        except errors.BzrError as e:
 
1547
        except errors.BzrError, e:
1617
1548
            self._changes_aborted = True
1618
1549
            if 'integrity error' not in str(e):
1619
1550
                raise
1620
1551
            # _get_entry raises BzrError when a request is inconsistent; we
1621
 
            # want such errors to be shown as InconsistentDelta - and that
1622
 
            # fits the behaviour we trigger.
1623
 
            raise errors.InconsistentDeltaDelta(delta,
1624
 
                "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.")
1625
1557
 
1626
 
        self._mark_modified(header_modified=True)
 
1558
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
1559
        self._header_state = DirState.IN_MEMORY_MODIFIED
1627
1560
        self._id_index = None
1628
1561
        return
1629
1562
 
1633
1566
            return
1634
1567
        id_index = self._get_id_index()
1635
1568
        for file_id in new_ids:
1636
 
            for key in id_index.get(file_id, ()):
 
1569
            for key in id_index.get(file_id, []):
1637
1570
                block_i, entry_i, d_present, f_present = \
1638
1571
                    self._get_block_entry_index(key[0], key[1], tree_index)
1639
1572
                if not f_present:
1643
1576
                if entry[0][2] != file_id:
1644
1577
                    # Different file_id, so not what we want.
1645
1578
                    continue
1646
 
                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,
1647
1583
                    "This file_id is new in the delta but already present in "
1648
1584
                    "the target")
1649
1585
 
1650
 
    def _raise_invalid(self, path, file_id, reason):
1651
 
        self._changes_aborted = True
1652
 
        raise errors.InconsistentDelta(path, file_id, reason)
1653
 
 
1654
1586
    def _update_basis_apply_adds(self, adds):
1655
1587
        """Apply a sequence of adds to tree 1 during update_basis_by_delta.
1656
1588
 
1664
1596
        """
1665
1597
        # Adds are accumulated partly from renames, so can be in any input
1666
1598
        # order - sort it.
1667
 
        # TODO: we may want to sort in dirblocks order. That way each entry
1668
 
        #       will end up in the same directory, allowing the _get_entry
1669
 
        #       fast-path for looking up 2 items in the same dir work.
1670
 
        adds.sort(key=lambda x: x[1])
 
1599
        adds.sort()
1671
1600
        # adds is now in lexographic order, which places all parents before
1672
1601
        # their children, so we can process it linearly.
1673
 
        st = static_tuple.StaticTuple
 
1602
        absent = 'ar'
1674
1603
        for old_path, new_path, file_id, new_details, real_add in adds:
1675
 
            dirname, basename = osutils.split(new_path)
1676
 
            entry_key = st(dirname, basename, file_id)
1677
 
            block_index, present = self._find_block_index_from_key(entry_key)
1678
 
            if not present:
1679
 
                # The block where we want to put the file is not present.
1680
 
                # However, it might have just been an empty directory. Look for
1681
 
                # the parent in the basis-so-far before throwing an error.
1682
 
                parent_dir, parent_base = osutils.split(dirname)
1683
 
                parent_block_idx, parent_entry_idx, _, parent_present = \
1684
 
                    self._get_block_entry_index(parent_dir, parent_base, 1)
1685
 
                if not parent_present:
1686
 
                    self._raise_invalid(new_path, file_id,
1687
 
                        "Unable to find block for this record."
1688
 
                        " Was the parent added?")
1689
 
                self._ensure_block(parent_block_idx, parent_entry_idx, dirname)
1690
 
 
1691
 
            block = self._dirblocks[block_index][1]
1692
 
            entry_index, present = self._find_entry_index(entry_key, block)
1693
 
            if real_add:
1694
 
                if old_path is not None:
1695
 
                    self._raise_invalid(new_path, file_id,
1696
 
                        'considered a real add but still had old_path at %s'
1697
 
                        % (old_path,))
1698
 
            if present:
1699
 
                entry = block[entry_index]
1700
 
                basis_kind = entry[1][1][0]
1701
 
                if basis_kind == b'a':
1702
 
                    entry[1][1] = new_details
1703
 
                elif basis_kind == b'r':
1704
 
                    raise NotImplementedError()
1705
 
                else:
1706
 
                    self._raise_invalid(new_path, file_id,
1707
 
                        "An entry was marked as a new add"
1708
 
                        " but the basis target already existed")
1709
 
            else:
1710
 
                # The exact key was not found in the block. However, we need to
1711
 
                # check if there is a key next to us that would have matched.
1712
 
                # We only need to check 2 locations, because there are only 2
1713
 
                # trees present.
1714
 
                for maybe_index in range(entry_index-1, entry_index+1):
1715
 
                    if maybe_index < 0 or maybe_index >= len(block):
1716
 
                        continue
1717
 
                    maybe_entry = block[maybe_index]
1718
 
                    if maybe_entry[0][:2] != (dirname, basename):
1719
 
                        # Just a random neighbor
1720
 
                        continue
1721
 
                    if maybe_entry[0][2] == file_id:
1722
 
                        raise AssertionError(
1723
 
                            '_find_entry_index didnt find a key match'
1724
 
                            ' but walking the data did, for %s'
1725
 
                            % (entry_key,))
1726
 
                    basis_kind = maybe_entry[1][1][0]
1727
 
                    if basis_kind not in (b'a', b'r'):
1728
 
                        self._raise_invalid(new_path, file_id,
1729
 
                            "we have an add record for path, but the path"
1730
 
                            " is already present with another file_id %s"
1731
 
                            % (maybe_entry[0][2],))
1732
 
 
1733
 
                entry = (entry_key, [DirState.NULL_PARENT_DETAILS,
1734
 
                                     new_details])
1735
 
                block.insert(entry_index, entry)
1736
 
 
1737
 
            active_kind = entry[1][0][0]
1738
 
            if active_kind == b'a':
1739
 
                # The active record shows up as absent, this could be genuine,
1740
 
                # or it could be present at some other location. We need to
1741
 
                # verify.
1742
 
                id_index = self._get_id_index()
1743
 
                # The id_index may not be perfectly accurate for tree1, because
1744
 
                # we haven't been keeping it updated. However, it should be
1745
 
                # fine for tree0, and that gives us enough info for what we
1746
 
                # need
1747
 
                keys = id_index.get(file_id, ())
1748
 
                for key in keys:
1749
 
                    block_i, entry_i, d_present, f_present = \
1750
 
                        self._get_block_entry_index(key[0], key[1], 0)
1751
 
                    if not f_present:
1752
 
                        continue
1753
 
                    active_entry = self._dirblocks[block_i][1][entry_i]
1754
 
                    if (active_entry[0][2] != file_id):
1755
 
                        # Some other file is at this path, we don't need to
1756
 
                        # link it.
1757
 
                        continue
1758
 
                    real_active_kind = active_entry[1][0][0]
1759
 
                    if real_active_kind in (b'a', b'r'):
1760
 
                        # We found a record, which was not *this* record,
1761
 
                        # which matches the file_id, but is not actually
1762
 
                        # present. Something seems *really* wrong.
1763
 
                        self._raise_invalid(new_path, file_id,
1764
 
                            "We found a tree0 entry that doesnt make sense")
1765
 
                    # Now, we've found a tree0 entry which matches the file_id
1766
 
                    # but is at a different location. So update them to be
1767
 
                    # rename records.
1768
 
                    active_dir, active_name = active_entry[0][:2]
1769
 
                    if active_dir:
1770
 
                        active_path = active_dir + '/' + active_name
1771
 
                    else:
1772
 
                        active_path = active_name
1773
 
                    active_entry[1][1] = st('r', new_path, 0, False, '')
1774
 
                    entry[1][0] = st('r', active_path, 0, False, '')
1775
 
            elif active_kind == 'r':
1776
 
                raise NotImplementedError()
1777
 
 
1778
 
            new_kind = new_details[0]
1779
 
            if new_kind == 'd':
1780
 
                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
1781
1619
 
1782
1620
    def _update_basis_apply_changes(self, changes):
1783
1621
        """Apply a sequence of changes to tree 1 during update_basis_by_delta.
1785
1623
        :param adds: A sequence of changes. Each change is a tuple:
1786
1624
            (path_utf8, path_utf8, file_id, (entry_details))
1787
1625
        """
 
1626
        absent = 'ar'
1788
1627
        for old_path, new_path, file_id, new_details in changes:
1789
1628
            # the entry for this file_id must be in tree 0.
1790
 
            entry = self._get_entry(1, file_id, new_path)
1791
 
            if entry[0] is None or entry[1][1][0] in (b'a', b'r'):
1792
 
                self._raise_invalid(new_path, file_id,
1793
 
                    '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')
1794
1639
            entry[1][1] = new_details
1795
1640
 
1796
1641
    def _update_basis_apply_deletes(self, deletes):
1808
1653
        null = DirState.NULL_PARENT_DETAILS
1809
1654
        for old_path, new_path, file_id, _, real_delete in deletes:
1810
1655
            if real_delete != (new_path is None):
1811
 
                self._raise_invalid(old_path, file_id, "bad delete delta")
 
1656
                self._changes_aborted = True
 
1657
                raise AssertionError("bad delete delta")
1812
1658
            # the entry for this file_id must be in tree 1.
1813
1659
            dirname, basename = osutils.split(old_path)
1814
1660
            block_index, entry_index, dir_present, file_present = \
1815
1661
                self._get_block_entry_index(dirname, basename, 1)
1816
1662
            if not file_present:
1817
 
                self._raise_invalid(old_path, file_id,
 
1663
                self._changes_aborted = True
 
1664
                raise errors.InconsistentDelta(old_path, file_id,
1818
1665
                    'basis tree does not contain removed entry')
1819
1666
            entry = self._dirblocks[block_index][1][entry_index]
1820
 
            # The state of the entry in the 'active' WT
1821
 
            active_kind = entry[1][0][0]
1822
1667
            if entry[0][2] != file_id:
1823
 
                self._raise_invalid(old_path, file_id,
 
1668
                self._changes_aborted = True
 
1669
                raise errors.InconsistentDelta(old_path, file_id,
1824
1670
                    'mismatched file_id in tree 1')
1825
 
            dir_block = ()
1826
 
            old_kind = entry[1][1][0]
1827
 
            if active_kind in b'ar':
1828
 
                # The active tree doesn't have this file_id.
1829
 
                # The basis tree is changing this record. If this is a
1830
 
                # rename, then we don't want the record here at all
1831
 
                # anymore. If it is just an in-place change, we want the
1832
 
                # record here, but we'll add it if we need to. So we just
1833
 
                # delete it
1834
 
                if active_kind == b'r':
1835
 
                    active_path = entry[1][0][1]
1836
 
                    active_entry = self._get_entry(0, file_id, active_path)
1837
 
                    if active_entry[1][1][0] != b'r':
1838
 
                        self._raise_invalid(old_path, file_id,
1839
 
                            "Dirstate did not have matching rename entries")
1840
 
                    elif active_entry[1][0][0] in 'ar':
1841
 
                        self._raise_invalid(old_path, file_id,
1842
 
                            "Dirstate had a rename pointing at an inactive"
1843
 
                            " tree0")
1844
 
                    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.')
1845
1677
                del self._dirblocks[block_index][1][entry_index]
1846
 
                if old_kind == b'd':
1847
 
                    # This was a directory, and the active tree says it
1848
 
                    # doesn't exist, and now the basis tree says it doesn't
1849
 
                    # exist. Remove its dirblock if present
1850
 
                    (dir_block_index,
1851
 
                     present) = self._find_block_index_from_key(
1852
 
                        (old_path, '', ''))
1853
 
                    if present:
1854
 
                        dir_block = self._dirblocks[dir_block_index][1]
1855
 
                        if not dir_block:
1856
 
                            # This entry is empty, go ahead and just remove it
1857
 
                            del self._dirblocks[dir_block_index]
1858
1678
            else:
1859
 
                # There is still an active record, so just mark this
1860
 
                # removed.
1861
 
                entry[1][1] = null
1862
 
                block_i, entry_i, d_present, f_present = \
1863
 
                    self._get_block_entry_index(old_path, b'', 1)
1864
 
                if d_present:
1865
 
                    dir_block = self._dirblocks[block_i][1]
1866
 
            for child_entry in dir_block:
1867
 
                child_basis_kind = child_entry[1][1][0]
1868
 
                if child_basis_kind not in b'ar':
1869
 
                    self._raise_invalid(old_path, file_id,
1870
 
                        "The file id was deleted but its children were "
1871
 
                        "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
1872
1694
 
1873
1695
    def _after_delta_check_parents(self, parents, index):
1874
1696
        """Check that parents required by the delta are all intact.
1883
1705
            # has the right file id.
1884
1706
            entry = self._get_entry(index, file_id, dirname_utf8)
1885
1707
            if entry[1] is None:
1886
 
                self._raise_invalid(dirname_utf8.decode('utf8'),
 
1708
                self._changes_aborted = True
 
1709
                raise errors.InconsistentDelta(dirname_utf8.decode('utf8'),
1887
1710
                    file_id, "This parent is not present.")
1888
1711
            # Parents of things must be directories
1889
 
            if entry[1][index][0] != b'd':
1890
 
                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'),
1891
1715
                    file_id, "This parent is not a directory.")
1892
1716
 
1893
1717
    def _observed_sha1(self, entry, sha1, stat_value,
1894
 
        _stat_to_minikind=_stat_to_minikind):
 
1718
        _stat_to_minikind=_stat_to_minikind, _pack_stat=pack_stat):
1895
1719
        """Note the sha1 of a file.
1896
1720
 
1897
1721
        :param entry: The entry the sha1 is for.
1899
1723
        :param stat_value: The os.lstat for the file.
1900
1724
        """
1901
1725
        try:
1902
 
            minikind = _stat_to_minikind[stat_value.st_mode & 0o170000]
 
1726
            minikind = _stat_to_minikind[stat_value.st_mode & 0170000]
1903
1727
        except KeyError:
1904
1728
            # Unhandled kind
1905
1729
            return None
 
1730
        packed_stat = _pack_stat(stat_value)
1906
1731
        if minikind == 'f':
1907
1732
            if self._cutoff_time is None:
1908
1733
                self._sha_cutoff_time()
1909
1734
            if (stat_value.st_mtime < self._cutoff_time
1910
1735
                and stat_value.st_ctime < self._cutoff_time):
1911
 
                entry[1][0] = ('f', sha1, stat_value.st_size, entry[1][0][3],
1912
 
                               pack_stat(stat_value))
1913
 
                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
1914
1739
 
1915
1740
    def _sha_cutoff_time(self):
1916
1741
        """Return cutoff time.
1953
1778
        #       higher level, because there either won't be anything on disk,
1954
1779
        #       or the thing on disk will be a file.
1955
1780
        fs_encoding = osutils._fs_enc
1956
 
        if isinstance(abspath, text_type):
 
1781
        if isinstance(abspath, unicode):
1957
1782
            # abspath is defined as the path to pass to lstat. readlink is
1958
1783
            # buggy in python < 2.6 (it doesn't encode unicode path into FS
1959
1784
            # encoding), so we need to encode ourselves knowing that unicode
1960
1785
            # paths are produced by UnicodeDirReader on purpose.
1961
1786
            abspath = abspath.encode(fs_encoding)
1962
1787
        target = os.readlink(abspath)
1963
 
        if fs_encoding not in ('utf-8', 'ascii'):
 
1788
        if fs_encoding not in ('UTF-8', 'US-ASCII', 'ANSI_X3.4-1968'):
1964
1789
            # Change encoding if needed
1965
1790
            target = target.decode(fs_encoding).encode('UTF-8')
1966
1791
        return target
1974
1799
        """Serialise the entire dirstate to a sequence of lines."""
1975
1800
        if (self._header_state == DirState.IN_MEMORY_UNMODIFIED and
1976
1801
            self._dirblock_state == DirState.IN_MEMORY_UNMODIFIED):
1977
 
            # read what's on disk.
 
1802
            # read whats on disk.
1978
1803
            self._state_file.seek(0)
1979
1804
            return self._state_file.readlines()
1980
1805
        lines = []
1981
1806
        lines.append(self._get_parents_line(self.get_parent_ids()))
1982
1807
        lines.append(self._get_ghosts_line(self._ghosts))
1983
 
        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()))
1984
1810
        return self._get_output_lines(lines)
1985
1811
 
1986
1812
    def _get_ghosts_line(self, ghost_ids):
1987
1813
        """Create a line for the state file for ghost information."""
1988
 
        return b'\0'.join([b'%d' % len(ghost_ids)] + ghost_ids)
 
1814
        return '\0'.join([str(len(ghost_ids))] + ghost_ids)
1989
1815
 
1990
1816
    def _get_parents_line(self, parent_ids):
1991
1817
        """Create a line for the state file for parents information."""
1992
 
        return b'\0'.join([b'%d' % len(parent_ids)] + parent_ids)
1993
 
 
1994
 
    def _iter_entry_lines(self):
1995
 
        """Create lines for entries."""
1996
 
        return map(self._entry_to_line, self._iter_entries())
 
1818
        return '\0'.join([str(len(parent_ids))] + parent_ids)
1997
1819
 
1998
1820
    def _get_fields_to_entry(self):
1999
1821
        """Get a function which converts entry fields into a entry record.
2072
1894
                          _int(fields[cur+2]),        # size
2073
1895
                          fields[cur+3] == 'y',       # executable
2074
1896
                          fields[cur+4],              # stat or revision_id
2075
 
                         ) for cur in range(3, len(fields)-1, 5)]
 
1897
                         ) for cur in xrange(3, len(fields)-1, 5)]
2076
1898
                return path_name_file_id_key, trees
2077
1899
            return fields_to_entry_n_parents
2078
1900
 
2102
1924
            tree present there.
2103
1925
        """
2104
1926
        self._read_dirblocks_if_needed()
2105
 
        key = dirname, basename, b''
 
1927
        key = dirname, basename, ''
2106
1928
        block_index, present = self._find_block_index_from_key(key)
2107
1929
        if not present:
2108
1930
            # no such directory - return the dir index and 0 for the row.
2112
1934
        # linear search through entries at this path to find the one
2113
1935
        # requested.
2114
1936
        while entry_index < len(block) and block[entry_index][0][1] == basename:
2115
 
            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':
2116
1938
                # neither absent or relocated
2117
1939
                return block_index, entry_index, True, True
2118
1940
            entry_index += 1
2119
1941
        return block_index, entry_index, True, False
2120
1942
 
2121
 
    def _get_entry(self, tree_index, fileid_utf8=None, path_utf8=None,
2122
 
                   include_deleted=False):
 
1943
    def _get_entry(self, tree_index, fileid_utf8=None, path_utf8=None, include_deleted=False):
2123
1944
        """Get the dirstate entry for path in tree tree_index.
2124
1945
 
2125
1946
        If either file_id or path is supplied, it is used as the key to lookup.
2140
1961
        """
2141
1962
        self._read_dirblocks_if_needed()
2142
1963
        if path_utf8 is not None:
2143
 
            if not isinstance(path_utf8, bytes):
2144
 
                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'
2145
1966
                    % (type(path_utf8), path_utf8))
2146
1967
            # path lookups are faster
2147
1968
            dirname, basename = osutils.split(path_utf8)
2150
1971
            if not file_present:
2151
1972
                return None, None
2152
1973
            entry = self._dirblocks[block_index][1][entry_index]
2153
 
            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')):
2154
1975
                raise AssertionError('unversioned entry?')
2155
1976
            if fileid_utf8:
2156
1977
                if entry[0][2] != fileid_utf8:
2159
1980
                                          ' tree_index, file_id and path')
2160
1981
            return entry
2161
1982
        else:
2162
 
            possible_keys = self._get_id_index().get(fileid_utf8, ())
 
1983
            possible_keys = self._get_id_index().get(fileid_utf8, None)
2163
1984
            if not possible_keys:
2164
1985
                return None, None
2165
1986
            for key in possible_keys:
2178
1999
                    entry = self._dirblocks[block_index][1][entry_index]
2179
2000
                    # TODO: We might want to assert that entry[0][2] ==
2180
2001
                    #       fileid_utf8.
2181
 
                    # GZ 2017-06-09: Hoist set of minkinds somewhere
2182
 
                    if entry[1][tree_index][0] in {b'f', b'd', b'l', b't'}:
 
2002
                    if entry[1][tree_index][0] in 'fdlt':
2183
2003
                        # this is the result we are looking for: the
2184
2004
                        # real home of this file_id in this tree.
2185
2005
                        return entry
2186
 
                    if entry[1][tree_index][0] == b'a':
 
2006
                    if entry[1][tree_index][0] == 'a':
2187
2007
                        # there is no home for this entry in this tree
2188
2008
                        if include_deleted:
2189
2009
                            return entry
2190
2010
                        return None, None
2191
 
                    if entry[1][tree_index][0] != b'r':
 
2011
                    if entry[1][tree_index][0] != 'r':
2192
2012
                        raise AssertionError(
2193
2013
                            "entry %r has invalid minikind %r for tree %r" \
2194
2014
                            % (entry,
2220
2040
            sha1_provider = DefaultSHA1Provider()
2221
2041
        result = cls(path, sha1_provider)
2222
2042
        # root dir and root dir contents with no children.
2223
 
        empty_tree_dirblocks = [(b'', []), (b'', [])]
 
2043
        empty_tree_dirblocks = [('', []), ('', [])]
2224
2044
        # a new root directory, with a NULLSTAT.
2225
2045
        empty_tree_dirblocks[0][1].append(
2226
 
            ((b'', b'', inventory.ROOT_ID), [
2227
 
                (b'd', b'', 0, False, DirState.NULLSTAT),
 
2046
            (('', '', inventory.ROOT_ID), [
 
2047
                ('d', '', 0, False, DirState.NULLSTAT),
2228
2048
            ]))
2229
2049
        result.lock_write()
2230
2050
        try:
2248
2068
        minikind = DirState._kind_to_minikind[kind]
2249
2069
        tree_data = inv_entry.revision
2250
2070
        if kind == 'directory':
2251
 
            fingerprint = b''
 
2071
            fingerprint = ''
2252
2072
            size = 0
2253
2073
            executable = False
2254
2074
        elif kind == 'symlink':
2255
2075
            if inv_entry.symlink_target is None:
2256
 
                fingerprint = b''
 
2076
                fingerprint = ''
2257
2077
            else:
2258
2078
                fingerprint = inv_entry.symlink_target.encode('utf8')
2259
2079
            size = 0
2260
2080
            executable = False
2261
2081
        elif kind == 'file':
2262
 
            fingerprint = inv_entry.text_sha1 or b''
 
2082
            fingerprint = inv_entry.text_sha1 or ''
2263
2083
            size = inv_entry.text_size or 0
2264
2084
            executable = inv_entry.executable
2265
2085
        elif kind == 'tree-reference':
2266
 
            fingerprint = inv_entry.reference_revision or b''
 
2086
            fingerprint = inv_entry.reference_revision or ''
2267
2087
            size = 0
2268
2088
            executable = False
2269
2089
        else:
2270
2090
            raise Exception("can't pack %s" % inv_entry)
2271
 
        return static_tuple.StaticTuple(minikind, fingerprint, size,
2272
 
                                        executable, tree_data)
 
2091
        return (minikind, fingerprint, size, executable, tree_data)
2273
2092
 
2274
2093
    def _iter_child_entries(self, tree_index, path_utf8):
2275
2094
        """Iterate over all the entries that are children of path_utf.
2284
2103
        """
2285
2104
        pending_dirs = []
2286
2105
        next_pending_dirs = [path_utf8]
2287
 
        absent = (b'a', b'r')
 
2106
        absent = 'ar'
2288
2107
        while next_pending_dirs:
2289
2108
            pending_dirs = next_pending_dirs
2290
2109
            next_pending_dirs = []
2291
2110
            for path in pending_dirs:
2292
2111
                block_index, present = self._find_block_index_from_key(
2293
 
                    (path, b'', b''))
 
2112
                    (path, '', ''))
2294
2113
                if block_index == 0:
2295
2114
                    block_index = 1
2296
2115
                    if len(self._dirblocks) == 1:
2305
2124
                    kind = entry[1][tree_index][0]
2306
2125
                    if kind not in absent:
2307
2126
                        yield entry
2308
 
                    if kind == b'd':
 
2127
                    if kind == 'd':
2309
2128
                        if entry[0][0]:
2310
 
                            path = entry[0][0] + b'/' + entry[0][1]
 
2129
                            path = entry[0][0] + '/' + entry[0][1]
2311
2130
                        else:
2312
2131
                            path = entry[0][1]
2313
2132
                        next_pending_dirs.append(path)
2316
2135
        """Iterate over all the entries in the dirstate.
2317
2136
 
2318
2137
        Each yelt item is an entry in the standard format described in the
2319
 
        docstring of breezy.dirstate.
 
2138
        docstring of bzrlib.dirstate.
2320
2139
        """
2321
2140
        self._read_dirblocks_if_needed()
2322
2141
        for directory in self._dirblocks:
2324
2143
                yield entry
2325
2144
 
2326
2145
    def _get_id_index(self):
2327
 
        """Get an id index of self._dirblocks.
2328
 
 
2329
 
        This maps from file_id => [(directory, name, file_id)] entries where
2330
 
        that file_id appears in one of the trees.
2331
 
        """
 
2146
        """Get an id index of self._dirblocks."""
2332
2147
        if self._id_index is None:
2333
2148
            id_index = {}
2334
2149
            for key, tree_details in self._iter_entries():
2335
 
                self._add_to_id_index(id_index, key)
 
2150
                id_index.setdefault(key[2], set()).add(key)
2336
2151
            self._id_index = id_index
2337
2152
        return self._id_index
2338
2153
 
2339
 
    def _add_to_id_index(self, id_index, entry_key):
2340
 
        """Add this entry to the _id_index mapping."""
2341
 
        # This code used to use a set for every entry in the id_index. However,
2342
 
        # it is *rare* to have more than one entry. So a set is a large
2343
 
        # overkill. And even when we do, we won't ever have more than the
2344
 
        # number of parent trees. Which is still a small number (rarely >2). As
2345
 
        # such, we use a simple tuple, and do our own uniqueness checks. While
2346
 
        # the 'in' check is O(N) since N is nicely bounded it shouldn't ever
2347
 
        # cause quadratic failure.
2348
 
        file_id = entry_key[2]
2349
 
        entry_key = static_tuple.StaticTuple.from_sequence(entry_key)
2350
 
        if file_id not in id_index:
2351
 
            id_index[file_id] = static_tuple.StaticTuple(entry_key,)
2352
 
        else:
2353
 
            entry_keys = id_index[file_id]
2354
 
            if entry_key not in entry_keys:
2355
 
                id_index[file_id] = entry_keys + (entry_key,)
2356
 
 
2357
 
    def _remove_from_id_index(self, id_index, entry_key):
2358
 
        """Remove this entry from the _id_index mapping.
2359
 
 
2360
 
        It is an programming error to call this when the entry_key is not
2361
 
        already present.
2362
 
        """
2363
 
        file_id = entry_key[2]
2364
 
        entry_keys = list(id_index[file_id])
2365
 
        entry_keys.remove(entry_key)
2366
 
        id_index[file_id] = static_tuple.StaticTuple.from_sequence(entry_keys)
2367
 
 
2368
2154
    def _get_output_lines(self, lines):
2369
2155
        """Format lines for final output.
2370
2156
 
2372
2158
            path lines.
2373
2159
        """
2374
2160
        output_lines = [DirState.HEADER_FORMAT_3]
2375
 
        lines.append(b'') # a final newline
2376
 
        inventory_text = b'\0\n\0'.join(lines)
2377
 
        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),))
2378
2164
        # -3, 1 for num parents, 1 for ghosts, 1 for final newline
2379
2165
        num_entries = len(lines)-3
2380
 
        output_lines.append(b'num_entries: %d\n' % (num_entries,))
 
2166
        output_lines.append('num_entries: %s\n' % (num_entries,))
2381
2167
        output_lines.append(inventory_text)
2382
2168
        return output_lines
2383
2169
 
2384
2170
    def _make_deleted_row(self, fileid_utf8, parents):
2385
2171
        """Return a deleted row for fileid_utf8."""
2386
 
        return (b'/', b'RECYCLED.BIN', b'file', fileid_utf8, 0, DirState.NULLSTAT,
2387
 
            b''), parents
 
2172
        return ('/', 'RECYCLED.BIN', 'file', fileid_utf8, 0, DirState.NULLSTAT,
 
2173
            ''), parents
2388
2174
 
2389
2175
    def _num_present_parents(self):
2390
2176
        """The number of parent entries in each record row."""
2391
2177
        return len(self._parents) - len(self._ghosts)
2392
2178
 
2393
 
    @classmethod
2394
 
    def on_file(cls, path, sha1_provider=None, worth_saving_limit=0):
 
2179
    @staticmethod
 
2180
    def on_file(path, sha1_provider=None):
2395
2181
        """Construct a DirState on the file at path "path".
2396
2182
 
2397
2183
        :param path: The path at which the dirstate file on disk should live.
2398
2184
        :param sha1_provider: an object meeting the SHA1Provider interface.
2399
2185
            If None, a DefaultSHA1Provider is used.
2400
 
        :param worth_saving_limit: when the exact number of hash changed
2401
 
            entries is known, only bother saving the dirstate if more than
2402
 
            this count of entries have changed. -1 means never save.
2403
2186
        :return: An unlocked DirState object, associated with the given path.
2404
2187
        """
2405
2188
        if sha1_provider is None:
2406
2189
            sha1_provider = DefaultSHA1Provider()
2407
 
        result = cls(path, sha1_provider,
2408
 
                     worth_saving_limit=worth_saving_limit)
 
2190
        result = DirState(path, sha1_provider)
2409
2191
        return result
2410
2192
 
2411
2193
    def _read_dirblocks_if_needed(self):
2429
2211
        """
2430
2212
        self._read_prelude()
2431
2213
        parent_line = self._state_file.readline()
2432
 
        info = parent_line.split(b'\0')
 
2214
        info = parent_line.split('\0')
2433
2215
        num_parents = int(info[0])
2434
2216
        self._parents = info[1:-1]
2435
2217
        ghost_line = self._state_file.readline()
2436
 
        info = ghost_line.split(b'\0')
 
2218
        info = ghost_line.split('\0')
2437
2219
        num_ghosts = int(info[1])
2438
2220
        self._ghosts = info[2:-1]
2439
2221
        self._header_state = DirState.IN_MEMORY_UNMODIFIED
2461
2243
            raise errors.BzrError(
2462
2244
                'invalid header line: %r' % (header,))
2463
2245
        crc_line = self._state_file.readline()
2464
 
        if not crc_line.startswith(b'crc32: '):
 
2246
        if not crc_line.startswith('crc32: '):
2465
2247
            raise errors.BzrError('missing crc32 checksum: %r' % crc_line)
2466
 
        self.crc_expected = int(crc_line[len(b'crc32: '):-1])
 
2248
        self.crc_expected = int(crc_line[len('crc32: '):-1])
2467
2249
        num_entries_line = self._state_file.readline()
2468
 
        if not num_entries_line.startswith(b'num_entries: '):
 
2250
        if not num_entries_line.startswith('num_entries: '):
2469
2251
            raise errors.BzrError('missing num_entries line')
2470
 
        self._num_entries = int(num_entries_line[len(b'num_entries: '):-1])
 
2252
        self._num_entries = int(num_entries_line[len('num_entries: '):-1])
2471
2253
 
2472
 
    def sha1_from_stat(self, path, stat_result):
 
2254
    def sha1_from_stat(self, path, stat_result, _pack_stat=pack_stat):
2473
2255
        """Find a sha1 given a stat lookup."""
2474
 
        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)
2475
2257
 
2476
2258
    def _get_packed_stat_index(self):
2477
2259
        """Get a packed_stat index of self._dirblocks."""
2478
2260
        if self._packed_stat_index is None:
2479
2261
            index = {}
2480
2262
            for key, tree_details in self._iter_entries():
2481
 
                if tree_details[0][0] == b'f':
 
2263
                if tree_details[0][0] == 'f':
2482
2264
                    index[tree_details[0][4]] = tree_details[0][1]
2483
2265
            self._packed_stat_index = index
2484
2266
        return self._packed_stat_index
2503
2285
            trace.mutter('Not saving DirState because '
2504
2286
                    '_changes_aborted is set.')
2505
2287
            return
2506
 
        # TODO: Since we now distinguish IN_MEMORY_MODIFIED from
2507
 
        #       IN_MEMORY_HASH_MODIFIED, we should only fail quietly if we fail
2508
 
        #       to save an IN_MEMORY_HASH_MODIFIED, and fail *noisily* if we
2509
 
        #       fail to save IN_MEMORY_MODIFIED
2510
 
        if not self._worth_saving():
2511
 
            return
 
2288
        if (self._header_state == DirState.IN_MEMORY_MODIFIED or
 
2289
            self._dirblock_state == DirState.IN_MEMORY_MODIFIED):
2512
2290
 
2513
 
        grabbed_write_lock = False
2514
 
        if self._lock_state != 'w':
2515
 
            grabbed_write_lock, new_lock = self._lock_token.temporary_write_lock()
2516
 
            # Switch over to the new lock, as the old one may be closed.
2517
 
            # TODO: jam 20070315 We should validate the disk file has
2518
 
            #       not changed contents, since temporary_write_lock may
2519
 
            #       not be an atomic operation.
2520
 
            self._lock_token = new_lock
2521
 
            self._state_file = new_lock.f
2522
 
            if not grabbed_write_lock:
2523
 
                # We couldn't grab a write lock, so we switch back to a read one
2524
 
                return
2525
 
        try:
2526
 
            lines = self.get_lines()
2527
 
            self._state_file.seek(0)
2528
 
            self._state_file.writelines(lines)
2529
 
            self._state_file.truncate()
2530
 
            self._state_file.flush()
2531
 
            self._maybe_fdatasync()
2532
 
            self._mark_unmodified()
2533
 
        finally:
2534
 
            if grabbed_write_lock:
2535
 
                self._lock_token = self._lock_token.restore_read_lock()
2536
 
                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.
2537
2295
                # TODO: jam 20070315 We should validate the disk file has
2538
 
                #       not changed contents. Since restore_read_lock may
2539
 
                #       not be an atomic operation.                
2540
 
 
2541
 
    def _maybe_fdatasync(self):
2542
 
        """Flush to disk if possible and if not configured off."""
2543
 
        if self._config_stack.get('dirstate.fdatasync'):
2544
 
            osutils.fdatasync(self._state_file.fileno())
2545
 
 
2546
 
    def _worth_saving(self):
2547
 
        """Is it worth saving the dirstate or not?"""
2548
 
        if (self._header_state == DirState.IN_MEMORY_MODIFIED
2549
 
            or self._dirblock_state == DirState.IN_MEMORY_MODIFIED):
2550
 
            return True
2551
 
        if self._dirblock_state == DirState.IN_MEMORY_HASH_MODIFIED:
2552
 
            if self._worth_saving_limit == -1:
2553
 
                # We never save hash changes when the limit is -1
2554
 
                return False
2555
 
            # If we're using smart saving and only a small number of
2556
 
            # entries have changed their hash, don't bother saving. John has
2557
 
            # suggested using a heuristic here based on the size of the
2558
 
            # changed files and/or tree. For now, we go with a configurable
2559
 
            # number of changes, keeping the calculation time
2560
 
            # as low overhead as possible. (This also keeps all existing
2561
 
            # tests passing as the default is 0, i.e. always save.)
2562
 
            if len(self._known_hash_changes) >= self._worth_saving_limit:
2563
 
                return True
2564
 
        return False
 
2296
                #       not changed contents. Since temporary_write_lock may
 
2297
                #       not be an atomic operation.
 
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.
2565
2317
 
2566
2318
    def _set_data(self, parent_ids, dirblocks):
2567
2319
        """Set the full dirstate data in memory.
2576
2328
        """
2577
2329
        # our memory copy is now authoritative.
2578
2330
        self._dirblocks = dirblocks
2579
 
        self._mark_modified(header_modified=True)
 
2331
        self._header_state = DirState.IN_MEMORY_MODIFIED
 
2332
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
2580
2333
        self._parents = list(parent_ids)
2581
2334
        self._id_index = None
2582
2335
        self._packed_stat_index = None
2598
2351
        if entry[0][2] == new_id:
2599
2352
            # Nothing to change.
2600
2353
            return
2601
 
        if new_id.__class__ != bytes:
2602
 
            raise AssertionError(
2603
 
                "must be a utf8 file_id not %s" % (type(new_id), ))
2604
2354
        # mark the old path absent, and insert a new root path
2605
2355
        self._make_absent(entry)
2606
 
        self.update_minimal((b'', b'', new_id), b'd',
2607
 
            path_utf8=b'', packed_stat=entry[1][0][4])
2608
 
        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
2609
2359
 
2610
2360
    def set_parent_trees(self, trees, ghosts):
2611
2361
        """Set the parent trees for the dirstate.
2656
2406
        parent_trees = [tree for rev_id, tree in trees if rev_id not in ghosts]
2657
2407
        # how many trees do we end up with
2658
2408
        parent_count = len(parent_trees)
2659
 
        st = static_tuple.StaticTuple
2660
2409
 
2661
2410
        # one: the current tree
2662
2411
        for entry in self._iter_entries():
2663
2412
            # skip entries not in the current tree
2664
 
            if entry[1][0][0] in (b'a', b'r'): # absent, relocated
 
2413
            if entry[1][0][0] in 'ar': # absent, relocated
2665
2414
                continue
2666
2415
            by_path[entry[0]] = [entry[1][0]] + \
2667
2416
                [DirState.NULL_PARENT_DETAILS] * parent_count
2668
 
            # TODO: Possibly inline this, since we know it isn't present yet
2669
 
            #       id_index[entry[0][2]] = (entry[0],)
2670
 
            self._add_to_id_index(id_index, entry[0])
 
2417
            id_index[entry[0][2]] = set([entry[0]])
2671
2418
 
2672
2419
        # now the parent trees:
2673
2420
        for tree_index, tree in enumerate(parent_trees):
2679
2426
            # the suffix is from tree_index+1:parent_count+1.
2680
2427
            new_location_suffix = [DirState.NULL_PARENT_DETAILS] * (parent_count - tree_index)
2681
2428
            # now stitch in all the entries from this tree
2682
 
            last_dirname = None
2683
 
            for path, entry in tree.iter_entries_by_dir():
 
2429
            for path, entry in tree.inventory.iter_entries_by_dir():
2684
2430
                # here we process each trees details for each item in the tree.
2685
2431
                # we first update any existing entries for the id at other paths,
2686
2432
                # then we either create or update the entry for the id at the
2693
2439
                file_id = entry.file_id
2694
2440
                path_utf8 = path.encode('utf8')
2695
2441
                dirname, basename = osutils.split(path_utf8)
2696
 
                if dirname == last_dirname:
2697
 
                    # Try to re-use objects as much as possible
2698
 
                    dirname = last_dirname
2699
 
                else:
2700
 
                    last_dirname = dirname
2701
 
                new_entry_key = st(dirname, basename, file_id)
 
2442
                new_entry_key = (dirname, basename, file_id)
2702
2443
                # tree index consistency: All other paths for this id in this tree
2703
2444
                # index must point to the correct path.
2704
 
                entry_keys = id_index.get(file_id, ())
2705
 
                for entry_key in entry_keys:
 
2445
                for entry_key in id_index.setdefault(file_id, set()):
2706
2446
                    # TODO:PROFILING: It might be faster to just update
2707
2447
                    # rather than checking if we need to, and then overwrite
2708
2448
                    # the one we are located at.
2711
2451
                        # other trees, so put absent pointers there
2712
2452
                        # This is the vertical axis in the matrix, all pointing
2713
2453
                        # to the real path.
2714
 
                        by_path[entry_key][tree_index] = st(b'r', path_utf8, 0,
2715
 
                                                            False, b'')
2716
 
                # by path consistency: Insert into an existing path record
2717
 
                # (trivial), or add a new one with relocation pointers for the
2718
 
                # other tree indexes.
2719
 
                if new_entry_key in entry_keys:
2720
 
                    # there is already an entry where this data belongs, just
2721
 
                    # 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.
2722
2459
                    by_path[new_entry_key][tree_index] = \
2723
2460
                        self._inv_entry_to_details(entry)
2724
2461
                else:
2726
2463
                    # mapping from path,id. We need to look up the correct path
2727
2464
                    # for the indexes from 0 to tree_index -1
2728
2465
                    new_details = []
2729
 
                    for lookup_index in range(tree_index):
 
2466
                    for lookup_index in xrange(tree_index):
2730
2467
                        # boundary case: this is the first occurence of file_id
2731
 
                        # so there are no id_indexes, possibly take this out of
 
2468
                        # so there are no id_indexs, possibly take this out of
2732
2469
                        # the loop?
2733
 
                        if not len(entry_keys):
 
2470
                        if not len(id_index[file_id]):
2734
2471
                            new_details.append(DirState.NULL_PARENT_DETAILS)
2735
2472
                        else:
2736
2473
                            # grab any one entry, use it to find the right path.
2737
 
                            a_key = next(iter(entry_keys))
2738
 
                            if by_path[a_key][lookup_index][0] in (b'r', b'a'):
2739
 
                                # its a pointer or missing statement, use it as
2740
 
                                # 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.
2741
2480
                                new_details.append(by_path[a_key][lookup_index])
2742
2481
                            else:
2743
2482
                                # we have the right key, make a pointer to it.
2744
 
                                real_path = (b'/'.join(a_key[0:2])).strip(b'/')
2745
 
                                new_details.append(st(b'r', real_path, 0, False,
2746
 
                                                      b''))
 
2483
                                real_path = ('/'.join(a_key[0:2])).strip('/')
 
2484
                                new_details.append(('r', real_path, 0, False, ''))
2747
2485
                    new_details.append(self._inv_entry_to_details(entry))
2748
2486
                    new_details.extend(new_location_suffix)
2749
2487
                    by_path[new_entry_key] = new_details
2750
 
                    self._add_to_id_index(id_index, new_entry_key)
 
2488
                    id_index[file_id].add(new_entry_key)
2751
2489
        # --- end generation of full tree mappings
2752
2490
 
2753
2491
        # sort and output all the entries
2754
 
        new_entries = self._sort_entries(viewitems(by_path))
 
2492
        new_entries = self._sort_entries(by_path.items())
2755
2493
        self._entries_to_current_state(new_entries)
2756
2494
        self._parents = [rev_id for rev_id, tree in trees]
2757
2495
        self._ghosts = list(ghosts)
2758
 
        self._mark_modified(header_modified=True)
 
2496
        self._header_state = DirState.IN_MEMORY_MODIFIED
 
2497
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
2759
2498
        self._id_index = id_index
2760
2499
 
2761
2500
    def _sort_entries(self, entry_list):
2765
2504
        try to keep everything in sorted blocks all the time, but sometimes
2766
2505
        it's easier to sort after the fact.
2767
2506
        """
2768
 
        # When sorting, we usually have 10x more entries than directories. (69k
2769
 
        # total entries, 4k directories). So cache the results of splitting.
2770
 
        # Saving time and objects. Also, use StaticTuple to avoid putting all
2771
 
        # of these object into python's garbage collector.
2772
 
        split_dirs = {}
2773
 
        def _key(entry, _split_dirs=split_dirs, _st=static_tuple.StaticTuple):
 
2507
        def _key(entry):
2774
2508
            # sort by: directory parts, file name, file id
2775
 
            dirpath, fname, file_id = entry[0]
2776
 
            try:
2777
 
                split = _split_dirs[dirpath]
2778
 
            except KeyError:
2779
 
                split = _st.from_sequence(dirpath.split(b'/'))
2780
 
                _split_dirs[dirpath] = split
2781
 
            return _st(split, fname, file_id)
 
2509
            return entry[0][0].split('/'), entry[0][1], entry[0][2]
2782
2510
        return sorted(entry_list, key=_key)
2783
2511
 
2784
2512
    def set_state_from_inventory(self, new_inv):
2814
2542
        # underlying dirstate.
2815
2543
        old_iterator = iter(list(self._iter_entries()))
2816
2544
        # both must have roots so this is safe:
2817
 
        current_new = next(new_iterator)
2818
 
        current_old = next(old_iterator)
 
2545
        current_new = new_iterator.next()
 
2546
        current_old = old_iterator.next()
2819
2547
        def advance(iterator):
2820
2548
            try:
2821
 
                return next(iterator)
 
2549
                return iterator.next()
2822
2550
            except StopIteration:
2823
2551
                return None
2824
2552
        while current_new or current_old:
2825
2553
            # skip entries in old that are not really there
2826
 
            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':
2827
2555
                # relocated or absent
2828
2556
                current_old = advance(old_iterator)
2829
2557
                continue
2835
2563
                new_entry_key = (new_dirname, new_basename, new_id)
2836
2564
                current_new_minikind = \
2837
2565
                    DirState._kind_to_minikind[current_new[1].kind]
2838
 
                if current_new_minikind == b't':
2839
 
                    fingerprint = current_new[1].reference_revision or b''
 
2566
                if current_new_minikind == 't':
 
2567
                    fingerprint = current_new[1].reference_revision or ''
2840
2568
                else:
2841
2569
                    # We normally only insert or remove records, or update
2842
2570
                    # them when it has significantly changed.  Then we want to
2843
2571
                    # erase its fingerprint.  Unaffected records should
2844
2572
                    # normally not be updated at all.
2845
 
                    fingerprint = b''
 
2573
                    fingerprint = ''
2846
2574
            else:
2847
2575
                # for safety disable variables
2848
2576
                new_path_utf8 = new_dirname = new_basename = new_id = \
2887
2615
                # both sides are dealt with, move on
2888
2616
                current_old = advance(old_iterator)
2889
2617
                current_new = advance(new_iterator)
2890
 
            elif (lt_by_dirs(new_dirname, current_old[0][0])
 
2618
            elif (cmp_by_dirs(new_dirname, current_old[0][0]) < 0
2891
2619
                  or (new_dirname == current_old[0][0]
2892
2620
                      and new_entry_key[1:] < current_old[0][1:])):
2893
2621
                # new comes before:
2909
2637
                        current_old[0][1].decode('utf8'))
2910
2638
                self._make_absent(current_old)
2911
2639
                current_old = advance(old_iterator)
2912
 
        self._mark_modified()
 
2640
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
2913
2641
        self._id_index = None
2914
2642
        self._packed_stat_index = None
2915
2643
        if tracing:
2916
2644
            trace.mutter("set_state_from_inventory complete.")
2917
2645
 
2918
 
    def set_state_from_scratch(self, working_inv, parent_trees, parent_ghosts):
2919
 
        """Wipe the currently stored state and set it to something new.
2920
 
 
2921
 
        This is a hard-reset for the data we are working with.
2922
 
        """
2923
 
        # Technically, we really want a write lock, but until we write, we
2924
 
        # don't really need it.
2925
 
        self._requires_lock()
2926
 
        # root dir and root dir contents with no children. We have to have a
2927
 
        # root for set_state_from_inventory to work correctly.
2928
 
        empty_root = ((b'', b'', inventory.ROOT_ID),
2929
 
                      [(b'd', b'', 0, False, DirState.NULLSTAT)])
2930
 
        empty_tree_dirblocks = [(b'', [empty_root]), (b'', [])]
2931
 
        self._set_data([], empty_tree_dirblocks)
2932
 
        self.set_state_from_inventory(working_inv)
2933
 
        self.set_parent_trees(parent_trees, parent_ghosts)
2934
 
 
2935
2646
    def _make_absent(self, current_old):
2936
2647
        """Mark current_old - an entry - as absent for tree 0.
2937
2648
 
2944
2655
        all_remaining_keys = set()
2945
2656
        # Dont check the working tree, because it's going.
2946
2657
        for details in current_old[1][1:]:
2947
 
            if details[0] not in (b'a', b'r'): # absent, relocated
 
2658
            if details[0] not in 'ar': # absent, relocated
2948
2659
                all_remaining_keys.add(current_old[0])
2949
 
            elif details[0] == b'r': # relocated
 
2660
            elif details[0] == 'r': # relocated
2950
2661
                # record the key for the real path.
2951
2662
                all_remaining_keys.add(tuple(osutils.split(details[1])) + (current_old[0][2],))
2952
2663
            # absent rows are not present at any path.
2962
2673
            block[1].pop(entry_index)
2963
2674
            # if we have an id_index in use, remove this key from it for this id.
2964
2675
            if self._id_index is not None:
2965
 
                self._remove_from_id_index(self._id_index, current_old[0])
 
2676
                self._id_index[current_old[0][2]].remove(current_old[0])
2966
2677
        # update all remaining keys for this id to record it as absent. The
2967
2678
        # existing details may either be the record we are marking as deleted
2968
2679
        # (if there were other trees with the id present at this path), or may
2978
2689
                raise AssertionError('could not find entry for %s' % (update_key,))
2979
2690
            update_tree_details = self._dirblocks[update_block_index][1][update_entry_index][1]
2980
2691
            # it must not be absent at the moment
2981
 
            if update_tree_details[0][0] == b'a': # absent
 
2692
            if update_tree_details[0][0] == 'a': # absent
2982
2693
                raise AssertionError('bad row %r' % (update_tree_details,))
2983
2694
            update_tree_details[0] = DirState.NULL_PARENT_DETAILS
2984
 
        self._mark_modified()
 
2695
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
2985
2696
        return last_reference
2986
2697
 
2987
 
    def update_minimal(self, key, minikind, executable=False, fingerprint=b'',
 
2698
    def update_minimal(self, key, minikind, executable=False, fingerprint='',
2988
2699
        packed_stat=None, size=0, path_utf8=None, fullscan=False):
2989
2700
        """Update an entry to the state in tree 0.
2990
2701
 
3021
2732
        if not present:
3022
2733
            # New record. Check there isn't a entry at this path already.
3023
2734
            if not fullscan:
3024
 
                low_index, _ = self._find_entry_index(key[0:2] + (b'',), block)
 
2735
                low_index, _ = self._find_entry_index(key[0:2] + ('',), block)
3025
2736
                while low_index < len(block):
3026
2737
                    entry = block[low_index]
3027
2738
                    if entry[0][0:2] == key[0:2]:
3028
 
                        if entry[1][0][0] not in (b'a', b'r'):
 
2739
                        if entry[1][0][0] not in 'ar':
3029
2740
                            # This entry has the same path (but a different id) as
3030
2741
                            # the new entry we're adding, and is present in ths
3031
2742
                            # tree.
3032
 
                            self._raise_invalid(
3033
 
                                (b"%s/%s" % key[0:2]).decode('utf8'), key[2],
 
2743
                            raise errors.InconsistentDelta(
 
2744
                                ("%s/%s" % key[0:2]).decode('utf8'), key[2],
3034
2745
                                "Attempt to add item at path already occupied by "
3035
2746
                                "id %r" % entry[0][2])
3036
2747
                        low_index += 1
3037
2748
                    else:
3038
2749
                        break
3039
2750
            # new entry, synthesis cross reference here,
3040
 
            existing_keys = id_index.get(key[2], ())
 
2751
            existing_keys = id_index.setdefault(key[2], set())
3041
2752
            if not existing_keys:
3042
2753
                # not currently in the state, simplest case
3043
2754
                new_entry = key, [new_details] + self._empty_parent_info()
3073
2784
                    # entry, if not already examined, is skipped over by that
3074
2785
                    # loop.
3075
2786
                    other_entry = other_block[other_entry_index]
3076
 
                    other_entry[1][0] = (b'r', path_utf8, 0, False, b'')
3077
 
                    if self._maybe_remove_row(other_block, other_entry_index,
3078
 
                                              id_index):
3079
 
                        # If the row holding this was removed, we need to
3080
 
                        # recompute where this entry goes
3081
 
                        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)
3082
2790
 
3083
2791
                # This loop:
3084
2792
                # adds a tuple to the new details for each column
3086
2794
                #  - or by creating a new pointer to the right row inside that column
3087
2795
                num_present_parents = self._num_present_parents()
3088
2796
                if num_present_parents:
3089
 
                    # TODO: This re-evaluates the existing_keys set, do we need
3090
 
                    #       to do that ourselves?
3091
2797
                    other_key = list(existing_keys)[0]
3092
 
                for lookup_index in range(1, num_present_parents + 1):
 
2798
                for lookup_index in xrange(1, num_present_parents + 1):
3093
2799
                    # grab any one entry, use it to find the right path.
3094
2800
                    # TODO: optimise this to reduce memory use in highly
3095
2801
                    # fragmented situations by reusing the relocation
3103
2809
                    if not present:
3104
2810
                        raise AssertionError('update_minimal: could not find entry for %s' % (other_key,))
3105
2811
                    update_details = self._dirblocks[update_block_index][1][update_entry_index][1][lookup_index]
3106
 
                    if update_details[0] in (b'a', b'r'): # relocated, absent
 
2812
                    if update_details[0] in 'ar': # relocated, absent
3107
2813
                        # its a pointer or absent in lookup_index's tree, use
3108
2814
                        # it as is.
3109
2815
                        new_entry[1].append(update_details)
3110
2816
                    else:
3111
2817
                        # we have the right key, make a pointer to it.
3112
2818
                        pointer_path = osutils.pathjoin(*other_key[0:2])
3113
 
                        new_entry[1].append((b'r', pointer_path, 0, False, b''))
 
2819
                        new_entry[1].append(('r', pointer_path, 0, False, ''))
3114
2820
            block.insert(entry_index, new_entry)
3115
 
            self._add_to_id_index(id_index, key)
 
2821
            existing_keys.add(key)
3116
2822
        else:
3117
2823
            # Does the new state matter?
3118
2824
            block[entry_index][1][0] = new_details
3127
2833
            # converted to relocated.
3128
2834
            if path_utf8 is None:
3129
2835
                raise AssertionError('no path')
3130
 
            existing_keys = id_index.get(key[2], ())
3131
 
            if key not in existing_keys:
3132
 
                raise AssertionError('We found the entry in the blocks, but'
3133
 
                    ' the key is not in the id_index.'
3134
 
                    ' key: %s, existing_keys: %s' % (key, existing_keys))
3135
 
            for entry_key in existing_keys:
 
2836
            for entry_key in id_index.setdefault(key[2], set()):
3136
2837
                # TODO:PROFILING: It might be faster to just update
3137
2838
                # rather than checking if we need to, and then overwrite
3138
2839
                # the one we are located at.
3148
2849
                    if not present:
3149
2850
                        raise AssertionError('not present: %r', entry_key)
3150
2851
                    self._dirblocks[block_index][1][entry_index][1][0] = \
3151
 
                        (b'r', path_utf8, 0, False, b'')
 
2852
                        ('r', path_utf8, 0, False, '')
3152
2853
        # add a containing dirblock if needed.
3153
 
        if new_details[0] == b'd':
3154
 
            # GZ 2017-06-09: Using pathjoin why?
3155
 
            subdir_key = (osutils.pathjoin(*key[0:2]), b'', b'')
 
2854
        if new_details[0] == 'd':
 
2855
            subdir_key = (osutils.pathjoin(*key[0:2]), '', '')
3156
2856
            block_index, present = self._find_block_index_from_key(subdir_key)
3157
2857
            if not present:
3158
2858
                self._dirblocks.insert(block_index, (subdir_key[0], []))
3159
2859
 
3160
 
        self._mark_modified()
 
2860
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
3161
2861
 
3162
2862
    def _maybe_remove_row(self, block, index, id_index):
3163
2863
        """Remove index if it is absent or relocated across the row.
3164
2864
        
3165
2865
        id_index is updated accordingly.
3166
 
        :return: True if we removed the row, False otherwise
3167
2866
        """
3168
2867
        present_in_row = False
3169
2868
        entry = block[index]
3170
2869
        for column in entry[1]:
3171
 
            if column[0] not in (b'a', b'r'):
 
2870
            if column[0] not in 'ar':
3172
2871
                present_in_row = True
3173
2872
                break
3174
2873
        if not present_in_row:
3175
2874
            block.pop(index)
3176
 
            self._remove_from_id_index(id_index, entry[0])
3177
 
            return True
3178
 
        return False
 
2875
            id_index[entry[0][2]].remove(entry[0])
3179
2876
 
3180
2877
    def _validate(self):
3181
2878
        """Check that invariants on the dirblock are correct.
3199
2896
        from pprint import pformat
3200
2897
        self._read_dirblocks_if_needed()
3201
2898
        if len(self._dirblocks) > 0:
3202
 
            if not self._dirblocks[0][0] == b'':
 
2899
            if not self._dirblocks[0][0] == '':
3203
2900
                raise AssertionError(
3204
2901
                    "dirblocks don't start with root block:\n" + \
3205
2902
                    pformat(self._dirblocks))
3206
2903
        if len(self._dirblocks) > 1:
3207
 
            if not self._dirblocks[1][0] == b'':
 
2904
            if not self._dirblocks[1][0] == '':
3208
2905
                raise AssertionError(
3209
2906
                    "dirblocks missing root directory:\n" + \
3210
2907
                    pformat(self._dirblocks))
3211
2908
        # the dirblocks are sorted by their path components, name, and dir id
3212
 
        dir_names = [d[0].split(b'/')
 
2909
        dir_names = [d[0].split('/')
3213
2910
                for d in self._dirblocks[1:]]
3214
2911
        if dir_names != sorted(dir_names):
3215
2912
            raise AssertionError(
3239
2936
            current tree. (It is invalid to have a non-absent file in an absent
3240
2937
            directory.)
3241
2938
            """
3242
 
            if entry[0][0:2] == (b'', b''):
 
2939
            if entry[0][0:2] == ('', ''):
3243
2940
                # There should be no parent for the root row
3244
2941
                return
3245
2942
            parent_entry = self._get_entry(tree_index, path_utf8=entry[0][0])
3247
2944
                raise AssertionError(
3248
2945
                    "no parent entry for: %s in tree %s"
3249
2946
                    % (this_path, tree_index))
3250
 
            if parent_entry[1][tree_index][0] != b'd':
 
2947
            if parent_entry[1][tree_index][0] != 'd':
3251
2948
                raise AssertionError(
3252
2949
                    "Parent entry for %s is not marked as a valid"
3253
2950
                    " directory. %s" % (this_path, parent_entry,))
3261
2958
        # We check this with a dict per tree pointing either to the present
3262
2959
        # name, or None if absent.
3263
2960
        tree_count = self._num_present_parents() + 1
3264
 
        id_path_maps = [{} for _ in range(tree_count)]
 
2961
        id_path_maps = [dict() for i in range(tree_count)]
3265
2962
        # Make sure that all renamed entries point to the correct location.
3266
2963
        for entry in self._iter_entries():
3267
2964
            file_id = entry[0][2]
3275
2972
            for tree_index, tree_state in enumerate(entry[1]):
3276
2973
                this_tree_map = id_path_maps[tree_index]
3277
2974
                minikind = tree_state[0]
3278
 
                if minikind in (b'a', b'r'):
 
2975
                if minikind in 'ar':
3279
2976
                    absent_positions += 1
3280
2977
                # have we seen this id before in this column?
3281
2978
                if file_id in this_tree_map:
3282
2979
                    previous_path, previous_loc = this_tree_map[file_id]
3283
2980
                    # any later mention of this file must be consistent with
3284
2981
                    # what was said before
3285
 
                    if minikind == b'a':
 
2982
                    if minikind == 'a':
3286
2983
                        if previous_path is not None:
3287
2984
                            raise AssertionError(
3288
2985
                            "file %s is absent in row %r but also present " \
3289
2986
                            "at %r"% \
3290
2987
                            (file_id, entry, previous_path))
3291
 
                    elif minikind == b'r':
 
2988
                    elif minikind == 'r':
3292
2989
                        target_location = tree_state[1]
3293
2990
                        if previous_path != target_location:
3294
2991
                            raise AssertionError(
3304
3001
                                (entry, previous_path, previous_loc))
3305
3002
                        check_valid_parent()
3306
3003
                else:
3307
 
                    if minikind == b'a':
 
3004
                    if minikind == 'a':
3308
3005
                        # absent; should not occur anywhere else
3309
3006
                        this_tree_map[file_id] = None, this_path
3310
 
                    elif minikind == b'r':
 
3007
                    elif minikind == 'r':
3311
3008
                        # relocation, must occur at expected location
3312
3009
                        this_tree_map[file_id] = tree_state[1], this_path
3313
3010
                    else:
3317
3014
                raise AssertionError(
3318
3015
                    "entry %r has no data for any tree." % (entry,))
3319
3016
        if self._id_index is not None:
3320
 
            for file_id, entry_keys in viewitems(self._id_index):
 
3017
            for file_id, entry_keys in self._id_index.iteritems():
3321
3018
                for entry_key in entry_keys:
3322
 
                    # Check that the entry in the map is pointing to the same
3323
 
                    # file_id
3324
3019
                    if entry_key[2] != file_id:
3325
3020
                        raise AssertionError(
3326
3021
                            'file_id %r did not match entry key %s'
3327
3022
                            % (file_id, entry_key))
3328
 
                    # And that from this entry key, we can look up the original
3329
 
                    # record
3330
 
                    block_index, present = self._find_block_index_from_key(entry_key)
3331
 
                    if not present:
3332
 
                        raise AssertionError('missing block for entry key: %r', entry_key)
3333
 
                    entry_index, present = self._find_entry_index(entry_key, self._dirblocks[block_index][1])
3334
 
                    if not present:
3335
 
                        raise AssertionError('missing entry for key: %r', entry_key)
3336
 
                if len(entry_keys) != len(set(entry_keys)):
3337
 
                    raise AssertionError(
3338
 
                        'id_index contained non-unique data for %s'
3339
 
                        % (entry_keys,))
3340
3023
 
3341
3024
    def _wipe_state(self):
3342
3025
        """Forget all state information about the dirstate."""
3364
3047
        self._lock_state = 'r'
3365
3048
        self._state_file = self._lock_token.f
3366
3049
        self._wipe_state()
3367
 
        return lock.LogicalLockResult(self.unlock)
3368
3050
 
3369
3051
    def lock_write(self):
3370
3052
        """Acquire a write lock on the dirstate."""
3378
3060
        self._lock_state = 'w'
3379
3061
        self._state_file = self._lock_token.f
3380
3062
        self._wipe_state()
3381
 
        return lock.LogicalLockResult(self.unlock, self._lock_token)
3382
3063
 
3383
3064
    def unlock(self):
3384
3065
        """Drop any locks held on the dirstate."""
3401
3082
 
3402
3083
 
3403
3084
def py_update_entry(state, entry, abspath, stat_value,
3404
 
                    _stat_to_minikind=DirState._stat_to_minikind):
 
3085
                 _stat_to_minikind=DirState._stat_to_minikind,
 
3086
                 _pack_stat=pack_stat):
3405
3087
    """Update the entry based on what is actually on disk.
3406
3088
 
3407
3089
    This function only calculates the sha if it needs to - if the entry is
3416
3098
        target of a symlink.
3417
3099
    """
3418
3100
    try:
3419
 
        minikind = _stat_to_minikind[stat_value.st_mode & 0o170000]
 
3101
        minikind = _stat_to_minikind[stat_value.st_mode & 0170000]
3420
3102
    except KeyError:
3421
3103
        # Unhandled kind
3422
3104
        return None
3423
 
    packed_stat = pack_stat(stat_value)
 
3105
    packed_stat = _pack_stat(stat_value)
3424
3106
    (saved_minikind, saved_link_or_sha1, saved_file_size,
3425
3107
     saved_executable, saved_packed_stat) = entry[1][0]
3426
3108
 
3427
 
    if minikind == b'd' and saved_minikind == b't':
3428
 
        minikind = b't'
 
3109
    if minikind == 'd' and saved_minikind == 't':
 
3110
        minikind = 't'
3429
3111
    if (minikind == saved_minikind
3430
3112
        and packed_stat == saved_packed_stat):
3431
3113
        # The stat hasn't changed since we saved, so we can re-use the
3432
3114
        # saved sha hash.
3433
 
        if minikind == b'd':
 
3115
        if minikind == 'd':
3434
3116
            return None
3435
3117
 
3436
3118
        # size should also be in packed_stat
3440
3122
    # If we have gotten this far, that means that we need to actually
3441
3123
    # process this entry.
3442
3124
    link_or_sha1 = None
3443
 
    worth_saving = True
3444
 
    if minikind == b'f':
 
3125
    if minikind == 'f':
3445
3126
        executable = state._is_executable(stat_value.st_mode,
3446
3127
                                         saved_executable)
3447
3128
        if state._cutoff_time is None:
3449
3130
        if (stat_value.st_mtime < state._cutoff_time
3450
3131
            and stat_value.st_ctime < state._cutoff_time
3451
3132
            and len(entry[1]) > 1
3452
 
            and entry[1][1][0] != b'a'):
 
3133
            and entry[1][1][0] != 'a'):
3453
3134
            # Could check for size changes for further optimised
3454
3135
            # avoidance of sha1's. However the most prominent case of
3455
3136
            # over-shaing is during initial add, which this catches.
3457
3138
            # are calculated at the same time, so checking just the size
3458
3139
            # gains nothing w.r.t. performance.
3459
3140
            link_or_sha1 = state._sha1_file(abspath)
3460
 
            entry[1][0] = (b'f', link_or_sha1, stat_value.st_size,
 
3141
            entry[1][0] = ('f', link_or_sha1, stat_value.st_size,
3461
3142
                           executable, packed_stat)
3462
3143
        else:
3463
 
            entry[1][0] = (b'f', b'', stat_value.st_size,
 
3144
            entry[1][0] = ('f', '', stat_value.st_size,
3464
3145
                           executable, DirState.NULLSTAT)
3465
 
            worth_saving = False
3466
 
    elif minikind == b'd':
 
3146
    elif minikind == 'd':
3467
3147
        link_or_sha1 = None
3468
 
        entry[1][0] = (b'd', b'', 0, False, packed_stat)
3469
 
        if saved_minikind != b'd':
 
3148
        entry[1][0] = ('d', '', 0, False, packed_stat)
 
3149
        if saved_minikind != 'd':
3470
3150
            # This changed from something into a directory. Make sure we
3471
3151
            # have a directory block for it. This doesn't happen very
3472
3152
            # often, so this doesn't have to be super fast.
3474
3154
                state._get_block_entry_index(entry[0][0], entry[0][1], 0)
3475
3155
            state._ensure_block(block_index, entry_index,
3476
3156
                               osutils.pathjoin(entry[0][0], entry[0][1]))
3477
 
        else:
3478
 
            worth_saving = False
3479
 
    elif minikind == b'l':
3480
 
        if saved_minikind == b'l':
3481
 
            worth_saving = False
 
3157
    elif minikind == 'l':
3482
3158
        link_or_sha1 = state._read_link(abspath, saved_link_or_sha1)
3483
3159
        if state._cutoff_time is None:
3484
3160
            state._sha_cutoff_time()
3485
3161
        if (stat_value.st_mtime < state._cutoff_time
3486
3162
            and stat_value.st_ctime < state._cutoff_time):
3487
 
            entry[1][0] = (b'l', link_or_sha1, stat_value.st_size,
 
3163
            entry[1][0] = ('l', link_or_sha1, stat_value.st_size,
3488
3164
                           False, packed_stat)
3489
3165
        else:
3490
 
            entry[1][0] = (b'l', b'', stat_value.st_size,
 
3166
            entry[1][0] = ('l', '', stat_value.st_size,
3491
3167
                           False, DirState.NULLSTAT)
3492
 
    if worth_saving:
3493
 
        state._mark_modified([entry])
 
3168
    state._dirblock_state = DirState.IN_MEMORY_MODIFIED
3494
3169
    return link_or_sha1
3495
3170
 
3496
3171
 
3509
3184
        self.old_dirname_to_file_id = {}
3510
3185
        self.new_dirname_to_file_id = {}
3511
3186
        # Are we doing a partial iter_changes?
3512
 
        self.partial = search_specific_files != {''}
 
3187
        self.partial = search_specific_files != set([''])
3513
3188
        # Using a list so that we can access the values and change them in
3514
3189
        # nested scope. Each one is [path, file_id, entry]
3515
3190
        self.last_source_parent = [None, None]
3561
3236
            source_details = DirState.NULL_PARENT_DETAILS
3562
3237
        else:
3563
3238
            source_details = entry[1][self.source_index]
3564
 
        # GZ 2017-06-09: Eck, more sets.
3565
 
        _fdltr = {b'f', b'd', b'l', b't', b'r'}
3566
 
        _fdlt = {b'f', b'd', b'l', b't'}
3567
 
        _ra = (b'r', b'a')
3568
3239
        target_details = entry[1][self.target_index]
3569
3240
        target_minikind = target_details[0]
3570
 
        if path_info is not None and target_minikind in _fdlt:
 
3241
        if path_info is not None and target_minikind in 'fdlt':
3571
3242
            if not (self.target_index == 0):
3572
3243
                raise AssertionError()
3573
3244
            link_or_sha1 = update_entry(self.state, entry,
3579
3250
            link_or_sha1 = None
3580
3251
        file_id = entry[0][2]
3581
3252
        source_minikind = source_details[0]
3582
 
        if source_minikind in _fdltr and target_minikind in _fdlt:
 
3253
        if source_minikind in 'fdltr' and target_minikind in 'fdlt':
3583
3254
            # claimed content in both: diff
3584
3255
            #   r    | fdlt   |      | add source to search, add id path move and perform
3585
3256
            #        |        |      | diff check on source-target
3586
3257
            #   r    | fdlt   |  a   | dangling file that was present in the basis.
3587
3258
            #        |        |      | ???
3588
 
            if source_minikind == b'r':
 
3259
            if source_minikind in 'r':
3589
3260
                # add the source to the search path to find any children it
3590
3261
                # has.  TODO ? : only add if it is a container ?
3591
3262
                if not osutils.is_inside_any(self.searched_specific_files,
3601
3272
                # update the source details variable to be the real
3602
3273
                # location.
3603
3274
                if old_entry == (None, None):
3604
 
                    raise DirstateCorrupt(self.state._filename,
 
3275
                    raise errors.CorruptDirstate(self.state._filename,
3605
3276
                        "entry '%s/%s' is considered renamed from %r"
3606
3277
                        " but source does not exist\n"
3607
3278
                        "entry: %s" % (entry[0][0], entry[0][1], old_path, entry))
3623
3294
                    if path is None:
3624
3295
                        old_path = path = pathjoin(old_dirname, old_basename)
3625
3296
                    self.new_dirname_to_file_id[path] = file_id
3626
 
                    if source_minikind != b'd':
 
3297
                    if source_minikind != 'd':
3627
3298
                        content_change = True
3628
3299
                    else:
3629
3300
                        # directories have no fingerprint
3630
3301
                        content_change = False
3631
3302
                    target_exec = False
3632
3303
                elif target_kind == 'file':
3633
 
                    if source_minikind != b'f':
 
3304
                    if source_minikind != 'f':
3634
3305
                        content_change = True
3635
3306
                    else:
3636
3307
                        # Check the sha. We can't just rely on the size as
3652
3323
                    else:
3653
3324
                        target_exec = target_details[3]
3654
3325
                elif target_kind == 'symlink':
3655
 
                    if source_minikind != b'l':
 
3326
                    if source_minikind != 'l':
3656
3327
                        content_change = True
3657
3328
                    else:
3658
3329
                        content_change = (link_or_sha1 != source_details[1])
3659
3330
                    target_exec = False
3660
3331
                elif target_kind == 'tree-reference':
3661
 
                    if source_minikind != b't':
 
3332
                    if source_minikind != 't':
3662
3333
                        content_change = True
3663
3334
                    else:
3664
3335
                        content_change = False
3667
3338
                    if path is None:
3668
3339
                        path = pathjoin(old_dirname, old_basename)
3669
3340
                    raise errors.BadFileKindError(path, path_info[2])
3670
 
            if source_minikind == b'd':
 
3341
            if source_minikind == 'd':
3671
3342
                if path is None:
3672
3343
                    old_path = path = pathjoin(old_dirname, old_basename)
3673
3344
                self.old_dirname_to_file_id[old_path] = file_id
3738
3409
                       (self.utf8_decode(old_basename)[0], self.utf8_decode(entry[0][1])[0]),
3739
3410
                       (source_kind, target_kind),
3740
3411
                       (source_exec, target_exec)), changed
3741
 
        elif source_minikind in b'a' and target_minikind in _fdlt:
 
3412
        elif source_minikind in 'a' and target_minikind in 'fdlt':
3742
3413
            # looks like a new file
3743
3414
            path = pathjoin(entry[0][0], entry[0][1])
3744
3415
            # parent id is the entry for the path in the target tree
3775
3446
                       (None, self.utf8_decode(entry[0][1])[0]),
3776
3447
                       (None, None),
3777
3448
                       (None, False)), True
3778
 
        elif source_minikind in _fdlt and target_minikind in b'a':
 
3449
        elif source_minikind in 'fdlt' and target_minikind in 'a':
3779
3450
            # unversioned, possibly, or possibly not deleted: we dont care.
3780
3451
            # if its still on disk, *and* theres no other entry at this
3781
3452
            # path [we dont know this in this routine at the moment -
3793
3464
                   (self.utf8_decode(entry[0][1])[0], None),
3794
3465
                   (DirState._minikind_to_kind[source_minikind], None),
3795
3466
                   (source_details[3], None)), True
3796
 
        elif source_minikind in _fdlt and target_minikind in b'r':
 
3467
        elif source_minikind in 'fdlt' and target_minikind in 'r':
3797
3468
            # a rename; could be a true rename, or a rename inherited from
3798
3469
            # a renamed parent. TODO: handle this efficiently. Its not
3799
3470
            # common case to rename dirs though, so a correct but slow
3800
3471
            # implementation will do.
3801
3472
            if not osutils.is_inside_any(self.searched_specific_files, target_details[1]):
3802
3473
                self.search_specific_files.add(target_details[1])
3803
 
        elif source_minikind in _ra and target_minikind in _ra:
 
3474
        elif source_minikind in 'ra' and target_minikind in 'ra':
3804
3475
            # neither of the selected trees contain this file,
3805
3476
            # so skip over it. This is not currently directly tested, but
3806
3477
            # is indirectly via test_too_much.TestCommands.test_conflicts.
3809
3480
            raise AssertionError("don't know how to compare "
3810
3481
                "source_minikind=%r, target_minikind=%r"
3811
3482
                % (source_minikind, target_minikind))
 
3483
            ## import pdb;pdb.set_trace()
3812
3484
        return None, None
3813
3485
 
3814
3486
    def __iter__(self):
3828
3500
        if new_path:
3829
3501
            # Not the root and not a delete: queue up the parents of the path.
3830
3502
            self.search_specific_file_parents.update(
3831
 
                p.encode('utf8') for p in osutils.parent_directories(new_path))
 
3503
                osutils.parent_directories(new_path.encode('utf8')))
3832
3504
            # Add the root directory which parent_directories does not
3833
3505
            # provide.
3834
 
            self.search_specific_file_parents.add(b'')
 
3506
            self.search_specific_file_parents.add('')
3835
3507
 
3836
3508
    def iter_changes(self):
3837
3509
        """Iterate over the changes."""
3838
3510
        utf8_decode = cache_utf8._utf8_decode
3839
 
        _lt_by_dirs = lt_by_dirs
 
3511
        _cmp_by_dirs = cmp_by_dirs
3840
3512
        _process_entry = self._process_entry
3841
3513
        search_specific_files = self.search_specific_files
3842
3514
        searched_specific_files = self.searched_specific_files
3891
3563
            root_abspath = self.tree.abspath(current_root_unicode)
3892
3564
            try:
3893
3565
                root_stat = os.lstat(root_abspath)
3894
 
            except OSError as e:
 
3566
            except OSError, e:
3895
3567
                if e.errno == errno.ENOENT:
3896
3568
                    # the path does not exist: let _process_entry know that.
3897
3569
                    root_dir_info = None
3899
3571
                    # some other random error: hand it up.
3900
3572
                    raise
3901
3573
            else:
3902
 
                root_dir_info = (b'', current_root,
 
3574
                root_dir_info = ('', current_root,
3903
3575
                    osutils.file_kind_from_stat_mode(root_stat.st_mode), root_stat,
3904
3576
                    root_abspath)
3905
3577
                if root_dir_info[2] == 'directory':
3933
3605
                       (None, root_dir_info[2]),
3934
3606
                       (None, new_executable)
3935
3607
                      )
3936
 
            initial_key = (current_root, b'', b'')
 
3608
            initial_key = (current_root, '', '')
3937
3609
            block_index, _ = self.state._find_block_index_from_key(initial_key)
3938
3610
            if block_index == 0:
3939
3611
                # we have processed the total root already, but because the
3944
3616
            else:
3945
3617
                dir_iterator = osutils._walkdirs_utf8(root_abspath, prefix=current_root)
3946
3618
                try:
3947
 
                    current_dir_info = next(dir_iterator)
3948
 
                except OSError as e:
 
3619
                    current_dir_info = dir_iterator.next()
 
3620
                except OSError, e:
3949
3621
                    # on win32, python2.4 has e.errno == ERROR_DIRECTORY, but
3950
3622
                    # python 2.5 has e.errno == EINVAL,
3951
3623
                    #            and e.winerror == ERROR_DIRECTORY
3963
3635
                    else:
3964
3636
                        raise
3965
3637
                else:
3966
 
                    if current_dir_info[0][0] == b'':
 
3638
                    if current_dir_info[0][0] == '':
3967
3639
                        # remove .bzr from iteration
3968
 
                        bzr_index = bisect.bisect_left(current_dir_info[1], (b'.bzr',))
3969
 
                        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':
3970
3642
                            raise AssertionError()
3971
3643
                        del current_dir_info[1][bzr_index]
3972
3644
            # walk until both the directory listing and the versioned metadata
3980
3652
                   current_block is not None):
3981
3653
                if (current_dir_info and current_block
3982
3654
                    and current_dir_info[0][0] != current_block[0]):
3983
 
                    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:
3984
3656
                        # filesystem data refers to paths not covered by the dirblock.
3985
3657
                        # this has two possibilities:
3986
3658
                        # A) it is versioned but empty, so there is no block for it
4020
3692
 
4021
3693
                        # This dir info has been handled, go to the next
4022
3694
                        try:
4023
 
                            current_dir_info = next(dir_iterator)
 
3695
                            current_dir_info = dir_iterator.next()
4024
3696
                        except StopIteration:
4025
3697
                            current_dir_info = None
4026
3698
                    else:
4081
3753
                            if changed or self.include_unchanged:
4082
3754
                                yield result
4083
3755
                    elif (current_entry[0][1] != current_path_info[1]
4084
 
                          or current_entry[1][self.target_index][0] in (b'a', b'r')):
 
3756
                          or current_entry[1][self.target_index][0] in 'ar'):
4085
3757
                        # The current path on disk doesn't match the dirblock
4086
3758
                        # record. Either the dirblock is marked as absent, or
4087
3759
                        # the file on disk is not present at all in the
4172
3844
                        current_block = None
4173
3845
                if current_dir_info is not None:
4174
3846
                    try:
4175
 
                        current_dir_info = next(dir_iterator)
 
3847
                        current_dir_info = dir_iterator.next()
4176
3848
                    except StopIteration:
4177
3849
                        current_dir_info = None
4178
3850
        for result in self._iter_specific_file_parents():
4200
3872
            found_item = False
4201
3873
            for candidate_entry in path_entries:
4202
3874
                # Find entries present in target at this path:
4203
 
                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':
4204
3876
                    found_item = True
4205
3877
                    selected_entries.append(candidate_entry)
4206
3878
                # Find entries present in source at this path:
4207
3879
                elif (self.source_index is not None and
4208
 
                    candidate_entry[1][self.source_index][0] not in (b'a', b'r')):
 
3880
                    candidate_entry[1][self.source_index][0] not in 'ar'):
4209
3881
                    found_item = True
4210
 
                    if candidate_entry[1][self.target_index][0] == b'a':
 
3882
                    if candidate_entry[1][self.target_index][0] == 'a':
4211
3883
                        # Deleted, emit it here.
4212
3884
                        selected_entries.append(candidate_entry)
4213
3885
                    else:
4237
3909
                        result[6][1] != 'directory'):
4238
3910
                        # This stopped being a directory, the old children have
4239
3911
                        # to be included.
4240
 
                        if entry[1][self.source_index][0] == b'r':
 
3912
                        if entry[1][self.source_index][0] == 'r':
4241
3913
                            # renamed, take the source path
4242
3914
                            entry_path_utf8 = entry[1][self.source_index][1]
4243
3915
                        else:
4244
3916
                            entry_path_utf8 = path_utf8
4245
 
                        initial_key = (entry_path_utf8, b'', b'')
 
3917
                        initial_key = (entry_path_utf8, '', '')
4246
3918
                        block_index, _ = self.state._find_block_index_from_key(
4247
3919
                            initial_key)
4248
3920
                        if block_index == 0:
4257
3929
                                current_block = None
4258
3930
                        if current_block is not None:
4259
3931
                            for entry in current_block[1]:
4260
 
                                if entry[1][self.source_index][0] in (b'a', b'r'):
 
3932
                                if entry[1][self.source_index][0] in 'ar':
4261
3933
                                    # Not in the source tree, so doesn't have to be
4262
3934
                                    # included.
4263
3935
                                    continue
4277
3949
        abspath = self.tree.abspath(unicode_path)
4278
3950
        try:
4279
3951
            stat = os.lstat(abspath)
4280
 
        except OSError as e:
 
3952
        except OSError, e:
4281
3953
            if e.errno == errno.ENOENT:
4282
3954
                # the path does not exist.
4283
3955
                return None
4284
3956
            else:
4285
3957
                raise
4286
 
        utf8_basename = utf8_path.rsplit(b'/', 1)[-1]
 
3958
        utf8_basename = utf8_path.rsplit('/', 1)[-1]
4287
3959
        dir_info = (utf8_path, utf8_basename,
4288
3960
            osutils.file_kind_from_stat_mode(stat.st_mode), stat,
4289
3961
            abspath)
4297
3969
 
4298
3970
# Try to load the compiled form if possible
4299
3971
try:
4300
 
    from ._dirstate_helpers_pyx import (
 
3972
    from bzrlib._dirstate_helpers_pyx import (
4301
3973
        _read_dirblocks,
4302
3974
        bisect_dirblock,
4303
3975
        _bisect_path_left,
4304
3976
        _bisect_path_right,
4305
 
        lt_by_dirs,
4306
 
        pack_stat,
 
3977
        cmp_by_dirs,
4307
3978
        ProcessEntryC as _process_entry,
4308
3979
        update_entry as update_entry,
4309
3980
        )
4310
 
except ImportError as e:
 
3981
except ImportError, e:
4311
3982
    osutils.failed_to_load_extension(e)
4312
 
    from ._dirstate_helpers_py import (
 
3983
    from bzrlib._dirstate_helpers_py import (
4313
3984
        _read_dirblocks,
4314
3985
        bisect_dirblock,
4315
3986
        _bisect_path_left,
4316
3987
        _bisect_path_right,
4317
 
        lt_by_dirs,
4318
 
        pack_stat,
 
3988
        cmp_by_dirs,
4319
3989
        )
4320
3990
    # FIXME: It would be nice to be able to track moved lines so that the
4321
3991
    # corresponding python code can be moved to the _dirstate_helpers_py