/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: John Ferlito
  • Date: 2009-09-02 04:31:45 UTC
  • mto: (4665.7.1 serve-init)
  • mto: This revision was merged to the branch mainline in revision 4913.
  • Revision ID: johnf@inodes.org-20090902043145-gxdsfw03ilcwbyn5
Add a debian init script for bzr --serve

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006-2011 Canonical Ltd
 
1
# Copyright (C) 2006, 2007, 2008 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
20
20
lines by NL. The field delimiters are ommitted in the grammar, line delimiters
21
21
are not - this is done for clarity of reading. All string data is in utf8.
22
22
 
23
 
::
24
 
 
25
 
    MINIKIND = "f" | "d" | "l" | "a" | "r" | "t";
26
 
    NL = "\\n";
27
 
    NULL = "\\0";
28
 
    WHOLE_NUMBER = {digit}, digit;
29
 
    BOOLEAN = "y" | "n";
30
 
    REVISION_ID = a non-empty utf8 string;
31
 
 
32
 
    dirstate format = header line, full checksum, row count, parent details,
33
 
     ghost_details, entries;
34
 
    header line = "#bazaar dirstate flat format 3", NL;
35
 
    full checksum = "crc32: ", ["-"], WHOLE_NUMBER, NL;
36
 
    row count = "num_entries: ", WHOLE_NUMBER, NL;
37
 
    parent_details = WHOLE NUMBER, {REVISION_ID}* NL;
38
 
    ghost_details = WHOLE NUMBER, {REVISION_ID}*, NL;
39
 
    entries = {entry};
40
 
    entry = entry_key, current_entry_details, {parent_entry_details};
41
 
    entry_key = dirname,  basename, fileid;
42
 
    current_entry_details = common_entry_details, working_entry_details;
43
 
    parent_entry_details = common_entry_details, history_entry_details;
44
 
    common_entry_details = MINIKIND, fingerprint, size, executable
45
 
    working_entry_details = packed_stat
46
 
    history_entry_details = REVISION_ID;
47
 
    executable = BOOLEAN;
48
 
    size = WHOLE_NUMBER;
49
 
    fingerprint = a nonempty utf8 sequence with meaning defined by minikind.
50
 
 
51
 
Given this definition, the following is useful to know::
52
 
 
53
 
    entry (aka row) - all the data for a given key.
54
 
    entry[0]: The key (dirname, basename, fileid)
55
 
    entry[0][0]: dirname
56
 
    entry[0][1]: basename
57
 
    entry[0][2]: fileid
58
 
    entry[1]: The tree(s) data for this path and id combination.
59
 
    entry[1][0]: The current tree
60
 
    entry[1][1]: The second tree
61
 
 
62
 
For an entry for a tree, we have (using tree 0 - current tree) to demonstrate::
63
 
 
64
 
    entry[1][0][0]: minikind
65
 
    entry[1][0][1]: fingerprint
66
 
    entry[1][0][2]: size
67
 
    entry[1][0][3]: executable
68
 
    entry[1][0][4]: packed_stat
69
 
 
70
 
OR (for non tree-0)::
71
 
 
72
 
    entry[1][1][4]: revision_id
 
23
MINIKIND = "f" | "d" | "l" | "a" | "r" | "t";
 
24
NL = "\n";
 
25
NULL = "\0";
 
26
WHOLE_NUMBER = {digit}, digit;
 
27
BOOLEAN = "y" | "n";
 
28
REVISION_ID = a non-empty utf8 string;
 
29
 
 
30
dirstate format = header line, full checksum, row count, parent details,
 
31
 ghost_details, entries;
 
32
header line = "#bazaar dirstate flat format 3", NL;
 
33
full checksum = "crc32: ", ["-"], WHOLE_NUMBER, NL;
 
34
row count = "num_entries: ", WHOLE_NUMBER, NL;
 
35
parent_details = WHOLE NUMBER, {REVISION_ID}* NL;
 
36
ghost_details = WHOLE NUMBER, {REVISION_ID}*, NL;
 
37
entries = {entry};
 
38
entry = entry_key, current_entry_details, {parent_entry_details};
 
39
entry_key = dirname,  basename, fileid;
 
40
current_entry_details = common_entry_details, working_entry_details;
 
41
parent_entry_details = common_entry_details, history_entry_details;
 
42
common_entry_details = MINIKIND, fingerprint, size, executable
 
43
working_entry_details = packed_stat
 
44
history_entry_details = REVISION_ID;
 
45
executable = BOOLEAN;
 
46
size = WHOLE_NUMBER;
 
47
fingerprint = a nonempty utf8 sequence with meaning defined by minikind.
 
48
 
 
49
Given this definition, the following is useful to know:
 
50
entry (aka row) - all the data for a given key.
 
51
entry[0]: The key (dirname, basename, fileid)
 
52
entry[0][0]: dirname
 
53
entry[0][1]: basename
 
54
entry[0][2]: fileid
 
55
entry[1]: The tree(s) data for this path and id combination.
 
56
entry[1][0]: The current tree
 
57
entry[1][1]: The second tree
 
58
 
 
59
For an entry for a tree, we have (using tree 0 - current tree) to demonstrate:
 
60
entry[1][0][0]: minikind
 
61
entry[1][0][1]: fingerprint
 
62
entry[1][0][2]: size
 
63
entry[1][0][3]: executable
 
64
entry[1][0][4]: packed_stat
 
65
OR (for non tree-0)
 
66
entry[1][1][4]: revision_id
73
67
 
74
68
There may be multiple rows at the root, one per id present in the root, so the
75
 
in memory root row is now::
76
 
 
77
 
    self._dirblocks[0] -> ('', [entry ...]),
78
 
 
79
 
and the entries in there are::
80
 
 
81
 
    entries[0][0]: b''
82
 
    entries[0][1]: b''
83
 
    entries[0][2]: file_id
84
 
    entries[1][0]: The tree data for the current tree for this fileid at /
85
 
    etc.
86
 
 
87
 
Kinds::
88
 
 
89
 
   b'r' is a relocated entry: This path is not present in this tree with this
90
 
        id, but the id can be found at another location. The fingerprint is
91
 
        used to point to the target location.
92
 
   b'a' is an absent entry: In that tree the id is not present at this path.
93
 
   b'd' is a directory entry: This path in this tree is a directory with the
94
 
        current file id. There is no fingerprint for directories.
95
 
   b'f' is a file entry: As for directory, but it's a file. The fingerprint is
96
 
        the sha1 value of the file's canonical form, i.e. after any read
97
 
        filters have been applied to the convenience form stored in the working
98
 
        tree.
99
 
   b'l' is a symlink entry: As for directory, but a symlink. The fingerprint is
100
 
        the link target.
101
 
   b't' is a reference to a nested subtree; the fingerprint is the referenced
102
 
        revision.
 
69
in memory root row is now:
 
70
self._dirblocks[0] -> ('', [entry ...]),
 
71
and the entries in there are
 
72
entries[0][0]: ''
 
73
entries[0][1]: ''
 
74
entries[0][2]: file_id
 
75
entries[1][0]: The tree data for the current tree for this fileid at /
 
76
etc.
 
77
 
 
78
Kinds:
 
79
'r' is a relocated entry: This path is not present in this tree with this id,
 
80
    but the id can be found at another location. The fingerprint is used to
 
81
    point to the target location.
 
82
'a' is an absent entry: In that tree the id is not present at this path.
 
83
'd' is a directory entry: This path in this tree is a directory with the
 
84
    current file id. There is no fingerprint for directories.
 
85
'f' is a file entry: As for directory, but it's a file. The fingerprint is the
 
86
    sha1 value of the file's canonical form, i.e. after any read filters have
 
87
    been applied to the convenience form stored in the working tree.
 
88
'l' is a symlink entry: As for directory, but a symlink. The fingerprint is the
 
89
    link target.
 
90
't' is a reference to a nested subtree; the fingerprint is the referenced
 
91
    revision.
103
92
 
104
93
Ordering:
105
94
 
106
 
The entries on disk and in memory are ordered according to the following keys::
 
95
The entries on disk and in memory are ordered according to the following keys:
107
96
 
108
97
    directory, as a list of components
109
98
    filename
110
99
    file-id
111
100
 
112
101
--- Format 1 had the following different definition: ---
113
 
 
114
 
::
115
 
 
116
 
    rows = dirname, NULL, basename, NULL, MINIKIND, NULL, fileid_utf8, NULL,
117
 
        WHOLE NUMBER (* size *), NULL, packed stat, NULL, sha1|symlink target,
118
 
        {PARENT ROW}
119
 
    PARENT ROW = NULL, revision_utf8, NULL, MINIKIND, NULL, dirname, NULL,
120
 
        basename, NULL, WHOLE NUMBER (* size *), NULL, "y" | "n", NULL,
121
 
        SHA1
 
102
rows = dirname, NULL, basename, NULL, MINIKIND, NULL, fileid_utf8, NULL,
 
103
    WHOLE NUMBER (* size *), NULL, packed stat, NULL, sha1|symlink target,
 
104
    {PARENT ROW}
 
105
PARENT ROW = NULL, revision_utf8, NULL, MINIKIND, NULL, dirname, NULL,
 
106
    basename, NULL, WHOLE NUMBER (* size *), NULL, "y" | "n", NULL,
 
107
    SHA1
122
108
 
123
109
PARENT ROW's are emitted for every parent that is not in the ghosts details
124
110
line. That is, if the parents are foo, bar, baz, and the ghosts are bar, then
149
135
----
150
136
 
151
137
Design priorities:
152
 
 1. Fast end to end use for bzr's top 5 uses cases. (commmit/diff/status/merge/???)
153
 
 2. fall back current object model as needed.
154
 
 3. scale usably to the largest trees known today - say 50K entries. (mozilla
 
138
 1) Fast end to end use for bzr's top 5 uses cases. (commmit/diff/status/merge/???)
 
139
 2) fall back current object model as needed.
 
140
 3) scale usably to the largest trees known today - say 50K entries. (mozilla
155
141
    is an example of this)
156
142
 
157
143
 
158
144
Locking:
159
 
 
160
145
 Eventually reuse dirstate objects across locks IFF the dirstate file has not
161
146
 been modified, but will require that we flush/ignore cached stat-hit data
162
147
 because we won't want to restat all files on disk just because a lock was
163
148
 acquired, yet we cannot trust the data after the previous lock was released.
164
149
 
165
 
Memory representation::
166
 
 
 
150
Memory representation:
167
151
 vector of all directories, and vector of the childen ?
168
152
   i.e.
169
 
     root_entries = (direntry for root, [parent_direntries_for_root]),
 
153
     root_entrie = (direntry for root, [parent_direntries_for_root]),
170
154
     dirblocks = [
171
155
     ('', ['data for achild', 'data for bchild', 'data for cchild'])
172
156
     ('dir', ['achild', 'cchild', 'echild'])
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
219
202
"""
220
203
 
221
204
import bisect
222
 
import contextlib
 
205
import binascii
223
206
import errno
224
207
import operator
225
208
import os
226
209
from stat import S_IEXEC
227
210
import stat
 
211
import struct
228
212
import sys
229
213
import time
230
214
import zlib
231
215
 
232
 
from . import (
233
 
    inventory,
234
 
    )
235
 
from .. import (
 
216
from bzrlib import (
236
217
    cache_utf8,
237
 
    config,
238
218
    debug,
239
219
    errors,
 
220
    inventory,
240
221
    lock,
241
222
    osutils,
242
 
    static_tuple,
243
223
    trace,
244
 
    urlutils,
245
224
    )
246
 
from ..tree import TreeChange
247
225
 
248
226
 
249
227
# This is the Windows equivalent of ENOTDIR
253
231
ERROR_DIRECTORY = 267
254
232
 
255
233
 
256
 
class DirstateCorrupt(errors.BzrError):
257
 
 
258
 
    _fmt = "The dirstate file (%(state)s) appears to be corrupt: %(msg)s"
259
 
 
260
 
    def __init__(self, state, msg):
261
 
        errors.BzrError.__init__(self)
262
 
        self.state = state
263
 
        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)
264
265
 
265
266
 
266
267
class SHA1Provider(object):
276
277
 
277
278
    def stat_and_sha1(self, abspath):
278
279
        """Return the stat and sha1 of a file given its absolute path.
279
 
 
 
280
        
280
281
        :param abspath:  May be a filesystem encoded absolute path
281
282
             or a unicode path.
282
283
 
295
296
 
296
297
    def stat_and_sha1(self, abspath):
297
298
        """Return the stat and sha1 of a file given its absolute path."""
298
 
        with open(abspath, 'rb') as file_obj:
 
299
        file_obj = file(abspath, 'rb')
 
300
        try:
299
301
            statvalue = os.fstat(file_obj.fileno())
300
302
            sha1 = osutils.sha_file(file_obj)
 
303
        finally:
 
304
            file_obj.close()
301
305
        return statvalue, sha1
302
306
 
303
307
 
318
322
    """
319
323
 
320
324
    _kind_to_minikind = {
321
 
        'absent': b'a',
322
 
        'file': b'f',
323
 
        'directory': b'd',
324
 
        'relocated': b'r',
325
 
        'symlink': b'l',
326
 
        'tree-reference': b't',
 
325
            'absent': 'a',
 
326
            'file': 'f',
 
327
            'directory': 'd',
 
328
            'relocated': 'r',
 
329
            'symlink': 'l',
 
330
            'tree-reference': 't',
327
331
        }
328
332
    _minikind_to_kind = {
329
 
        b'a': 'absent',
330
 
        b'f': 'file',
331
 
        b'd': 'directory',
332
 
        b'l': 'symlink',
333
 
        b'r': 'relocated',
334
 
        b't': 'tree-reference',
 
333
            'a': 'absent',
 
334
            'f': 'file',
 
335
            'd': 'directory',
 
336
            'l':'symlink',
 
337
            'r': 'relocated',
 
338
            't': 'tree-reference',
335
339
        }
336
340
    _stat_to_minikind = {
337
 
        stat.S_IFDIR: b'd',
338
 
        stat.S_IFREG: b'f',
339
 
        stat.S_IFLNK: b'l',
 
341
        stat.S_IFDIR:'d',
 
342
        stat.S_IFREG:'f',
 
343
        stat.S_IFLNK:'l',
340
344
    }
341
 
    _to_yesno = {True: b'y', False: b'n'}  # TODO profile the performance gain
342
 
    # of using int conversion rather than a dict here. AND BLAME ANDREW IF
343
 
    # it is faster.
 
345
    _to_yesno = {True:'y', False: 'n'} # TODO profile the performance gain
 
346
     # of using int conversion rather than a dict here. AND BLAME ANDREW IF
 
347
     # it is faster.
344
348
 
345
349
    # TODO: jam 20070221 Figure out what to do if we have a record that exceeds
346
350
    #       the BISECT_PAGE_SIZE. For now, we just have to make it large enough
350
354
    NOT_IN_MEMORY = 0
351
355
    IN_MEMORY_UNMODIFIED = 1
352
356
    IN_MEMORY_MODIFIED = 2
353
 
    IN_MEMORY_HASH_MODIFIED = 3  # Only hash-cache updates
354
357
 
355
358
    # A pack_stat (the x's) that is just noise and will never match the output
356
359
    # of base64 encode.
357
 
    NULLSTAT = b'x' * 32
358
 
    NULL_PARENT_DETAILS = static_tuple.StaticTuple(b'a', b'', 0, False, b'')
359
 
 
360
 
    HEADER_FORMAT_2 = b'#bazaar dirstate flat format 2\n'
361
 
    HEADER_FORMAT_3 = b'#bazaar dirstate flat format 3\n'
362
 
 
363
 
    def __init__(self, path, sha1_provider, worth_saving_limit=0,
364
 
                 use_filesystem_for_exec=True):
 
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):
365
367
        """Create a  DirState object.
366
368
 
367
369
        :param path: The path at which the dirstate file on disk should live.
368
370
        :param sha1_provider: an object meeting the SHA1Provider interface.
369
 
        :param worth_saving_limit: when the exact number of hash changed
370
 
            entries is known, only bother saving the dirstate if more than
371
 
            this count of entries have changed.
372
 
            -1 means never save hash changes, 0 means always save hash changes.
373
 
        :param use_filesystem_for_exec: Whether to trust the filesystem
374
 
            for executable bit information
375
371
        """
376
372
        # _header_state and _dirblock_state represent the current state
377
373
        # of the dirstate metadata and the per-row data respectiely.
414
410
        # during commit.
415
411
        self._last_block_index = None
416
412
        self._last_entry_index = None
417
 
        # The set of known hash changes
418
 
        self._known_hash_changes = set()
419
 
        # How many hash changed entries can we have without saving
420
 
        self._worth_saving_limit = worth_saving_limit
421
 
        self._config_stack = config.LocationStack(urlutils.local_path_to_url(
422
 
            path))
423
 
        self._use_filesystem_for_exec = use_filesystem_for_exec
424
413
 
425
414
    def __repr__(self):
426
415
        return "%s(%r)" % \
427
416
            (self.__class__.__name__, self._filename)
428
417
 
429
 
    def _mark_modified(self, hash_changed_entries=None, header_modified=False):
430
 
        """Mark this dirstate as modified.
431
 
 
432
 
        :param hash_changed_entries: if non-None, mark just these entries as
433
 
            having their hash modified.
434
 
        :param header_modified: mark the header modified as well, not just the
435
 
            dirblocks.
436
 
        """
437
 
        #trace.mutter_callsite(3, "modified hash entries: %s", hash_changed_entries)
438
 
        if hash_changed_entries:
439
 
            self._known_hash_changes.update(
440
 
                [e[0] for e in hash_changed_entries])
441
 
            if self._dirblock_state in (DirState.NOT_IN_MEMORY,
442
 
                                        DirState.IN_MEMORY_UNMODIFIED):
443
 
                # If the dirstate is already marked a IN_MEMORY_MODIFIED, then
444
 
                # that takes precedence.
445
 
                self._dirblock_state = DirState.IN_MEMORY_HASH_MODIFIED
446
 
        else:
447
 
            # TODO: Since we now have a IN_MEMORY_HASH_MODIFIED state, we
448
 
            #       should fail noisily if someone tries to set
449
 
            #       IN_MEMORY_MODIFIED but we don't have a write-lock!
450
 
            # We don't know exactly what changed so disable smart saving
451
 
            self._dirblock_state = DirState.IN_MEMORY_MODIFIED
452
 
        if header_modified:
453
 
            self._header_state = DirState.IN_MEMORY_MODIFIED
454
 
 
455
 
    def _mark_unmodified(self):
456
 
        """Mark this dirstate as unmodified."""
457
 
        self._header_state = DirState.IN_MEMORY_UNMODIFIED
458
 
        self._dirblock_state = DirState.IN_MEMORY_UNMODIFIED
459
 
        self._known_hash_changes = set()
460
 
 
461
418
    def add(self, path, file_id, kind, stat, fingerprint):
462
419
        """Add a path to be tracked.
463
420
 
464
 
        :param path: The path within the dirstate - b'' is the root, 'foo' is the
 
421
        :param path: The path within the dirstate - '' is the root, 'foo' is the
465
422
            path foo within the root, 'foo/bar' is the path bar within foo
466
423
            within the root.
467
424
        :param file_id: The file id of the path being added.
472
429
            after any read filters have been applied),
473
430
            or the target of a symlink,
474
431
            or the referenced revision id for tree-references,
475
 
            or b'' for directories.
 
432
            or '' for directories.
476
433
        """
477
434
        # adding a file:
478
435
        # find the block its in.
479
436
        # find the location in the block.
480
437
        # check its not there
481
438
        # add it.
482
 
        # ------- copied from inventory.ensure_normalized_name - keep synced.
 
439
        #------- copied from inventory.ensure_normalized_name - keep synced.
483
440
        # --- normalized_filename wants a unicode basename only, so get one.
484
441
        dirname, basename = osutils.split(path)
485
442
        # we dont import normalized_filename directly because we want to be
493
450
        # you should never have files called . or ..; just add the directory
494
451
        # in the parent, or according to the special treatment for the root
495
452
        if basename == '.' or basename == '..':
496
 
            raise inventory.InvalidEntryName(path)
 
453
            raise errors.InvalidEntryName(path)
497
454
        # now that we've normalised, we need the correct utf8 path and
498
455
        # dirname and basename elements. This single encode and split should be
499
456
        # faster than three separate encodes.
500
457
        utf8path = (dirname + '/' + basename).strip('/').encode('utf8')
501
458
        dirname, basename = osutils.split(utf8path)
502
459
        # uses __class__ for speed; the check is needed for safety
503
 
        if file_id.__class__ is not bytes:
 
460
        if file_id.__class__ is not str:
504
461
            raise AssertionError(
505
462
                "must be a utf8 file_id not %s" % (type(file_id), ))
506
463
        # Make sure the file_id does not exist in this tree
507
464
        rename_from = None
508
 
        file_id_entry = self._get_entry(
509
 
            0, fileid_utf8=file_id, include_deleted=True)
 
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],
515
 
                                        b'r',
516
 
                                        path_utf8=b'',
517
 
                                        packed_stat=b'',
518
 
                                        fingerprint=utf8path
519
 
                                        )
 
471
                        'r',
 
472
                        path_utf8='',
 
473
                        packed_stat='',
 
474
                        fingerprint=utf8path
 
475
                    )
520
476
                    rename_from = file_id_entry[0][0:2]
521
477
            else:
522
 
                path = osutils.pathjoin(
523
 
                    file_id_entry[0][0], file_id_entry[0][1])
 
478
                path = osutils.pathjoin(file_id_entry[0][0], file_id_entry[0][1])
524
479
                kind = DirState._minikind_to_kind[file_id_entry[1][0][0]]
525
480
                info = '%s:%s' % (kind, path)
526
 
                raise inventory.DuplicateFileId(file_id, info)
527
 
        first_key = (dirname, basename, b'')
 
481
                raise errors.DuplicateFileId(file_id, info)
 
482
        first_key = (dirname, basename, '')
528
483
        block_index, present = self._find_block_index_from_key(first_key)
529
484
        if present:
530
485
            # check the path is not in the tree
531
486
            block = self._dirblocks[block_index][1]
532
487
            entry_index, _ = self._find_entry_index(first_key, block)
533
488
            while (entry_index < len(block) and
534
 
                   block[entry_index][0][0:2] == first_key[0:2]):
535
 
                if block[entry_index][1][0][0] not in (b'a', b'r'):
 
489
                block[entry_index][0][0:2] == first_key[0:2]):
 
490
                if block[entry_index][1][0][0] not in 'ar':
536
491
                    # this path is in the dirstate in the current tree.
537
 
                    raise Exception("adding already added path!")
 
492
                    raise Exception, "adding already added path!"
538
493
                entry_index += 1
539
494
        else:
540
495
            # The block where we want to put the file is not present. But it
558
513
        minikind = DirState._kind_to_minikind[kind]
559
514
        if rename_from is not None:
560
515
            if rename_from[0]:
561
 
                old_path_utf8 = b'%s/%s' % rename_from
 
516
                old_path_utf8 = '%s/%s' % rename_from
562
517
            else:
563
518
                old_path_utf8 = rename_from[1]
564
 
            parent_info[0] = (b'r', old_path_utf8, 0, False, b'')
 
519
            parent_info[0] = ('r', old_path_utf8, 0, False, '')
565
520
        if kind == 'file':
566
521
            entry_data = entry_key, [
567
522
                (minikind, fingerprint, size, False, packed_stat),
568
523
                ] + parent_info
569
524
        elif kind == 'directory':
570
525
            entry_data = entry_key, [
571
 
                (minikind, b'', 0, False, packed_stat),
 
526
                (minikind, '', 0, False, packed_stat),
572
527
                ] + parent_info
573
528
        elif kind == 'symlink':
574
529
            entry_data = entry_key, [
584
539
        if not present:
585
540
            block.insert(entry_index, entry_data)
586
541
        else:
587
 
            if block[entry_index][1][0][0] != b'a':
588
 
                raise AssertionError(" %r(%r) already added" %
589
 
                                     (basename, file_id))
 
542
            if block[entry_index][1][0][0] != 'a':
 
543
                raise AssertionError(" %r(%r) already added" % (basename, file_id))
590
544
            block[entry_index][1][0] = entry_data[1][0]
591
545
 
592
546
        if kind == 'directory':
593
 
            # insert a new dirblock
594
 
            self._ensure_block(block_index, entry_index, utf8path)
595
 
        self._mark_modified()
 
547
           # insert a new dirblock
 
548
           self._ensure_block(block_index, entry_index, utf8path)
 
549
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
596
550
        if self._id_index:
597
 
            self._add_to_id_index(self._id_index, entry_key)
 
551
            self._id_index.setdefault(entry_key[2], set()).add(entry_key)
598
552
 
599
553
    def _bisect(self, paths):
600
554
        """Bisect through the disk structure for specific rows.
612
566
        # there, this function is only meant to handle when we want to read
613
567
        # part of the disk.
614
568
        if self._dirblock_state != DirState.NOT_IN_MEMORY:
615
 
            raise AssertionError("bad dirblock state %r" %
616
 
                                 self._dirblock_state)
 
569
            raise AssertionError("bad dirblock state %r" % self._dirblock_state)
617
570
 
618
571
        # The disk representation is generally info + '\0\n\0' at the end. But
619
572
        # for bisecting, it is easier to treat this as '\0' + info + '\0\n'
622
575
        file_size = os.fstat(state_file.fileno()).st_size
623
576
        # We end up with 2 extra fields, we should have a trailing '\n' to
624
577
        # ensure that we read the whole record, and we should have a precursur
625
 
        # b'' which ensures that we start after the previous '\n'
 
578
        # '' which ensures that we start after the previous '\n'
626
579
        entry_field_count = self._fields_per_entry() + 1
627
580
 
628
581
        low = self._end_of_header
629
 
        high = file_size - 1  # Ignore the final '\0'
 
582
        high = file_size - 1 # Ignore the final '\0'
630
583
        # Map from (dir, name) => entry
631
584
        found = {}
632
585
 
633
586
        # Avoid infinite seeking
634
 
        max_count = 30 * len(paths)
 
587
        max_count = 30*len(paths)
635
588
        count = 0
636
589
        # pending is a list of places to look.
637
590
        # each entry is a tuple of low, high, dir_names
656
609
            if count > max_count:
657
610
                raise errors.BzrError('Too many seeks, most likely a bug.')
658
611
 
659
 
            mid = max(low, (low + high - page_size) // 2)
 
612
            mid = max(low, (low+high-page_size)/2)
660
613
 
661
614
            state_file.seek(mid)
662
615
            # limit the read size, so we don't end up reading data that we have
663
616
            # already read.
664
 
            read_size = min(page_size, (high - mid) + 1)
 
617
            read_size = min(page_size, (high-mid)+1)
665
618
            block = state_file.read(read_size)
666
619
 
667
620
            start = mid
668
 
            entries = block.split(b'\n')
 
621
            entries = block.split('\n')
669
622
 
670
623
            if len(entries) < 2:
671
624
                # We didn't find a '\n', so we cannot have found any records.
679
632
            # Check the first and last entries, in case they are partial, or if
680
633
            # we don't care about the rest of this page
681
634
            first_entry_num = 0
682
 
            first_fields = entries[0].split(b'\0')
 
635
            first_fields = entries[0].split('\0')
683
636
            if len(first_fields) < entry_field_count:
684
637
                # We didn't get the complete first entry
685
638
                # so move start, and grab the next, which
686
639
                # should be a full entry
687
 
                start += len(entries[0]) + 1
688
 
                first_fields = entries[1].split(b'\0')
 
640
                start += len(entries[0])+1
 
641
                first_fields = entries[1].split('\0')
689
642
                first_entry_num = 1
690
643
 
691
644
            if len(first_fields) <= 2:
699
652
                # after this first record.
700
653
                after = start
701
654
                if first_fields[1]:
702
 
                    first_path = first_fields[1] + b'/' + first_fields[2]
 
655
                    first_path = first_fields[1] + '/' + first_fields[2]
703
656
                else:
704
657
                    first_path = first_fields[2]
705
658
                first_loc = _bisect_path_left(cur_files, first_path)
714
667
                # We have files after the first entry
715
668
 
716
669
                # Parse the last entry
717
 
                last_entry_num = len(entries) - 1
718
 
                last_fields = entries[last_entry_num].split(b'\0')
 
670
                last_entry_num = len(entries)-1
 
671
                last_fields = entries[last_entry_num].split('\0')
719
672
                if len(last_fields) < entry_field_count:
720
673
                    # The very last hunk was not complete,
721
674
                    # read the previous hunk
722
675
                    after = mid + len(block) - len(entries[-1])
723
676
                    last_entry_num -= 1
724
 
                    last_fields = entries[last_entry_num].split(b'\0')
 
677
                    last_fields = entries[last_entry_num].split('\0')
725
678
                else:
726
679
                    after = mid + len(block)
727
680
 
728
681
                if last_fields[1]:
729
 
                    last_path = last_fields[1] + b'/' + last_fields[2]
 
682
                    last_path = last_fields[1] + '/' + last_fields[2]
730
683
                else:
731
684
                    last_path = last_fields[2]
732
685
                last_loc = _bisect_path_right(post, last_path)
747
700
                        post.insert(0, last_path)
748
701
 
749
702
                    # Find out what paths we have
750
 
                    paths = {first_path: [first_fields]}
 
703
                    paths = {first_path:[first_fields]}
751
704
                    # last_path might == first_path so we need to be
752
705
                    # careful if we should append rather than overwrite
753
706
                    if last_entry_num != first_entry_num:
754
707
                        paths.setdefault(last_path, []).append(last_fields)
755
 
                    for num in range(first_entry_num + 1, last_entry_num):
 
708
                    for num in xrange(first_entry_num+1, last_entry_num):
756
709
                        # TODO: jam 20070223 We are already splitting here, so
757
710
                        #       shouldn't we just split the whole thing rather
758
711
                        #       than doing the split again in add_one_record?
759
 
                        fields = entries[num].split(b'\0')
 
712
                        fields = entries[num].split('\0')
760
713
                        if fields[1]:
761
 
                            path = fields[1] + b'/' + fields[2]
 
714
                            path = fields[1] + '/' + fields[2]
762
715
                        else:
763
716
                            path = fields[2]
764
717
                        paths.setdefault(path, []).append(fields)
779
732
            if post:
780
733
                pending.append((after, high, post))
781
734
            if pre:
782
 
                pending.append((low, start - 1, pre))
 
735
                pending.append((low, start-1, pre))
783
736
 
784
737
        # Consider that we may want to return the directory entries in sorted
785
738
        # order. For now, we just return them in whatever order we found them,
806
759
        # there, this function is only meant to handle when we want to read
807
760
        # part of the disk.
808
761
        if self._dirblock_state != DirState.NOT_IN_MEMORY:
809
 
            raise AssertionError("bad dirblock state %r" %
810
 
                                 self._dirblock_state)
 
762
            raise AssertionError("bad dirblock state %r" % self._dirblock_state)
811
763
        # The disk representation is generally info + '\0\n\0' at the end. But
812
764
        # for bisecting, it is easier to treat this as '\0' + info + '\0\n'
813
765
        # Because it means we can sync on the '\n'
815
767
        file_size = os.fstat(state_file.fileno()).st_size
816
768
        # We end up with 2 extra fields, we should have a trailing '\n' to
817
769
        # ensure that we read the whole record, and we should have a precursur
818
 
        # b'' which ensures that we start after the previous '\n'
 
770
        # '' which ensures that we start after the previous '\n'
819
771
        entry_field_count = self._fields_per_entry() + 1
820
772
 
821
773
        low = self._end_of_header
822
 
        high = file_size - 1  # Ignore the final '\0'
 
774
        high = file_size - 1 # Ignore the final '\0'
823
775
        # Map from dir => entry
824
776
        found = {}
825
777
 
826
778
        # Avoid infinite seeking
827
 
        max_count = 30 * len(dir_list)
 
779
        max_count = 30*len(dir_list)
828
780
        count = 0
829
781
        # pending is a list of places to look.
830
782
        # each entry is a tuple of low, high, dir_names
849
801
            if count > max_count:
850
802
                raise errors.BzrError('Too many seeks, most likely a bug.')
851
803
 
852
 
            mid = max(low, (low + high - page_size) // 2)
 
804
            mid = max(low, (low+high-page_size)/2)
853
805
 
854
806
            state_file.seek(mid)
855
807
            # limit the read size, so we don't end up reading data that we have
856
808
            # already read.
857
 
            read_size = min(page_size, (high - mid) + 1)
 
809
            read_size = min(page_size, (high-mid)+1)
858
810
            block = state_file.read(read_size)
859
811
 
860
812
            start = mid
861
 
            entries = block.split(b'\n')
 
813
            entries = block.split('\n')
862
814
 
863
815
            if len(entries) < 2:
864
816
                # We didn't find a '\n', so we cannot have found any records.
872
824
            # Check the first and last entries, in case they are partial, or if
873
825
            # we don't care about the rest of this page
874
826
            first_entry_num = 0
875
 
            first_fields = entries[0].split(b'\0')
 
827
            first_fields = entries[0].split('\0')
876
828
            if len(first_fields) < entry_field_count:
877
829
                # We didn't get the complete first entry
878
830
                # so move start, and grab the next, which
879
831
                # should be a full entry
880
 
                start += len(entries[0]) + 1
881
 
                first_fields = entries[1].split(b'\0')
 
832
                start += len(entries[0])+1
 
833
                first_fields = entries[1].split('\0')
882
834
                first_entry_num = 1
883
835
 
884
836
            if len(first_fields) <= 1:
904
856
                # We have records to look at after the first entry
905
857
 
906
858
                # Parse the last entry
907
 
                last_entry_num = len(entries) - 1
908
 
                last_fields = entries[last_entry_num].split(b'\0')
 
859
                last_entry_num = len(entries)-1
 
860
                last_fields = entries[last_entry_num].split('\0')
909
861
                if len(last_fields) < entry_field_count:
910
862
                    # The very last hunk was not complete,
911
863
                    # read the previous hunk
912
864
                    after = mid + len(block) - len(entries[-1])
913
865
                    last_entry_num -= 1
914
 
                    last_fields = entries[last_entry_num].split(b'\0')
 
866
                    last_fields = entries[last_entry_num].split('\0')
915
867
                else:
916
868
                    after = mid + len(block)
917
869
 
934
886
                        post.insert(0, last_dir)
935
887
 
936
888
                    # Find out what paths we have
937
 
                    paths = {first_dir: [first_fields]}
 
889
                    paths = {first_dir:[first_fields]}
938
890
                    # last_dir might == first_dir so we need to be
939
891
                    # careful if we should append rather than overwrite
940
892
                    if last_entry_num != first_entry_num:
941
893
                        paths.setdefault(last_dir, []).append(last_fields)
942
 
                    for num in range(first_entry_num + 1, last_entry_num):
 
894
                    for num in xrange(first_entry_num+1, last_entry_num):
943
895
                        # TODO: jam 20070223 We are already splitting here, so
944
896
                        #       shouldn't we just split the whole thing rather
945
897
                        #       than doing the split again in add_one_record?
946
 
                        fields = entries[num].split(b'\0')
 
898
                        fields = entries[num].split('\0')
947
899
                        paths.setdefault(fields[1], []).append(fields)
948
900
 
949
901
                    for cur_dir in middle_files:
962
914
            if post:
963
915
                pending.append((after, high, post))
964
916
            if pre:
965
 
                pending.append((low, start - 1, pre))
 
917
                pending.append((low, start-1, pre))
966
918
 
967
919
        return found
968
920
 
974
926
        directories. (and renames?)
975
927
 
976
928
        :param paths: A sorted list of (dir, name) pairs
977
 
             eg: [('', b'a'), ('', b'f'), ('a/b', b'c')]
 
929
             eg: [('', 'a'), ('', 'f'), ('a/b', 'c')]
978
930
        :return: A dictionary mapping (dir, name, file_id) => [tree_info]
979
931
        """
980
932
        # Map from (dir, name, file_id) => [tree_info]
991
943
            # Directories that need to be read
992
944
            pending_dirs = set()
993
945
            paths_to_search = set()
994
 
            for entry_list in newly_found.values():
 
946
            for entry_list in newly_found.itervalues():
995
947
                for dir_name_id, trees_info in entry_list:
996
948
                    found[dir_name_id] = trees_info
997
949
                    found_dir_names.add(dir_name_id[:2])
998
950
                    is_dir = False
999
951
                    for tree_info in trees_info:
1000
952
                        minikind = tree_info[0]
1001
 
                        if minikind == b'd':
 
953
                        if minikind == 'd':
1002
954
                            if is_dir:
1003
955
                                # We already processed this one as a directory,
1004
956
                                # we don't need to do the extra work again.
1008
960
                            is_dir = True
1009
961
                            if path not in processed_dirs:
1010
962
                                pending_dirs.add(path)
1011
 
                        elif minikind == b'r':
 
963
                        elif minikind == 'r':
1012
964
                            # Rename, we need to directly search the target
1013
965
                            # which is contained in the fingerprint column
1014
966
                            dir_name = osutils.split(tree_info[1])
1041
993
            return
1042
994
        # only require all dirblocks if we are doing a full-pass removal.
1043
995
        self._read_dirblocks_if_needed()
1044
 
        dead_patterns = {(b'a', b'r'), (b'a', b'a'),
1045
 
                         (b'r', b'r'), (b'r', b'a')}
1046
 
 
 
996
        dead_patterns = set([('a', 'r'), ('a', 'a'), ('r', 'r'), ('r', 'a')])
1047
997
        def iter_entries_removable():
1048
998
            for block in self._dirblocks:
1049
999
                deleted_positions = []
1068
1018
 
1069
1019
        self._ghosts = []
1070
1020
        self._parents = [parents[0]]
1071
 
        self._mark_modified(header_modified=True)
 
1021
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
1022
        self._header_state = DirState.IN_MEMORY_MODIFIED
1072
1023
 
1073
1024
    def _empty_parent_info(self):
1074
1025
        return [DirState.NULL_PARENT_DETAILS] * (len(self._parents) -
1075
 
                                                 len(self._ghosts))
 
1026
                                                    len(self._ghosts))
1076
1027
 
1077
1028
    def _ensure_block(self, parent_block_index, parent_row_index, dirname):
1078
1029
        """Ensure a block for dirname exists.
1094
1045
        :param dirname: The utf8 dirname to ensure there is a block for.
1095
1046
        :return: The index for the block.
1096
1047
        """
1097
 
        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:
1098
1049
            # This is the signature of the root row, and the
1099
1050
            # contents-of-root row is always index 1
1100
1051
            return 1
1101
1052
        # the basename of the directory must be the end of its full name.
1102
1053
        if not (parent_block_index == -1 and
1103
 
                parent_block_index == -1 and dirname == b''):
 
1054
            parent_block_index == -1 and dirname == ''):
1104
1055
            if not dirname.endswith(
1105
1056
                    self._dirblocks[parent_block_index][1][parent_row_index][0][1]):
1106
1057
                raise AssertionError("bad dirname %r" % dirname)
1107
 
        block_index, present = self._find_block_index_from_key(
1108
 
            (dirname, b'', b''))
 
1058
        block_index, present = self._find_block_index_from_key((dirname, '', ''))
1109
1059
        if not present:
1110
 
            # In future, when doing partial parsing, this should load and
 
1060
            ## In future, when doing partial parsing, this should load and
1111
1061
            # populate the entire block.
1112
1062
            self._dirblocks.insert(block_index, (dirname, []))
1113
1063
        return block_index
1122
1072
            to prevent unneeded overhead when callers have a sorted list already.
1123
1073
        :return: Nothing.
1124
1074
        """
1125
 
        if new_entries[0][0][0:2] != (b'', b''):
 
1075
        if new_entries[0][0][0:2] != ('', ''):
1126
1076
            raise AssertionError(
1127
1077
                "Missing root row %r" % (new_entries[0][0],))
1128
1078
        # The two blocks here are deliberate: the root block and the
1129
1079
        # contents-of-root block.
1130
 
        self._dirblocks = [(b'', []), (b'', [])]
 
1080
        self._dirblocks = [('', []), ('', [])]
1131
1081
        current_block = self._dirblocks[0][1]
1132
 
        current_dirname = b''
1133
 
        root_key = (b'', b'')
 
1082
        current_dirname = ''
 
1083
        root_key = ('', '')
1134
1084
        append_entry = current_block.append
1135
1085
        for entry in new_entries:
1136
1086
            if entry[0][0] != current_dirname:
1152
1102
        # The above loop leaves the "root block" entries mixed with the
1153
1103
        # "contents-of-root block". But we don't want an if check on
1154
1104
        # all entries, so instead we just fix it up here.
1155
 
        if self._dirblocks[1] != (b'', []):
 
1105
        if self._dirblocks[1] != ('', []):
1156
1106
            raise ValueError("bad dirblock start %r" % (self._dirblocks[1],))
1157
1107
        root_block = []
1158
1108
        contents_of_root_block = []
1159
1109
        for entry in self._dirblocks[0][1]:
1160
 
            if not entry[0][1]:  # This is a root entry
 
1110
            if not entry[0][1]: # This is a root entry
1161
1111
                root_block.append(entry)
1162
1112
            else:
1163
1113
                contents_of_root_block.append(entry)
1164
 
        self._dirblocks[0] = (b'', root_block)
1165
 
        self._dirblocks[1] = (b'', contents_of_root_block)
 
1114
        self._dirblocks[0] = ('', root_block)
 
1115
        self._dirblocks[1] = ('', contents_of_root_block)
1166
1116
 
1167
1117
    def _entries_for_path(self, path):
1168
1118
        """Return a list with all the entries that match path for all ids."""
1169
1119
        dirname, basename = os.path.split(path)
1170
 
        key = (dirname, basename, b'')
 
1120
        key = (dirname, basename, '')
1171
1121
        block_index, present = self._find_block_index_from_key(key)
1172
1122
        if not present:
1173
1123
            # the block which should contain path is absent.
1177
1127
        entry_index, _ = self._find_entry_index(key, block)
1178
1128
        # we may need to look at multiple entries at this path: walk while the specific_files match.
1179
1129
        while (entry_index < len(block) and
1180
 
               block[entry_index][0][0:2] == key[0:2]):
 
1130
            block[entry_index][0][0:2] == key[0:2]):
1181
1131
            result.append(block[entry_index])
1182
1132
            entry_index += 1
1183
1133
        return result
1196
1146
            # minikind
1197
1147
            entire_entry[tree_offset + 0] = tree_data[0]
1198
1148
            # size
1199
 
            entire_entry[tree_offset + 2] = b'%d' % tree_data[2]
 
1149
            entire_entry[tree_offset + 2] = str(tree_data[2])
1200
1150
            # executable
1201
1151
            entire_entry[tree_offset + 3] = DirState._to_yesno[tree_data[3]]
1202
 
        return b'\0'.join(entire_entry)
 
1152
        return '\0'.join(entire_entry)
1203
1153
 
1204
1154
    def _fields_per_entry(self):
1205
1155
        """How many null separated fields should be in each entry row.
1206
1156
 
1207
 
        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
1208
1158
        so we just skip over it
1209
 
 
1210
 
        entry size::
 
1159
        entry size:
1211
1160
            3 fields for the key
1212
1161
            + number of fields per tree_data (5) * tree count
1213
1162
            + newline
1242
1191
 
1243
1192
        :return: The block index, True if the block for the key is present.
1244
1193
        """
1245
 
        if key[0:2] == (b'', b''):
 
1194
        if key[0:2] == ('', ''):
1246
1195
            return 0, True
1247
1196
        try:
1248
1197
            if (self._last_block_index is not None and
1249
 
                    self._dirblocks[self._last_block_index][0] == key[0]):
 
1198
                self._dirblocks[self._last_block_index][0] == key[0]):
1250
1199
                return self._last_block_index, True
1251
1200
        except IndexError:
1252
1201
            pass
1254
1203
                                      cache=self._split_path_cache)
1255
1204
        # _right returns one-past-where-key is so we have to subtract
1256
1205
        # one to use it. we use _right here because there are two
1257
 
        # b'' blocks - the root, and the contents of root
 
1206
        # '' blocks - the root, and the contents of root
1258
1207
        # we always have a minimum of 2 in self._dirblocks: root and
1259
 
        # root-contents, and for b'', we get 2 back, so this is
 
1208
        # root-contents, and for '', we get 2 back, so this is
1260
1209
        # simple and correct:
1261
1210
        present = (block_index < len(self._dirblocks) and
1262
 
                   self._dirblocks[block_index][0] == key[0])
 
1211
            self._dirblocks[block_index][0] == key[0])
1263
1212
        self._last_block_index = block_index
1264
1213
        # Reset the entry index cache to the beginning of the block.
1265
1214
        self._last_entry_index = -1
1278
1227
                # A hit is when the key is after the last slot, and before or
1279
1228
                # equal to the next slot.
1280
1229
                if ((entry_index > 0 and block[entry_index - 1][0] < key) and
1281
 
                        key <= block[entry_index][0]):
 
1230
                    key <= block[entry_index][0]):
1282
1231
                    self._last_entry_index = entry_index
1283
1232
                    present = (block[entry_index][0] == key)
1284
1233
                    return entry_index, present
1286
1235
            pass
1287
1236
        entry_index = bisect.bisect_left(block, (key, []))
1288
1237
        present = (entry_index < len_block and
1289
 
                   block[entry_index][0] == key)
 
1238
            block[entry_index][0] == key)
1290
1239
        self._last_entry_index = entry_index
1291
1240
        return entry_index, present
1292
1241
 
1302
1251
            (it was locked by DirState.initialize)
1303
1252
        """
1304
1253
        result = DirState.initialize(dir_state_filename,
1305
 
                                     sha1_provider=sha1_provider)
 
1254
            sha1_provider=sha1_provider)
1306
1255
        try:
1307
 
            with contextlib.ExitStack() as exit_stack:
1308
 
                exit_stack.enter_context(tree.lock_read())
 
1256
            tree.lock_read()
 
1257
            try:
1309
1258
                parent_ids = tree.get_parent_ids()
1310
1259
                num_parents = len(parent_ids)
1311
1260
                parent_trees = []
1312
1261
                for parent_id in parent_ids:
1313
 
                    parent_tree = tree.branch.repository.revision_tree(
1314
 
                        parent_id)
 
1262
                    parent_tree = tree.branch.repository.revision_tree(parent_id)
1315
1263
                    parent_trees.append((parent_id, parent_tree))
1316
 
                    exit_stack.enter_context(parent_tree.lock_read())
 
1264
                    parent_tree.lock_read()
1317
1265
                result.set_parent_trees(parent_trees, [])
1318
 
                result.set_state_from_inventory(tree.root_inventory)
 
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()
1319
1271
        except:
1320
1272
            # The caller won't have a chance to unlock this, so make sure we
1321
1273
            # cleanup ourselves
1323
1275
            raise
1324
1276
        return result
1325
1277
 
1326
 
    def _check_delta_is_valid(self, delta):
1327
 
        delta = list(inventory._check_delta_unique_ids(
1328
 
                     inventory._check_delta_unique_old_paths(
1329
 
                         inventory._check_delta_unique_new_paths(
1330
 
                             inventory._check_delta_ids_match_entry(
1331
 
                                 inventory._check_delta_ids_are_valid(
1332
 
                                     inventory._check_delta_new_path_entry_both_or_None(delta)))))))
1333
 
 
1334
 
        def delta_key(d):
1335
 
            (old_path, new_path, file_id, new_entry) = d
1336
 
            if old_path is None:
1337
 
                old_path = ''
1338
 
            if new_path is None:
1339
 
                new_path = ''
1340
 
            return (old_path, new_path, file_id, new_entry)
1341
 
        delta.sort(key=delta_key, reverse=True)
1342
 
        return delta
1343
 
 
1344
1278
    def update_by_delta(self, delta):
1345
1279
        """Apply an inventory delta to the dirstate for tree 0
1346
1280
 
1364
1298
        new_ids = set()
1365
1299
        # This loop transforms the delta to single atomic operations that can
1366
1300
        # be executed and validated.
1367
 
        delta = self._check_delta_is_valid(delta)
1368
 
        for old_path, new_path, file_id, inv_entry in delta:
1369
 
            if not isinstance(file_id, bytes):
1370
 
                raise AssertionError(
1371
 
                    "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):
1372
1308
            if (file_id in insertions) or (file_id in removals):
1373
 
                self._raise_invalid(old_path or new_path, file_id,
1374
 
                                    "repeated file_id")
 
1309
                raise errors.InconsistentDelta(old_path or new_path, file_id,
 
1310
                    "repeated file_id")
1375
1311
            if old_path is not None:
1376
1312
                old_path = old_path.encode('utf-8')
1377
1313
                removals[file_id] = old_path
1379
1315
                new_ids.add(file_id)
1380
1316
            if new_path is not None:
1381
1317
                if inv_entry is None:
1382
 
                    self._raise_invalid(new_path, file_id,
1383
 
                                        "new_path with no entry")
 
1318
                    raise errors.InconsistentDelta(new_path, file_id,
 
1319
                        "new_path with no entry")
1384
1320
                new_path = new_path.encode('utf-8')
1385
1321
                dirname_utf8, basename = osutils.split(new_path)
1386
1322
                if basename:
1387
1323
                    parents.add((dirname_utf8, inv_entry.parent_id))
1388
1324
                key = (dirname_utf8, basename, file_id)
1389
1325
                minikind = DirState._kind_to_minikind[inv_entry.kind]
1390
 
                if minikind == b't':
1391
 
                    fingerprint = inv_entry.reference_revision or b''
 
1326
                if minikind == 't':
 
1327
                    fingerprint = inv_entry.reference_revision
1392
1328
                else:
1393
 
                    fingerprint = b''
 
1329
                    fingerprint = ''
1394
1330
                insertions[file_id] = (key, minikind, inv_entry.executable,
1395
1331
                                       fingerprint, new_path)
1396
1332
            # Transform moves into delete+add pairs
1403
1339
                    minikind = child[1][0][0]
1404
1340
                    fingerprint = child[1][0][4]
1405
1341
                    executable = child[1][0][3]
1406
 
                    old_child_path = osutils.pathjoin(child_dirname,
1407
 
                                                      child_basename)
 
1342
                    old_child_path = osutils.pathjoin(child[0][0],
 
1343
                                                      child[0][1])
1408
1344
                    removals[child[0][2]] = old_child_path
1409
1345
                    child_suffix = child_dirname[len(old_path):]
1410
1346
                    new_child_dirname = (new_path + child_suffix)
1411
1347
                    key = (new_child_dirname, child_basename, child[0][2])
1412
 
                    new_child_path = osutils.pathjoin(new_child_dirname,
1413
 
                                                      child_basename)
 
1348
                    new_child_path = os.path.join(new_child_dirname,
 
1349
                                                  child_basename)
1414
1350
                    insertions[child[0][2]] = (key, minikind, executable,
1415
1351
                                               fingerprint, new_child_path)
1416
1352
        self._check_delta_ids_absent(new_ids, delta, 0)
1417
1353
        try:
1418
 
            self._apply_removals(removals.items())
 
1354
            self._apply_removals(removals.iteritems())
1419
1355
            self._apply_insertions(insertions.values())
1420
1356
            # Validate parents
1421
1357
            self._after_delta_check_parents(parents, 0)
1422
 
        except errors.BzrError as e:
 
1358
        except errors.BzrError, e:
1423
1359
            self._changes_aborted = True
1424
1360
            if 'integrity error' not in str(e):
1425
1361
                raise
1426
1362
            # _get_entry raises BzrError when a request is inconsistent; we
1427
 
            # want such errors to be shown as InconsistentDelta - and that
 
1363
            # want such errors to be shown as InconsistentDelta - and that 
1428
1364
            # fits the behaviour we trigger.
1429
 
            raise errors.InconsistentDeltaDelta(delta,
1430
 
                                                "error from _get_entry. %s" % (e,))
 
1365
            raise errors.InconsistentDeltaDelta(delta, "error from _get_entry.")
1431
1366
 
1432
1367
    def _apply_removals(self, removals):
1433
1368
        for file_id, path in sorted(removals, reverse=True,
1434
 
                                    key=operator.itemgetter(1)):
 
1369
            key=operator.itemgetter(1)):
1435
1370
            dirname, basename = osutils.split(path)
1436
1371
            block_i, entry_i, d_present, f_present = \
1437
1372
                self._get_block_entry_index(dirname, basename, 0)
1438
1373
            try:
1439
1374
                entry = self._dirblocks[block_i][1][entry_i]
1440
1375
            except IndexError:
1441
 
                self._raise_invalid(path, file_id,
1442
 
                                    "Wrong path for old path.")
1443
 
            if not f_present or entry[1][0][0] in (b'a', b'r'):
1444
 
                self._raise_invalid(path, file_id,
1445
 
                                    "Wrong path for old path.")
 
1376
                self._changes_aborted = True
 
1377
                raise errors.InconsistentDelta(path, file_id,
 
1378
                    "Wrong path for old path.")
 
1379
            if not f_present or entry[1][0][0] in 'ar':
 
1380
                self._changes_aborted = True
 
1381
                raise errors.InconsistentDelta(path, file_id,
 
1382
                    "Wrong path for old path.")
1446
1383
            if file_id != entry[0][2]:
1447
 
                self._raise_invalid(path, file_id,
1448
 
                                    "Attempt to remove path has wrong id - found %r."
1449
 
                                    % entry[0][2])
 
1384
                self._changes_aborted = True
 
1385
                raise errors.InconsistentDelta(path, file_id,
 
1386
                    "Attempt to remove path has wrong id - found %r."
 
1387
                    % entry[0][2])
1450
1388
            self._make_absent(entry)
1451
1389
            # See if we have a malformed delta: deleting a directory must not
1452
1390
            # leave crud behind. This increases the number of bisects needed
1454
1392
            # is rare enough it shouldn't be an issue (famous last words?) RBC
1455
1393
            # 20080730.
1456
1394
            block_i, entry_i, d_present, f_present = \
1457
 
                self._get_block_entry_index(path, b'', 0)
 
1395
                self._get_block_entry_index(path, '', 0)
1458
1396
            if d_present:
1459
1397
                # The dir block is still present in the dirstate; this could
1460
1398
                # be due to it being in a parent tree, or a corrupt delta.
1461
1399
                for child_entry in self._dirblocks[block_i][1]:
1462
 
                    if child_entry[1][0][0] not in (b'r', b'a'):
1463
 
                        self._raise_invalid(path, entry[0][2],
1464
 
                                            "The file id was deleted but its children were "
1465
 
                                            "not deleted.")
 
1400
                    if child_entry[1][0][0] not in ('r', 'a'):
 
1401
                        self._changes_aborted = True
 
1402
                        raise errors.InconsistentDelta(path, entry[0][2],
 
1403
                            "The file id was deleted but its children were "
 
1404
                            "not deleted.")
1466
1405
 
1467
1406
    def _apply_insertions(self, adds):
1468
1407
        try:
1470
1409
                self.update_minimal(key, minikind, executable, fingerprint,
1471
1410
                                    path_utf8=path_utf8)
1472
1411
        except errors.NotVersionedError:
1473
 
            self._raise_invalid(path_utf8.decode('utf8'), key[2],
1474
 
                                "Missing parent")
 
1412
            self._changes_aborted = True
 
1413
            raise errors.InconsistentDelta(path_utf8.decode('utf8'), key[2],
 
1414
                "Missing parent")
1475
1415
 
1476
1416
    def update_basis_by_delta(self, delta, new_revid):
1477
1417
        """Update the parents of this tree after a commit.
1484
1424
        Note that an exception during the operation of this method will leave
1485
1425
        the dirstate in a corrupt state where it should not be saved.
1486
1426
 
 
1427
        Finally, we expect all changes to be synchronising the basis tree with
 
1428
        the working tree.
 
1429
 
1487
1430
        :param new_revid: The new revision id for the trees parent.
1488
1431
        :param delta: An inventory delta (see apply_inventory_delta) describing
1489
1432
            the changes from the current left most parent revision to new_revid.
1501
1444
 
1502
1445
        self._parents[0] = new_revid
1503
1446
 
1504
 
        delta = self._check_delta_is_valid(delta)
 
1447
        delta = sorted(delta, reverse=True)
1505
1448
        adds = []
1506
1449
        changes = []
1507
1450
        deletes = []
1527
1470
        # ids.
1528
1471
        new_ids = set()
1529
1472
        for old_path, new_path, file_id, inv_entry in delta:
1530
 
            if file_id.__class__ is not bytes:
1531
 
                raise AssertionError(
1532
 
                    "must be a utf8 file_id not %s" % (type(file_id), ))
1533
1473
            if inv_entry is not None and file_id != inv_entry.file_id:
1534
 
                self._raise_invalid(new_path, file_id,
1535
 
                                    "mismatched entry file_id %r" % inv_entry)
1536
 
            if new_path is None:
1537
 
                new_path_utf8 = None
1538
 
            else:
 
1474
                raise errors.InconsistentDelta(new_path, file_id,
 
1475
                    "mismatched entry file_id %r" % inv_entry)
 
1476
            if new_path is not None:
1539
1477
                if inv_entry is None:
1540
 
                    self._raise_invalid(new_path, file_id,
1541
 
                                        "new_path with no entry")
 
1478
                    raise errors.InconsistentDelta(new_path, file_id,
 
1479
                        "new_path with no entry")
1542
1480
                new_path_utf8 = encode(new_path)
1543
1481
                # note the parent for validation
1544
1482
                dirname_utf8, basename_utf8 = osutils.split(new_path_utf8)
1545
1483
                if basename_utf8:
1546
1484
                    parents.add((dirname_utf8, inv_entry.parent_id))
1547
1485
            if old_path is None:
1548
 
                old_path_utf8 = None
1549
 
            else:
1550
 
                old_path_utf8 = encode(old_path)
1551
 
            if old_path is None:
1552
 
                adds.append((None, new_path_utf8, file_id,
1553
 
                             inv_to_entry(inv_entry), True))
 
1486
                adds.append((None, encode(new_path), file_id,
 
1487
                    inv_to_entry(inv_entry), True))
1554
1488
                new_ids.add(file_id)
1555
1489
            elif new_path is None:
1556
 
                deletes.append((old_path_utf8, None, file_id, None, True))
1557
 
            elif (old_path, new_path) == root_only:
1558
 
                # change things in-place
1559
 
                # Note: the case of a parent directory changing its file_id
1560
 
                #       tends to break optimizations here, because officially
1561
 
                #       the file has actually been moved, it just happens to
1562
 
                #       end up at the same path. If we can figure out how to
1563
 
                #       handle that case, we can avoid a lot of add+delete
1564
 
                #       pairs for objects that stay put.
1565
 
                # elif old_path == new_path:
1566
 
                changes.append((old_path_utf8, new_path_utf8, file_id,
1567
 
                                inv_to_entry(inv_entry)))
1568
 
            else:
 
1490
                deletes.append((encode(old_path), None, file_id, None, True))
 
1491
            elif (old_path, new_path) != root_only:
1569
1492
                # Renames:
1570
1493
                # Because renames must preserve their children we must have
1571
1494
                # processed all relocations and removes before hand. The sort
1574
1497
                # pair will result in the deleted item being reinserted, or
1575
1498
                # renamed items being reinserted twice - and possibly at the
1576
1499
                # wrong place. Splitting into a delete/add pair also simplifies
1577
 
                # the handling of entries with (b'f', ...), (b'r' ...) because
1578
 
                # the target of the b'r' is old_path here, and we add that to
 
1500
                # the handling of entries with ('f', ...), ('r' ...) because
 
1501
                # the target of the 'r' is old_path here, and we add that to
1579
1502
                # deletes, meaning that the add handler does not need to check
1580
 
                # for b'r' items on every pass.
 
1503
                # for 'r' items on every pass.
1581
1504
                self._update_basis_apply_deletes(deletes)
1582
1505
                deletes = []
1583
1506
                # Split into an add/delete pair recursively.
1584
 
                adds.append((old_path_utf8, new_path_utf8, file_id,
1585
 
                             inv_to_entry(inv_entry), False))
 
1507
                adds.append((None, new_path_utf8, file_id,
 
1508
                    inv_to_entry(inv_entry), False))
1586
1509
                # Expunge deletes that we've seen so that deleted/renamed
1587
1510
                # children of a rename directory are handled correctly.
1588
 
                new_deletes = reversed(list(
1589
 
                    self._iter_child_entries(1, old_path_utf8)))
 
1511
                new_deletes = reversed(list(self._iter_child_entries(1,
 
1512
                    encode(old_path))))
1590
1513
                # Remove the current contents of the tree at orig_path, and
1591
1514
                # reinsert at the correct new path.
1592
1515
                for entry in new_deletes:
1593
 
                    child_dirname, child_basename, child_file_id = entry[0]
1594
 
                    if child_dirname:
1595
 
                        source_path = child_dirname + b'/' + child_basename
 
1516
                    if entry[0][0]:
 
1517
                        source_path = entry[0][0] + '/' + entry[0][1]
1596
1518
                    else:
1597
 
                        source_path = child_basename
 
1519
                        source_path = entry[0][1]
1598
1520
                    if new_path_utf8:
1599
 
                        target_path = \
1600
 
                            new_path_utf8 + source_path[len(old_path_utf8):]
 
1521
                        target_path = new_path_utf8 + source_path[len(old_path):]
1601
1522
                    else:
1602
 
                        if old_path_utf8 == b'':
 
1523
                        if old_path == '':
1603
1524
                            raise AssertionError("cannot rename directory to"
1604
 
                                                 " itself")
1605
 
                        target_path = source_path[len(old_path_utf8) + 1:]
1606
 
                    adds.append(
1607
 
                        (None, target_path, entry[0][2], entry[1][1], False))
 
1525
                                " itself")
 
1526
                        target_path = source_path[len(old_path) + 1:]
 
1527
                    adds.append((None, target_path, entry[0][2], entry[1][1], False))
1608
1528
                    deletes.append(
1609
1529
                        (source_path, target_path, entry[0][2], None, False))
1610
1530
                deletes.append(
1611
 
                    (old_path_utf8, new_path_utf8, file_id, None, False))
1612
 
 
 
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)))
1613
1537
        self._check_delta_ids_absent(new_ids, delta, 1)
1614
1538
        try:
1615
1539
            # Finish expunging deletes/first half of renames.
1620
1544
            self._update_basis_apply_changes(changes)
1621
1545
            # Validate parents
1622
1546
            self._after_delta_check_parents(parents, 1)
1623
 
        except errors.BzrError as e:
 
1547
        except errors.BzrError, e:
1624
1548
            self._changes_aborted = True
1625
1549
            if 'integrity error' not in str(e):
1626
1550
                raise
1627
1551
            # _get_entry raises BzrError when a request is inconsistent; we
1628
 
            # want such errors to be shown as InconsistentDelta - and that
1629
 
            # fits the behaviour we trigger.
1630
 
            raise errors.InconsistentDeltaDelta(delta,
1631
 
                                                "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.")
1632
1557
 
1633
 
        self._mark_modified(header_modified=True)
 
1558
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
1559
        self._header_state = DirState.IN_MEMORY_MODIFIED
1634
1560
        self._id_index = None
1635
1561
        return
1636
1562
 
1640
1566
            return
1641
1567
        id_index = self._get_id_index()
1642
1568
        for file_id in new_ids:
1643
 
            for key in id_index.get(file_id, ()):
 
1569
            for key in id_index.get(file_id, []):
1644
1570
                block_i, entry_i, d_present, f_present = \
1645
1571
                    self._get_block_entry_index(key[0], key[1], tree_index)
1646
1572
                if not f_present:
1650
1576
                if entry[0][2] != file_id:
1651
1577
                    # Different file_id, so not what we want.
1652
1578
                    continue
1653
 
                self._raise_invalid((b"%s/%s" % key[0:2]).decode('utf8'), file_id,
1654
 
                                    "This file_id is new in the delta but already present in "
1655
 
                                    "the target")
1656
 
 
1657
 
    def _raise_invalid(self, path, file_id, reason):
1658
 
        self._changes_aborted = True
1659
 
        raise errors.InconsistentDelta(path, file_id, reason)
 
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,
 
1583
                    "This file_id is new in the delta but already present in "
 
1584
                    "the target")
1660
1585
 
1661
1586
    def _update_basis_apply_adds(self, adds):
1662
1587
        """Apply a sequence of adds to tree 1 during update_basis_by_delta.
1671
1596
        """
1672
1597
        # Adds are accumulated partly from renames, so can be in any input
1673
1598
        # order - sort it.
1674
 
        # TODO: we may want to sort in dirblocks order. That way each entry
1675
 
        #       will end up in the same directory, allowing the _get_entry
1676
 
        #       fast-path for looking up 2 items in the same dir work.
1677
 
        adds.sort(key=lambda x: x[1])
 
1599
        adds.sort()
1678
1600
        # adds is now in lexographic order, which places all parents before
1679
1601
        # their children, so we can process it linearly.
1680
 
        st = static_tuple.StaticTuple
 
1602
        absent = 'ar'
1681
1603
        for old_path, new_path, file_id, new_details, real_add in adds:
1682
 
            dirname, basename = osutils.split(new_path)
1683
 
            entry_key = st(dirname, basename, file_id)
1684
 
            block_index, present = self._find_block_index_from_key(entry_key)
1685
 
            if not present:
1686
 
                # The block where we want to put the file is not present.
1687
 
                # However, it might have just been an empty directory. Look for
1688
 
                # the parent in the basis-so-far before throwing an error.
1689
 
                parent_dir, parent_base = osutils.split(dirname)
1690
 
                parent_block_idx, parent_entry_idx, _, parent_present = \
1691
 
                    self._get_block_entry_index(parent_dir, parent_base, 1)
1692
 
                if not parent_present:
1693
 
                    self._raise_invalid(new_path, file_id,
1694
 
                                        "Unable to find block for this record."
1695
 
                                        " Was the parent added?")
1696
 
                self._ensure_block(parent_block_idx, parent_entry_idx, dirname)
1697
 
 
1698
 
            block = self._dirblocks[block_index][1]
1699
 
            entry_index, present = self._find_entry_index(entry_key, block)
1700
 
            if real_add:
1701
 
                if old_path is not None:
1702
 
                    self._raise_invalid(new_path, file_id,
1703
 
                                        'considered a real add but still had old_path at %s'
1704
 
                                        % (old_path,))
1705
 
            if present:
1706
 
                entry = block[entry_index]
1707
 
                basis_kind = entry[1][1][0]
1708
 
                if basis_kind == b'a':
1709
 
                    entry[1][1] = new_details
1710
 
                elif basis_kind == b'r':
1711
 
                    raise NotImplementedError()
1712
 
                else:
1713
 
                    self._raise_invalid(new_path, file_id,
1714
 
                                        "An entry was marked as a new add"
1715
 
                                        " but the basis target already existed")
1716
 
            else:
1717
 
                # The exact key was not found in the block. However, we need to
1718
 
                # check if there is a key next to us that would have matched.
1719
 
                # We only need to check 2 locations, because there are only 2
1720
 
                # trees present.
1721
 
                for maybe_index in range(entry_index - 1, entry_index + 1):
1722
 
                    if maybe_index < 0 or maybe_index >= len(block):
1723
 
                        continue
1724
 
                    maybe_entry = block[maybe_index]
1725
 
                    if maybe_entry[0][:2] != (dirname, basename):
1726
 
                        # Just a random neighbor
1727
 
                        continue
1728
 
                    if maybe_entry[0][2] == file_id:
1729
 
                        raise AssertionError(
1730
 
                            '_find_entry_index didnt find a key match'
1731
 
                            ' but walking the data did, for %s'
1732
 
                            % (entry_key,))
1733
 
                    basis_kind = maybe_entry[1][1][0]
1734
 
                    if basis_kind not in (b'a', b'r'):
1735
 
                        self._raise_invalid(new_path, file_id,
1736
 
                                            "we have an add record for path, but the path"
1737
 
                                            " is already present with another file_id %s"
1738
 
                                            % (maybe_entry[0][2],))
1739
 
 
1740
 
                entry = (entry_key, [DirState.NULL_PARENT_DETAILS,
1741
 
                                     new_details])
1742
 
                block.insert(entry_index, entry)
1743
 
 
1744
 
            active_kind = entry[1][0][0]
1745
 
            if active_kind == b'a':
1746
 
                # The active record shows up as absent, this could be genuine,
1747
 
                # or it could be present at some other location. We need to
1748
 
                # verify.
1749
 
                id_index = self._get_id_index()
1750
 
                # The id_index may not be perfectly accurate for tree1, because
1751
 
                # we haven't been keeping it updated. However, it should be
1752
 
                # fine for tree0, and that gives us enough info for what we
1753
 
                # need
1754
 
                keys = id_index.get(file_id, ())
1755
 
                for key in keys:
1756
 
                    block_i, entry_i, d_present, f_present = \
1757
 
                        self._get_block_entry_index(key[0], key[1], 0)
1758
 
                    if not f_present:
1759
 
                        continue
1760
 
                    active_entry = self._dirblocks[block_i][1][entry_i]
1761
 
                    if (active_entry[0][2] != file_id):
1762
 
                        # Some other file is at this path, we don't need to
1763
 
                        # link it.
1764
 
                        continue
1765
 
                    real_active_kind = active_entry[1][0][0]
1766
 
                    if real_active_kind in (b'a', b'r'):
1767
 
                        # We found a record, which was not *this* record,
1768
 
                        # which matches the file_id, but is not actually
1769
 
                        # present. Something seems *really* wrong.
1770
 
                        self._raise_invalid(new_path, file_id,
1771
 
                                            "We found a tree0 entry that doesnt make sense")
1772
 
                    # Now, we've found a tree0 entry which matches the file_id
1773
 
                    # but is at a different location. So update them to be
1774
 
                    # rename records.
1775
 
                    active_dir, active_name = active_entry[0][:2]
1776
 
                    if active_dir:
1777
 
                        active_path = active_dir + b'/' + active_name
1778
 
                    else:
1779
 
                        active_path = active_name
1780
 
                    active_entry[1][1] = st(b'r', new_path, 0, False, b'')
1781
 
                    entry[1][0] = st(b'r', active_path, 0, False, b'')
1782
 
            elif active_kind == b'r':
1783
 
                raise NotImplementedError()
1784
 
 
1785
 
            new_kind = new_details[0]
1786
 
            if new_kind == b'd':
1787
 
                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
1788
1619
 
1789
1620
    def _update_basis_apply_changes(self, changes):
1790
1621
        """Apply a sequence of changes to tree 1 during update_basis_by_delta.
1792
1623
        :param adds: A sequence of changes. Each change is a tuple:
1793
1624
            (path_utf8, path_utf8, file_id, (entry_details))
1794
1625
        """
 
1626
        absent = 'ar'
1795
1627
        for old_path, new_path, file_id, new_details in changes:
1796
1628
            # the entry for this file_id must be in tree 0.
1797
 
            entry = self._get_entry(1, file_id, new_path)
1798
 
            if entry[0] is None or entry[1][1][0] in (b'a', b'r'):
1799
 
                self._raise_invalid(new_path, file_id,
1800
 
                                    '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')
1801
1639
            entry[1][1] = new_details
1802
1640
 
1803
1641
    def _update_basis_apply_deletes(self, deletes):
1815
1653
        null = DirState.NULL_PARENT_DETAILS
1816
1654
        for old_path, new_path, file_id, _, real_delete in deletes:
1817
1655
            if real_delete != (new_path is None):
1818
 
                self._raise_invalid(old_path, file_id, "bad delete delta")
 
1656
                self._changes_aborted = True
 
1657
                raise AssertionError("bad delete delta")
1819
1658
            # the entry for this file_id must be in tree 1.
1820
1659
            dirname, basename = osutils.split(old_path)
1821
1660
            block_index, entry_index, dir_present, file_present = \
1822
1661
                self._get_block_entry_index(dirname, basename, 1)
1823
1662
            if not file_present:
1824
 
                self._raise_invalid(old_path, file_id,
1825
 
                                    'basis tree does not contain removed entry')
 
1663
                self._changes_aborted = True
 
1664
                raise errors.InconsistentDelta(old_path, file_id,
 
1665
                    'basis tree does not contain removed entry')
1826
1666
            entry = self._dirblocks[block_index][1][entry_index]
1827
 
            # The state of the entry in the 'active' WT
1828
 
            active_kind = entry[1][0][0]
1829
1667
            if entry[0][2] != file_id:
1830
 
                self._raise_invalid(old_path, file_id,
1831
 
                                    'mismatched file_id in tree 1')
1832
 
            dir_block = ()
1833
 
            old_kind = entry[1][1][0]
1834
 
            if active_kind in b'ar':
1835
 
                # The active tree doesn't have this file_id.
1836
 
                # The basis tree is changing this record. If this is a
1837
 
                # rename, then we don't want the record here at all
1838
 
                # anymore. If it is just an in-place change, we want the
1839
 
                # record here, but we'll add it if we need to. So we just
1840
 
                # delete it
1841
 
                if active_kind == b'r':
1842
 
                    active_path = entry[1][0][1]
1843
 
                    active_entry = self._get_entry(0, file_id, active_path)
1844
 
                    if active_entry[1][1][0] != b'r':
1845
 
                        self._raise_invalid(old_path, file_id,
1846
 
                                            "Dirstate did not have matching rename entries")
1847
 
                    elif active_entry[1][0][0] in b'ar':
1848
 
                        self._raise_invalid(old_path, file_id,
1849
 
                                            "Dirstate had a rename pointing at an inactive"
1850
 
                                            " tree0")
1851
 
                    active_entry[1][1] = null
 
1668
                self._changes_aborted = True
 
1669
                raise errors.InconsistentDelta(old_path, file_id,
 
1670
                    'mismatched file_id in tree 1')
 
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.')
1852
1677
                del self._dirblocks[block_index][1][entry_index]
1853
 
                if old_kind == b'd':
1854
 
                    # This was a directory, and the active tree says it
1855
 
                    # doesn't exist, and now the basis tree says it doesn't
1856
 
                    # exist. Remove its dirblock if present
1857
 
                    (dir_block_index,
1858
 
                     present) = self._find_block_index_from_key(
1859
 
                        (old_path, b'', b''))
1860
 
                    if present:
1861
 
                        dir_block = self._dirblocks[dir_block_index][1]
1862
 
                        if not dir_block:
1863
 
                            # This entry is empty, go ahead and just remove it
1864
 
                            del self._dirblocks[dir_block_index]
1865
1678
            else:
1866
 
                # There is still an active record, so just mark this
1867
 
                # removed.
1868
 
                entry[1][1] = null
1869
 
                block_i, entry_i, d_present, f_present = \
1870
 
                    self._get_block_entry_index(old_path, b'', 1)
1871
 
                if d_present:
1872
 
                    dir_block = self._dirblocks[block_i][1]
1873
 
            for child_entry in dir_block:
1874
 
                child_basis_kind = child_entry[1][1][0]
1875
 
                if child_basis_kind not in b'ar':
1876
 
                    self._raise_invalid(old_path, file_id,
1877
 
                                        "The file id was deleted but its children were "
1878
 
                                        "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
1879
1694
 
1880
1695
    def _after_delta_check_parents(self, parents, index):
1881
1696
        """Check that parents required by the delta are all intact.
1882
 
 
 
1697
        
1883
1698
        :param parents: An iterable of (path_utf8, file_id) tuples which are
1884
1699
            required to be present in tree 'index' at path_utf8 with id file_id
1885
1700
            and be a directory.
1890
1705
            # has the right file id.
1891
1706
            entry = self._get_entry(index, file_id, dirname_utf8)
1892
1707
            if entry[1] is None:
1893
 
                self._raise_invalid(dirname_utf8.decode('utf8'),
1894
 
                                    file_id, "This parent is not present.")
 
1708
                self._changes_aborted = True
 
1709
                raise errors.InconsistentDelta(dirname_utf8.decode('utf8'),
 
1710
                    file_id, "This parent is not present.")
1895
1711
            # Parents of things must be directories
1896
 
            if entry[1][index][0] != b'd':
1897
 
                self._raise_invalid(dirname_utf8.decode('utf8'),
1898
 
                                    file_id, "This parent is not a directory.")
 
1712
            if entry[1][index][0] != 'd':
 
1713
                self._changes_aborted = True
 
1714
                raise errors.InconsistentDelta(dirname_utf8.decode('utf8'),
 
1715
                    file_id, "This parent is not a directory.")
1899
1716
 
1900
1717
    def _observed_sha1(self, entry, sha1, stat_value,
1901
 
                       _stat_to_minikind=_stat_to_minikind):
 
1718
        _stat_to_minikind=_stat_to_minikind, _pack_stat=pack_stat):
1902
1719
        """Note the sha1 of a file.
1903
1720
 
1904
1721
        :param entry: The entry the sha1 is for.
1906
1723
        :param stat_value: The os.lstat for the file.
1907
1724
        """
1908
1725
        try:
1909
 
            minikind = _stat_to_minikind[stat_value.st_mode & 0o170000]
 
1726
            minikind = _stat_to_minikind[stat_value.st_mode & 0170000]
1910
1727
        except KeyError:
1911
1728
            # Unhandled kind
1912
1729
            return None
1913
 
        if minikind == b'f':
 
1730
        packed_stat = _pack_stat(stat_value)
 
1731
        if minikind == 'f':
1914
1732
            if self._cutoff_time is None:
1915
1733
                self._sha_cutoff_time()
1916
1734
            if (stat_value.st_mtime < self._cutoff_time
1917
 
                    and stat_value.st_ctime < self._cutoff_time):
1918
 
                entry[1][0] = (b'f', sha1, stat_value.st_size, entry[1][0][3],
1919
 
                               pack_stat(stat_value))
1920
 
                self._mark_modified([entry])
 
1735
                and stat_value.st_ctime < self._cutoff_time):
 
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
1921
1739
 
1922
1740
    def _sha_cutoff_time(self):
1923
1741
        """Return cutoff time.
1944
1762
 
1945
1763
    def _is_executable(self, mode, old_executable):
1946
1764
        """Is this file executable?"""
1947
 
        if self._use_filesystem_for_exec:
1948
 
            return bool(S_IEXEC & mode)
1949
 
        else:
1950
 
            return old_executable
 
1765
        return bool(S_IEXEC & mode)
 
1766
 
 
1767
    def _is_executable_win32(self, mode, old_executable):
 
1768
        """On win32 the executable bit is stored in the dirstate."""
 
1769
        return old_executable
 
1770
 
 
1771
    if sys.platform == 'win32':
 
1772
        _is_executable = _is_executable_win32
1951
1773
 
1952
1774
    def _read_link(self, abspath, old_link):
1953
1775
        """Read the target of a symlink"""
1956
1778
        #       higher level, because there either won't be anything on disk,
1957
1779
        #       or the thing on disk will be a file.
1958
1780
        fs_encoding = osutils._fs_enc
1959
 
        if isinstance(abspath, str):
 
1781
        if isinstance(abspath, unicode):
1960
1782
            # abspath is defined as the path to pass to lstat. readlink is
1961
1783
            # buggy in python < 2.6 (it doesn't encode unicode path into FS
1962
1784
            # encoding), so we need to encode ourselves knowing that unicode
1963
1785
            # paths are produced by UnicodeDirReader on purpose.
1964
1786
            abspath = abspath.encode(fs_encoding)
1965
1787
        target = os.readlink(abspath)
1966
 
        if fs_encoding not in ('utf-8', 'ascii'):
 
1788
        if fs_encoding not in ('UTF-8', 'US-ASCII', 'ANSI_X3.4-1968'):
1967
1789
            # Change encoding if needed
1968
1790
            target = target.decode(fs_encoding).encode('UTF-8')
1969
1791
        return target
1976
1798
    def get_lines(self):
1977
1799
        """Serialise the entire dirstate to a sequence of lines."""
1978
1800
        if (self._header_state == DirState.IN_MEMORY_UNMODIFIED and
1979
 
                self._dirblock_state == DirState.IN_MEMORY_UNMODIFIED):
1980
 
            # read what's on disk.
 
1801
            self._dirblock_state == DirState.IN_MEMORY_UNMODIFIED):
 
1802
            # read whats on disk.
1981
1803
            self._state_file.seek(0)
1982
1804
            return self._state_file.readlines()
1983
1805
        lines = []
1984
1806
        lines.append(self._get_parents_line(self.get_parent_ids()))
1985
1807
        lines.append(self._get_ghosts_line(self._ghosts))
1986
 
        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()))
1987
1810
        return self._get_output_lines(lines)
1988
1811
 
1989
1812
    def _get_ghosts_line(self, ghost_ids):
1990
1813
        """Create a line for the state file for ghost information."""
1991
 
        return b'\0'.join([b'%d' % len(ghost_ids)] + ghost_ids)
 
1814
        return '\0'.join([str(len(ghost_ids))] + ghost_ids)
1992
1815
 
1993
1816
    def _get_parents_line(self, parent_ids):
1994
1817
        """Create a line for the state file for parents information."""
1995
 
        return b'\0'.join([b'%d' % len(parent_ids)] + parent_ids)
1996
 
 
1997
 
    def _iter_entry_lines(self):
1998
 
        """Create lines for entries."""
1999
 
        return map(self._entry_to_line, self._iter_entries())
 
1818
        return '\0'.join([str(len(parent_ids))] + parent_ids)
2000
1819
 
2001
1820
    def _get_fields_to_entry(self):
2002
1821
        """Get a function which converts entry fields into a entry record.
2012
1831
            def fields_to_entry_0_parents(fields, _int=int):
2013
1832
                path_name_file_id_key = (fields[0], fields[1], fields[2])
2014
1833
                return (path_name_file_id_key, [
2015
 
                    (  # Current tree
 
1834
                    ( # Current tree
2016
1835
                        fields[3],                # minikind
2017
1836
                        fields[4],                # fingerprint
2018
1837
                        _int(fields[5]),          # size
2019
 
                        fields[6] == b'y',         # executable
 
1838
                        fields[6] == 'y',         # executable
2020
1839
                        fields[7],                # packed_stat or revision_id
2021
1840
                    )])
2022
1841
            return fields_to_entry_0_parents
2024
1843
            def fields_to_entry_1_parent(fields, _int=int):
2025
1844
                path_name_file_id_key = (fields[0], fields[1], fields[2])
2026
1845
                return (path_name_file_id_key, [
2027
 
                    (  # Current tree
 
1846
                    ( # Current tree
2028
1847
                        fields[3],                # minikind
2029
1848
                        fields[4],                # fingerprint
2030
1849
                        _int(fields[5]),          # size
2031
 
                        fields[6] == b'y',         # executable
 
1850
                        fields[6] == 'y',         # executable
2032
1851
                        fields[7],                # packed_stat or revision_id
2033
1852
                    ),
2034
 
                    (  # Parent 1
 
1853
                    ( # Parent 1
2035
1854
                        fields[8],                # minikind
2036
1855
                        fields[9],                # fingerprint
2037
1856
                        _int(fields[10]),         # size
2038
 
                        fields[11] == b'y',        # executable
 
1857
                        fields[11] == 'y',        # executable
2039
1858
                        fields[12],               # packed_stat or revision_id
2040
1859
                    ),
2041
1860
                    ])
2044
1863
            def fields_to_entry_2_parents(fields, _int=int):
2045
1864
                path_name_file_id_key = (fields[0], fields[1], fields[2])
2046
1865
                return (path_name_file_id_key, [
2047
 
                    (  # Current tree
 
1866
                    ( # Current tree
2048
1867
                        fields[3],                # minikind
2049
1868
                        fields[4],                # fingerprint
2050
1869
                        _int(fields[5]),          # size
2051
 
                        fields[6] == b'y',         # executable
 
1870
                        fields[6] == 'y',         # executable
2052
1871
                        fields[7],                # packed_stat or revision_id
2053
1872
                    ),
2054
 
                    (  # Parent 1
 
1873
                    ( # Parent 1
2055
1874
                        fields[8],                # minikind
2056
1875
                        fields[9],                # fingerprint
2057
1876
                        _int(fields[10]),         # size
2058
 
                        fields[11] == b'y',        # executable
 
1877
                        fields[11] == 'y',        # executable
2059
1878
                        fields[12],               # packed_stat or revision_id
2060
1879
                    ),
2061
 
                    (  # Parent 2
 
1880
                    ( # Parent 2
2062
1881
                        fields[13],               # minikind
2063
1882
                        fields[14],               # fingerprint
2064
1883
                        _int(fields[15]),         # size
2065
 
                        fields[16] == b'y',        # executable
 
1884
                        fields[16] == 'y',        # executable
2066
1885
                        fields[17],               # packed_stat or revision_id
2067
1886
                    ),
2068
1887
                    ])
2071
1890
            def fields_to_entry_n_parents(fields, _int=int):
2072
1891
                path_name_file_id_key = (fields[0], fields[1], fields[2])
2073
1892
                trees = [(fields[cur],                # minikind
2074
 
                          fields[cur + 1],              # fingerprint
2075
 
                          _int(fields[cur + 2]),        # size
2076
 
                          fields[cur + 3] == b'y',       # executable
2077
 
                          fields[cur + 4],              # stat or revision_id
2078
 
                          ) for cur in range(3, len(fields) - 1, 5)]
 
1893
                          fields[cur+1],              # fingerprint
 
1894
                          _int(fields[cur+2]),        # size
 
1895
                          fields[cur+3] == 'y',       # executable
 
1896
                          fields[cur+4],              # stat or revision_id
 
1897
                         ) for cur in xrange(3, len(fields)-1, 5)]
2079
1898
                return path_name_file_id_key, trees
2080
1899
            return fields_to_entry_n_parents
2081
1900
 
2105
1924
            tree present there.
2106
1925
        """
2107
1926
        self._read_dirblocks_if_needed()
2108
 
        key = dirname, basename, b''
 
1927
        key = dirname, basename, ''
2109
1928
        block_index, present = self._find_block_index_from_key(key)
2110
1929
        if not present:
2111
1930
            # no such directory - return the dir index and 0 for the row.
2112
1931
            return block_index, 0, False, False
2113
 
        block = self._dirblocks[block_index][1]  # access the entries only
 
1932
        block = self._dirblocks[block_index][1] # access the entries only
2114
1933
        entry_index, present = self._find_entry_index(key, block)
2115
1934
        # linear search through entries at this path to find the one
2116
1935
        # requested.
2117
1936
        while entry_index < len(block) and block[entry_index][0][1] == basename:
2118
 
            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':
2119
1938
                # neither absent or relocated
2120
1939
                return block_index, entry_index, True, True
2121
1940
            entry_index += 1
2122
1941
        return block_index, entry_index, True, False
2123
1942
 
2124
 
    def _get_entry(self, tree_index, fileid_utf8=None, path_utf8=None,
2125
 
                   include_deleted=False):
 
1943
    def _get_entry(self, tree_index, fileid_utf8=None, path_utf8=None, include_deleted=False):
2126
1944
        """Get the dirstate entry for path in tree tree_index.
2127
1945
 
2128
1946
        If either file_id or path is supplied, it is used as the key to lookup.
2143
1961
        """
2144
1962
        self._read_dirblocks_if_needed()
2145
1963
        if path_utf8 is not None:
2146
 
            if not isinstance(path_utf8, bytes):
2147
 
                raise errors.BzrError('path_utf8 is not bytes: %s %r'
2148
 
                                      % (type(path_utf8), path_utf8))
 
1964
            if type(path_utf8) is not str:
 
1965
                raise errors.BzrError('path_utf8 is not a str: %s %r'
 
1966
                    % (type(path_utf8), path_utf8))
2149
1967
            # path lookups are faster
2150
1968
            dirname, basename = osutils.split(path_utf8)
2151
1969
            block_index, entry_index, dir_present, file_present = \
2153
1971
            if not file_present:
2154
1972
                return None, None
2155
1973
            entry = self._dirblocks[block_index][1][entry_index]
2156
 
            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')):
2157
1975
                raise AssertionError('unversioned entry?')
2158
1976
            if fileid_utf8:
2159
1977
                if entry[0][2] != fileid_utf8:
2162
1980
                                          ' tree_index, file_id and path')
2163
1981
            return entry
2164
1982
        else:
2165
 
            possible_keys = self._get_id_index().get(fileid_utf8, ())
 
1983
            possible_keys = self._get_id_index().get(fileid_utf8, None)
2166
1984
            if not possible_keys:
2167
1985
                return None, None
2168
1986
            for key in possible_keys:
2179
1997
                entry_index, present = self._find_entry_index(key, block)
2180
1998
                if present:
2181
1999
                    entry = self._dirblocks[block_index][1][entry_index]
2182
 
                    # TODO: We might want to assert that entry[0][2] ==
2183
 
                    #       fileid_utf8.
2184
 
                    # GZ 2017-06-09: Hoist set of minkinds somewhere
2185
 
                    if entry[1][tree_index][0] in {b'f', b'd', b'l', b't'}:
 
2000
                    if entry[1][tree_index][0] in 'fdlt':
2186
2001
                        # this is the result we are looking for: the
2187
2002
                        # real home of this file_id in this tree.
2188
2003
                        return entry
2189
 
                    if entry[1][tree_index][0] == b'a':
 
2004
                    if entry[1][tree_index][0] == 'a':
2190
2005
                        # there is no home for this entry in this tree
2191
2006
                        if include_deleted:
2192
2007
                            return entry
2193
2008
                        return None, None
2194
 
                    if entry[1][tree_index][0] != b'r':
 
2009
                    if entry[1][tree_index][0] != 'r':
2195
2010
                        raise AssertionError(
2196
 
                            "entry %r has invalid minikind %r for tree %r"
 
2011
                            "entry %r has invalid minikind %r for tree %r" \
2197
2012
                            % (entry,
2198
2013
                               entry[1][tree_index][0],
2199
2014
                               tree_index))
2200
2015
                    real_path = entry[1][tree_index][1]
2201
2016
                    return self._get_entry(tree_index, fileid_utf8=fileid_utf8,
2202
 
                                           path_utf8=real_path)
 
2017
                        path_utf8=real_path)
2203
2018
            return None, None
2204
2019
 
2205
2020
    @classmethod
2223
2038
            sha1_provider = DefaultSHA1Provider()
2224
2039
        result = cls(path, sha1_provider)
2225
2040
        # root dir and root dir contents with no children.
2226
 
        empty_tree_dirblocks = [(b'', []), (b'', [])]
 
2041
        empty_tree_dirblocks = [('', []), ('', [])]
2227
2042
        # a new root directory, with a NULLSTAT.
2228
2043
        empty_tree_dirblocks[0][1].append(
2229
 
            ((b'', b'', inventory.ROOT_ID), [
2230
 
                (b'd', b'', 0, False, DirState.NULLSTAT),
 
2044
            (('', '', inventory.ROOT_ID), [
 
2045
                ('d', '', 0, False, DirState.NULLSTAT),
2231
2046
            ]))
2232
2047
        result.lock_write()
2233
2048
        try:
2251
2066
        minikind = DirState._kind_to_minikind[kind]
2252
2067
        tree_data = inv_entry.revision
2253
2068
        if kind == 'directory':
2254
 
            fingerprint = b''
 
2069
            fingerprint = ''
2255
2070
            size = 0
2256
2071
            executable = False
2257
2072
        elif kind == 'symlink':
2258
2073
            if inv_entry.symlink_target is None:
2259
 
                fingerprint = b''
 
2074
                fingerprint = ''
2260
2075
            else:
2261
2076
                fingerprint = inv_entry.symlink_target.encode('utf8')
2262
2077
            size = 0
2263
2078
            executable = False
2264
2079
        elif kind == 'file':
2265
 
            fingerprint = inv_entry.text_sha1 or b''
 
2080
            fingerprint = inv_entry.text_sha1 or ''
2266
2081
            size = inv_entry.text_size or 0
2267
2082
            executable = inv_entry.executable
2268
2083
        elif kind == 'tree-reference':
2269
 
            fingerprint = inv_entry.reference_revision or b''
 
2084
            fingerprint = inv_entry.reference_revision or ''
2270
2085
            size = 0
2271
2086
            executable = False
2272
2087
        else:
2273
2088
            raise Exception("can't pack %s" % inv_entry)
2274
 
        return static_tuple.StaticTuple(minikind, fingerprint, size,
2275
 
                                        executable, tree_data)
 
2089
        return (minikind, fingerprint, size, executable, tree_data)
2276
2090
 
2277
2091
    def _iter_child_entries(self, tree_index, path_utf8):
2278
2092
        """Iterate over all the entries that are children of path_utf.
2279
2093
 
2280
 
        This only returns entries that are present (not in b'a', b'r') in
 
2094
        This only returns entries that are present (not in 'a', 'r') in
2281
2095
        tree_index. tree_index data is not refreshed, so if tree 0 is used,
2282
2096
        results may differ from that obtained if paths were statted to
2283
2097
        determine what ones were directories.
2287
2101
        """
2288
2102
        pending_dirs = []
2289
2103
        next_pending_dirs = [path_utf8]
2290
 
        absent = (b'a', b'r')
 
2104
        absent = 'ar'
2291
2105
        while next_pending_dirs:
2292
2106
            pending_dirs = next_pending_dirs
2293
2107
            next_pending_dirs = []
2294
2108
            for path in pending_dirs:
2295
2109
                block_index, present = self._find_block_index_from_key(
2296
 
                    (path, b'', b''))
 
2110
                    (path, '', ''))
2297
2111
                if block_index == 0:
2298
2112
                    block_index = 1
2299
2113
                    if len(self._dirblocks) == 1:
2308
2122
                    kind = entry[1][tree_index][0]
2309
2123
                    if kind not in absent:
2310
2124
                        yield entry
2311
 
                    if kind == b'd':
 
2125
                    if kind == 'd':
2312
2126
                        if entry[0][0]:
2313
 
                            path = entry[0][0] + b'/' + entry[0][1]
 
2127
                            path = entry[0][0] + '/' + entry[0][1]
2314
2128
                        else:
2315
2129
                            path = entry[0][1]
2316
2130
                        next_pending_dirs.append(path)
2319
2133
        """Iterate over all the entries in the dirstate.
2320
2134
 
2321
2135
        Each yelt item is an entry in the standard format described in the
2322
 
        docstring of breezy.dirstate.
 
2136
        docstring of bzrlib.dirstate.
2323
2137
        """
2324
2138
        self._read_dirblocks_if_needed()
2325
2139
        for directory in self._dirblocks:
2327
2141
                yield entry
2328
2142
 
2329
2143
    def _get_id_index(self):
2330
 
        """Get an id index of self._dirblocks.
2331
 
 
2332
 
        This maps from file_id => [(directory, name, file_id)] entries where
2333
 
        that file_id appears in one of the trees.
2334
 
        """
 
2144
        """Get an id index of self._dirblocks."""
2335
2145
        if self._id_index is None:
2336
2146
            id_index = {}
2337
2147
            for key, tree_details in self._iter_entries():
2338
 
                self._add_to_id_index(id_index, key)
 
2148
                id_index.setdefault(key[2], set()).add(key)
2339
2149
            self._id_index = id_index
2340
2150
        return self._id_index
2341
2151
 
2342
 
    def _add_to_id_index(self, id_index, entry_key):
2343
 
        """Add this entry to the _id_index mapping."""
2344
 
        # This code used to use a set for every entry in the id_index. However,
2345
 
        # it is *rare* to have more than one entry. So a set is a large
2346
 
        # overkill. And even when we do, we won't ever have more than the
2347
 
        # number of parent trees. Which is still a small number (rarely >2). As
2348
 
        # such, we use a simple tuple, and do our own uniqueness checks. While
2349
 
        # the 'in' check is O(N) since N is nicely bounded it shouldn't ever
2350
 
        # cause quadratic failure.
2351
 
        file_id = entry_key[2]
2352
 
        entry_key = static_tuple.StaticTuple.from_sequence(entry_key)
2353
 
        if file_id not in id_index:
2354
 
            id_index[file_id] = static_tuple.StaticTuple(entry_key,)
2355
 
        else:
2356
 
            entry_keys = id_index[file_id]
2357
 
            if entry_key not in entry_keys:
2358
 
                id_index[file_id] = entry_keys + (entry_key,)
2359
 
 
2360
 
    def _remove_from_id_index(self, id_index, entry_key):
2361
 
        """Remove this entry from the _id_index mapping.
2362
 
 
2363
 
        It is an programming error to call this when the entry_key is not
2364
 
        already present.
2365
 
        """
2366
 
        file_id = entry_key[2]
2367
 
        entry_keys = list(id_index[file_id])
2368
 
        entry_keys.remove(entry_key)
2369
 
        id_index[file_id] = static_tuple.StaticTuple.from_sequence(entry_keys)
2370
 
 
2371
2152
    def _get_output_lines(self, lines):
2372
2153
        """Format lines for final output.
2373
2154
 
2375
2156
            path lines.
2376
2157
        """
2377
2158
        output_lines = [DirState.HEADER_FORMAT_3]
2378
 
        lines.append(b'')  # a final newline
2379
 
        inventory_text = b'\0\n\0'.join(lines)
2380
 
        output_lines.append(b'crc32: %d\n' % (zlib.crc32(inventory_text),))
 
2159
        lines.append('') # a final newline
 
2160
        inventory_text = '\0\n\0'.join(lines)
 
2161
        output_lines.append('crc32: %s\n' % (zlib.crc32(inventory_text),))
2381
2162
        # -3, 1 for num parents, 1 for ghosts, 1 for final newline
2382
 
        num_entries = len(lines) - 3
2383
 
        output_lines.append(b'num_entries: %d\n' % (num_entries,))
 
2163
        num_entries = len(lines)-3
 
2164
        output_lines.append('num_entries: %s\n' % (num_entries,))
2384
2165
        output_lines.append(inventory_text)
2385
2166
        return output_lines
2386
2167
 
2387
2168
    def _make_deleted_row(self, fileid_utf8, parents):
2388
2169
        """Return a deleted row for fileid_utf8."""
2389
 
        return (b'/', b'RECYCLED.BIN', b'file', fileid_utf8, 0, DirState.NULLSTAT,
2390
 
                b''), parents
 
2170
        return ('/', 'RECYCLED.BIN', 'file', fileid_utf8, 0, DirState.NULLSTAT,
 
2171
            ''), parents
2391
2172
 
2392
2173
    def _num_present_parents(self):
2393
2174
        """The number of parent entries in each record row."""
2394
2175
        return len(self._parents) - len(self._ghosts)
2395
2176
 
2396
 
    @classmethod
2397
 
    def on_file(cls, path, sha1_provider=None, worth_saving_limit=0,
2398
 
                use_filesystem_for_exec=True):
 
2177
    @staticmethod
 
2178
    def on_file(path, sha1_provider=None):
2399
2179
        """Construct a DirState on the file at path "path".
2400
2180
 
2401
2181
        :param path: The path at which the dirstate file on disk should live.
2402
2182
        :param sha1_provider: an object meeting the SHA1Provider interface.
2403
2183
            If None, a DefaultSHA1Provider is used.
2404
 
        :param worth_saving_limit: when the exact number of hash changed
2405
 
            entries is known, only bother saving the dirstate if more than
2406
 
            this count of entries have changed. -1 means never save.
2407
 
        :param use_filesystem_for_exec: Whether to trust the filesystem
2408
 
            for executable bit information
2409
2184
        :return: An unlocked DirState object, associated with the given path.
2410
2185
        """
2411
2186
        if sha1_provider is None:
2412
2187
            sha1_provider = DefaultSHA1Provider()
2413
 
        result = cls(path, sha1_provider,
2414
 
                     worth_saving_limit=worth_saving_limit,
2415
 
                     use_filesystem_for_exec=use_filesystem_for_exec)
 
2188
        result = DirState(path, sha1_provider)
2416
2189
        return result
2417
2190
 
2418
2191
    def _read_dirblocks_if_needed(self):
2436
2209
        """
2437
2210
        self._read_prelude()
2438
2211
        parent_line = self._state_file.readline()
2439
 
        info = parent_line.split(b'\0')
 
2212
        info = parent_line.split('\0')
2440
2213
        num_parents = int(info[0])
2441
2214
        self._parents = info[1:-1]
2442
2215
        ghost_line = self._state_file.readline()
2443
 
        info = ghost_line.split(b'\0')
 
2216
        info = ghost_line.split('\0')
2444
2217
        num_ghosts = int(info[1])
2445
2218
        self._ghosts = info[2:-1]
2446
2219
        self._header_state = DirState.IN_MEMORY_UNMODIFIED
2468
2241
            raise errors.BzrError(
2469
2242
                'invalid header line: %r' % (header,))
2470
2243
        crc_line = self._state_file.readline()
2471
 
        if not crc_line.startswith(b'crc32: '):
 
2244
        if not crc_line.startswith('crc32: '):
2472
2245
            raise errors.BzrError('missing crc32 checksum: %r' % crc_line)
2473
 
        self.crc_expected = int(crc_line[len(b'crc32: '):-1])
 
2246
        self.crc_expected = int(crc_line[len('crc32: '):-1])
2474
2247
        num_entries_line = self._state_file.readline()
2475
 
        if not num_entries_line.startswith(b'num_entries: '):
 
2248
        if not num_entries_line.startswith('num_entries: '):
2476
2249
            raise errors.BzrError('missing num_entries line')
2477
 
        self._num_entries = int(num_entries_line[len(b'num_entries: '):-1])
 
2250
        self._num_entries = int(num_entries_line[len('num_entries: '):-1])
2478
2251
 
2479
 
    def sha1_from_stat(self, path, stat_result):
 
2252
    def sha1_from_stat(self, path, stat_result, _pack_stat=pack_stat):
2480
2253
        """Find a sha1 given a stat lookup."""
2481
 
        return self._get_packed_stat_index().get(pack_stat(stat_result), None)
 
2254
        return self._get_packed_stat_index().get(_pack_stat(stat_result), None)
2482
2255
 
2483
2256
    def _get_packed_stat_index(self):
2484
2257
        """Get a packed_stat index of self._dirblocks."""
2485
2258
        if self._packed_stat_index is None:
2486
2259
            index = {}
2487
2260
            for key, tree_details in self._iter_entries():
2488
 
                if tree_details[0][0] == b'f':
 
2261
                if tree_details[0][0] == 'f':
2489
2262
                    index[tree_details[0][4]] = tree_details[0][1]
2490
2263
            self._packed_stat_index = index
2491
2264
        return self._packed_stat_index
2508
2281
            # Should this be a warning? For now, I'm expecting that places that
2509
2282
            # mark it inconsistent will warn, making a warning here redundant.
2510
2283
            trace.mutter('Not saving DirState because '
2511
 
                         '_changes_aborted is set.')
2512
 
            return
2513
 
        # TODO: Since we now distinguish IN_MEMORY_MODIFIED from
2514
 
        #       IN_MEMORY_HASH_MODIFIED, we should only fail quietly if we fail
2515
 
        #       to save an IN_MEMORY_HASH_MODIFIED, and fail *noisily* if we
2516
 
        #       fail to save IN_MEMORY_MODIFIED
2517
 
        if not self._worth_saving():
2518
 
            return
 
2284
                    '_changes_aborted is set.')
 
2285
            return
 
2286
        if (self._header_state == DirState.IN_MEMORY_MODIFIED or
 
2287
            self._dirblock_state == DirState.IN_MEMORY_MODIFIED):
2519
2288
 
2520
 
        grabbed_write_lock = False
2521
 
        if self._lock_state != 'w':
2522
 
            grabbed_write_lock, new_lock = self._lock_token.temporary_write_lock()
2523
 
            # Switch over to the new lock, as the old one may be closed.
2524
 
            # TODO: jam 20070315 We should validate the disk file has
2525
 
            #       not changed contents, since temporary_write_lock may
2526
 
            #       not be an atomic operation.
2527
 
            self._lock_token = new_lock
2528
 
            self._state_file = new_lock.f
2529
 
            if not grabbed_write_lock:
2530
 
                # We couldn't grab a write lock, so we switch back to a read one
2531
 
                return
2532
 
        try:
2533
 
            lines = self.get_lines()
2534
 
            self._state_file.seek(0)
2535
 
            self._state_file.writelines(lines)
2536
 
            self._state_file.truncate()
2537
 
            self._state_file.flush()
2538
 
            self._maybe_fdatasync()
2539
 
            self._mark_unmodified()
2540
 
        finally:
2541
 
            if grabbed_write_lock:
2542
 
                self._lock_token = self._lock_token.restore_read_lock()
2543
 
                self._state_file = self._lock_token.f
 
2289
            grabbed_write_lock = False
 
2290
            if self._lock_state != 'w':
 
2291
                grabbed_write_lock, new_lock = self._lock_token.temporary_write_lock()
 
2292
                # Switch over to the new lock, as the old one may be closed.
2544
2293
                # TODO: jam 20070315 We should validate the disk file has
2545
 
                #       not changed contents. Since restore_read_lock may
 
2294
                #       not changed contents. Since temporary_write_lock may
2546
2295
                #       not be an atomic operation.
2547
 
 
2548
 
    def _maybe_fdatasync(self):
2549
 
        """Flush to disk if possible and if not configured off."""
2550
 
        if self._config_stack.get('dirstate.fdatasync'):
2551
 
            osutils.fdatasync(self._state_file.fileno())
2552
 
 
2553
 
    def _worth_saving(self):
2554
 
        """Is it worth saving the dirstate or not?"""
2555
 
        if (self._header_state == DirState.IN_MEMORY_MODIFIED
2556
 
                or self._dirblock_state == DirState.IN_MEMORY_MODIFIED):
2557
 
            return True
2558
 
        if self._dirblock_state == DirState.IN_MEMORY_HASH_MODIFIED:
2559
 
            if self._worth_saving_limit == -1:
2560
 
                # We never save hash changes when the limit is -1
2561
 
                return False
2562
 
            # If we're using smart saving and only a small number of
2563
 
            # entries have changed their hash, don't bother saving. John has
2564
 
            # suggested using a heuristic here based on the size of the
2565
 
            # changed files and/or tree. For now, we go with a configurable
2566
 
            # number of changes, keeping the calculation time
2567
 
            # as low overhead as possible. (This also keeps all existing
2568
 
            # tests passing as the default is 0, i.e. always save.)
2569
 
            if len(self._known_hash_changes) >= self._worth_saving_limit:
2570
 
                return True
2571
 
        return False
 
2296
                self._lock_token = new_lock
 
2297
                self._state_file = new_lock.f
 
2298
                if not grabbed_write_lock:
 
2299
                    # We couldn't grab a write lock, so we switch back to a read one
 
2300
                    return
 
2301
            try:
 
2302
                self._state_file.seek(0)
 
2303
                self._state_file.writelines(self.get_lines())
 
2304
                self._state_file.truncate()
 
2305
                self._state_file.flush()
 
2306
                self._header_state = DirState.IN_MEMORY_UNMODIFIED
 
2307
                self._dirblock_state = DirState.IN_MEMORY_UNMODIFIED
 
2308
            finally:
 
2309
                if grabbed_write_lock:
 
2310
                    self._lock_token = self._lock_token.restore_read_lock()
 
2311
                    self._state_file = self._lock_token.f
 
2312
                    # TODO: jam 20070315 We should validate the disk file has
 
2313
                    #       not changed contents. Since restore_read_lock may
 
2314
                    #       not be an atomic operation.
2572
2315
 
2573
2316
    def _set_data(self, parent_ids, dirblocks):
2574
2317
        """Set the full dirstate data in memory.
2583
2326
        """
2584
2327
        # our memory copy is now authoritative.
2585
2328
        self._dirblocks = dirblocks
2586
 
        self._mark_modified(header_modified=True)
 
2329
        self._header_state = DirState.IN_MEMORY_MODIFIED
 
2330
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
2587
2331
        self._parents = list(parent_ids)
2588
2332
        self._id_index = None
2589
2333
        self._packed_stat_index = None
2591
2335
    def set_path_id(self, path, new_id):
2592
2336
        """Change the id of path to new_id in the current working tree.
2593
2337
 
2594
 
        :param path: The path inside the tree to set - b'' is the root, 'foo'
 
2338
        :param path: The path inside the tree to set - '' is the root, 'foo'
2595
2339
            is the path foo in the root.
2596
2340
        :param new_id: The new id to assign to the path. This must be a utf8
2597
2341
            file id (not unicode, and not None).
2605
2349
        if entry[0][2] == new_id:
2606
2350
            # Nothing to change.
2607
2351
            return
2608
 
        if new_id.__class__ != bytes:
2609
 
            raise AssertionError(
2610
 
                "must be a utf8 file_id not %s" % (type(new_id), ))
2611
2352
        # mark the old path absent, and insert a new root path
2612
2353
        self._make_absent(entry)
2613
 
        self.update_minimal((b'', b'', new_id), b'd',
2614
 
                            path_utf8=b'', packed_stat=entry[1][0][4])
2615
 
        self._mark_modified()
 
2354
        self.update_minimal(('', '', new_id), 'd',
 
2355
            path_utf8='', packed_stat=entry[1][0][4])
 
2356
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
2357
        if self._id_index is not None:
 
2358
            self._id_index.setdefault(new_id, set()).add(entry[0])
2616
2359
 
2617
2360
    def set_parent_trees(self, trees, ghosts):
2618
2361
        """Set the parent trees for the dirstate.
2663
2406
        parent_trees = [tree for rev_id, tree in trees if rev_id not in ghosts]
2664
2407
        # how many trees do we end up with
2665
2408
        parent_count = len(parent_trees)
2666
 
        st = static_tuple.StaticTuple
2667
2409
 
2668
2410
        # one: the current tree
2669
2411
        for entry in self._iter_entries():
2670
2412
            # skip entries not in the current tree
2671
 
            if entry[1][0][0] in (b'a', b'r'):  # absent, relocated
 
2413
            if entry[1][0][0] in 'ar': # absent, relocated
2672
2414
                continue
2673
2415
            by_path[entry[0]] = [entry[1][0]] + \
2674
2416
                [DirState.NULL_PARENT_DETAILS] * parent_count
2675
 
            # TODO: Possibly inline this, since we know it isn't present yet
2676
 
            #       id_index[entry[0][2]] = (entry[0],)
2677
 
            self._add_to_id_index(id_index, entry[0])
 
2417
            id_index[entry[0][2]] = set([entry[0]])
2678
2418
 
2679
2419
        # now the parent trees:
2680
2420
        for tree_index, tree in enumerate(parent_trees):
2684
2424
            # any fileid in this tree as we set the by_path[id] to:
2685
2425
            # already_processed_tree_details + new_details + new_location_suffix
2686
2426
            # the suffix is from tree_index+1:parent_count+1.
2687
 
            new_location_suffix = [
2688
 
                DirState.NULL_PARENT_DETAILS] * (parent_count - tree_index)
 
2427
            new_location_suffix = [DirState.NULL_PARENT_DETAILS] * (parent_count - tree_index)
2689
2428
            # now stitch in all the entries from this tree
2690
 
            last_dirname = None
2691
 
            for path, entry in tree.iter_entries_by_dir():
 
2429
            for path, entry in tree.inventory.iter_entries_by_dir():
2692
2430
                # here we process each trees details for each item in the tree.
2693
2431
                # we first update any existing entries for the id at other paths,
2694
2432
                # then we either create or update the entry for the id at the
2701
2439
                file_id = entry.file_id
2702
2440
                path_utf8 = path.encode('utf8')
2703
2441
                dirname, basename = osutils.split(path_utf8)
2704
 
                if dirname == last_dirname:
2705
 
                    # Try to re-use objects as much as possible
2706
 
                    dirname = last_dirname
2707
 
                else:
2708
 
                    last_dirname = dirname
2709
 
                new_entry_key = st(dirname, basename, file_id)
 
2442
                new_entry_key = (dirname, basename, file_id)
2710
2443
                # tree index consistency: All other paths for this id in this tree
2711
2444
                # index must point to the correct path.
2712
 
                entry_keys = id_index.get(file_id, ())
2713
 
                for entry_key in entry_keys:
 
2445
                for entry_key in id_index.setdefault(file_id, set()):
2714
2446
                    # TODO:PROFILING: It might be faster to just update
2715
2447
                    # rather than checking if we need to, and then overwrite
2716
2448
                    # the one we are located at.
2719
2451
                        # other trees, so put absent pointers there
2720
2452
                        # This is the vertical axis in the matrix, all pointing
2721
2453
                        # to the real path.
2722
 
                        by_path[entry_key][tree_index] = st(b'r', path_utf8, 0,
2723
 
                                                            False, b'')
2724
 
                # by path consistency: Insert into an existing path record
2725
 
                # (trivial), or add a new one with relocation pointers for the
2726
 
                # other tree indexes.
2727
 
                if new_entry_key in entry_keys:
2728
 
                    # there is already an entry where this data belongs, just
2729
 
                    # 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.
2730
2459
                    by_path[new_entry_key][tree_index] = \
2731
2460
                        self._inv_entry_to_details(entry)
2732
2461
                else:
2734
2463
                    # mapping from path,id. We need to look up the correct path
2735
2464
                    # for the indexes from 0 to tree_index -1
2736
2465
                    new_details = []
2737
 
                    for lookup_index in range(tree_index):
 
2466
                    for lookup_index in xrange(tree_index):
2738
2467
                        # boundary case: this is the first occurence of file_id
2739
 
                        # so there are no id_indexes, possibly take this out of
 
2468
                        # so there are no id_indexs, possibly take this out of
2740
2469
                        # the loop?
2741
 
                        if not len(entry_keys):
 
2470
                        if not len(id_index[file_id]):
2742
2471
                            new_details.append(DirState.NULL_PARENT_DETAILS)
2743
2472
                        else:
2744
2473
                            # grab any one entry, use it to find the right path.
2745
 
                            a_key = next(iter(entry_keys))
2746
 
                            if by_path[a_key][lookup_index][0] in (b'r', b'a'):
2747
 
                                # its a pointer or missing statement, use it as
2748
 
                                # is.
2749
 
                                new_details.append(
2750
 
                                    by_path[a_key][lookup_index])
 
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.
 
2480
                                new_details.append(by_path[a_key][lookup_index])
2751
2481
                            else:
2752
2482
                                # we have the right key, make a pointer to it.
2753
 
                                real_path = (b'/'.join(a_key[0:2])).strip(b'/')
2754
 
                                new_details.append(st(b'r', real_path, 0, False,
2755
 
                                                      b''))
 
2483
                                real_path = ('/'.join(a_key[0:2])).strip('/')
 
2484
                                new_details.append(('r', real_path, 0, False, ''))
2756
2485
                    new_details.append(self._inv_entry_to_details(entry))
2757
2486
                    new_details.extend(new_location_suffix)
2758
2487
                    by_path[new_entry_key] = new_details
2759
 
                    self._add_to_id_index(id_index, new_entry_key)
 
2488
                    id_index[file_id].add(new_entry_key)
2760
2489
        # --- end generation of full tree mappings
2761
2490
 
2762
2491
        # sort and output all the entries
2764
2493
        self._entries_to_current_state(new_entries)
2765
2494
        self._parents = [rev_id for rev_id, tree in trees]
2766
2495
        self._ghosts = list(ghosts)
2767
 
        self._mark_modified(header_modified=True)
 
2496
        self._header_state = DirState.IN_MEMORY_MODIFIED
 
2497
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
2768
2498
        self._id_index = id_index
2769
2499
 
2770
2500
    def _sort_entries(self, entry_list):
2774
2504
        try to keep everything in sorted blocks all the time, but sometimes
2775
2505
        it's easier to sort after the fact.
2776
2506
        """
2777
 
        # When sorting, we usually have 10x more entries than directories. (69k
2778
 
        # total entries, 4k directories). So cache the results of splitting.
2779
 
        # Saving time and objects. Also, use StaticTuple to avoid putting all
2780
 
        # of these object into python's garbage collector.
2781
 
        split_dirs = {}
2782
 
 
2783
 
        def _key(entry, _split_dirs=split_dirs, _st=static_tuple.StaticTuple):
 
2507
        def _key(entry):
2784
2508
            # sort by: directory parts, file name, file id
2785
 
            dirpath, fname, file_id = entry[0]
2786
 
            try:
2787
 
                split = _split_dirs[dirpath]
2788
 
            except KeyError:
2789
 
                split = _st.from_sequence(dirpath.split(b'/'))
2790
 
                _split_dirs[dirpath] = split
2791
 
            return _st(split, fname, file_id)
 
2509
            return entry[0][0].split('/'), entry[0][1], entry[0][2]
2792
2510
        return sorted(entry_list, key=_key)
2793
2511
 
2794
2512
    def set_state_from_inventory(self, new_inv):
2801
2519
        """
2802
2520
        if 'evil' in debug.debug_flags:
2803
2521
            trace.mutter_callsite(1,
2804
 
                                  "set_state_from_inventory called; please mutate the tree instead")
 
2522
                "set_state_from_inventory called; please mutate the tree instead")
2805
2523
        tracing = 'dirstate' in debug.debug_flags
2806
2524
        if tracing:
2807
2525
            trace.mutter("set_state_from_inventory trace:")
2824
2542
        # underlying dirstate.
2825
2543
        old_iterator = iter(list(self._iter_entries()))
2826
2544
        # both must have roots so this is safe:
2827
 
        current_new = next(new_iterator)
2828
 
        current_old = next(old_iterator)
2829
 
 
 
2545
        current_new = new_iterator.next()
 
2546
        current_old = old_iterator.next()
2830
2547
        def advance(iterator):
2831
2548
            try:
2832
 
                return next(iterator)
 
2549
                return iterator.next()
2833
2550
            except StopIteration:
2834
2551
                return None
2835
2552
        while current_new or current_old:
2836
2553
            # skip entries in old that are not really there
2837
 
            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':
2838
2555
                # relocated or absent
2839
2556
                current_old = advance(old_iterator)
2840
2557
                continue
2846
2563
                new_entry_key = (new_dirname, new_basename, new_id)
2847
2564
                current_new_minikind = \
2848
2565
                    DirState._kind_to_minikind[current_new[1].kind]
2849
 
                if current_new_minikind == b't':
2850
 
                    fingerprint = current_new[1].reference_revision or b''
 
2566
                if current_new_minikind == 't':
 
2567
                    fingerprint = current_new[1].reference_revision or ''
2851
2568
                else:
2852
2569
                    # We normally only insert or remove records, or update
2853
2570
                    # them when it has significantly changed.  Then we want to
2854
2571
                    # erase its fingerprint.  Unaffected records should
2855
2572
                    # normally not be updated at all.
2856
 
                    fingerprint = b''
 
2573
                    fingerprint = ''
2857
2574
            else:
2858
2575
                # for safety disable variables
2859
2576
                new_path_utf8 = new_dirname = new_basename = new_id = \
2864
2581
                # old is finished: insert current_new into the state.
2865
2582
                if tracing:
2866
2583
                    trace.mutter("Appending from new '%s'.",
2867
 
                                 new_path_utf8.decode('utf8'))
 
2584
                        new_path_utf8.decode('utf8'))
2868
2585
                self.update_minimal(new_entry_key, current_new_minikind,
2869
 
                                    executable=current_new[1].executable,
2870
 
                                    path_utf8=new_path_utf8, fingerprint=fingerprint,
2871
 
                                    fullscan=True)
 
2586
                    executable=current_new[1].executable,
 
2587
                    path_utf8=new_path_utf8, fingerprint=fingerprint,
 
2588
                    fullscan=True)
2872
2589
                current_new = advance(new_iterator)
2873
2590
            elif not current_new:
2874
2591
                # new is finished
2875
2592
                if tracing:
2876
2593
                    trace.mutter("Truncating from old '%s/%s'.",
2877
 
                                 current_old[0][0].decode('utf8'),
2878
 
                                 current_old[0][1].decode('utf8'))
 
2594
                        current_old[0][0].decode('utf8'),
 
2595
                        current_old[0][1].decode('utf8'))
2879
2596
                self._make_absent(current_old)
2880
2597
                current_old = advance(old_iterator)
2881
2598
            elif new_entry_key == current_old[0]:
2887
2604
                # the minimal required trigger is if the execute bit or cached
2888
2605
                # kind has changed.
2889
2606
                if (current_old[1][0][3] != current_new[1].executable or
2890
 
                        current_old[1][0][0] != current_new_minikind):
 
2607
                    current_old[1][0][0] != current_new_minikind):
2891
2608
                    if tracing:
2892
2609
                        trace.mutter("Updating in-place change '%s'.",
2893
 
                                     new_path_utf8.decode('utf8'))
 
2610
                            new_path_utf8.decode('utf8'))
2894
2611
                    self.update_minimal(current_old[0], current_new_minikind,
2895
 
                                        executable=current_new[1].executable,
2896
 
                                        path_utf8=new_path_utf8, fingerprint=fingerprint,
2897
 
                                        fullscan=True)
 
2612
                        executable=current_new[1].executable,
 
2613
                        path_utf8=new_path_utf8, fingerprint=fingerprint,
 
2614
                        fullscan=True)
2898
2615
                # both sides are dealt with, move on
2899
2616
                current_old = advance(old_iterator)
2900
2617
                current_new = advance(new_iterator)
2901
 
            elif (lt_by_dirs(new_dirname, current_old[0][0])
2902
 
                  or (new_dirname == current_old[0][0] and
2903
 
                      new_entry_key[1:] < current_old[0][1:])):
 
2618
            elif (cmp_by_dirs(new_dirname, current_old[0][0]) < 0
 
2619
                  or (new_dirname == current_old[0][0]
 
2620
                      and new_entry_key[1:] < current_old[0][1:])):
2904
2621
                # new comes before:
2905
2622
                # add a entry for this and advance new
2906
2623
                if tracing:
2907
2624
                    trace.mutter("Inserting from new '%s'.",
2908
 
                                 new_path_utf8.decode('utf8'))
 
2625
                        new_path_utf8.decode('utf8'))
2909
2626
                self.update_minimal(new_entry_key, current_new_minikind,
2910
 
                                    executable=current_new[1].executable,
2911
 
                                    path_utf8=new_path_utf8, fingerprint=fingerprint,
2912
 
                                    fullscan=True)
 
2627
                    executable=current_new[1].executable,
 
2628
                    path_utf8=new_path_utf8, fingerprint=fingerprint,
 
2629
                    fullscan=True)
2913
2630
                current_new = advance(new_iterator)
2914
2631
            else:
2915
2632
                # we've advanced past the place where the old key would be,
2916
2633
                # without seeing it in the new list.  so it must be gone.
2917
2634
                if tracing:
2918
2635
                    trace.mutter("Deleting from old '%s/%s'.",
2919
 
                                 current_old[0][0].decode('utf8'),
2920
 
                                 current_old[0][1].decode('utf8'))
 
2636
                        current_old[0][0].decode('utf8'),
 
2637
                        current_old[0][1].decode('utf8'))
2921
2638
                self._make_absent(current_old)
2922
2639
                current_old = advance(old_iterator)
2923
 
        self._mark_modified()
 
2640
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
2924
2641
        self._id_index = None
2925
2642
        self._packed_stat_index = None
2926
2643
        if tracing:
2927
2644
            trace.mutter("set_state_from_inventory complete.")
2928
2645
 
2929
 
    def set_state_from_scratch(self, working_inv, parent_trees, parent_ghosts):
2930
 
        """Wipe the currently stored state and set it to something new.
2931
 
 
2932
 
        This is a hard-reset for the data we are working with.
2933
 
        """
2934
 
        # Technically, we really want a write lock, but until we write, we
2935
 
        # don't really need it.
2936
 
        self._requires_lock()
2937
 
        # root dir and root dir contents with no children. We have to have a
2938
 
        # root for set_state_from_inventory to work correctly.
2939
 
        empty_root = ((b'', b'', inventory.ROOT_ID),
2940
 
                      [(b'd', b'', 0, False, DirState.NULLSTAT)])
2941
 
        empty_tree_dirblocks = [(b'', [empty_root]), (b'', [])]
2942
 
        self._set_data([], empty_tree_dirblocks)
2943
 
        self.set_state_from_inventory(working_inv)
2944
 
        self.set_parent_trees(parent_trees, parent_ghosts)
2945
 
 
2946
2646
    def _make_absent(self, current_old):
2947
2647
        """Mark current_old - an entry - as absent for tree 0.
2948
2648
 
2955
2655
        all_remaining_keys = set()
2956
2656
        # Dont check the working tree, because it's going.
2957
2657
        for details in current_old[1][1:]:
2958
 
            if details[0] not in (b'a', b'r'):  # absent, relocated
 
2658
            if details[0] not in 'ar': # absent, relocated
2959
2659
                all_remaining_keys.add(current_old[0])
2960
 
            elif details[0] == b'r':  # relocated
 
2660
            elif details[0] == 'r': # relocated
2961
2661
                # record the key for the real path.
2962
 
                all_remaining_keys.add(
2963
 
                    tuple(osutils.split(details[1])) + (current_old[0][2],))
 
2662
                all_remaining_keys.add(tuple(osutils.split(details[1])) + (current_old[0][2],))
2964
2663
            # absent rows are not present at any path.
2965
2664
        last_reference = current_old[0] not in all_remaining_keys
2966
2665
        if last_reference:
2968
2667
            # absent), and relocated or absent entries for the other trees:
2969
2668
            # Remove it, its meaningless.
2970
2669
            block = self._find_block(current_old[0])
2971
 
            entry_index, present = self._find_entry_index(
2972
 
                current_old[0], block[1])
 
2670
            entry_index, present = self._find_entry_index(current_old[0], block[1])
2973
2671
            if not present:
2974
 
                raise AssertionError(
2975
 
                    'could not find entry for %s' % (current_old,))
 
2672
                raise AssertionError('could not find entry for %s' % (current_old,))
2976
2673
            block[1].pop(entry_index)
2977
2674
            # if we have an id_index in use, remove this key from it for this id.
2978
2675
            if self._id_index is not None:
2979
 
                self._remove_from_id_index(self._id_index, current_old[0])
 
2676
                self._id_index[current_old[0][2]].remove(current_old[0])
2980
2677
        # update all remaining keys for this id to record it as absent. The
2981
2678
        # existing details may either be the record we are marking as deleted
2982
2679
        # (if there were other trees with the id present at this path), or may
2985
2682
            update_block_index, present = \
2986
2683
                self._find_block_index_from_key(update_key)
2987
2684
            if not present:
2988
 
                raise AssertionError(
2989
 
                    'could not find block for %s' % (update_key,))
 
2685
                raise AssertionError('could not find block for %s' % (update_key,))
2990
2686
            update_entry_index, present = \
2991
 
                self._find_entry_index(
2992
 
                    update_key, self._dirblocks[update_block_index][1])
 
2687
                self._find_entry_index(update_key, self._dirblocks[update_block_index][1])
2993
2688
            if not present:
2994
 
                raise AssertionError(
2995
 
                    'could not find entry for %s' % (update_key,))
 
2689
                raise AssertionError('could not find entry for %s' % (update_key,))
2996
2690
            update_tree_details = self._dirblocks[update_block_index][1][update_entry_index][1]
2997
2691
            # it must not be absent at the moment
2998
 
            if update_tree_details[0][0] == b'a':  # absent
 
2692
            if update_tree_details[0][0] == 'a': # absent
2999
2693
                raise AssertionError('bad row %r' % (update_tree_details,))
3000
2694
            update_tree_details[0] = DirState.NULL_PARENT_DETAILS
3001
 
        self._mark_modified()
 
2695
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
3002
2696
        return last_reference
3003
2697
 
3004
 
    def update_minimal(self, key, minikind, executable=False, fingerprint=b'',
3005
 
                       packed_stat=None, size=0, path_utf8=None, fullscan=False):
 
2698
    def update_minimal(self, key, minikind, executable=False, fingerprint='',
 
2699
        packed_stat=None, size=0, path_utf8=None, fullscan=False):
3006
2700
        """Update an entry to the state in tree 0.
3007
2701
 
3008
2702
        This will either create a new entry at 'key' or update an existing one.
3010
2704
        updated as well.
3011
2705
 
3012
2706
        :param key: (dir, name, file_id) for the new entry
3013
 
        :param minikind: The type for the entry (b'f' == 'file', b'd' ==
 
2707
        :param minikind: The type for the entry ('f' == 'file', 'd' ==
3014
2708
                'directory'), etc.
3015
2709
        :param executable: Should the executable bit be set?
3016
2710
        :param fingerprint: Simple fingerprint for new entry: canonical-form
3029
2723
        block = self._find_block(key)[1]
3030
2724
        if packed_stat is None:
3031
2725
            packed_stat = DirState.NULLSTAT
3032
 
        # XXX: Some callers pass b'' as the packed_stat, and it seems to be
 
2726
        # XXX: Some callers pass '' as the packed_stat, and it seems to be
3033
2727
        # sometimes present in the dirstate - this seems oddly inconsistent.
3034
2728
        # mbp 20071008
3035
2729
        entry_index, present = self._find_entry_index(key, block)
3038
2732
        if not present:
3039
2733
            # New record. Check there isn't a entry at this path already.
3040
2734
            if not fullscan:
3041
 
                low_index, _ = self._find_entry_index(key[0:2] + (b'',), block)
 
2735
                low_index, _ = self._find_entry_index(key[0:2] + ('',), block)
3042
2736
                while low_index < len(block):
3043
2737
                    entry = block[low_index]
3044
2738
                    if entry[0][0:2] == key[0:2]:
3045
 
                        if entry[1][0][0] not in (b'a', b'r'):
 
2739
                        if entry[1][0][0] not in 'ar':
3046
2740
                            # This entry has the same path (but a different id) as
3047
2741
                            # the new entry we're adding, and is present in ths
3048
2742
                            # tree.
3049
 
                            self._raise_invalid(
3050
 
                                (b"%s/%s" % key[0:2]).decode('utf8'), key[2],
 
2743
                            raise errors.InconsistentDelta(
 
2744
                                ("%s/%s" % key[0:2]).decode('utf8'), key[2],
3051
2745
                                "Attempt to add item at path already occupied by "
3052
2746
                                "id %r" % entry[0][2])
3053
2747
                        low_index += 1
3054
2748
                    else:
3055
2749
                        break
3056
2750
            # new entry, synthesis cross reference here,
3057
 
            existing_keys = id_index.get(key[2], ())
 
2751
            existing_keys = id_index.setdefault(key[2], set())
3058
2752
            if not existing_keys:
3059
2753
                # not currently in the state, simplest case
3060
2754
                new_entry = key, [new_details] + self._empty_parent_info()
3090
2784
                    # entry, if not already examined, is skipped over by that
3091
2785
                    # loop.
3092
2786
                    other_entry = other_block[other_entry_index]
3093
 
                    other_entry[1][0] = (b'r', path_utf8, 0, False, b'')
3094
 
                    if self._maybe_remove_row(other_block, other_entry_index,
3095
 
                                              id_index):
3096
 
                        # If the row holding this was removed, we need to
3097
 
                        # recompute where this entry goes
3098
 
                        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)
3099
2790
 
3100
2791
                # This loop:
3101
2792
                # adds a tuple to the new details for each column
3103
2794
                #  - or by creating a new pointer to the right row inside that column
3104
2795
                num_present_parents = self._num_present_parents()
3105
2796
                if num_present_parents:
3106
 
                    # TODO: This re-evaluates the existing_keys set, do we need
3107
 
                    #       to do that ourselves?
3108
2797
                    other_key = list(existing_keys)[0]
3109
 
                for lookup_index in range(1, num_present_parents + 1):
 
2798
                for lookup_index in xrange(1, num_present_parents + 1):
3110
2799
                    # grab any one entry, use it to find the right path.
3111
2800
                    # TODO: optimise this to reduce memory use in highly
3112
2801
                    # fragmented situations by reusing the relocation
3114
2803
                    update_block_index, present = \
3115
2804
                        self._find_block_index_from_key(other_key)
3116
2805
                    if not present:
3117
 
                        raise AssertionError(
3118
 
                            'could not find block for %s' % (other_key,))
 
2806
                        raise AssertionError('could not find block for %s' % (other_key,))
3119
2807
                    update_entry_index, present = \
3120
 
                        self._find_entry_index(
3121
 
                            other_key, self._dirblocks[update_block_index][1])
 
2808
                        self._find_entry_index(other_key, self._dirblocks[update_block_index][1])
3122
2809
                    if not present:
3123
 
                        raise AssertionError(
3124
 
                            'update_minimal: could not find entry for %s' % (other_key,))
 
2810
                        raise AssertionError('update_minimal: could not find entry for %s' % (other_key,))
3125
2811
                    update_details = self._dirblocks[update_block_index][1][update_entry_index][1][lookup_index]
3126
 
                    if update_details[0] in (b'a', b'r'):  # relocated, absent
 
2812
                    if update_details[0] in 'ar': # relocated, absent
3127
2813
                        # its a pointer or absent in lookup_index's tree, use
3128
2814
                        # it as is.
3129
2815
                        new_entry[1].append(update_details)
3130
2816
                    else:
3131
2817
                        # we have the right key, make a pointer to it.
3132
2818
                        pointer_path = osutils.pathjoin(*other_key[0:2])
3133
 
                        new_entry[1].append(
3134
 
                            (b'r', pointer_path, 0, False, b''))
 
2819
                        new_entry[1].append(('r', pointer_path, 0, False, ''))
3135
2820
            block.insert(entry_index, new_entry)
3136
 
            self._add_to_id_index(id_index, key)
 
2821
            existing_keys.add(key)
3137
2822
        else:
3138
2823
            # Does the new state matter?
3139
2824
            block[entry_index][1][0] = new_details
3148
2833
            # converted to relocated.
3149
2834
            if path_utf8 is None:
3150
2835
                raise AssertionError('no path')
3151
 
            existing_keys = id_index.get(key[2], ())
3152
 
            if key not in existing_keys:
3153
 
                raise AssertionError('We found the entry in the blocks, but'
3154
 
                                     ' the key is not in the id_index.'
3155
 
                                     ' key: %s, existing_keys: %s' % (key, existing_keys))
3156
 
            for entry_key in existing_keys:
 
2836
            for entry_key in id_index.setdefault(key[2], set()):
3157
2837
                # TODO:PROFILING: It might be faster to just update
3158
2838
                # rather than checking if we need to, and then overwrite
3159
2839
                # the one we are located at.
3162
2842
                    # other trees, so put absent pointers there
3163
2843
                    # This is the vertical axis in the matrix, all pointing
3164
2844
                    # to the real path.
3165
 
                    block_index, present = self._find_block_index_from_key(
3166
 
                        entry_key)
 
2845
                    block_index, present = self._find_block_index_from_key(entry_key)
3167
2846
                    if not present:
3168
2847
                        raise AssertionError('not present: %r', entry_key)
3169
 
                    entry_index, present = self._find_entry_index(
3170
 
                        entry_key, self._dirblocks[block_index][1])
 
2848
                    entry_index, present = self._find_entry_index(entry_key, self._dirblocks[block_index][1])
3171
2849
                    if not present:
3172
2850
                        raise AssertionError('not present: %r', entry_key)
3173
2851
                    self._dirblocks[block_index][1][entry_index][1][0] = \
3174
 
                        (b'r', path_utf8, 0, False, b'')
 
2852
                        ('r', path_utf8, 0, False, '')
3175
2853
        # add a containing dirblock if needed.
3176
 
        if new_details[0] == b'd':
3177
 
            # GZ 2017-06-09: Using pathjoin why?
3178
 
            subdir_key = (osutils.pathjoin(*key[0:2]), b'', b'')
 
2854
        if new_details[0] == 'd':
 
2855
            subdir_key = (osutils.pathjoin(*key[0:2]), '', '')
3179
2856
            block_index, present = self._find_block_index_from_key(subdir_key)
3180
2857
            if not present:
3181
2858
                self._dirblocks.insert(block_index, (subdir_key[0], []))
3182
2859
 
3183
 
        self._mark_modified()
 
2860
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
3184
2861
 
3185
2862
    def _maybe_remove_row(self, block, index, id_index):
3186
2863
        """Remove index if it is absent or relocated across the row.
3187
 
 
 
2864
        
3188
2865
        id_index is updated accordingly.
3189
 
        :return: True if we removed the row, False otherwise
3190
2866
        """
3191
2867
        present_in_row = False
3192
2868
        entry = block[index]
3193
2869
        for column in entry[1]:
3194
 
            if column[0] not in (b'a', b'r'):
 
2870
            if column[0] not in 'ar':
3195
2871
                present_in_row = True
3196
2872
                break
3197
2873
        if not present_in_row:
3198
2874
            block.pop(index)
3199
 
            self._remove_from_id_index(id_index, entry[0])
3200
 
            return True
3201
 
        return False
 
2875
            id_index[entry[0][2]].remove(entry[0])
3202
2876
 
3203
2877
    def _validate(self):
3204
2878
        """Check that invariants on the dirblock are correct.
3211
2885
        # NOTE: This must always raise AssertionError not just assert,
3212
2886
        # otherwise it may not behave properly under python -O
3213
2887
        #
3214
 
        # TODO: All entries must have some content that's not b'a' or b'r',
 
2888
        # TODO: All entries must have some content that's not 'a' or 'r',
3215
2889
        # otherwise it could just be removed.
3216
2890
        #
3217
2891
        # TODO: All relocations must point directly to a real entry.
3222
2896
        from pprint import pformat
3223
2897
        self._read_dirblocks_if_needed()
3224
2898
        if len(self._dirblocks) > 0:
3225
 
            if not self._dirblocks[0][0] == b'':
 
2899
            if not self._dirblocks[0][0] == '':
3226
2900
                raise AssertionError(
3227
 
                    "dirblocks don't start with root block:\n"
3228
 
                    + pformat(self._dirblocks))
 
2901
                    "dirblocks don't start with root block:\n" + \
 
2902
                    pformat(self._dirblocks))
3229
2903
        if len(self._dirblocks) > 1:
3230
 
            if not self._dirblocks[1][0] == b'':
 
2904
            if not self._dirblocks[1][0] == '':
3231
2905
                raise AssertionError(
3232
 
                    "dirblocks missing root directory:\n"
3233
 
                    + pformat(self._dirblocks))
 
2906
                    "dirblocks missing root directory:\n" + \
 
2907
                    pformat(self._dirblocks))
3234
2908
        # the dirblocks are sorted by their path components, name, and dir id
3235
 
        dir_names = [d[0].split(b'/')
3236
 
                     for d in self._dirblocks[1:]]
 
2909
        dir_names = [d[0].split('/')
 
2910
                for d in self._dirblocks[1:]]
3237
2911
        if dir_names != sorted(dir_names):
3238
2912
            raise AssertionError(
3239
 
                "dir names are not in sorted order:\n" +
3240
 
                pformat(self._dirblocks) +
 
2913
                "dir names are not in sorted order:\n" + \
 
2914
                pformat(self._dirblocks) + \
3241
2915
                "\nkeys:\n" +
3242
2916
                pformat(dir_names))
3243
2917
        for dirblock in self._dirblocks:
3251
2925
                        (entry, pformat(dirblock)))
3252
2926
            if dirblock[1] != sorted(dirblock[1]):
3253
2927
                raise AssertionError(
3254
 
                    "dirblock for %r is not sorted:\n%s" %
 
2928
                    "dirblock for %r is not sorted:\n%s" % \
3255
2929
                    (dirblock[0], pformat(dirblock)))
3256
2930
 
3257
2931
        def check_valid_parent():
3262
2936
            current tree. (It is invalid to have a non-absent file in an absent
3263
2937
            directory.)
3264
2938
            """
3265
 
            if entry[0][0:2] == (b'', b''):
 
2939
            if entry[0][0:2] == ('', ''):
3266
2940
                # There should be no parent for the root row
3267
2941
                return
3268
2942
            parent_entry = self._get_entry(tree_index, path_utf8=entry[0][0])
3270
2944
                raise AssertionError(
3271
2945
                    "no parent entry for: %s in tree %s"
3272
2946
                    % (this_path, tree_index))
3273
 
            if parent_entry[1][tree_index][0] != b'd':
 
2947
            if parent_entry[1][tree_index][0] != 'd':
3274
2948
                raise AssertionError(
3275
2949
                    "Parent entry for %s is not marked as a valid"
3276
2950
                    " directory. %s" % (this_path, parent_entry,))
3284
2958
        # We check this with a dict per tree pointing either to the present
3285
2959
        # name, or None if absent.
3286
2960
        tree_count = self._num_present_parents() + 1
3287
 
        id_path_maps = [{} for _ in range(tree_count)]
 
2961
        id_path_maps = [dict() for i in range(tree_count)]
3288
2962
        # Make sure that all renamed entries point to the correct location.
3289
2963
        for entry in self._iter_entries():
3290
2964
            file_id = entry[0][2]
3291
2965
            this_path = osutils.pathjoin(entry[0][0], entry[0][1])
3292
2966
            if len(entry[1]) != tree_count:
3293
2967
                raise AssertionError(
3294
 
                    "wrong number of entry details for row\n%s"
3295
 
                    ",\nexpected %d" %
3296
 
                    (pformat(entry), tree_count))
 
2968
                "wrong number of entry details for row\n%s" \
 
2969
                ",\nexpected %d" % \
 
2970
                (pformat(entry), tree_count))
3297
2971
            absent_positions = 0
3298
2972
            for tree_index, tree_state in enumerate(entry[1]):
3299
2973
                this_tree_map = id_path_maps[tree_index]
3300
2974
                minikind = tree_state[0]
3301
 
                if minikind in (b'a', b'r'):
 
2975
                if minikind in 'ar':
3302
2976
                    absent_positions += 1
3303
2977
                # have we seen this id before in this column?
3304
2978
                if file_id in this_tree_map:
3305
2979
                    previous_path, previous_loc = this_tree_map[file_id]
3306
2980
                    # any later mention of this file must be consistent with
3307
2981
                    # what was said before
3308
 
                    if minikind == b'a':
 
2982
                    if minikind == 'a':
3309
2983
                        if previous_path is not None:
3310
2984
                            raise AssertionError(
3311
 
                                "file %s is absent in row %r but also present "
3312
 
                                "at %r" %
3313
 
                                (file_id.decode('utf-8'), entry, previous_path))
3314
 
                    elif minikind == b'r':
 
2985
                            "file %s is absent in row %r but also present " \
 
2986
                            "at %r"% \
 
2987
                            (file_id, entry, previous_path))
 
2988
                    elif minikind == 'r':
3315
2989
                        target_location = tree_state[1]
3316
2990
                        if previous_path != target_location:
3317
2991
                            raise AssertionError(
3318
 
                                "file %s relocation in row %r but also at %r"
3319
 
                                % (file_id, entry, previous_path))
 
2992
                            "file %s relocation in row %r but also at %r" \
 
2993
                            % (file_id, entry, previous_path))
3320
2994
                    else:
3321
2995
                        # a file, directory, etc - may have been previously
3322
2996
                        # pointed to by a relocation, which must point here
3327
3001
                                (entry, previous_path, previous_loc))
3328
3002
                        check_valid_parent()
3329
3003
                else:
3330
 
                    if minikind == b'a':
 
3004
                    if minikind == 'a':
3331
3005
                        # absent; should not occur anywhere else
3332
3006
                        this_tree_map[file_id] = None, this_path
3333
 
                    elif minikind == b'r':
 
3007
                    elif minikind == 'r':
3334
3008
                        # relocation, must occur at expected location
3335
3009
                        this_tree_map[file_id] = tree_state[1], this_path
3336
3010
                    else:
3339
3013
            if absent_positions == tree_count:
3340
3014
                raise AssertionError(
3341
3015
                    "entry %r has no data for any tree." % (entry,))
3342
 
        if self._id_index is not None:
3343
 
            for file_id, entry_keys in self._id_index.items():
3344
 
                for entry_key in entry_keys:
3345
 
                    # Check that the entry in the map is pointing to the same
3346
 
                    # file_id
3347
 
                    if entry_key[2] != file_id:
3348
 
                        raise AssertionError(
3349
 
                            'file_id %r did not match entry key %s'
3350
 
                            % (file_id, entry_key))
3351
 
                    # And that from this entry key, we can look up the original
3352
 
                    # record
3353
 
                    block_index, present = self._find_block_index_from_key(
3354
 
                        entry_key)
3355
 
                    if not present:
3356
 
                        raise AssertionError(
3357
 
                            'missing block for entry key: %r', entry_key)
3358
 
                    entry_index, present = self._find_entry_index(
3359
 
                        entry_key, self._dirblocks[block_index][1])
3360
 
                    if not present:
3361
 
                        raise AssertionError(
3362
 
                            'missing entry for key: %r', entry_key)
3363
 
                if len(entry_keys) != len(set(entry_keys)):
3364
 
                    raise AssertionError(
3365
 
                        'id_index contained non-unique data for %s'
3366
 
                        % (entry_keys,))
3367
3016
 
3368
3017
    def _wipe_state(self):
3369
3018
        """Forget all state information about the dirstate."""
3391
3040
        self._lock_state = 'r'
3392
3041
        self._state_file = self._lock_token.f
3393
3042
        self._wipe_state()
3394
 
        return lock.LogicalLockResult(self.unlock)
3395
3043
 
3396
3044
    def lock_write(self):
3397
3045
        """Acquire a write lock on the dirstate."""
3405
3053
        self._lock_state = 'w'
3406
3054
        self._state_file = self._lock_token.f
3407
3055
        self._wipe_state()
3408
 
        return lock.LogicalLockResult(self.unlock, self._lock_token)
3409
3056
 
3410
3057
    def unlock(self):
3411
3058
        """Drop any locks held on the dirstate."""
3428
3075
 
3429
3076
 
3430
3077
def py_update_entry(state, entry, abspath, stat_value,
3431
 
                    _stat_to_minikind=DirState._stat_to_minikind):
 
3078
                 _stat_to_minikind=DirState._stat_to_minikind,
 
3079
                 _pack_stat=pack_stat):
3432
3080
    """Update the entry based on what is actually on disk.
3433
3081
 
3434
3082
    This function only calculates the sha if it needs to - if the entry is
3443
3091
        target of a symlink.
3444
3092
    """
3445
3093
    try:
3446
 
        minikind = _stat_to_minikind[stat_value.st_mode & 0o170000]
 
3094
        minikind = _stat_to_minikind[stat_value.st_mode & 0170000]
3447
3095
    except KeyError:
3448
3096
        # Unhandled kind
3449
3097
        return None
3450
 
    packed_stat = pack_stat(stat_value)
 
3098
    packed_stat = _pack_stat(stat_value)
3451
3099
    (saved_minikind, saved_link_or_sha1, saved_file_size,
3452
3100
     saved_executable, saved_packed_stat) = entry[1][0]
3453
 
    if not isinstance(saved_minikind, bytes):
3454
 
        raise TypeError(saved_minikind)
3455
3101
 
3456
 
    if minikind == b'd' and saved_minikind == b't':
3457
 
        minikind = b't'
 
3102
    if minikind == 'd' and saved_minikind == 't':
 
3103
        minikind = 't'
3458
3104
    if (minikind == saved_minikind
3459
 
            and packed_stat == saved_packed_stat):
 
3105
        and packed_stat == saved_packed_stat):
3460
3106
        # The stat hasn't changed since we saved, so we can re-use the
3461
3107
        # saved sha hash.
3462
 
        if minikind == b'd':
 
3108
        if minikind == 'd':
3463
3109
            return None
3464
3110
 
3465
3111
        # size should also be in packed_stat
3469
3115
    # If we have gotten this far, that means that we need to actually
3470
3116
    # process this entry.
3471
3117
    link_or_sha1 = None
3472
 
    worth_saving = True
3473
 
    if minikind == b'f':
 
3118
    if minikind == 'f':
3474
3119
        executable = state._is_executable(stat_value.st_mode,
3475
 
                                          saved_executable)
 
3120
                                         saved_executable)
3476
3121
        if state._cutoff_time is None:
3477
3122
            state._sha_cutoff_time()
3478
3123
        if (stat_value.st_mtime < state._cutoff_time
3479
3124
            and stat_value.st_ctime < state._cutoff_time
3480
3125
            and len(entry[1]) > 1
3481
 
                and entry[1][1][0] != b'a'):
 
3126
            and entry[1][1][0] != 'a'):
3482
3127
            # Could check for size changes for further optimised
3483
3128
            # avoidance of sha1's. However the most prominent case of
3484
3129
            # over-shaing is during initial add, which this catches.
3486
3131
            # are calculated at the same time, so checking just the size
3487
3132
            # gains nothing w.r.t. performance.
3488
3133
            link_or_sha1 = state._sha1_file(abspath)
3489
 
            entry[1][0] = (b'f', link_or_sha1, stat_value.st_size,
 
3134
            entry[1][0] = ('f', link_or_sha1, stat_value.st_size,
3490
3135
                           executable, packed_stat)
3491
3136
        else:
3492
 
            entry[1][0] = (b'f', b'', stat_value.st_size,
 
3137
            entry[1][0] = ('f', '', stat_value.st_size,
3493
3138
                           executable, DirState.NULLSTAT)
3494
 
            worth_saving = False
3495
 
    elif minikind == b'd':
 
3139
    elif minikind == 'd':
3496
3140
        link_or_sha1 = None
3497
 
        entry[1][0] = (b'd', b'', 0, False, packed_stat)
3498
 
        if saved_minikind != b'd':
 
3141
        entry[1][0] = ('d', '', 0, False, packed_stat)
 
3142
        if saved_minikind != 'd':
3499
3143
            # This changed from something into a directory. Make sure we
3500
3144
            # have a directory block for it. This doesn't happen very
3501
3145
            # often, so this doesn't have to be super fast.
3502
3146
            block_index, entry_index, dir_present, file_present = \
3503
3147
                state._get_block_entry_index(entry[0][0], entry[0][1], 0)
3504
3148
            state._ensure_block(block_index, entry_index,
3505
 
                                osutils.pathjoin(entry[0][0], entry[0][1]))
3506
 
        else:
3507
 
            worth_saving = False
3508
 
    elif minikind == b'l':
3509
 
        if saved_minikind == b'l':
3510
 
            worth_saving = False
 
3149
                               osutils.pathjoin(entry[0][0], entry[0][1]))
 
3150
    elif minikind == 'l':
3511
3151
        link_or_sha1 = state._read_link(abspath, saved_link_or_sha1)
3512
3152
        if state._cutoff_time is None:
3513
3153
            state._sha_cutoff_time()
3514
3154
        if (stat_value.st_mtime < state._cutoff_time
3515
 
                and stat_value.st_ctime < state._cutoff_time):
3516
 
            entry[1][0] = (b'l', link_or_sha1, stat_value.st_size,
 
3155
            and stat_value.st_ctime < state._cutoff_time):
 
3156
            entry[1][0] = ('l', link_or_sha1, stat_value.st_size,
3517
3157
                           False, packed_stat)
3518
3158
        else:
3519
 
            entry[1][0] = (b'l', b'', stat_value.st_size,
 
3159
            entry[1][0] = ('l', '', stat_value.st_size,
3520
3160
                           False, DirState.NULLSTAT)
3521
 
    if worth_saving:
3522
 
        state._mark_modified([entry])
 
3161
    state._dirblock_state = DirState.IN_MEMORY_MODIFIED
3523
3162
    return link_or_sha1
3524
3163
 
3525
3164
 
3526
3165
class ProcessEntryPython(object):
3527
3166
 
3528
3167
    __slots__ = ["old_dirname_to_file_id", "new_dirname_to_file_id",
3529
 
                 "last_source_parent", "last_target_parent", "include_unchanged",
3530
 
                 "partial", "use_filesystem_for_exec", "utf8_decode",
3531
 
                 "searched_specific_files", "search_specific_files",
3532
 
                 "searched_exact_paths", "search_specific_file_parents", "seen_ids",
3533
 
                 "state", "source_index", "target_index", "want_unversioned", "tree"]
 
3168
        "last_source_parent", "last_target_parent", "include_unchanged",
 
3169
        "partial", "use_filesystem_for_exec", "utf8_decode",
 
3170
        "searched_specific_files", "search_specific_files",
 
3171
        "searched_exact_paths", "search_specific_file_parents", "seen_ids",
 
3172
        "state", "source_index", "target_index", "want_unversioned", "tree"]
3534
3173
 
3535
3174
    def __init__(self, include_unchanged, use_filesystem_for_exec,
3536
 
                 search_specific_files, state, source_index, target_index,
3537
 
                 want_unversioned, tree):
 
3175
        search_specific_files, state, source_index, target_index,
 
3176
        want_unversioned, tree):
3538
3177
        self.old_dirname_to_file_id = {}
3539
3178
        self.new_dirname_to_file_id = {}
3540
3179
        # Are we doing a partial iter_changes?
3541
 
        self.partial = search_specific_files != {''}
 
3180
        self.partial = search_specific_files != set([''])
3542
3181
        # Using a list so that we can access the values and change them in
3543
3182
        # nested scope. Each one is [path, file_id, entry]
3544
3183
        self.last_source_parent = [None, None]
3573
3212
        """Compare an entry and real disk to generate delta information.
3574
3213
 
3575
3214
        :param path_info: top_relpath, basename, kind, lstat, abspath for
3576
 
            the path of entry. If None, then the path is considered absent in
 
3215
            the path of entry. If None, then the path is considered absent in 
3577
3216
            the target (Perhaps we should pass in a concrete entry for this ?)
3578
3217
            Basename is returned as a utf8 string because we expect this
3579
3218
            tuple will be ignored, and don't want to take the time to
3590
3229
            source_details = DirState.NULL_PARENT_DETAILS
3591
3230
        else:
3592
3231
            source_details = entry[1][self.source_index]
3593
 
        # GZ 2017-06-09: Eck, more sets.
3594
 
        _fdltr = {b'f', b'd', b'l', b't', b'r'}
3595
 
        _fdlt = {b'f', b'd', b'l', b't'}
3596
 
        _ra = (b'r', b'a')
3597
3232
        target_details = entry[1][self.target_index]
3598
3233
        target_minikind = target_details[0]
3599
 
        if path_info is not None and target_minikind in _fdlt:
 
3234
        if path_info is not None and target_minikind in 'fdlt':
3600
3235
            if not (self.target_index == 0):
3601
3236
                raise AssertionError()
3602
3237
            link_or_sha1 = update_entry(self.state, entry,
3603
 
                                        abspath=path_info[4], stat_value=path_info[3])
 
3238
                abspath=path_info[4], stat_value=path_info[3])
3604
3239
            # The entry may have been modified by update_entry
3605
3240
            target_details = entry[1][self.target_index]
3606
3241
            target_minikind = target_details[0]
3608
3243
            link_or_sha1 = None
3609
3244
        file_id = entry[0][2]
3610
3245
        source_minikind = source_details[0]
3611
 
        if source_minikind in _fdltr and target_minikind in _fdlt:
 
3246
        if source_minikind in 'fdltr' and target_minikind in 'fdlt':
3612
3247
            # claimed content in both: diff
3613
3248
            #   r    | fdlt   |      | add source to search, add id path move and perform
3614
3249
            #        |        |      | diff check on source-target
3615
3250
            #   r    | fdlt   |  a   | dangling file that was present in the basis.
3616
3251
            #        |        |      | ???
3617
 
            if source_minikind == b'r':
 
3252
            if source_minikind in 'r':
3618
3253
                # add the source to the search path to find any children it
3619
3254
                # has.  TODO ? : only add if it is a container ?
3620
3255
                if not osutils.is_inside_any(self.searched_specific_files,
3626
3261
                old_dirname, old_basename = os.path.split(old_path)
3627
3262
                path = pathjoin(entry[0][0], entry[0][1])
3628
3263
                old_entry = self.state._get_entry(self.source_index,
3629
 
                                                  path_utf8=old_path)
 
3264
                                             path_utf8=old_path)
3630
3265
                # update the source details variable to be the real
3631
3266
                # location.
3632
3267
                if old_entry == (None, None):
3633
 
                    raise DirstateCorrupt(self.state._filename,
3634
 
                                          "entry '%s/%s' is considered renamed from %r"
3635
 
                                          " but source does not exist\n"
3636
 
                                          "entry: %s" % (entry[0][0], entry[0][1], old_path, entry))
 
3268
                    raise errors.CorruptDirstate(self.state._filename,
 
3269
                        "entry '%s/%s' is considered renamed from %r"
 
3270
                        " but source does not exist\n"
 
3271
                        "entry: %s" % (entry[0][0], entry[0][1], old_path, entry))
3637
3272
                source_details = old_entry[1][self.source_index]
3638
3273
                source_minikind = source_details[0]
3639
3274
            else:
3652
3287
                    if path is None:
3653
3288
                        old_path = path = pathjoin(old_dirname, old_basename)
3654
3289
                    self.new_dirname_to_file_id[path] = file_id
3655
 
                    if source_minikind != b'd':
 
3290
                    if source_minikind != 'd':
3656
3291
                        content_change = True
3657
3292
                    else:
3658
3293
                        # directories have no fingerprint
3659
3294
                        content_change = False
3660
3295
                    target_exec = False
3661
3296
                elif target_kind == 'file':
3662
 
                    if source_minikind != b'f':
 
3297
                    if source_minikind != 'f':
3663
3298
                        content_change = True
3664
3299
                    else:
3665
3300
                        # Check the sha. We can't just rely on the size as
3669
3304
                            # Stat cache miss:
3670
3305
                            statvalue, link_or_sha1 = \
3671
3306
                                self.state._sha1_provider.stat_and_sha1(
3672
 
                                    path_info[4])
 
3307
                                path_info[4])
3673
3308
                            self.state._observed_sha1(entry, link_or_sha1,
3674
 
                                                      statvalue)
 
3309
                                statvalue)
3675
3310
                        content_change = (link_or_sha1 != source_details[1])
3676
3311
                    # Target details is updated at update_entry time
3677
3312
                    if self.use_filesystem_for_exec:
3681
3316
                    else:
3682
3317
                        target_exec = target_details[3]
3683
3318
                elif target_kind == 'symlink':
3684
 
                    if source_minikind != b'l':
 
3319
                    if source_minikind != 'l':
3685
3320
                        content_change = True
3686
3321
                    else:
3687
3322
                        content_change = (link_or_sha1 != source_details[1])
3688
3323
                    target_exec = False
3689
3324
                elif target_kind == 'tree-reference':
3690
 
                    if source_minikind != b't':
 
3325
                    if source_minikind != 't':
3691
3326
                        content_change = True
3692
3327
                    else:
3693
3328
                        content_change = False
3694
3329
                    target_exec = False
3695
3330
                else:
3696
 
                    if path is None:
3697
 
                        path = pathjoin(old_dirname, old_basename)
3698
 
                    raise errors.BadFileKindError(path, path_info[2])
3699
 
            if source_minikind == b'd':
 
3331
                    raise Exception, "unknown kind %s" % path_info[2]
 
3332
            if source_minikind == 'd':
3700
3333
                if path is None:
3701
3334
                    old_path = path = pathjoin(old_dirname, old_basename)
3702
3335
                self.old_dirname_to_file_id[old_path] = file_id
3708
3341
                    source_parent_id = self.old_dirname_to_file_id[old_dirname]
3709
3342
                except KeyError:
3710
3343
                    source_parent_entry = self.state._get_entry(self.source_index,
3711
 
                                                                path_utf8=old_dirname)
 
3344
                                                           path_utf8=old_dirname)
3712
3345
                    source_parent_id = source_parent_entry[0][2]
3713
3346
                if source_parent_id == entry[0][2]:
3714
3347
                    # This is the root, so the parent is None
3726
3359
                    # TODO: We don't always need to do the lookup, because the
3727
3360
                    #       parent entry will be the same as the source entry.
3728
3361
                    target_parent_entry = self.state._get_entry(self.target_index,
3729
 
                                                                path_utf8=new_dirname)
 
3362
                                                           path_utf8=new_dirname)
3730
3363
                    if target_parent_entry == (None, None):
3731
3364
                        raise AssertionError(
3732
3365
                            "Could not find target parent in wt: %s\nparent of: %s"
3741
3374
 
3742
3375
            source_exec = source_details[3]
3743
3376
            changed = (content_change
3744
 
                       or source_parent_id != target_parent_id
3745
 
                       or old_basename != entry[0][1]
3746
 
                       or source_exec != target_exec
3747
 
                       )
 
3377
                or source_parent_id != target_parent_id
 
3378
                or old_basename != entry[0][1]
 
3379
                or source_exec != target_exec
 
3380
                )
3748
3381
            if not changed and not self.include_unchanged:
3749
3382
                return None, False
3750
3383
            else:
3759
3392
                    else:
3760
3393
                        path_u = self.utf8_decode(path)[0]
3761
3394
                source_kind = DirState._minikind_to_kind[source_minikind]
3762
 
                return TreeChange(
3763
 
                    entry[0][2],
3764
 
                    (old_path_u, path_u),
3765
 
                    content_change,
3766
 
                    (True, True),
3767
 
                    (source_parent_id, target_parent_id),
3768
 
                    (self.utf8_decode(old_basename)[
3769
 
                     0], self.utf8_decode(entry[0][1])[0]),
3770
 
                    (source_kind, target_kind),
3771
 
                    (source_exec, target_exec)), changed
3772
 
        elif source_minikind in b'a' and target_minikind in _fdlt:
 
3395
                return (entry[0][2],
 
3396
                       (old_path_u, path_u),
 
3397
                       content_change,
 
3398
                       (True, True),
 
3399
                       (source_parent_id, target_parent_id),
 
3400
                       (self.utf8_decode(old_basename)[0], self.utf8_decode(entry[0][1])[0]),
 
3401
                       (source_kind, target_kind),
 
3402
                       (source_exec, target_exec)), changed
 
3403
        elif source_minikind in 'a' and target_minikind in 'fdlt':
3773
3404
            # looks like a new file
3774
3405
            path = pathjoin(entry[0][0], entry[0][1])
3775
3406
            # parent id is the entry for the path in the target tree
3776
3407
            # TODO: these are the same for an entire directory: cache em.
3777
3408
            parent_id = self.state._get_entry(self.target_index,
3778
 
                                              path_utf8=entry[0][0])[0][2]
 
3409
                                         path_utf8=entry[0][0])[0][2]
3779
3410
            if parent_id == entry[0][2]:
3780
3411
                parent_id = None
3781
3412
            if path_info is not None:
3788
3419
                        and stat.S_IEXEC & path_info[3].st_mode)
3789
3420
                else:
3790
3421
                    target_exec = target_details[3]
3791
 
                return TreeChange(
3792
 
                    entry[0][2],
3793
 
                    (None, self.utf8_decode(path)[0]),
3794
 
                    True,
3795
 
                    (False, True),
3796
 
                    (None, parent_id),
3797
 
                    (None, self.utf8_decode(entry[0][1])[0]),
3798
 
                    (None, path_info[2]),
3799
 
                    (None, target_exec)), True
 
3422
                return (entry[0][2],
 
3423
                       (None, self.utf8_decode(path)[0]),
 
3424
                       True,
 
3425
                       (False, True),
 
3426
                       (None, parent_id),
 
3427
                       (None, self.utf8_decode(entry[0][1])[0]),
 
3428
                       (None, path_info[2]),
 
3429
                       (None, target_exec)), True
3800
3430
            else:
3801
3431
                # Its a missing file, report it as such.
3802
 
                return TreeChange(
3803
 
                    entry[0][2],
3804
 
                    (None, self.utf8_decode(path)[0]),
3805
 
                    False,
3806
 
                    (False, True),
3807
 
                    (None, parent_id),
3808
 
                    (None, self.utf8_decode(entry[0][1])[0]),
3809
 
                    (None, None),
3810
 
                    (None, False)), True
3811
 
        elif source_minikind in _fdlt and target_minikind in b'a':
 
3432
                return (entry[0][2],
 
3433
                       (None, self.utf8_decode(path)[0]),
 
3434
                       False,
 
3435
                       (False, True),
 
3436
                       (None, parent_id),
 
3437
                       (None, self.utf8_decode(entry[0][1])[0]),
 
3438
                       (None, None),
 
3439
                       (None, False)), True
 
3440
        elif source_minikind in 'fdlt' and target_minikind in 'a':
3812
3441
            # unversioned, possibly, or possibly not deleted: we dont care.
3813
3442
            # if its still on disk, *and* theres no other entry at this
3814
3443
            # path [we dont know this in this routine at the moment -
3815
3444
            # perhaps we should change this - then it would be an unknown.
3816
3445
            old_path = pathjoin(entry[0][0], entry[0][1])
3817
3446
            # parent id is the entry for the path in the target tree
3818
 
            parent_id = self.state._get_entry(
3819
 
                self.source_index, path_utf8=entry[0][0])[0][2]
 
3447
            parent_id = self.state._get_entry(self.source_index, path_utf8=entry[0][0])[0][2]
3820
3448
            if parent_id == entry[0][2]:
3821
3449
                parent_id = None
3822
 
            return TreeChange(
3823
 
                entry[0][2],
3824
 
                (self.utf8_decode(old_path)[0], None),
3825
 
                True,
3826
 
                (True, False),
3827
 
                (parent_id, None),
3828
 
                (self.utf8_decode(entry[0][1])[0], None),
3829
 
                (DirState._minikind_to_kind[source_minikind], None),
3830
 
                (source_details[3], None)), True
3831
 
        elif source_minikind in _fdlt and target_minikind in b'r':
 
3450
            return (entry[0][2],
 
3451
                   (self.utf8_decode(old_path)[0], None),
 
3452
                   True,
 
3453
                   (True, False),
 
3454
                   (parent_id, None),
 
3455
                   (self.utf8_decode(entry[0][1])[0], None),
 
3456
                   (DirState._minikind_to_kind[source_minikind], None),
 
3457
                   (source_details[3], None)), True
 
3458
        elif source_minikind in 'fdlt' and target_minikind in 'r':
3832
3459
            # a rename; could be a true rename, or a rename inherited from
3833
3460
            # a renamed parent. TODO: handle this efficiently. Its not
3834
3461
            # common case to rename dirs though, so a correct but slow
3835
3462
            # implementation will do.
3836
 
            if not osutils.is_inside_any(self.searched_specific_files,
3837
 
                                         target_details[1]):
 
3463
            if not osutils.is_inside_any(self.searched_specific_files, target_details[1]):
3838
3464
                self.search_specific_files.add(target_details[1])
3839
 
        elif source_minikind in _ra and target_minikind in _ra:
 
3465
        elif source_minikind in 'ra' and target_minikind in 'ra':
3840
3466
            # neither of the selected trees contain this file,
3841
3467
            # so skip over it. This is not currently directly tested, but
3842
3468
            # is indirectly via test_too_much.TestCommands.test_conflicts.
3843
3469
            pass
3844
3470
        else:
3845
3471
            raise AssertionError("don't know how to compare "
3846
 
                                 "source_minikind=%r, target_minikind=%r"
3847
 
                                 % (source_minikind, target_minikind))
 
3472
                "source_minikind=%r, target_minikind=%r"
 
3473
                % (source_minikind, target_minikind))
 
3474
            ## import pdb;pdb.set_trace()
3848
3475
        return None, None
3849
3476
 
3850
3477
    def __iter__(self):
3852
3479
 
3853
3480
    def _gather_result_for_consistency(self, result):
3854
3481
        """Check a result we will yield to make sure we are consistent later.
3855
 
 
 
3482
        
3856
3483
        This gathers result's parents into a set to output later.
3857
3484
 
3858
3485
        :param result: A result tuple.
3859
3486
        """
3860
 
        if not self.partial or not result.file_id:
 
3487
        if not self.partial or not result[0]:
3861
3488
            return
3862
 
        self.seen_ids.add(result.file_id)
3863
 
        new_path = result.path[1]
 
3489
        self.seen_ids.add(result[0])
 
3490
        new_path = result[1][1]
3864
3491
        if new_path:
3865
3492
            # Not the root and not a delete: queue up the parents of the path.
3866
3493
            self.search_specific_file_parents.update(
3867
 
                p.encode('utf8') for p in osutils.parent_directories(new_path))
 
3494
                osutils.parent_directories(new_path.encode('utf8')))
3868
3495
            # Add the root directory which parent_directories does not
3869
3496
            # provide.
3870
 
            self.search_specific_file_parents.add(b'')
 
3497
            self.search_specific_file_parents.add('')
3871
3498
 
3872
3499
    def iter_changes(self):
3873
3500
        """Iterate over the changes."""
3874
3501
        utf8_decode = cache_utf8._utf8_decode
3875
 
        _lt_by_dirs = lt_by_dirs
 
3502
        _cmp_by_dirs = cmp_by_dirs
3876
3503
        _process_entry = self._process_entry
3877
3504
        search_specific_files = self.search_specific_files
3878
3505
        searched_specific_files = self.searched_specific_files
3927
3554
            root_abspath = self.tree.abspath(current_root_unicode)
3928
3555
            try:
3929
3556
                root_stat = os.lstat(root_abspath)
3930
 
            except OSError as e:
 
3557
            except OSError, e:
3931
3558
                if e.errno == errno.ENOENT:
3932
3559
                    # the path does not exist: let _process_entry know that.
3933
3560
                    root_dir_info = None
3935
3562
                    # some other random error: hand it up.
3936
3563
                    raise
3937
3564
            else:
3938
 
                root_dir_info = (b'', current_root,
3939
 
                                 osutils.file_kind_from_stat_mode(
3940
 
                                     root_stat.st_mode), root_stat,
3941
 
                                 root_abspath)
 
3565
                root_dir_info = ('', current_root,
 
3566
                    osutils.file_kind_from_stat_mode(root_stat.st_mode), root_stat,
 
3567
                    root_abspath)
3942
3568
                if root_dir_info[2] == 'directory':
3943
3569
                    if self.tree._directory_is_tree_reference(
3944
 
                            current_root.decode('utf8')):
 
3570
                        current_root.decode('utf8')):
3945
3571
                        root_dir_info = root_dir_info[:2] + \
3946
3572
                            ('tree-reference',) + root_dir_info[3:]
3947
3573
 
3961
3587
                new_executable = bool(
3962
3588
                    stat.S_ISREG(root_dir_info[3].st_mode)
3963
3589
                    and stat.S_IEXEC & root_dir_info[3].st_mode)
3964
 
                yield TreeChange(
3965
 
                    None,
3966
 
                    (None, current_root_unicode),
3967
 
                    True,
3968
 
                    (False, False),
3969
 
                    (None, None),
3970
 
                    (None, splitpath(current_root_unicode)[-1]),
3971
 
                    (None, root_dir_info[2]),
3972
 
                    (None, new_executable)
3973
 
                    )
3974
 
            initial_key = (current_root, b'', b'')
 
3590
                yield (None,
 
3591
                       (None, current_root_unicode),
 
3592
                       True,
 
3593
                       (False, False),
 
3594
                       (None, None),
 
3595
                       (None, splitpath(current_root_unicode)[-1]),
 
3596
                       (None, root_dir_info[2]),
 
3597
                       (None, new_executable)
 
3598
                      )
 
3599
            initial_key = (current_root, '', '')
3975
3600
            block_index, _ = self.state._find_block_index_from_key(initial_key)
3976
3601
            if block_index == 0:
3977
3602
                # we have processed the total root already, but because the
3978
3603
                # initial key matched it we should skip it here.
3979
 
                block_index += 1
 
3604
                block_index +=1
3980
3605
            if root_dir_info and root_dir_info[2] == 'tree-reference':
3981
3606
                current_dir_info = None
3982
3607
            else:
3983
 
                dir_iterator = osutils._walkdirs_utf8(
3984
 
                    root_abspath, prefix=current_root)
 
3608
                dir_iterator = osutils._walkdirs_utf8(root_abspath, prefix=current_root)
3985
3609
                try:
3986
 
                    current_dir_info = next(dir_iterator)
3987
 
                except OSError as e:
 
3610
                    current_dir_info = dir_iterator.next()
 
3611
                except OSError, e:
3988
3612
                    # on win32, python2.4 has e.errno == ERROR_DIRECTORY, but
3989
3613
                    # python 2.5 has e.errno == EINVAL,
3990
3614
                    #            and e.winerror == ERROR_DIRECTORY
3996
3620
                    if e.errno in (errno.ENOENT, errno.ENOTDIR, errno.EINVAL):
3997
3621
                        current_dir_info = None
3998
3622
                    elif (sys.platform == 'win32'
3999
 
                          and (e.errno in win_errors or
4000
 
                               e_winerror in win_errors)):
 
3623
                          and (e.errno in win_errors
 
3624
                               or e_winerror in win_errors)):
4001
3625
                        current_dir_info = None
4002
3626
                    else:
4003
3627
                        raise
4004
3628
                else:
4005
 
                    if current_dir_info[0][0] == b'':
 
3629
                    if current_dir_info[0][0] == '':
4006
3630
                        # remove .bzr from iteration
4007
 
                        bzr_index = bisect.bisect_left(
4008
 
                            current_dir_info[1], (b'.bzr',))
4009
 
                        if current_dir_info[1][bzr_index][0] != b'.bzr':
 
3631
                        bzr_index = bisect.bisect_left(current_dir_info[1], ('.bzr',))
 
3632
                        if current_dir_info[1][bzr_index][0] != '.bzr':
4010
3633
                            raise AssertionError()
4011
3634
                        del current_dir_info[1][bzr_index]
4012
3635
            # walk until both the directory listing and the versioned metadata
4013
3636
            # are exhausted.
4014
3637
            if (block_index < len(self.state._dirblocks) and
4015
 
                osutils.is_inside(current_root,
4016
 
                                  self.state._dirblocks[block_index][0])):
 
3638
                osutils.is_inside(current_root, self.state._dirblocks[block_index][0])):
4017
3639
                current_block = self.state._dirblocks[block_index]
4018
3640
            else:
4019
3641
                current_block = None
4020
3642
            while (current_dir_info is not None or
4021
3643
                   current_block is not None):
4022
3644
                if (current_dir_info and current_block
4023
 
                        and current_dir_info[0][0] != current_block[0]):
4024
 
                    if _lt_by_dirs(current_dir_info[0][0], current_block[0]):
 
3645
                    and current_dir_info[0][0] != current_block[0]):
 
3646
                    if _cmp_by_dirs(current_dir_info[0][0], current_block[0]) < 0:
4025
3647
                        # filesystem data refers to paths not covered by the dirblock.
4026
3648
                        # this has two possibilities:
4027
3649
                        # A) it is versioned but empty, so there is no block for it
4033
3655
                        # recurse into unknown directories.
4034
3656
                        path_index = 0
4035
3657
                        while path_index < len(current_dir_info[1]):
4036
 
                            current_path_info = current_dir_info[1][path_index]
4037
 
                            if self.want_unversioned:
4038
 
                                if current_path_info[2] == 'directory':
4039
 
                                    if self.tree._directory_is_tree_reference(
 
3658
                                current_path_info = current_dir_info[1][path_index]
 
3659
                                if self.want_unversioned:
 
3660
                                    if current_path_info[2] == 'directory':
 
3661
                                        if self.tree._directory_is_tree_reference(
4040
3662
                                            current_path_info[0].decode('utf8')):
4041
 
                                        current_path_info = current_path_info[:2] + \
4042
 
                                            ('tree-reference',) + \
4043
 
                                            current_path_info[3:]
4044
 
                                new_executable = bool(
4045
 
                                    stat.S_ISREG(current_path_info[3].st_mode)
4046
 
                                    and stat.S_IEXEC & current_path_info[3].st_mode)
4047
 
                                yield TreeChange(
4048
 
                                    None,
4049
 
                                    (None, utf8_decode(current_path_info[0])[0]),
4050
 
                                    True,
4051
 
                                    (False, False),
4052
 
                                    (None, None),
4053
 
                                    (None, utf8_decode(current_path_info[1])[0]),
4054
 
                                    (None, current_path_info[2]),
4055
 
                                    (None, new_executable))
4056
 
                            # dont descend into this unversioned path if it is
4057
 
                            # a dir
4058
 
                            if current_path_info[2] in ('directory',
4059
 
                                                        'tree-reference'):
4060
 
                                del current_dir_info[1][path_index]
4061
 
                                path_index -= 1
4062
 
                            path_index += 1
 
3663
                                            current_path_info = current_path_info[:2] + \
 
3664
                                                ('tree-reference',) + current_path_info[3:]
 
3665
                                    new_executable = bool(
 
3666
                                        stat.S_ISREG(current_path_info[3].st_mode)
 
3667
                                        and stat.S_IEXEC & current_path_info[3].st_mode)
 
3668
                                    yield (None,
 
3669
                                        (None, utf8_decode(current_path_info[0])[0]),
 
3670
                                        True,
 
3671
                                        (False, False),
 
3672
                                        (None, None),
 
3673
                                        (None, utf8_decode(current_path_info[1])[0]),
 
3674
                                        (None, current_path_info[2]),
 
3675
                                        (None, new_executable))
 
3676
                                # dont descend into this unversioned path if it is
 
3677
                                # a dir
 
3678
                                if current_path_info[2] in ('directory',
 
3679
                                                            'tree-reference'):
 
3680
                                    del current_dir_info[1][path_index]
 
3681
                                    path_index -= 1
 
3682
                                path_index += 1
4063
3683
 
4064
3684
                        # This dir info has been handled, go to the next
4065
3685
                        try:
4066
 
                            current_dir_info = next(dir_iterator)
 
3686
                            current_dir_info = dir_iterator.next()
4067
3687
                        except StopIteration:
4068
3688
                            current_dir_info = None
4069
3689
                    else:
4077
3697
                        for current_entry in current_block[1]:
4078
3698
                            # entry referring to file not present on disk.
4079
3699
                            # advance the entry only, after processing.
4080
 
                            result, changed = _process_entry(
4081
 
                                current_entry, None)
 
3700
                            result, changed = _process_entry(current_entry, None)
4082
3701
                            if changed is not None:
4083
3702
                                if changed:
4084
3703
                                    self._gather_result_for_consistency(result)
4085
3704
                                if changed or self.include_unchanged:
4086
3705
                                    yield result
4087
 
                        block_index += 1
 
3706
                        block_index +=1
4088
3707
                        if (block_index < len(self.state._dirblocks) and
4089
3708
                            osutils.is_inside(current_root,
4090
3709
                                              self.state._dirblocks[block_index][0])):
4103
3722
                    current_path_info = current_dir_info[1][path_index]
4104
3723
                    if current_path_info[2] == 'directory':
4105
3724
                        if self.tree._directory_is_tree_reference(
4106
 
                                current_path_info[0].decode('utf8')):
 
3725
                            current_path_info[0].decode('utf8')):
4107
3726
                            current_path_info = current_path_info[:2] + \
4108
3727
                                ('tree-reference',) + current_path_info[3:]
4109
3728
                else:
4111
3730
                advance_path = True
4112
3731
                path_handled = False
4113
3732
                while (current_entry is not None or
4114
 
                       current_path_info is not None):
 
3733
                    current_path_info is not None):
4115
3734
                    if current_entry is None:
4116
3735
                        # the check for path_handled when the path is advanced
4117
3736
                        # will yield this path if needed.
4118
3737
                        pass
4119
3738
                    elif current_path_info is None:
4120
3739
                        # no path is fine: the per entry code will handle it.
4121
 
                        result, changed = _process_entry(
4122
 
                            current_entry, current_path_info)
 
3740
                        result, changed = _process_entry(current_entry, current_path_info)
4123
3741
                        if changed is not None:
4124
3742
                            if changed:
4125
3743
                                self._gather_result_for_consistency(result)
4126
3744
                            if changed or self.include_unchanged:
4127
3745
                                yield result
4128
3746
                    elif (current_entry[0][1] != current_path_info[1]
4129
 
                          or current_entry[1][self.target_index][0] in (b'a', b'r')):
 
3747
                          or current_entry[1][self.target_index][0] in 'ar'):
4130
3748
                        # The current path on disk doesn't match the dirblock
4131
3749
                        # record. Either the dirblock is marked as absent, or
4132
3750
                        # the file on disk is not present at all in the
4142
3760
                        else:
4143
3761
                            # entry referring to file not present on disk.
4144
3762
                            # advance the entry only, after processing.
4145
 
                            result, changed = _process_entry(
4146
 
                                current_entry, None)
 
3763
                            result, changed = _process_entry(current_entry, None)
4147
3764
                            if changed is not None:
4148
3765
                                if changed:
4149
3766
                                    self._gather_result_for_consistency(result)
4151
3768
                                    yield result
4152
3769
                            advance_path = False
4153
3770
                    else:
4154
 
                        result, changed = _process_entry(
4155
 
                            current_entry, current_path_info)
 
3771
                        result, changed = _process_entry(current_entry, current_path_info)
4156
3772
                        if changed is not None:
4157
3773
                            path_handled = True
4158
3774
                            if changed:
4166
3782
                        else:
4167
3783
                            current_entry = None
4168
3784
                    else:
4169
 
                        advance_entry = True  # reset the advance flaga
 
3785
                        advance_entry = True # reset the advance flaga
4170
3786
                    if advance_path and current_path_info is not None:
4171
3787
                        if not path_handled:
4172
3788
                            # unversioned in all regards
4175
3791
                                    stat.S_ISREG(current_path_info[3].st_mode)
4176
3792
                                    and stat.S_IEXEC & current_path_info[3].st_mode)
4177
3793
                                try:
4178
 
                                    relpath_unicode = utf8_decode(
4179
 
                                        current_path_info[0])[0]
 
3794
                                    relpath_unicode = utf8_decode(current_path_info[0])[0]
4180
3795
                                except UnicodeDecodeError:
4181
3796
                                    raise errors.BadFilenameEncoding(
4182
3797
                                        current_path_info[0], osutils._fs_enc)
4183
 
                                yield TreeChange(
4184
 
                                    None,
 
3798
                                yield (None,
4185
3799
                                    (None, relpath_unicode),
4186
3800
                                    True,
4187
3801
                                    (False, False),
4204
3818
                            current_path_info = current_dir_info[1][path_index]
4205
3819
                            if current_path_info[2] == 'directory':
4206
3820
                                if self.tree._directory_is_tree_reference(
4207
 
                                        current_path_info[0].decode('utf8')):
 
3821
                                    current_path_info[0].decode('utf8')):
4208
3822
                                    current_path_info = current_path_info[:2] + \
4209
 
                                        ('tree-reference',) + \
4210
 
                                        current_path_info[3:]
 
3823
                                        ('tree-reference',) + current_path_info[3:]
4211
3824
                        else:
4212
3825
                            current_path_info = None
4213
3826
                        path_handled = False
4214
3827
                    else:
4215
 
                        advance_path = True  # reset the advance flagg.
 
3828
                        advance_path = True # reset the advance flagg.
4216
3829
                if current_block is not None:
4217
3830
                    block_index += 1
4218
3831
                    if (block_index < len(self.state._dirblocks) and
4219
 
                        osutils.is_inside(current_root,
4220
 
                                          self.state._dirblocks[block_index][0])):
 
3832
                        osutils.is_inside(current_root, self.state._dirblocks[block_index][0])):
4221
3833
                        current_block = self.state._dirblocks[block_index]
4222
3834
                    else:
4223
3835
                        current_block = None
4224
3836
                if current_dir_info is not None:
4225
3837
                    try:
4226
 
                        current_dir_info = next(dir_iterator)
 
3838
                        current_dir_info = dir_iterator.next()
4227
3839
                    except StopIteration:
4228
3840
                        current_dir_info = None
4229
3841
        for result in self._iter_specific_file_parents():
4251
3863
            found_item = False
4252
3864
            for candidate_entry in path_entries:
4253
3865
                # Find entries present in target at this path:
4254
 
                if candidate_entry[1][self.target_index][0] not in (b'a', b'r'):
 
3866
                if candidate_entry[1][self.target_index][0] not in 'ar':
4255
3867
                    found_item = True
4256
3868
                    selected_entries.append(candidate_entry)
4257
3869
                # Find entries present in source at this path:
4258
3870
                elif (self.source_index is not None and
4259
 
                      candidate_entry[1][self.source_index][0] not in (b'a', b'r')):
 
3871
                    candidate_entry[1][self.source_index][0] not in 'ar'):
4260
3872
                    found_item = True
4261
 
                    if candidate_entry[1][self.target_index][0] == b'a':
 
3873
                    if candidate_entry[1][self.target_index][0] == 'a':
4262
3874
                        # Deleted, emit it here.
4263
3875
                        selected_entries.append(candidate_entry)
4264
3876
                    else:
4269
3881
            if not found_item:
4270
3882
                raise AssertionError(
4271
3883
                    "Missing entry for specific path parent %r, %r" % (
4272
 
                        path_utf8, path_entries))
 
3884
                    path_utf8, path_entries))
4273
3885
            path_info = self._path_info(path_utf8, path_utf8.decode('utf8'))
4274
3886
            for entry in selected_entries:
4275
3887
                if entry[0][2] in self.seen_ids:
4279
3891
                    raise AssertionError(
4280
3892
                        "Got entry<->path mismatch for specific path "
4281
3893
                        "%r entry %r path_info %r " % (
4282
 
                            path_utf8, entry, path_info))
 
3894
                        path_utf8, entry, path_info))
4283
3895
                # Only include changes - we're outside the users requested
4284
3896
                # expansion.
4285
3897
                if changed:
4286
3898
                    self._gather_result_for_consistency(result)
4287
 
                    if (result.kind[0] == 'directory' and
4288
 
                            result.kind[1] != 'directory'):
 
3899
                    if (result[6][0] == 'directory' and
 
3900
                        result[6][1] != 'directory'):
4289
3901
                        # This stopped being a directory, the old children have
4290
3902
                        # to be included.
4291
 
                        if entry[1][self.source_index][0] == b'r':
 
3903
                        if entry[1][self.source_index][0] == 'r':
4292
3904
                            # renamed, take the source path
4293
3905
                            entry_path_utf8 = entry[1][self.source_index][1]
4294
3906
                        else:
4295
3907
                            entry_path_utf8 = path_utf8
4296
 
                        initial_key = (entry_path_utf8, b'', b'')
 
3908
                        initial_key = (entry_path_utf8, '', '')
4297
3909
                        block_index, _ = self.state._find_block_index_from_key(
4298
3910
                            initial_key)
4299
3911
                        if block_index == 0:
4300
3912
                            # The children of the root are in block index 1.
4301
 
                            block_index += 1
 
3913
                            block_index +=1
4302
3914
                        current_block = None
4303
3915
                        if block_index < len(self.state._dirblocks):
4304
3916
                            current_block = self.state._dirblocks[block_index]
4305
3917
                            if not osutils.is_inside(
4306
 
                                    entry_path_utf8, current_block[0]):
 
3918
                                entry_path_utf8, current_block[0]):
4307
3919
                                # No entries for this directory at all.
4308
3920
                                current_block = None
4309
3921
                        if current_block is not None:
4310
3922
                            for entry in current_block[1]:
4311
 
                                if entry[1][self.source_index][0] in (b'a', b'r'):
 
3923
                                if entry[1][self.source_index][0] in 'ar':
4312
3924
                                    # Not in the source tree, so doesn't have to be
4313
3925
                                    # included.
4314
3926
                                    continue
4328
3940
        abspath = self.tree.abspath(unicode_path)
4329
3941
        try:
4330
3942
            stat = os.lstat(abspath)
4331
 
        except OSError as e:
 
3943
        except OSError, e:
4332
3944
            if e.errno == errno.ENOENT:
4333
3945
                # the path does not exist.
4334
3946
                return None
4335
3947
            else:
4336
3948
                raise
4337
 
        utf8_basename = utf8_path.rsplit(b'/', 1)[-1]
 
3949
        utf8_basename = utf8_path.rsplit('/', 1)[-1]
4338
3950
        dir_info = (utf8_path, utf8_basename,
4339
 
                    osutils.file_kind_from_stat_mode(stat.st_mode), stat,
4340
 
                    abspath)
 
3951
            osutils.file_kind_from_stat_mode(stat.st_mode), stat,
 
3952
            abspath)
4341
3953
        if dir_info[2] == 'directory':
4342
3954
            if self.tree._directory_is_tree_reference(
4343
 
                    unicode_path):
 
3955
                unicode_path):
4344
3956
                self.root_dir_info = self.root_dir_info[:2] + \
4345
3957
                    ('tree-reference',) + self.root_dir_info[3:]
4346
3958
        return dir_info
4348
3960
 
4349
3961
# Try to load the compiled form if possible
4350
3962
try:
4351
 
    from ._dirstate_helpers_pyx import (
 
3963
    from bzrlib._dirstate_helpers_pyx import (
4352
3964
        _read_dirblocks,
4353
3965
        bisect_dirblock,
4354
3966
        _bisect_path_left,
4355
3967
        _bisect_path_right,
4356
 
        lt_by_dirs,
4357
 
        pack_stat,
 
3968
        cmp_by_dirs,
4358
3969
        ProcessEntryC as _process_entry,
4359
3970
        update_entry as update_entry,
4360
3971
        )
4361
 
except ImportError as e:
4362
 
    osutils.failed_to_load_extension(e)
4363
 
    from ._dirstate_helpers_py import (
 
3972
except ImportError:
 
3973
    from bzrlib._dirstate_helpers_py import (
4364
3974
        _read_dirblocks,
4365
3975
        bisect_dirblock,
4366
3976
        _bisect_path_left,
4367
3977
        _bisect_path_right,
4368
 
        lt_by_dirs,
4369
 
        pack_stat,
 
3978
        cmp_by_dirs,
4370
3979
        )
4371
3980
    # FIXME: It would be nice to be able to track moved lines so that the
4372
3981
    # corresponding python code can be moved to the _dirstate_helpers_py