~bzr-pqm/bzr/bzr.dev

5361.3.4 by John Arbash Meinel
id_index size drops to 230kB with StaticTuples.
1
# Copyright (C) 2007-2010 Canonical Ltd
2474.1.1 by John Arbash Meinel
Create a Pyrex extension for reading the dirstate file.
2
#
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
7
#
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
12
#
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
2474.1.1 by John Arbash Meinel
Create a Pyrex extension for reading the dirstate file.
16
17
"""Helper functions for DirState.
18
19
This is the python implementation for DirState functions.
20
"""
21
3696.4.3 by Robert Collins
Some tuning of update_entry.
22
import binascii
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
23
import bisect
24
import errno
3696.4.8 by Robert Collins
Fix up inter_changes with dirstate both C and python.
25
import os
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
26
import stat
3763.1.1 by Benjamin Peterson
fix two small oversights
27
import sys
3696.4.3 by Robert Collins
Some tuning of update_entry.
28
3696.4.6 by Robert Collins
Fixes for the relocated code, and use _update_entry within the C accelerated code, another 8 percent saving.
29
from bzrlib import cache_utf8, errors, osutils
3696.4.17 by Robert Collins
Review feedback.
30
from bzrlib.dirstate import DirState
4570.2.3 by Robert Collins
Change the way iter_changes treats specific files to prevent InconsistentDeltas.
31
from bzrlib.osutils import parent_directories, pathjoin, splitpath
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
32
33
34
# This is the Windows equivalent of ENOTDIR
35
# It is defined in pywin32.winerror, but we don't want a strong dependency for
36
# just an error code.
37
# XXX: Perhaps we could get it from a windows header ?
38
cdef int ERROR_PATH_NOT_FOUND
39
ERROR_PATH_NOT_FOUND = 3
40
cdef int ERROR_DIRECTORY
41
ERROR_DIRECTORY = 267
2474.1.1 by John Arbash Meinel
Create a Pyrex extension for reading the dirstate file.
42
3737.1.3 by John Arbash Meinel
Move more compatibility code into python-compat.h
43
#python2.4 support, and other platform-dependent includes
3731.1.1 by Robert Collins
* The C extensions now build on python 2.4 (Robert Collins, #271939)
44
cdef extern from "python-compat.h":
3737.1.3 by John Arbash Meinel
Move more compatibility code into python-compat.h
45
    unsigned long htonl(unsigned long)
3731.1.1 by Robert Collins
* The C extensions now build on python 2.4 (Robert Collins, #271939)
46
2474.1.72 by John Arbash Meinel
Document a bit more what is going on in _dirstate_helpers_c.pyx, from Martin's comments
47
# Give Pyrex some function definitions for it to understand.
48
# All of these are just hints to Pyrex, so that it can try to convert python
49
# objects into similar C objects. (such as PyInt => int).
50
# In anything defined 'cdef extern from XXX' the real C header will be
51
# imported, and the real definition will be used from there. So these are just
52
# hints, and do not need to match exactly to the C definitions.
53
2474.1.13 by John Arbash Meinel
Now that we have bisect_dirblock working again, bring back cmp_dirblock_strings.
54
cdef extern from *:
2474.1.72 by John Arbash Meinel
Document a bit more what is going on in _dirstate_helpers_c.pyx, from Martin's comments
55
    ctypedef unsigned long size_t
2474.1.69 by John Arbash Meinel
Thanks to Jan 'RedBully' Seiffert, some review cleanups
56
4459.2.1 by Vincent Ladeuil
Use a consistent scheme for naming pyrex source files.
57
cdef extern from "_dirstate_helpers_pyx.h":
2474.1.69 by John Arbash Meinel
Thanks to Jan 'RedBully' Seiffert, some review cleanups
58
    ctypedef int intptr_t
2474.1.13 by John Arbash Meinel
Now that we have bisect_dirblock working again, bring back cmp_dirblock_strings.
59
2474.1.30 by John Arbash Meinel
Start working towards a parser which uses a Reader (producer)
60
3696.4.3 by Robert Collins
Some tuning of update_entry.
61
2474.1.30 by John Arbash Meinel
Start working towards a parser which uses a Reader (producer)
62
cdef extern from "stdlib.h":
63
    unsigned long int strtoul(char *nptr, char **endptr, int base)
64
3696.4.3 by Robert Collins
Some tuning of update_entry.
65
66
cdef extern from 'sys/stat.h':
67
    int S_ISDIR(int mode)
68
    int S_ISREG(int mode)
3737.1.3 by John Arbash Meinel
Move more compatibility code into python-compat.h
69
    # On win32, this actually comes from "python-compat.h"
3696.4.3 by Robert Collins
Some tuning of update_entry.
70
    int S_ISLNK(int mode)
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
71
    int S_IXUSR
2474.1.30 by John Arbash Meinel
Start working towards a parser which uses a Reader (producer)
72
2474.1.72 by John Arbash Meinel
Document a bit more what is going on in _dirstate_helpers_c.pyx, from Martin's comments
73
# These functions allow us access to a bit of the 'bare metal' of python
74
# objects, rather than going through the object abstraction. (For example,
75
# PyList_Append, rather than getting the 'append' attribute of the object, and
76
# creating a tuple, and then using PyCallObject).
77
# Functions that return (or take) a void* are meant to grab a C PyObject*. This
78
# differs from the Pyrex 'object'. If you declare a variable as 'object' Pyrex
79
# will automatically Py_INCREF and Py_DECREF when appropriate. But for some
80
# inner loops, we don't need to do that at all, as the reference only lasts for
81
# a very short time.
3696.4.12 by Robert Collins
More Cification of iter_changes, smaller functions, explicit type usage.
82
# Note that the C API GetItem calls borrow references, so pyrex does the wrong
83
# thing if you declare e.g. object PyList_GetItem(object lst, int index) - you
84
# need to manually Py_INCREF yourself.
2474.1.4 by John Arbash Meinel
Add benchmarks for dirstate.bisect_dirblocks, and implement bisect_dirblocks in pyrex.
85
cdef extern from "Python.h":
3640.2.6 by John Arbash Meinel
PQM's pyrex needs a Py_ssize_t typedef.
86
    ctypedef int Py_ssize_t
3696.4.3 by Robert Collins
Some tuning of update_entry.
87
    ctypedef struct PyObject:
88
        pass
2474.1.23 by John Arbash Meinel
A C implementation of _fields_to_entry_0_parents drops the time from 400ms to 330ms for a 21k-entry tree
89
    int PyList_Append(object lst, object item) except -1
2474.1.12 by John Arbash Meinel
Clean up bisect_dirstate to not use temporary variables.
90
    void *PyList_GetItem_object_void "PyList_GET_ITEM" (object lst, int index)
3696.4.3 by Robert Collins
Some tuning of update_entry.
91
    void *PyList_GetItem_void_void "PyList_GET_ITEM" (void * lst, int index)
3696.4.12 by Robert Collins
More Cification of iter_changes, smaller functions, explicit type usage.
92
    object PyList_GET_ITEM(object lst, Py_ssize_t index)
2474.1.10 by John Arbash Meinel
Explicitly calling Py_INCREF makes things happier again.
93
    int PyList_CheckExact(object)
3696.4.12 by Robert Collins
More Cification of iter_changes, smaller functions, explicit type usage.
94
    Py_ssize_t PyList_GET_SIZE (object p)
2474.1.23 by John Arbash Meinel
A C implementation of _fields_to_entry_0_parents drops the time from 400ms to 330ms for a 21k-entry tree
95
96
    void *PyTuple_GetItem_void_void "PyTuple_GET_ITEM" (void* tpl, int index)
3696.4.3 by Robert Collins
Some tuning of update_entry.
97
    object PyTuple_GetItem_void_object "PyTuple_GET_ITEM" (void* tpl, int index)
3696.4.12 by Robert Collins
More Cification of iter_changes, smaller functions, explicit type usage.
98
    object PyTuple_GET_ITEM(object tpl, Py_ssize_t index)
99
6015.37.5 by Martin Packman
Use PyInt_AsUnsignedLongMask to correctly downcast larger fields in pyrex _pack_stat
100
    unsigned long PyInt_AsUnsignedLongMask(object number) except? -1
2474.1.10 by John Arbash Meinel
Explicitly calling Py_INCREF makes things happier again.
101
2474.1.13 by John Arbash Meinel
Now that we have bisect_dirblock working again, bring back cmp_dirblock_strings.
102
    char *PyString_AsString(object p)
3696.4.3 by Robert Collins
Some tuning of update_entry.
103
    char *PyString_AsString_obj "PyString_AsString" (PyObject *string)
2474.1.16 by John Arbash Meinel
Shave off maybe 10% by using the PyString_* macros instead of functions.
104
    char *PyString_AS_STRING_void "PyString_AS_STRING" (void *p)
3696.4.12 by Robert Collins
More Cification of iter_changes, smaller functions, explicit type usage.
105
    int PyString_AsStringAndSize(object str, char **buffer, Py_ssize_t *length) except -1
2474.1.30 by John Arbash Meinel
Start working towards a parser which uses a Reader (producer)
106
    object PyString_FromString(char *)
3640.2.1 by John Arbash Meinel
More safety checks around PyString_FromStringAndSize,
107
    object PyString_FromStringAndSize(char *, Py_ssize_t)
2474.1.13 by John Arbash Meinel
Now that we have bisect_dirblock working again, bring back cmp_dirblock_strings.
108
    int PyString_Size(object p)
2474.1.16 by John Arbash Meinel
Shave off maybe 10% by using the PyString_* macros instead of functions.
109
    int PyString_GET_SIZE_void "PyString_GET_SIZE" (void *p)
2474.1.14 by John Arbash Meinel
Switching bisect_dirblocks remove the extra .split('/')
110
    int PyString_CheckExact(object p)
3696.4.3 by Robert Collins
Some tuning of update_entry.
111
    void Py_INCREF(object o)
112
    void Py_DECREF(object o)
2474.1.13 by John Arbash Meinel
Now that we have bisect_dirblock working again, bring back cmp_dirblock_strings.
113
2474.1.23 by John Arbash Meinel
A C implementation of _fields_to_entry_0_parents drops the time from 400ms to 330ms for a 21k-entry tree
114
2474.1.13 by John Arbash Meinel
Now that we have bisect_dirblock working again, bring back cmp_dirblock_strings.
115
cdef extern from "string.h":
2474.1.25 by John Arbash Meinel
Refactor into a helper function to make implementation clearer
116
    int strncmp(char *s1, char *s2, int len)
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
117
    void *memchr(void *s, int c, size_t len)
118
    int memcmp(void *b1, void *b2, size_t len)
119
    # ??? memrchr is a GNU extension :(
120
    # void *memrchr(void *s, int c, size_t len)
121
5361.3.4 by John Arbash Meinel
id_index size drops to 230kB with StaticTuples.
122
# cimport all of the definitions we will need to access
5361.3.6 by John Arbash Meinel
Doing the StaticTuple_New dance gets us to 3.37ms. not great.
123
from _static_tuple_c cimport import_static_tuple_c, StaticTuple, \
124
    StaticTuple_New, StaticTuple_SET_ITEM
5361.3.4 by John Arbash Meinel
id_index size drops to 230kB with StaticTuples.
125
126
import_static_tuple_c()
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
127
4634.117.10 by John Arbash Meinel
Change 'no except' to 'cannot_raise'
128
cdef void* _my_memrchr(void *s, int c, size_t n): # cannot_raise
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
129
    # memrchr seems to be a GNU extension, so we have to implement it ourselves
2474.1.69 by John Arbash Meinel
Thanks to Jan 'RedBully' Seiffert, some review cleanups
130
    cdef char *pos
131
    cdef char *start
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
132
2474.1.69 by John Arbash Meinel
Thanks to Jan 'RedBully' Seiffert, some review cleanups
133
    start = <char*>s
134
    pos = start + n - 1
135
    while pos >= start:
136
        if pos[0] == c:
137
            return <void*>pos
138
        pos = pos - 1
139
    return NULL
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
140
141
142
def _py_memrchr(s, c):
143
    """Just to expose _my_memrchr for testing.
144
145
    :param s: The Python string to search
146
    :param c: The character to search for
147
    :return: The offset to the last instance of 'c' in s
148
    """
149
    cdef void *_s
150
    cdef void *found
151
    cdef int length
152
    cdef char *_c
153
154
    _s = PyString_AsString(s)
155
    length = PyString_Size(s)
156
157
    _c = PyString_AsString(c)
158
    assert PyString_Size(c) == 1,\
159
        'Must be a single character string, not %s' % (c,)
160
    found = _my_memrchr(_s, _c[0], length)
161
    if found == NULL:
162
        return None
2668.1.1 by John Arbash Meinel
(Lukáš Lalinský) Add a special header for intptr_t for MSVC which doesn't have it in the standard place
163
    return <char*>found - <char*>_s
2474.1.4 by John Arbash Meinel
Add benchmarks for dirstate.bisect_dirblocks, and implement bisect_dirblocks in pyrex.
164
5037.1.1 by Martin Pool
Avoid showing pointer in safe_string_from_size; not helpful and gives compiler warning
165
3640.2.1 by John Arbash Meinel
More safety checks around PyString_FromStringAndSize,
166
cdef object safe_string_from_size(char *s, Py_ssize_t size):
167
    if size < 0:
168
        raise AssertionError(
5037.1.1 by Martin Pool
Avoid showing pointer in safe_string_from_size; not helpful and gives compiler warning
169
            'tried to create a string with an invalid size: %d'
170
            % (size))
3640.2.1 by John Arbash Meinel
More safety checks around PyString_FromStringAndSize,
171
    return PyString_FromStringAndSize(s, size)
172
2474.1.4 by John Arbash Meinel
Add benchmarks for dirstate.bisect_dirblocks, and implement bisect_dirblocks in pyrex.
173
4634.117.10 by John Arbash Meinel
Change 'no except' to 'cannot_raise'
174
cdef int _is_aligned(void *ptr): # cannot_raise
2474.1.69 by John Arbash Meinel
Thanks to Jan 'RedBully' Seiffert, some review cleanups
175
    """Is this pointer aligned to an integer size offset?
176
177
    :return: 1 if this pointer is aligned, 0 otherwise.
178
    """
179
    return ((<intptr_t>ptr) & ((sizeof(int))-1)) == 0
180
181
4634.117.10 by John Arbash Meinel
Change 'no except' to 'cannot_raise'
182
cdef int _cmp_by_dirs(char *path1, int size1, char *path2, int size2): # cannot_raise
2474.1.70 by John Arbash Meinel
Lot's of fixes from Martin's comments.
183
    cdef unsigned char *cur1
184
    cdef unsigned char *cur2
185
    cdef unsigned char *end1
186
    cdef unsigned char *end2
2474.1.18 by John Arbash Meinel
Add an integer-size comparison loop at the begining, and
187
    cdef int *cur_int1
188
    cdef int *cur_int2
189
    cdef int *end_int1
190
    cdef int *end_int2
2474.1.17 by John Arbash Meinel
Using a custom loop seems to be the same speed, but is probably
191
2474.1.70 by John Arbash Meinel
Lot's of fixes from Martin's comments.
192
    if path1 == path2 and size1 == size2:
2474.1.54 by John Arbash Meinel
Optimize the simple case that the strings are the same object.
193
        return 0
194
2474.1.70 by John Arbash Meinel
Lot's of fixes from Martin's comments.
195
    end1 = <unsigned char*>path1+size1
196
    end2 = <unsigned char*>path2+size2
2474.1.17 by John Arbash Meinel
Using a custom loop seems to be the same speed, but is probably
197
2474.1.18 by John Arbash Meinel
Add an integer-size comparison loop at the begining, and
198
    # Use 32-bit comparisons for the matching portion of the string.
199
    # Almost all CPU's are faster at loading and comparing 32-bit integers,
200
    # than they are at 8-bit integers.
2474.1.69 by John Arbash Meinel
Thanks to Jan 'RedBully' Seiffert, some review cleanups
201
    # 99% of the time, these will be aligned, but in case they aren't just skip
202
    # this loop
203
    if _is_aligned(path1) and _is_aligned(path2):
204
        cur_int1 = <int*>path1
205
        cur_int2 = <int*>path2
2474.1.70 by John Arbash Meinel
Lot's of fixes from Martin's comments.
206
        end_int1 = <int*>(path1 + size1 - (size1 % sizeof(int)))
207
        end_int2 = <int*>(path2 + size2 - (size2 % sizeof(int)))
2474.1.69 by John Arbash Meinel
Thanks to Jan 'RedBully' Seiffert, some review cleanups
208
209
        while cur_int1 < end_int1 and cur_int2 < end_int2:
210
            if cur_int1[0] != cur_int2[0]:
211
                break
212
            cur_int1 = cur_int1 + 1
213
            cur_int2 = cur_int2 + 1
214
2474.1.70 by John Arbash Meinel
Lot's of fixes from Martin's comments.
215
        cur1 = <unsigned char*>cur_int1
216
        cur2 = <unsigned char*>cur_int2
2474.1.69 by John Arbash Meinel
Thanks to Jan 'RedBully' Seiffert, some review cleanups
217
    else:
2474.1.70 by John Arbash Meinel
Lot's of fixes from Martin's comments.
218
        cur1 = <unsigned char*>path1
219
        cur2 = <unsigned char*>path2
2474.1.18 by John Arbash Meinel
Add an integer-size comparison loop at the begining, and
220
2474.1.17 by John Arbash Meinel
Using a custom loop seems to be the same speed, but is probably
221
    while cur1 < end1 and cur2 < end2:
222
        if cur1[0] == cur2[0]:
223
            # This character matches, just go to the next one
224
            cur1 = cur1 + 1
225
            cur2 = cur2 + 1
226
            continue
227
        # The current characters do not match
228
        if cur1[0] == c'/':
2474.1.19 by John Arbash Meinel
Clean up _cmp_dirblock_strings_alt to make it the default.
229
            return -1 # Reached the end of path1 segment first
2474.1.17 by John Arbash Meinel
Using a custom loop seems to be the same speed, but is probably
230
        elif cur2[0] == c'/':
2474.1.19 by John Arbash Meinel
Clean up _cmp_dirblock_strings_alt to make it the default.
231
            return 1 # Reached the end of path2 segment first
2474.1.17 by John Arbash Meinel
Using a custom loop seems to be the same speed, but is probably
232
        elif cur1[0] < cur2[0]:
233
            return -1
234
        else:
235
            return 1
2474.1.19 by John Arbash Meinel
Clean up _cmp_dirblock_strings_alt to make it the default.
236
237
    # We reached the end of at least one of the strings
2474.1.17 by John Arbash Meinel
Using a custom loop seems to be the same speed, but is probably
238
    if cur1 < end1:
2474.1.19 by John Arbash Meinel
Clean up _cmp_dirblock_strings_alt to make it the default.
239
        return 1 # Not at the end of cur1, must be at the end of cur2
2474.1.18 by John Arbash Meinel
Add an integer-size comparison loop at the begining, and
240
    if cur2 < end2:
2474.1.19 by John Arbash Meinel
Clean up _cmp_dirblock_strings_alt to make it the default.
241
        return -1 # At the end of cur1, but not at cur2
2474.1.17 by John Arbash Meinel
Using a custom loop seems to be the same speed, but is probably
242
    # We reached the end of both strings
243
    return 0
244
245
4459.2.2 by Vincent Ladeuil
Use the same method or function names for _dirstate_helpers in pyrex and
246
def cmp_by_dirs(path1, path2):
2474.1.41 by John Arbash Meinel
Change the name of cmp_dirblock_strings to cmp_by_dirs
247
    """Compare two paths directory by directory.
248
249
    This is equivalent to doing::
250
251
       cmp(path1.split('/'), path2.split('/'))
252
253
    The idea is that you should compare path components separately. This
254
    differs from plain ``cmp(path1, path2)`` for paths like ``'a-b'`` and
255
    ``a/b``. "a-b" comes after "a" but would come before "a/b" lexically.
256
257
    :param path1: first path
258
    :param path2: second path
2872.4.10 by Martin Pool
docstrings for cmp_ functions seem to be backwards
259
    :return: negative number if ``path1`` comes first,
2474.1.41 by John Arbash Meinel
Change the name of cmp_dirblock_strings to cmp_by_dirs
260
        0 if paths are equal,
2872.4.10 by Martin Pool
docstrings for cmp_ functions seem to be backwards
261
        and positive number if ``path2`` sorts first
2474.1.41 by John Arbash Meinel
Change the name of cmp_dirblock_strings to cmp_by_dirs
262
    """
2474.1.70 by John Arbash Meinel
Lot's of fixes from Martin's comments.
263
    if not PyString_CheckExact(path1):
264
        raise TypeError("'path1' must be a plain string, not %s: %r"
265
                        % (type(path1), path1))
266
    if not PyString_CheckExact(path2):
267
        raise TypeError("'path2' must be a plain string, not %s: %r"
268
                        % (type(path2), path2))
2474.1.41 by John Arbash Meinel
Change the name of cmp_dirblock_strings to cmp_by_dirs
269
    return _cmp_by_dirs(PyString_AsString(path1),
270
                        PyString_Size(path1),
271
                        PyString_AsString(path2),
272
                        PyString_Size(path2))
2474.1.13 by John Arbash Meinel
Now that we have bisect_dirblock working again, bring back cmp_dirblock_strings.
273
274
4459.2.2 by Vincent Ladeuil
Use the same method or function names for _dirstate_helpers in pyrex and
275
def _cmp_path_by_dirblock(path1, path2):
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
276
    """Compare two paths based on what directory they are in.
277
278
    This generates a sort order, such that all children of a directory are
279
    sorted together, and grandchildren are in the same order as the
280
    children appear. But all grandchildren come after all children.
281
2474.1.66 by John Arbash Meinel
Some restructuring.
282
    In other words, all entries in a directory are sorted together, and
283
    directorys are sorted in cmp_by_dirs order.
284
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
285
    :param path1: first path
286
    :param path2: the second path
2872.4.10 by Martin Pool
docstrings for cmp_ functions seem to be backwards
287
    :return: negative number if ``path1`` comes first,
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
288
        0 if paths are equal
2872.4.10 by Martin Pool
docstrings for cmp_ functions seem to be backwards
289
        and a positive number if ``path2`` sorts first
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
290
    """
2474.1.70 by John Arbash Meinel
Lot's of fixes from Martin's comments.
291
    if not PyString_CheckExact(path1):
292
        raise TypeError("'path1' must be a plain string, not %s: %r"
293
                        % (type(path1), path1))
294
    if not PyString_CheckExact(path2):
295
        raise TypeError("'path2' must be a plain string, not %s: %r"
296
                        % (type(path2), path2))
4459.2.4 by Vincent Ladeuil
Fixed as per John and Martin reviews.
297
    return _cmp_path_by_dirblock_intern(PyString_AsString(path1),
298
                                        PyString_Size(path1),
299
                                        PyString_AsString(path2),
300
                                        PyString_Size(path2))
301
302
303
cdef int _cmp_path_by_dirblock_intern(char *path1, int path1_len,
4634.117.10 by John Arbash Meinel
Change 'no except' to 'cannot_raise'
304
                                      char *path2, int path2_len): # cannot_raise
2474.1.70 by John Arbash Meinel
Lot's of fixes from Martin's comments.
305
    """Compare two paths by what directory they are in.
306
4459.2.2 by Vincent Ladeuil
Use the same method or function names for _dirstate_helpers in pyrex and
307
    see ``_cmp_path_by_dirblock`` for details.
2474.1.70 by John Arbash Meinel
Lot's of fixes from Martin's comments.
308
    """
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
309
    cdef char *dirname1
310
    cdef int dirname1_len
311
    cdef char *dirname2
312
    cdef int dirname2_len
313
    cdef char *basename1
314
    cdef int basename1_len
315
    cdef char *basename2
316
    cdef int basename2_len
317
    cdef int cur_len
318
    cdef int cmp_val
319
320
    if path1_len == 0 and path2_len == 0:
321
        return 0
322
2474.1.70 by John Arbash Meinel
Lot's of fixes from Martin's comments.
323
    if path1 == path2 and path1_len == path2_len:
324
        return 0
325
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
326
    if path1_len == 0:
327
        return -1
328
329
    if path2_len == 0:
330
        return 1
331
2474.1.59 by John Arbash Meinel
Make sure to set basename_len. With that patch, the tests pass.
332
    basename1 = <char*>_my_memrchr(path1, c'/', path1_len)
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
333
334
    if basename1 == NULL:
2474.1.59 by John Arbash Meinel
Make sure to set basename_len. With that patch, the tests pass.
335
        basename1 = path1
336
        basename1_len = path1_len
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
337
        dirname1 = ''
338
        dirname1_len = 0
339
    else:
2474.1.59 by John Arbash Meinel
Make sure to set basename_len. With that patch, the tests pass.
340
        dirname1 = path1
341
        dirname1_len = basename1 - path1
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
342
        basename1 = basename1 + 1
2474.1.59 by John Arbash Meinel
Make sure to set basename_len. With that patch, the tests pass.
343
        basename1_len = path1_len - dirname1_len - 1
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
344
2474.1.59 by John Arbash Meinel
Make sure to set basename_len. With that patch, the tests pass.
345
    basename2 = <char*>_my_memrchr(path2, c'/', path2_len)
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
346
347
    if basename2 == NULL:
2474.1.59 by John Arbash Meinel
Make sure to set basename_len. With that patch, the tests pass.
348
        basename2 = path2
349
        basename2_len = path2_len
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
350
        dirname2 = ''
351
        dirname2_len = 0
352
    else:
2474.1.59 by John Arbash Meinel
Make sure to set basename_len. With that patch, the tests pass.
353
        dirname2 = path2
354
        dirname2_len = basename2 - path2
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
355
        basename2 = basename2 + 1
2474.1.59 by John Arbash Meinel
Make sure to set basename_len. With that patch, the tests pass.
356
        basename2_len = path2_len - dirname2_len - 1
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
357
358
    cmp_val = _cmp_by_dirs(dirname1, dirname1_len,
359
                           dirname2, dirname2_len)
360
    if cmp_val != 0:
361
        return cmp_val
362
363
    cur_len = basename1_len
364
    if basename2_len < basename1_len:
365
        cur_len = basename2_len
366
367
    cmp_val = memcmp(basename1, basename2, cur_len)
368
    if cmp_val != 0:
369
        return cmp_val
370
    if basename1_len == basename2_len:
371
        return 0
372
    if basename1_len < basename2_len:
373
        return -1
374
    return 1
375
376
4459.2.2 by Vincent Ladeuil
Use the same method or function names for _dirstate_helpers in pyrex and
377
def _bisect_path_left(paths, path):
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
378
    """Return the index where to insert path into paths.
379
380
    This uses a path-wise comparison so we get::
381
        a
382
        a-b
383
        a=b
384
        a/b
385
    Rather than::
386
        a
387
        a-b
388
        a/b
389
        a=b
390
    :param paths: A list of paths to search through
391
    :param path: A single path to insert
392
    :return: An offset where 'path' can be inserted.
393
    :seealso: bisect.bisect_left
394
    """
395
    cdef int _lo
396
    cdef int _hi
397
    cdef int _mid
2474.1.70 by John Arbash Meinel
Lot's of fixes from Martin's comments.
398
    cdef char *path_cstr
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
399
    cdef int path_size
2474.1.70 by John Arbash Meinel
Lot's of fixes from Martin's comments.
400
    cdef char *cur_cstr
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
401
    cdef int cur_size
402
    cdef void *cur
403
404
    if not PyList_CheckExact(paths):
2474.1.70 by John Arbash Meinel
Lot's of fixes from Martin's comments.
405
        raise TypeError("you must pass a python list for 'paths' not: %s %r"
406
                        % (type(paths), paths))
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
407
    if not PyString_CheckExact(path):
2474.1.70 by John Arbash Meinel
Lot's of fixes from Martin's comments.
408
        raise TypeError("you must pass a string for 'path' not: %s %r"
409
                        % (type(path), path))
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
410
411
    _hi = len(paths)
412
    _lo = 0
413
2474.1.70 by John Arbash Meinel
Lot's of fixes from Martin's comments.
414
    path_cstr = PyString_AsString(path)
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
415
    path_size = PyString_Size(path)
416
417
    while _lo < _hi:
418
        _mid = (_lo + _hi) / 2
419
        cur = PyList_GetItem_object_void(paths, _mid)
2474.1.70 by John Arbash Meinel
Lot's of fixes from Martin's comments.
420
        cur_cstr = PyString_AS_STRING_void(cur)
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
421
        cur_size = PyString_GET_SIZE_void(cur)
4459.2.4 by Vincent Ladeuil
Fixed as per John and Martin reviews.
422
        if _cmp_path_by_dirblock_intern(cur_cstr, cur_size,
423
                                        path_cstr, path_size) < 0:
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
424
            _lo = _mid + 1
425
        else:
426
            _hi = _mid
427
    return _lo
428
429
4459.2.2 by Vincent Ladeuil
Use the same method or function names for _dirstate_helpers in pyrex and
430
def _bisect_path_right(paths, path):
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
431
    """Return the index where to insert path into paths.
432
433
    This uses a path-wise comparison so we get::
434
        a
435
        a-b
436
        a=b
437
        a/b
438
    Rather than::
439
        a
440
        a-b
441
        a/b
442
        a=b
443
    :param paths: A list of paths to search through
444
    :param path: A single path to insert
445
    :return: An offset where 'path' can be inserted.
446
    :seealso: bisect.bisect_right
447
    """
448
    cdef int _lo
449
    cdef int _hi
450
    cdef int _mid
2474.1.70 by John Arbash Meinel
Lot's of fixes from Martin's comments.
451
    cdef char *path_cstr
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
452
    cdef int path_size
2474.1.70 by John Arbash Meinel
Lot's of fixes from Martin's comments.
453
    cdef char *cur_cstr
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
454
    cdef int cur_size
455
    cdef void *cur
456
457
    if not PyList_CheckExact(paths):
2474.1.70 by John Arbash Meinel
Lot's of fixes from Martin's comments.
458
        raise TypeError("you must pass a python list for 'paths' not: %s %r"
459
                        % (type(paths), paths))
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
460
    if not PyString_CheckExact(path):
2474.1.70 by John Arbash Meinel
Lot's of fixes from Martin's comments.
461
        raise TypeError("you must pass a string for 'path' not: %s %r"
462
                        % (type(path), path))
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
463
464
    _hi = len(paths)
465
    _lo = 0
466
2474.1.70 by John Arbash Meinel
Lot's of fixes from Martin's comments.
467
    path_cstr = PyString_AsString(path)
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
468
    path_size = PyString_Size(path)
469
470
    while _lo < _hi:
471
        _mid = (_lo + _hi) / 2
472
        cur = PyList_GetItem_object_void(paths, _mid)
2474.1.70 by John Arbash Meinel
Lot's of fixes from Martin's comments.
473
        cur_cstr = PyString_AS_STRING_void(cur)
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
474
        cur_size = PyString_GET_SIZE_void(cur)
4459.2.4 by Vincent Ladeuil
Fixed as per John and Martin reviews.
475
        if _cmp_path_by_dirblock_intern(path_cstr, path_size,
476
                                        cur_cstr, cur_size) < 0:
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
477
            _hi = _mid
478
        else:
479
            _lo = _mid + 1
480
    return _lo
481
482
4459.2.2 by Vincent Ladeuil
Use the same method or function names for _dirstate_helpers in pyrex and
483
def bisect_dirblock(dirblocks, dirname, lo=0, hi=None, cache=None):
2474.1.4 by John Arbash Meinel
Add benchmarks for dirstate.bisect_dirblocks, and implement bisect_dirblocks in pyrex.
484
    """Return the index where to insert dirname into the dirblocks.
485
486
    The return value idx is such that all directories blocks in dirblock[:idx]
487
    have names < dirname, and all blocks in dirblock[idx:] have names >=
488
    dirname.
489
490
    Optional args lo (default 0) and hi (default len(dirblocks)) bound the
491
    slice of a to be searched.
492
    """
493
    cdef int _lo
494
    cdef int _hi
495
    cdef int _mid
2474.1.70 by John Arbash Meinel
Lot's of fixes from Martin's comments.
496
    cdef char *dirname_cstr
2474.1.14 by John Arbash Meinel
Switching bisect_dirblocks remove the extra .split('/')
497
    cdef int dirname_size
2474.1.70 by John Arbash Meinel
Lot's of fixes from Martin's comments.
498
    cdef char *cur_cstr
2474.1.14 by John Arbash Meinel
Switching bisect_dirblocks remove the extra .split('/')
499
    cdef int cur_size
2474.1.12 by John Arbash Meinel
Clean up bisect_dirstate to not use temporary variables.
500
    cdef void *cur
2474.1.4 by John Arbash Meinel
Add benchmarks for dirstate.bisect_dirblocks, and implement bisect_dirblocks in pyrex.
501
2474.1.70 by John Arbash Meinel
Lot's of fixes from Martin's comments.
502
    if not PyList_CheckExact(dirblocks):
503
        raise TypeError("you must pass a python list for 'dirblocks' not: %s %r"
504
                        % (type(dirblocks), dirblocks))
505
    if not PyString_CheckExact(dirname):
506
        raise TypeError("you must pass a string for dirname not: %s %r"
507
                        % (type(dirname), dirname))
2474.1.4 by John Arbash Meinel
Add benchmarks for dirstate.bisect_dirblocks, and implement bisect_dirblocks in pyrex.
508
    if hi is None:
509
        _hi = len(dirblocks)
510
    else:
511
        _hi = hi
512
513
    _lo = lo
2474.1.70 by John Arbash Meinel
Lot's of fixes from Martin's comments.
514
    dirname_cstr = PyString_AsString(dirname)
2474.1.14 by John Arbash Meinel
Switching bisect_dirblocks remove the extra .split('/')
515
    dirname_size = PyString_Size(dirname)
516
2474.1.4 by John Arbash Meinel
Add benchmarks for dirstate.bisect_dirblocks, and implement bisect_dirblocks in pyrex.
517
    while _lo < _hi:
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
518
        _mid = (_lo + _hi) / 2
2474.1.4 by John Arbash Meinel
Add benchmarks for dirstate.bisect_dirblocks, and implement bisect_dirblocks in pyrex.
519
        # Grab the dirname for the current dirblock
2474.1.12 by John Arbash Meinel
Clean up bisect_dirstate to not use temporary variables.
520
        # cur = dirblocks[_mid][0]
521
        cur = PyTuple_GetItem_void_void(
522
                PyList_GetItem_object_void(dirblocks, _mid), 0)
2474.1.70 by John Arbash Meinel
Lot's of fixes from Martin's comments.
523
        cur_cstr = PyString_AS_STRING_void(cur)
2474.1.16 by John Arbash Meinel
Shave off maybe 10% by using the PyString_* macros instead of functions.
524
        cur_size = PyString_GET_SIZE_void(cur)
2474.1.70 by John Arbash Meinel
Lot's of fixes from Martin's comments.
525
        if _cmp_by_dirs(cur_cstr, cur_size, dirname_cstr, dirname_size) < 0:
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
526
            _lo = _mid + 1
2474.1.14 by John Arbash Meinel
Switching bisect_dirblocks remove the extra .split('/')
527
        else:
528
            _hi = _mid
2474.1.4 by John Arbash Meinel
Add benchmarks for dirstate.bisect_dirblocks, and implement bisect_dirblocks in pyrex.
529
    return _lo
530
531
2474.1.30 by John Arbash Meinel
Start working towards a parser which uses a Reader (producer)
532
cdef class Reader:
533
    """Maintain the current location, and return fields as you parse them."""
534
3640.2.5 by John Arbash Meinel
Change from using AssertionError to using DirstateCorrupt in a few places
535
    cdef object state # The DirState object
2474.1.30 by John Arbash Meinel
Start working towards a parser which uses a Reader (producer)
536
    cdef object text # The overall string object
2474.1.70 by John Arbash Meinel
Lot's of fixes from Martin's comments.
537
    cdef char *text_cstr # Pointer to the beginning of text
2474.1.30 by John Arbash Meinel
Start working towards a parser which uses a Reader (producer)
538
    cdef int text_size # Length of text
539
2474.1.70 by John Arbash Meinel
Lot's of fixes from Martin's comments.
540
    cdef char *end_cstr # End of text
541
    cdef char *cur_cstr # Pointer to the current record
2474.1.30 by John Arbash Meinel
Start working towards a parser which uses a Reader (producer)
542
    cdef char *next # Pointer to the end of this record
543
3640.2.5 by John Arbash Meinel
Change from using AssertionError to using DirstateCorrupt in a few places
544
    def __init__(self, text, state):
545
        self.state = state
2474.1.30 by John Arbash Meinel
Start working towards a parser which uses a Reader (producer)
546
        self.text = text
2474.1.70 by John Arbash Meinel
Lot's of fixes from Martin's comments.
547
        self.text_cstr = PyString_AsString(text)
2474.1.30 by John Arbash Meinel
Start working towards a parser which uses a Reader (producer)
548
        self.text_size = PyString_Size(text)
2474.1.70 by John Arbash Meinel
Lot's of fixes from Martin's comments.
549
        self.end_cstr = self.text_cstr + self.text_size
550
        self.cur_cstr = self.text_cstr
2474.1.30 by John Arbash Meinel
Start working towards a parser which uses a Reader (producer)
551
3640.2.1 by John Arbash Meinel
More safety checks around PyString_FromStringAndSize,
552
    cdef char *get_next(self, int *size) except NULL:
2474.1.30 by John Arbash Meinel
Start working towards a parser which uses a Reader (producer)
553
        """Return a pointer to the start of the next field."""
554
        cdef char *next
3640.2.1 by John Arbash Meinel
More safety checks around PyString_FromStringAndSize,
555
        cdef Py_ssize_t extra_len
556
557
        if self.cur_cstr == NULL:
558
            raise AssertionError('get_next() called when cur_str is NULL')
559
        elif self.cur_cstr >= self.end_cstr:
560
            raise AssertionError('get_next() called when there are no chars'
561
                                 ' left')
2474.1.70 by John Arbash Meinel
Lot's of fixes from Martin's comments.
562
        next = self.cur_cstr
3640.2.1 by John Arbash Meinel
More safety checks around PyString_FromStringAndSize,
563
        self.cur_cstr = <char*>memchr(next, c'\0', self.end_cstr - next)
564
        if self.cur_cstr == NULL:
565
            extra_len = self.end_cstr - next
3640.2.5 by John Arbash Meinel
Change from using AssertionError to using DirstateCorrupt in a few places
566
            raise errors.DirstateCorrupt(self.state,
567
                'failed to find trailing NULL (\\0).'
3640.2.1 by John Arbash Meinel
More safety checks around PyString_FromStringAndSize,
568
                ' Trailing garbage: %r'
569
                % safe_string_from_size(next, extra_len))
2474.1.70 by John Arbash Meinel
Lot's of fixes from Martin's comments.
570
        size[0] = self.cur_cstr - next
571
        self.cur_cstr = self.cur_cstr + 1
2474.1.30 by John Arbash Meinel
Start working towards a parser which uses a Reader (producer)
572
        return next
573
2474.1.53 by John Arbash Meinel
Changing Reader.get_next_str (which returns a Python String)
574
    cdef object get_next_str(self):
2474.1.30 by John Arbash Meinel
Start working towards a parser which uses a Reader (producer)
575
        """Get the next field as a Python string."""
2474.1.37 by John Arbash Meinel
get_next() returns the length of the string,
576
        cdef int size
577
        cdef char *next
578
        next = self.get_next(&size)
3640.2.1 by John Arbash Meinel
More safety checks around PyString_FromStringAndSize,
579
        return safe_string_from_size(next, size)
2474.1.30 by John Arbash Meinel
Start working towards a parser which uses a Reader (producer)
580
2474.1.70 by John Arbash Meinel
Lot's of fixes from Martin's comments.
581
    cdef int _init(self) except -1:
582
        """Get the pointer ready.
583
584
        This assumes that the dirstate header has already been read, and we
585
        already have the dirblock string loaded into memory.
586
        This just initializes our memory pointers, etc for parsing of the
587
        dirblock string.
588
        """
2474.1.32 by John Arbash Meinel
Skip past the first entry while reading,
589
        cdef char *first
2474.1.37 by John Arbash Meinel
get_next() returns the length of the string,
590
        cdef int size
2474.1.32 by John Arbash Meinel
Skip past the first entry while reading,
591
        # The first field should be an empty string left over from the Header
2474.1.37 by John Arbash Meinel
get_next() returns the length of the string,
592
        first = self.get_next(&size)
593
        if first[0] != c'\0' and size == 0:
2474.1.32 by John Arbash Meinel
Skip past the first entry while reading,
594
            raise AssertionError('First character should be null not: %s'
595
                                 % (first,))
2474.1.70 by John Arbash Meinel
Lot's of fixes from Martin's comments.
596
        return 0
2474.1.30 by John Arbash Meinel
Start working towards a parser which uses a Reader (producer)
597
2474.1.46 by John Arbash Meinel
Finish implementing _c_read_dirblocks for any number of parents.
598
    cdef object _get_entry(self, int num_trees, void **p_current_dirname,
599
                           int *new_block):
2474.1.70 by John Arbash Meinel
Lot's of fixes from Martin's comments.
600
        """Extract the next entry.
601
602
        This parses the next entry based on the current location in
603
        ``self.cur_cstr``.
604
        Each entry can be considered a "row" in the total table. And each row
605
        has a fixed number of columns. It is generally broken up into "key"
606
        columns, then "current" columns, and then "parent" columns.
607
608
        :param num_trees: How many parent trees need to be parsed
609
        :param p_current_dirname: A pointer to the current PyString
610
            representing the directory name.
611
            We pass this in as a void * so that pyrex doesn't have to
612
            increment/decrement the PyObject reference counter for each
613
            _get_entry call.
614
            We use a pointer so that _get_entry can update it with the new
615
            value.
616
        :param new_block: This is to let the caller know that it needs to
617
            create a new directory block to store the next entry.
618
        """
5361.3.6 by John Arbash Meinel
Doing the StaticTuple_New dance gets us to 3.37ms. not great.
619
        cdef StaticTuple path_name_file_id_key
620
        cdef StaticTuple tmp
2474.1.70 by John Arbash Meinel
Lot's of fixes from Martin's comments.
621
        cdef char *entry_size_cstr
2474.1.38 by John Arbash Meinel
Finally, faster than text.split() (156ms)
622
        cdef unsigned long int entry_size
2474.1.70 by John Arbash Meinel
Lot's of fixes from Martin's comments.
623
        cdef char* executable_cstr
2474.1.36 by John Arbash Meinel
Move functions into member functions on reader() class.
624
        cdef int is_executable
2474.1.70 by John Arbash Meinel
Lot's of fixes from Martin's comments.
625
        cdef char* dirname_cstr
2474.1.38 by John Arbash Meinel
Finally, faster than text.split() (156ms)
626
        cdef char* trailing
627
        cdef int cur_size
2474.1.46 by John Arbash Meinel
Finish implementing _c_read_dirblocks for any number of parents.
628
        cdef int i
2474.1.38 by John Arbash Meinel
Finally, faster than text.split() (156ms)
629
        cdef object minikind
630
        cdef object fingerprint
631
        cdef object info
632
2474.1.70 by John Arbash Meinel
Lot's of fixes from Martin's comments.
633
        # Read the 'key' information (dirname, name, file_id)
634
        dirname_cstr = self.get_next(&cur_size)
635
        # Check to see if we have started a new directory block.
636
        # If so, then we need to create a new dirname PyString, so that it can
637
        # be used in all of the tuples. This saves time and memory, by re-using
638
        # the same object repeatedly.
639
640
        # Do the cheap 'length of string' check first. If the string is a
641
        # different length, then we *have* to be a different directory.
642
        if (cur_size != PyString_GET_SIZE_void(p_current_dirname[0])
643
            or strncmp(dirname_cstr,
644
                       # Extract the char* from our current dirname string.  We
645
                       # know it is a PyString, so we can use
646
                       # PyString_AS_STRING, we use the _void version because
647
                       # we are tricking Pyrex by using a void* rather than an
648
                       # <object>
649
                       PyString_AS_STRING_void(p_current_dirname[0]),
650
                       cur_size+1) != 0):
3640.2.1 by John Arbash Meinel
More safety checks around PyString_FromStringAndSize,
651
            dirname = safe_string_from_size(dirname_cstr, cur_size)
2474.1.38 by John Arbash Meinel
Finally, faster than text.split() (156ms)
652
            p_current_dirname[0] = <void*>dirname
2474.1.36 by John Arbash Meinel
Move functions into member functions on reader() class.
653
            new_block[0] = 1
654
        else:
655
            new_block[0] = 0
2474.1.70 by John Arbash Meinel
Lot's of fixes from Martin's comments.
656
657
        # Build up the key that will be used.
658
        # By using <object>(void *) Pyrex will automatically handle the
659
        # Py_INCREF that we need.
5361.3.6 by John Arbash Meinel
Doing the StaticTuple_New dance gets us to 3.37ms. not great.
660
        cur_dirname = <object>p_current_dirname[0]
5361.3.8 by John Arbash Meinel
Per Vincent's request, clean up the code comments.
661
        # Use StaticTuple_New to pre-allocate, rather than creating a regular
662
        # tuple and passing it to the StaticTuple constructor.
663
        # path_name_file_id_key = StaticTuple(<object>p_current_dirname[0],
664
        #                          self.get_next_str(),
665
        #                          self.get_next_str(),
666
        #                         )
5361.3.6 by John Arbash Meinel
Doing the StaticTuple_New dance gets us to 3.37ms. not great.
667
        tmp = StaticTuple_New(3)
668
        Py_INCREF(cur_dirname); StaticTuple_SET_ITEM(tmp, 0, cur_dirname)
5361.3.8 by John Arbash Meinel
Per Vincent's request, clean up the code comments.
669
        cur_basename = self.get_next_str()
670
        cur_file_id = self.get_next_str()
671
        Py_INCREF(cur_basename); StaticTuple_SET_ITEM(tmp, 1, cur_basename)
672
        Py_INCREF(cur_file_id); StaticTuple_SET_ITEM(tmp, 2, cur_file_id)
5361.3.6 by John Arbash Meinel
Doing the StaticTuple_New dance gets us to 3.37ms. not great.
673
        path_name_file_id_key = tmp
2474.1.36 by John Arbash Meinel
Move functions into member functions on reader() class.
674
2474.1.70 by John Arbash Meinel
Lot's of fixes from Martin's comments.
675
        # Parse all of the per-tree information. current has the information in
676
        # the same location as parent trees. The only difference is that 'info'
677
        # is a 'packed_stat' for current, while it is a 'revision_id' for
678
        # parent trees.
679
        # minikind, fingerprint, and info will be returned as regular python
680
        # strings
681
        # entry_size and is_executable will be parsed into a python Long and
682
        # python Boolean, respectively.
683
        # TODO: jam 20070718 Consider changin the entry_size conversion to
684
        #       prefer python Int when possible. They are generally faster to
685
        #       work with, and it will be rare that we have a file >2GB.
686
        #       Especially since this code is pretty much fixed at a max of
687
        #       4GB.
2474.1.46 by John Arbash Meinel
Finish implementing _c_read_dirblocks for any number of parents.
688
        trees = []
689
        for i from 0 <= i < num_trees:
690
            minikind = self.get_next_str()
691
            fingerprint = self.get_next_str()
2474.1.70 by John Arbash Meinel
Lot's of fixes from Martin's comments.
692
            entry_size_cstr = self.get_next(&cur_size)
693
            entry_size = strtoul(entry_size_cstr, NULL, 10)
694
            executable_cstr = self.get_next(&cur_size)
695
            is_executable = (executable_cstr[0] == c'y')
2474.1.46 by John Arbash Meinel
Finish implementing _c_read_dirblocks for any number of parents.
696
            info = self.get_next_str()
5361.3.8 by John Arbash Meinel
Per Vincent's request, clean up the code comments.
697
            # TODO: If we want to use StaticTuple_New here we need to be pretty
698
            #       careful. We are relying on a bit of Pyrex
699
            #       automatic-conversion from 'int' to PyInt, and that doesn't
700
            #       play well with the StaticTuple_SET_ITEM macro.
701
            #       Timing doesn't (yet) show a worthwile improvement in speed
702
            #       versus complexity and maintainability.
5361.3.6 by John Arbash Meinel
Doing the StaticTuple_New dance gets us to 3.37ms. not great.
703
            # tmp = StaticTuple_New(5)
704
            # Py_INCREF(minikind); StaticTuple_SET_ITEM(tmp, 0, minikind)
705
            # Py_INCREF(fingerprint); StaticTuple_SET_ITEM(tmp, 1, fingerprint)
706
            # Py_INCREF(entry_size); StaticTuple_SET_ITEM(tmp, 2, entry_size)
707
            # Py_INCREF(is_executable); StaticTuple_SET_ITEM(tmp, 3, is_executable)
708
            # Py_INCREF(info); StaticTuple_SET_ITEM(tmp, 4, info)
709
            # PyList_Append(trees, tmp)
5361.3.4 by John Arbash Meinel
id_index size drops to 230kB with StaticTuples.
710
            PyList_Append(trees, StaticTuple(
2474.1.38 by John Arbash Meinel
Finally, faster than text.split() (156ms)
711
                minikind,     # minikind
712
                fingerprint,  # fingerprint
713
                entry_size,   # size
714
                is_executable,# executable
715
                info,         # packed_stat or revision_id
2474.1.46 by John Arbash Meinel
Finish implementing _c_read_dirblocks for any number of parents.
716
            ))
2474.1.36 by John Arbash Meinel
Move functions into member functions on reader() class.
717
2474.1.70 by John Arbash Meinel
Lot's of fixes from Martin's comments.
718
        # The returned tuple is (key, [trees])
2474.1.46 by John Arbash Meinel
Finish implementing _c_read_dirblocks for any number of parents.
719
        ret = (path_name_file_id_key, trees)
2474.1.70 by John Arbash Meinel
Lot's of fixes from Martin's comments.
720
        # Ignore the trailing newline, but assert that it does exist, this
721
        # ensures that we always finish parsing a line on an end-of-entry
722
        # marker.
2474.1.38 by John Arbash Meinel
Finally, faster than text.split() (156ms)
723
        trailing = self.get_next(&cur_size)
724
        if cur_size != 1 or trailing[0] != c'\n':
3640.2.5 by John Arbash Meinel
Change from using AssertionError to using DirstateCorrupt in a few places
725
            raise errors.DirstateCorrupt(self.state,
2474.1.38 by John Arbash Meinel
Finally, faster than text.split() (156ms)
726
                'Bad parse, we expected to end on \\n, not: %d %s: %s'
3640.2.1 by John Arbash Meinel
More safety checks around PyString_FromStringAndSize,
727
                % (cur_size, safe_string_from_size(trailing, cur_size),
2474.1.70 by John Arbash Meinel
Lot's of fixes from Martin's comments.
728
                   ret))
2474.1.38 by John Arbash Meinel
Finally, faster than text.split() (156ms)
729
        return ret
2474.1.36 by John Arbash Meinel
Move functions into member functions on reader() class.
730
3640.2.5 by John Arbash Meinel
Change from using AssertionError to using DirstateCorrupt in a few places
731
    def _parse_dirblocks(self):
2474.1.46 by John Arbash Meinel
Finish implementing _c_read_dirblocks for any number of parents.
732
        """Parse all dirblocks in the state file."""
733
        cdef int num_trees
2474.1.36 by John Arbash Meinel
Move functions into member functions on reader() class.
734
        cdef object current_block
735
        cdef object entry
736
        cdef void * current_dirname
737
        cdef int new_block
2474.1.46 by John Arbash Meinel
Finish implementing _c_read_dirblocks for any number of parents.
738
        cdef int expected_entry_count
739
        cdef int entry_count
740
3640.2.5 by John Arbash Meinel
Change from using AssertionError to using DirstateCorrupt in a few places
741
        num_trees = self.state._num_present_parents() + 1
742
        expected_entry_count = self.state._num_entries
2474.1.36 by John Arbash Meinel
Move functions into member functions on reader() class.
743
744
        # Ignore the first record
2474.1.70 by John Arbash Meinel
Lot's of fixes from Martin's comments.
745
        self._init()
2474.1.36 by John Arbash Meinel
Move functions into member functions on reader() class.
746
2474.1.37 by John Arbash Meinel
get_next() returns the length of the string,
747
        current_block = []
3640.2.5 by John Arbash Meinel
Change from using AssertionError to using DirstateCorrupt in a few places
748
        dirblocks = [('', current_block), ('', [])]
749
        self.state._dirblocks = dirblocks
2474.1.36 by John Arbash Meinel
Move functions into member functions on reader() class.
750
        obj = ''
2474.1.37 by John Arbash Meinel
get_next() returns the length of the string,
751
        current_dirname = <void*>obj
2474.1.36 by John Arbash Meinel
Move functions into member functions on reader() class.
752
        new_block = 0
2474.1.46 by John Arbash Meinel
Finish implementing _c_read_dirblocks for any number of parents.
753
        entry_count = 0
2474.1.36 by John Arbash Meinel
Move functions into member functions on reader() class.
754
2474.1.54 by John Arbash Meinel
Optimize the simple case that the strings are the same object.
755
        # TODO: jam 2007-05-07 Consider pre-allocating some space for the
756
        #       members, and then growing and shrinking from there. If most
757
        #       directories have close to 10 entries in them, it would save a
758
        #       few mallocs if we default our list size to something
759
        #       reasonable. Or we could malloc it to something large (100 or
760
        #       so), and then truncate. That would give us a malloc + realloc,
761
        #       rather than lots of reallocs.
2474.1.70 by John Arbash Meinel
Lot's of fixes from Martin's comments.
762
        while self.cur_cstr < self.end_cstr:
2474.1.46 by John Arbash Meinel
Finish implementing _c_read_dirblocks for any number of parents.
763
            entry = self._get_entry(num_trees, &current_dirname, &new_block)
2474.1.36 by John Arbash Meinel
Move functions into member functions on reader() class.
764
            if new_block:
765
                # new block - different dirname
766
                current_block = []
3640.2.5 by John Arbash Meinel
Change from using AssertionError to using DirstateCorrupt in a few places
767
                PyList_Append(dirblocks,
2474.1.36 by John Arbash Meinel
Move functions into member functions on reader() class.
768
                              (<object>current_dirname, current_block))
769
            PyList_Append(current_block, entry)
2474.1.46 by John Arbash Meinel
Finish implementing _c_read_dirblocks for any number of parents.
770
            entry_count = entry_count + 1
771
        if entry_count != expected_entry_count:
3640.2.5 by John Arbash Meinel
Change from using AssertionError to using DirstateCorrupt in a few places
772
            raise errors.DirstateCorrupt(self.state,
773
                    'We read the wrong number of entries.'
2474.1.46 by John Arbash Meinel
Finish implementing _c_read_dirblocks for any number of parents.
774
                    ' We expected to read %s, but read %s'
775
                    % (expected_entry_count, entry_count))
3640.2.5 by John Arbash Meinel
Change from using AssertionError to using DirstateCorrupt in a few places
776
        self.state._split_root_dirblock_into_contents()
2474.1.36 by John Arbash Meinel
Move functions into member functions on reader() class.
777
2474.1.30 by John Arbash Meinel
Start working towards a parser which uses a Reader (producer)
778
4459.2.2 by Vincent Ladeuil
Use the same method or function names for _dirstate_helpers in pyrex and
779
def _read_dirblocks(state):
2474.1.1 by John Arbash Meinel
Create a Pyrex extension for reading the dirstate file.
780
    """Read in the dirblocks for the given DirState object.
781
782
    This is tightly bound to the DirState internal representation. It should be
783
    thought of as a member function, which is only separated out so that we can
784
    re-write it in pyrex.
785
786
    :param state: A DirState object.
787
    :return: None
2474.1.70 by John Arbash Meinel
Lot's of fixes from Martin's comments.
788
    :postcondition: The dirblocks will be loaded into the appropriate fields in
789
        the DirState object.
2474.1.1 by John Arbash Meinel
Create a Pyrex extension for reading the dirstate file.
790
    """
791
    state._state_file.seek(state._end_of_header)
792
    text = state._state_file.read()
793
    # TODO: check the crc checksums. crc_measured = zlib.crc32(text)
794
3640.2.5 by John Arbash Meinel
Change from using AssertionError to using DirstateCorrupt in a few places
795
    reader = Reader(text, state)
2474.1.30 by John Arbash Meinel
Start working towards a parser which uses a Reader (producer)
796
3640.2.5 by John Arbash Meinel
Change from using AssertionError to using DirstateCorrupt in a few places
797
    reader._parse_dirblocks()
2474.1.1 by John Arbash Meinel
Create a Pyrex extension for reading the dirstate file.
798
    state._dirblock_state = DirState.IN_MEMORY_UNMODIFIED
3696.4.1 by Robert Collins
Refactor to allow a pluggable dirstate update_entry with interface tests.
799
800
4634.117.10 by John Arbash Meinel
Change 'no except' to 'cannot_raise'
801
cdef int minikind_from_mode(int mode): # cannot_raise
3696.4.3 by Robert Collins
Some tuning of update_entry.
802
    # in order of frequency:
803
    if S_ISREG(mode):
804
        return c"f"
805
    if S_ISDIR(mode):
806
        return c"d"
807
    if S_ISLNK(mode):
808
        return c"l"
809
    return 0
810
811
812
_encode = binascii.b2a_base64
813
3696.4.17 by Robert Collins
Review feedback.
814
3696.4.3 by Robert Collins
Some tuning of update_entry.
815
from struct import pack
816
cdef _pack_stat(stat_value):
817
    """return a string representing the stat value's key fields.
818
819
    :param stat_value: A stat oject with st_size, st_mtime, st_ctime, st_dev,
820
        st_ino and st_mode fields.
821
    """
822
    cdef char result[6*4] # 6 long ints
823
    cdef int *aliased
824
    aliased = <int *>result
6015.37.5 by Martin Packman
Use PyInt_AsUnsignedLongMask to correctly downcast larger fields in pyrex _pack_stat
825
    aliased[0] = htonl(PyInt_AsUnsignedLongMask(stat_value.st_size))
826
    # mtime and ctime will often be floats but get converted to PyInt within
827
    aliased[1] = htonl(PyInt_AsUnsignedLongMask(stat_value.st_mtime))
828
    aliased[2] = htonl(PyInt_AsUnsignedLongMask(stat_value.st_ctime))
829
    aliased[3] = htonl(PyInt_AsUnsignedLongMask(stat_value.st_dev))
830
    aliased[4] = htonl(PyInt_AsUnsignedLongMask(stat_value.st_ino))
831
    aliased[5] = htonl(PyInt_AsUnsignedLongMask(stat_value.st_mode))
3696.4.3 by Robert Collins
Some tuning of update_entry.
832
    packed = PyString_FromStringAndSize(result, 6*4)
833
    return _encode(packed)[:-1]
834
835
836
def update_entry(self, entry, abspath, stat_value):
3696.4.1 by Robert Collins
Refactor to allow a pluggable dirstate update_entry with interface tests.
837
    """Update the entry based on what is actually on disk.
838
3696.5.2 by Robert Collins
Integrate less aggressive sha logic with C iter-changes.
839
    This function only calculates the sha if it needs to - if the entry is
840
    uncachable, or clearly different to the first parent's entry, no sha
841
    is calculated, and None is returned.
842
3696.4.1 by Robert Collins
Refactor to allow a pluggable dirstate update_entry with interface tests.
843
    :param entry: This is the dirblock entry for the file in question.
844
    :param abspath: The path on disk for this file.
845
    :param stat_value: (optional) if we already have done a stat on the
846
        file, re-use it.
3696.5.2 by Robert Collins
Integrate less aggressive sha logic with C iter-changes.
847
    :return: None, or The sha1 hexdigest of the file (40 bytes) or link
848
        target of a symlink.
3696.4.1 by Robert Collins
Refactor to allow a pluggable dirstate update_entry with interface tests.
849
    """
3696.4.6 by Robert Collins
Fixes for the relocated code, and use _update_entry within the C accelerated code, another 8 percent saving.
850
    return _update_entry(self, entry, abspath, stat_value)
851
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
852
3696.4.6 by Robert Collins
Fixes for the relocated code, and use _update_entry within the C accelerated code, another 8 percent saving.
853
cdef _update_entry(self, entry, abspath, stat_value):
854
    """Update the entry based on what is actually on disk.
855
3696.5.2 by Robert Collins
Integrate less aggressive sha logic with C iter-changes.
856
    This function only calculates the sha if it needs to - if the entry is
857
    uncachable, or clearly different to the first parent's entry, no sha
858
    is calculated, and None is returned.
859
3696.4.17 by Robert Collins
Review feedback.
860
    :param self: The dirstate object this is operating on.
3696.4.6 by Robert Collins
Fixes for the relocated code, and use _update_entry within the C accelerated code, another 8 percent saving.
861
    :param entry: This is the dirblock entry for the file in question.
862
    :param abspath: The path on disk for this file.
3696.4.17 by Robert Collins
Review feedback.
863
    :param stat_value: The stat value done on the path.
3696.5.2 by Robert Collins
Integrate less aggressive sha logic with C iter-changes.
864
    :return: None, or The sha1 hexdigest of the file (40 bytes) or link
865
        target of a symlink.
3696.4.6 by Robert Collins
Fixes for the relocated code, and use _update_entry within the C accelerated code, another 8 percent saving.
866
    """
3696.4.17 by Robert Collins
Review feedback.
867
    # TODO - require pyrex 0.9.8, then use a pyd file to define access to the
868
    # _st mode of the compiled stat objects.
3696.4.3 by Robert Collins
Some tuning of update_entry.
869
    cdef int minikind, saved_minikind
870
    cdef void * details
5802.3.1 by John Arbash Meinel
Fix bug #765881. Having a file added on disk was skipping
871
    cdef int worth_saving
3696.4.3 by Robert Collins
Some tuning of update_entry.
872
    minikind = minikind_from_mode(stat_value.st_mode)
873
    if 0 == minikind:
3696.4.1 by Robert Collins
Refactor to allow a pluggable dirstate update_entry with interface tests.
874
        return None
875
    packed_stat = _pack_stat(stat_value)
3696.4.3 by Robert Collins
Some tuning of update_entry.
876
    details = PyList_GetItem_void_void(PyTuple_GetItem_void_void(<void *>entry, 1), 0)
877
    saved_minikind = PyString_AsString_obj(<PyObject *>PyTuple_GetItem_void_void(details, 0))[0]
4100.2.5 by Aaron Bentley
Stop resetting minikind to 'd' when comparing.
878
    if minikind == c'd' and saved_minikind == c't':
879
        minikind = c't'
3696.4.3 by Robert Collins
Some tuning of update_entry.
880
    saved_link_or_sha1 = PyTuple_GetItem_void_object(details, 1)
881
    saved_file_size = PyTuple_GetItem_void_object(details, 2)
882
    saved_executable = PyTuple_GetItem_void_object(details, 3)
883
    saved_packed_stat = PyTuple_GetItem_void_object(details, 4)
884
    # Deal with pyrex decrefing the objects
885
    Py_INCREF(saved_link_or_sha1)
886
    Py_INCREF(saved_file_size)
887
    Py_INCREF(saved_executable)
888
    Py_INCREF(saved_packed_stat)
889
    #(saved_minikind, saved_link_or_sha1, saved_file_size,
890
    # saved_executable, saved_packed_stat) = entry[1][0]
3696.4.1 by Robert Collins
Refactor to allow a pluggable dirstate update_entry with interface tests.
891
892
    if (minikind == saved_minikind
893
        and packed_stat == saved_packed_stat):
894
        # The stat hasn't changed since we saved, so we can re-use the
895
        # saved sha hash.
3696.4.3 by Robert Collins
Some tuning of update_entry.
896
        if minikind == c'd':
3696.4.1 by Robert Collins
Refactor to allow a pluggable dirstate update_entry with interface tests.
897
            return None
898
899
        # size should also be in packed_stat
900
        if saved_file_size == stat_value.st_size:
901
            return saved_link_or_sha1
902
903
    # If we have gotten this far, that means that we need to actually
904
    # process this entry.
905
    link_or_sha1 = None
5802.3.1 by John Arbash Meinel
Fix bug #765881. Having a file added on disk was skipping
906
    worth_saving = 1
3696.4.3 by Robert Collins
Some tuning of update_entry.
907
    if minikind == c'f':
3696.4.1 by Robert Collins
Refactor to allow a pluggable dirstate update_entry with interface tests.
908
        executable = self._is_executable(stat_value.st_mode,
909
                                         saved_executable)
910
        if self._cutoff_time is None:
911
            self._sha_cutoff_time()
912
        if (stat_value.st_mtime < self._cutoff_time
3696.5.2 by Robert Collins
Integrate less aggressive sha logic with C iter-changes.
913
            and stat_value.st_ctime < self._cutoff_time
914
            and len(entry[1]) > 1
915
            and entry[1][1][0] != 'a'):
916
                # Could check for size changes for further optimised
917
                # avoidance of sha1's. However the most prominent case of
918
                # over-shaing is during initial add, which this catches.
919
            link_or_sha1 = self._sha1_file(abspath)
3696.4.1 by Robert Collins
Refactor to allow a pluggable dirstate update_entry with interface tests.
920
            entry[1][0] = ('f', link_or_sha1, stat_value.st_size,
921
                           executable, packed_stat)
922
        else:
5802.3.1 by John Arbash Meinel
Fix bug #765881. Having a file added on disk was skipping
923
            # This file is not worth caching the sha1. Either it is too new, or
924
            # it is newly added. Regardless, the only things we are changing
925
            # are derived from the stat, and so are not worth caching. So we do
926
            # *not* set the IN_MEMORY_MODIFIED flag. (But we'll save the
927
            # updated values if there is *other* data worth saving.)
928
            entry[1][0] = ('f', '', stat_value.st_size, executable,
929
                           DirState.NULLSTAT)
930
            worth_saving = 0
3696.4.3 by Robert Collins
Some tuning of update_entry.
931
    elif minikind == c'd':
3696.4.1 by Robert Collins
Refactor to allow a pluggable dirstate update_entry with interface tests.
932
        entry[1][0] = ('d', '', 0, False, packed_stat)
3696.4.3 by Robert Collins
Some tuning of update_entry.
933
        if saved_minikind != c'd':
3696.4.1 by Robert Collins
Refactor to allow a pluggable dirstate update_entry with interface tests.
934
            # This changed from something into a directory. Make sure we
935
            # have a directory block for it. This doesn't happen very
936
            # often, so this doesn't have to be super fast.
937
            block_index, entry_index, dir_present, file_present = \
938
                self._get_block_entry_index(entry[0][0], entry[0][1], 0)
939
            self._ensure_block(block_index, entry_index,
3696.4.17 by Robert Collins
Review feedback.
940
                               pathjoin(entry[0][0], entry[0][1]))
5802.3.1 by John Arbash Meinel
Fix bug #765881. Having a file added on disk was skipping
941
        else:
942
            # Any changes are derived trivially from the stat object, not worth
943
            # re-writing a dirstate for just this
944
            worth_saving = 0
3696.4.3 by Robert Collins
Some tuning of update_entry.
945
    elif minikind == c'l':
5807.4.6 by John Arbash Meinel
Merge newer bzr.dev and resolve conflicts.
946
        if saved_minikind == c'l':
947
            # If the object hasn't changed kind, it isn't worth saving the
948
            # dirstate just for a symlink. The default is 'fast symlinks' which
949
            # save the target in the inode entry, rather than separately. So to
950
            # stat, we've already read everything off disk.
951
            worth_saving = 0
3696.4.1 by Robert Collins
Refactor to allow a pluggable dirstate update_entry with interface tests.
952
        link_or_sha1 = self._read_link(abspath, saved_link_or_sha1)
953
        if self._cutoff_time is None:
954
            self._sha_cutoff_time()
955
        if (stat_value.st_mtime < self._cutoff_time
956
            and stat_value.st_ctime < self._cutoff_time):
957
            entry[1][0] = ('l', link_or_sha1, stat_value.st_size,
958
                           False, packed_stat)
959
        else:
960
            entry[1][0] = ('l', '', stat_value.st_size,
961
                           False, DirState.NULLSTAT)
5802.3.1 by John Arbash Meinel
Fix bug #765881. Having a file added on disk was skipping
962
    if worth_saving:
5807.4.6 by John Arbash Meinel
Merge newer bzr.dev and resolve conflicts.
963
        # Note, even though _mark_modified will only set
964
        # IN_MEMORY_HASH_MODIFIED, it still isn't worth 
965
        self._mark_modified([entry])
3696.4.1 by Robert Collins
Refactor to allow a pluggable dirstate update_entry with interface tests.
966
    return link_or_sha1
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
967
968
4634.117.6 by John Arbash Meinel
Start going through the test failures.
969
# TODO: Do we want to worry about exceptions here?
970
cdef char _minikind_from_string(object string) except? -1:
3696.4.7 by Robert Collins
More tuning.
971
    """Convert a python string to a char."""
972
    return PyString_AsString(string)[0]
973
974
3696.4.8 by Robert Collins
Fix up inter_changes with dirstate both C and python.
975
cdef object _kind_absent
976
cdef object _kind_file
977
cdef object _kind_directory
978
cdef object _kind_symlink
979
cdef object _kind_relocated
980
cdef object _kind_tree_reference
981
_kind_absent = "absent"
982
_kind_file = "file"
983
_kind_directory = "directory"
984
_kind_symlink = "symlink"
985
_kind_relocated = "relocated"
986
_kind_tree_reference = "tree-reference"
987
988
3696.4.7 by Robert Collins
More tuning.
989
cdef object _minikind_to_kind(char minikind):
990
    """Create a string kind for minikind."""
991
    cdef char _minikind[1]
3696.4.8 by Robert Collins
Fix up inter_changes with dirstate both C and python.
992
    if minikind == c'f':
993
        return _kind_file
994
    elif minikind == c'd':
995
        return _kind_directory
996
    elif minikind == c'a':
997
        return _kind_absent
998
    elif minikind == c'r':
999
        return _kind_relocated
1000
    elif minikind == c'l':
1001
        return _kind_symlink
1002
    elif minikind == c't':
1003
        return _kind_tree_reference
3696.4.7 by Robert Collins
More tuning.
1004
    _minikind[0] = minikind
3696.4.8 by Robert Collins
Fix up inter_changes with dirstate both C and python.
1005
    raise KeyError(PyString_FromStringAndSize(_minikind, 1))
3696.4.7 by Robert Collins
More tuning.
1006
1007
4634.117.10 by John Arbash Meinel
Change 'no except' to 'cannot_raise'
1008
cdef int _versioned_minikind(char minikind): # cannot_raise
3696.4.7 by Robert Collins
More tuning.
1009
    """Return non-zero if minikind is in fltd"""
1010
    return (minikind == c'f' or
1011
            minikind == c'd' or
1012
            minikind == c'l' or
1013
            minikind == c't')
1014
1015
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
1016
cdef class ProcessEntryC:
1017
4570.2.5 by Robert Collins
Review feedback, including finding a bug with changes at the root.
1018
    cdef int doing_consistency_expansion
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
1019
    cdef object old_dirname_to_file_id # dict
1020
    cdef object new_dirname_to_file_id # dict
1021
    cdef object last_source_parent
1022
    cdef object last_target_parent
4570.2.3 by Robert Collins
Change the way iter_changes treats specific files to prevent InconsistentDeltas.
1023
    cdef int include_unchanged
1024
    cdef int partial
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
1025
    cdef object use_filesystem_for_exec
3696.4.6 by Robert Collins
Fixes for the relocated code, and use _update_entry within the C accelerated code, another 8 percent saving.
1026
    cdef object utf8_decode
3696.4.8 by Robert Collins
Fix up inter_changes with dirstate both C and python.
1027
    cdef readonly object searched_specific_files
4570.2.3 by Robert Collins
Change the way iter_changes treats specific files to prevent InconsistentDeltas.
1028
    cdef readonly object searched_exact_paths
3696.4.8 by Robert Collins
Fix up inter_changes with dirstate both C and python.
1029
    cdef object search_specific_files
4570.2.3 by Robert Collins
Change the way iter_changes treats specific files to prevent InconsistentDeltas.
1030
    # The parents up to the root of the paths we are searching.
1031
    # After all normal paths are returned, these specific items are returned.
1032
    cdef object search_specific_file_parents
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1033
    cdef object state
1034
    # Current iteration variables:
1035
    cdef object current_root
1036
    cdef object current_root_unicode
1037
    cdef object root_entries
1038
    cdef int root_entries_pos, root_entries_len
1039
    cdef object root_abspath
1040
    cdef int source_index, target_index
1041
    cdef int want_unversioned
1042
    cdef object tree
1043
    cdef object dir_iterator
1044
    cdef int block_index
1045
    cdef object current_block
1046
    cdef int current_block_pos
3696.4.12 by Robert Collins
More Cification of iter_changes, smaller functions, explicit type usage.
1047
    cdef object current_block_list
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1048
    cdef object current_dir_info
3696.4.12 by Robert Collins
More Cification of iter_changes, smaller functions, explicit type usage.
1049
    cdef object current_dir_list
4570.2.5 by Robert Collins
Review feedback, including finding a bug with changes at the root.
1050
    cdef object _pending_consistent_entries # list
3696.4.12 by Robert Collins
More Cification of iter_changes, smaller functions, explicit type usage.
1051
    cdef int path_index
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1052
    cdef object root_dir_info
1053
    cdef object bisect_left
3696.4.17 by Robert Collins
Review feedback.
1054
    cdef object pathjoin
3696.5.2 by Robert Collins
Integrate less aggressive sha logic with C iter-changes.
1055
    cdef object fstat
4570.2.3 by Robert Collins
Change the way iter_changes treats specific files to prevent InconsistentDeltas.
1056
    # A set of the ids we've output when doing partial output.
1057
    cdef object seen_ids
3696.5.2 by Robert Collins
Integrate less aggressive sha logic with C iter-changes.
1058
    cdef object sha_file
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
1059
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1060
    def __init__(self, include_unchanged, use_filesystem_for_exec,
1061
        search_specific_files, state, source_index, target_index,
1062
        want_unversioned, tree):
4570.2.5 by Robert Collins
Review feedback, including finding a bug with changes at the root.
1063
        self.doing_consistency_expansion = 0
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
1064
        self.old_dirname_to_file_id = {}
1065
        self.new_dirname_to_file_id = {}
4570.2.3 by Robert Collins
Change the way iter_changes treats specific files to prevent InconsistentDeltas.
1066
        # Are we doing a partial iter_changes?
1067
        self.partial = set(['']).__ne__(search_specific_files)
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
1068
        # Using a list so that we can access the values and change them in
1069
        # nested scope. Each one is [path, file_id, entry]
1070
        self.last_source_parent = [None, None]
1071
        self.last_target_parent = [None, None]
4570.2.4 by Robert Collins
Older pyrex compatibility.
1072
        if include_unchanged is None:
1073
            self.include_unchanged = False
1074
        else:
4570.2.9 by Robert Collins
Give a clearer error on bad input to dirstate iter_changes objects.
1075
            self.include_unchanged = int(include_unchanged)
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
1076
        self.use_filesystem_for_exec = use_filesystem_for_exec
3696.4.6 by Robert Collins
Fixes for the relocated code, and use _update_entry within the C accelerated code, another 8 percent saving.
1077
        self.utf8_decode = cache_utf8._utf8_decode
3696.4.8 by Robert Collins
Fix up inter_changes with dirstate both C and python.
1078
        # for all search_indexs in each path at or under each element of
4570.2.3 by Robert Collins
Change the way iter_changes treats specific files to prevent InconsistentDeltas.
1079
        # search_specific_files, if the detail is relocated: add the id, and
1080
        # add the relocated path as one to search if its not searched already.
1081
        # If the detail is not relocated, add the id.
3696.4.8 by Robert Collins
Fix up inter_changes with dirstate both C and python.
1082
        self.searched_specific_files = set()
4570.2.3 by Robert Collins
Change the way iter_changes treats specific files to prevent InconsistentDeltas.
1083
        # When we search exact paths without expanding downwards, we record
1084
        # that here.
1085
        self.searched_exact_paths = set()
3696.4.8 by Robert Collins
Fix up inter_changes with dirstate both C and python.
1086
        self.search_specific_files = search_specific_files
4570.2.3 by Robert Collins
Change the way iter_changes treats specific files to prevent InconsistentDeltas.
1087
        # The parents up to the root of the paths we are searching.
1088
        # After all normal paths are returned, these specific items are returned.
1089
        self.search_specific_file_parents = set()
1090
        # The ids we've sent out in the delta.
1091
        self.seen_ids = set()
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1092
        self.state = state
1093
        self.current_root = None
1094
        self.current_root_unicode = None
1095
        self.root_entries = None
1096
        self.root_entries_pos = 0
1097
        self.root_entries_len = 0
1098
        self.root_abspath = None
1099
        if source_index is None:
1100
            self.source_index = -1
1101
        else:
1102
            self.source_index = source_index
1103
        self.target_index = target_index
1104
        self.want_unversioned = want_unversioned
1105
        self.tree = tree
1106
        self.dir_iterator = None
1107
        self.block_index = -1
1108
        self.current_block = None
3696.4.12 by Robert Collins
More Cification of iter_changes, smaller functions, explicit type usage.
1109
        self.current_block_list = None
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1110
        self.current_block_pos = -1
1111
        self.current_dir_info = None
3696.4.12 by Robert Collins
More Cification of iter_changes, smaller functions, explicit type usage.
1112
        self.current_dir_list = None
4570.2.5 by Robert Collins
Review feedback, including finding a bug with changes at the root.
1113
        self._pending_consistent_entries = []
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1114
        self.path_index = 0
1115
        self.root_dir_info = None
1116
        self.bisect_left = bisect.bisect_left
3696.4.17 by Robert Collins
Review feedback.
1117
        self.pathjoin = osutils.pathjoin
3696.5.2 by Robert Collins
Integrate less aggressive sha logic with C iter-changes.
1118
        self.fstat = os.fstat
1119
        self.sha_file = osutils.sha_file
4570.2.3 by Robert Collins
Change the way iter_changes treats specific files to prevent InconsistentDeltas.
1120
        if target_index != 0:
1121
            # A lot of code in here depends on target_index == 0
1122
            raise errors.BzrError('unsupported target index')
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
1123
3696.4.11 by Robert Collins
Some Cification of iter_changes, and making the python one actually work.
1124
    cdef _process_entry(self, entry, path_info):
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
1125
        """Compare an entry and real disk to generate delta information.
1126
1127
        :param path_info: top_relpath, basename, kind, lstat, abspath for
4570.2.3 by Robert Collins
Change the way iter_changes treats specific files to prevent InconsistentDeltas.
1128
            the path of entry. If None, then the path is considered absent in 
1129
            the target (Perhaps we should pass in a concrete entry for this ?)
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
1130
            Basename is returned as a utf8 string because we expect this
1131
            tuple will be ignored, and don't want to take the time to
1132
            decode.
4570.2.1 by Robert Collins
Refactoring of dirstate iter_changes to make it possible to tell changed vs unchanged results internally.
1133
        :return: (iter_changes_result, changed). If the entry has not been
1134
            handled then changed is None. Otherwise it is False if no content
4570.2.3 by Robert Collins
Change the way iter_changes treats specific files to prevent InconsistentDeltas.
1135
            or metadata changes have occured, and True if any content or
1136
            metadata change has occurred. If self.include_unchanged is True then
4570.2.1 by Robert Collins
Refactoring of dirstate iter_changes to make it possible to tell changed vs unchanged results internally.
1137
            if changed is not None, iter_changes_result will always be a result
1138
            tuple. Otherwise, iter_changes_result is None unless changed is
1139
            True.
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
1140
        """
3696.4.6 by Robert Collins
Fixes for the relocated code, and use _update_entry within the C accelerated code, another 8 percent saving.
1141
        cdef char target_minikind
3696.4.7 by Robert Collins
More tuning.
1142
        cdef char source_minikind
3696.4.8 by Robert Collins
Fix up inter_changes with dirstate both C and python.
1143
        cdef object file_id
1144
        cdef int content_change
3696.4.9 by Robert Collins
Reduce lookups in process_entry.
1145
        cdef object details_list
3696.4.8 by Robert Collins
Fix up inter_changes with dirstate both C and python.
1146
        file_id = None
3696.4.9 by Robert Collins
Reduce lookups in process_entry.
1147
        details_list = entry[1]
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1148
        if -1 == self.source_index:
3696.4.6 by Robert Collins
Fixes for the relocated code, and use _update_entry within the C accelerated code, another 8 percent saving.
1149
            source_details = DirState.NULL_PARENT_DETAILS
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
1150
        else:
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1151
            source_details = details_list[self.source_index]
1152
        target_details = details_list[self.target_index]
3696.4.7 by Robert Collins
More tuning.
1153
        target_minikind = _minikind_from_string(target_details[0])
1154
        if path_info is not None and _versioned_minikind(target_minikind):
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1155
            if self.target_index != 0:
3763.1.1 by Benjamin Peterson
fix two small oversights
1156
                raise AssertionError("Unsupported target index %d" %
1157
                                     self.target_index)
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1158
            link_or_sha1 = _update_entry(self.state, entry, path_info[4], path_info[3])
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
1159
            # The entry may have been modified by update_entry
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1160
            target_details = details_list[self.target_index]
3696.4.7 by Robert Collins
More tuning.
1161
            target_minikind = _minikind_from_string(target_details[0])
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
1162
        else:
1163
            link_or_sha1 = None
3696.4.7 by Robert Collins
More tuning.
1164
        # the rest of this function is 0.3 seconds on 50K paths, or
1165
        # 0.000006 seconds per call.
1166
        source_minikind = _minikind_from_string(source_details[0])
1167
        if ((_versioned_minikind(source_minikind) or source_minikind == c'r')
1168
            and _versioned_minikind(target_minikind)):
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
1169
            # claimed content in both: diff
1170
            #   r    | fdlt   |      | add source to search, add id path move and perform
1171
            #        |        |      | diff check on source-target
1172
            #   r    | fdlt   |  a   | dangling file that was present in the basis.
1173
            #        |        |      | ???
3696.4.8 by Robert Collins
Fix up inter_changes with dirstate both C and python.
1174
            if source_minikind != c'r':
1175
                old_dirname = entry[0][0]
1176
                old_basename = entry[0][1]
1177
                old_path = path = None
1178
            else:
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
1179
                # add the source to the search path to find any children it
1180
                # has.  TODO ? : only add if it is a container ?
4570.2.5 by Robert Collins
Review feedback, including finding a bug with changes at the root.
1181
                if (not self.doing_consistency_expansion and 
4570.2.3 by Robert Collins
Change the way iter_changes treats specific files to prevent InconsistentDeltas.
1182
                    not osutils.is_inside_any(self.searched_specific_files,
1183
                                             source_details[1])):
3696.4.8 by Robert Collins
Fix up inter_changes with dirstate both C and python.
1184
                    self.search_specific_files.add(source_details[1])
4570.2.5 by Robert Collins
Review feedback, including finding a bug with changes at the root.
1185
                    # expanding from a user requested path, parent expansion
1186
                    # for delta consistency happens later.
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
1187
                # generate the old path; this is needed for stating later
1188
                # as well.
1189
                old_path = source_details[1]
1190
                old_dirname, old_basename = os.path.split(old_path)
3696.4.17 by Robert Collins
Review feedback.
1191
                path = self.pathjoin(entry[0][0], entry[0][1])
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1192
                old_entry = self.state._get_entry(self.source_index,
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
1193
                                             path_utf8=old_path)
1194
                # update the source details variable to be the real
1195
                # location.
1196
                if old_entry == (None, None):
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1197
                    raise errors.CorruptDirstate(self.state._filename,
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
1198
                        "entry '%s/%s' is considered renamed from %r"
1199
                        " but source does not exist\n"
1200
                        "entry: %s" % (entry[0][0], entry[0][1], old_path, entry))
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1201
                source_details = old_entry[1][self.source_index]
3696.4.7 by Robert Collins
More tuning.
1202
                source_minikind = _minikind_from_string(source_details[0])
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
1203
            if path_info is None:
1204
                # the file is missing on disk, show as removed.
3696.4.8 by Robert Collins
Fix up inter_changes with dirstate both C and python.
1205
                content_change = 1
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
1206
                target_kind = None
1207
                target_exec = False
1208
            else:
1209
                # source and target are both versioned and disk file is present.
1210
                target_kind = path_info[2]
1211
                if target_kind == 'directory':
1212
                    if path is None:
3696.4.17 by Robert Collins
Review feedback.
1213
                        old_path = path = self.pathjoin(old_dirname, old_basename)
3696.4.8 by Robert Collins
Fix up inter_changes with dirstate both C and python.
1214
                    file_id = entry[0][2]
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
1215
                    self.new_dirname_to_file_id[path] = file_id
3696.4.7 by Robert Collins
More tuning.
1216
                    if source_minikind != c'd':
3696.4.8 by Robert Collins
Fix up inter_changes with dirstate both C and python.
1217
                        content_change = 1
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
1218
                    else:
1219
                        # directories have no fingerprint
3696.4.8 by Robert Collins
Fix up inter_changes with dirstate both C and python.
1220
                        content_change = 0
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
1221
                    target_exec = False
1222
                elif target_kind == 'file':
3696.4.7 by Robert Collins
More tuning.
1223
                    if source_minikind != c'f':
3696.4.8 by Robert Collins
Fix up inter_changes with dirstate both C and python.
1224
                        content_change = 1
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
1225
                    else:
4393.3.2 by Ian Clatworthy
fix pyrex version of _process_entry as well
1226
                        # Check the sha. We can't just rely on the size as
1227
                        # content filtering may mean differ sizes actually
1228
                        # map to the same content
1229
                        if link_or_sha1 is None:
1230
                            # Stat cache miss:
1231
                            statvalue, link_or_sha1 = \
1232
                                self.state._sha1_provider.stat_and_sha1(
1233
                                path_info[4])
1234
                            self.state._observed_sha1(entry, link_or_sha1,
1235
                                statvalue)
1236
                        content_change = (link_or_sha1 != source_details[1])
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
1237
                    # Target details is updated at update_entry time
1238
                    if self.use_filesystem_for_exec:
1239
                        # We don't need S_ISREG here, because we are sure
1240
                        # we are dealing with a file.
1241
                        target_exec = bool(S_IXUSR & path_info[3].st_mode)
1242
                    else:
1243
                        target_exec = target_details[3]
1244
                elif target_kind == 'symlink':
3696.4.7 by Robert Collins
More tuning.
1245
                    if source_minikind != c'l':
3696.4.8 by Robert Collins
Fix up inter_changes with dirstate both C and python.
1246
                        content_change = 1
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
1247
                    else:
1248
                        content_change = (link_or_sha1 != source_details[1])
1249
                    target_exec = False
1250
                elif target_kind == 'tree-reference':
3696.4.7 by Robert Collins
More tuning.
1251
                    if source_minikind != c't':
3696.4.8 by Robert Collins
Fix up inter_changes with dirstate both C and python.
1252
                        content_change = 1
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
1253
                    else:
3696.4.8 by Robert Collins
Fix up inter_changes with dirstate both C and python.
1254
                        content_change = 0
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
1255
                    target_exec = False
1256
                else:
4634.58.1 by Robert Collins
Show a sensible error when a previously versionable path becomes a FIFO or other unversionable file.
1257
                    if path is None:
1258
                        path = self.pathjoin(old_dirname, old_basename)
1259
                    raise errors.BadFileKindError(path, path_info[2])
3696.4.7 by Robert Collins
More tuning.
1260
            if source_minikind == c'd':
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
1261
                if path is None:
3696.4.17 by Robert Collins
Review feedback.
1262
                    old_path = path = self.pathjoin(old_dirname, old_basename)
3696.4.8 by Robert Collins
Fix up inter_changes with dirstate both C and python.
1263
                if file_id is None:
1264
                    file_id = entry[0][2]
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
1265
                self.old_dirname_to_file_id[old_path] = file_id
1266
            # parent id is the entry for the path in the target tree
4570.2.3 by Robert Collins
Change the way iter_changes treats specific files to prevent InconsistentDeltas.
1267
            if old_basename and old_dirname == self.last_source_parent[0]:
4570.2.5 by Robert Collins
Review feedback, including finding a bug with changes at the root.
1268
                # use a cached hit for non-root source entries.
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
1269
                source_parent_id = self.last_source_parent[1]
1270
            else:
1271
                try:
1272
                    source_parent_id = self.old_dirname_to_file_id[old_dirname]
4634.153.1 by John Arbash Meinel
Workaround a bug (#582656) in recent versions of Pyrex.
1273
                except KeyError, _:
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1274
                    source_parent_entry = self.state._get_entry(self.source_index,
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
1275
                                                           path_utf8=old_dirname)
1276
                    source_parent_id = source_parent_entry[0][2]
1277
                if source_parent_id == entry[0][2]:
1278
                    # This is the root, so the parent is None
1279
                    source_parent_id = None
1280
                else:
1281
                    self.last_source_parent[0] = old_dirname
1282
                    self.last_source_parent[1] = source_parent_id
1283
            new_dirname = entry[0][0]
4570.2.3 by Robert Collins
Change the way iter_changes treats specific files to prevent InconsistentDeltas.
1284
            if entry[0][1] and new_dirname == self.last_target_parent[0]:
4570.2.5 by Robert Collins
Review feedback, including finding a bug with changes at the root.
1285
                # use a cached hit for non-root target entries.
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
1286
                target_parent_id = self.last_target_parent[1]
1287
            else:
1288
                try:
1289
                    target_parent_id = self.new_dirname_to_file_id[new_dirname]
4634.153.1 by John Arbash Meinel
Workaround a bug (#582656) in recent versions of Pyrex.
1290
                except KeyError, _:
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
1291
                    # TODO: We don't always need to do the lookup, because the
1292
                    #       parent entry will be the same as the source entry.
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1293
                    target_parent_entry = self.state._get_entry(self.target_index,
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
1294
                                                           path_utf8=new_dirname)
1295
                    if target_parent_entry == (None, None):
1296
                        raise AssertionError(
1297
                            "Could not find target parent in wt: %s\nparent of: %s"
1298
                            % (new_dirname, entry))
1299
                    target_parent_id = target_parent_entry[0][2]
1300
                if target_parent_id == entry[0][2]:
1301
                    # This is the root, so the parent is None
1302
                    target_parent_id = None
1303
                else:
1304
                    self.last_target_parent[0] = new_dirname
1305
                    self.last_target_parent[1] = target_parent_id
1306
1307
            source_exec = source_details[3]
4570.2.1 by Robert Collins
Refactoring of dirstate iter_changes to make it possible to tell changed vs unchanged results internally.
1308
            changed = (content_change
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
1309
                or source_parent_id != target_parent_id
1310
                or old_basename != entry[0][1]
1311
                or source_exec != target_exec
4570.2.1 by Robert Collins
Refactoring of dirstate iter_changes to make it possible to tell changed vs unchanged results internally.
1312
                )
1313
            if not changed and not self.include_unchanged:
1314
                return None, False
1315
            else:
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
1316
                if old_path is None:
3696.4.17 by Robert Collins
Review feedback.
1317
                    path = self.pathjoin(old_dirname, old_basename)
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1318
                    old_path = path
3696.4.6 by Robert Collins
Fixes for the relocated code, and use _update_entry within the C accelerated code, another 8 percent saving.
1319
                    old_path_u = self.utf8_decode(old_path)[0]
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
1320
                    path_u = old_path_u
1321
                else:
3696.4.6 by Robert Collins
Fixes for the relocated code, and use _update_entry within the C accelerated code, another 8 percent saving.
1322
                    old_path_u = self.utf8_decode(old_path)[0]
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
1323
                    if old_path == path:
1324
                        path_u = old_path_u
1325
                    else:
3696.4.6 by Robert Collins
Fixes for the relocated code, and use _update_entry within the C accelerated code, another 8 percent saving.
1326
                        path_u = self.utf8_decode(path)[0]
3696.4.7 by Robert Collins
More tuning.
1327
                source_kind = _minikind_to_kind(source_minikind)
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
1328
                return (entry[0][2],
1329
                       (old_path_u, path_u),
1330
                       content_change,
1331
                       (True, True),
1332
                       (source_parent_id, target_parent_id),
3696.4.6 by Robert Collins
Fixes for the relocated code, and use _update_entry within the C accelerated code, another 8 percent saving.
1333
                       (self.utf8_decode(old_basename)[0], self.utf8_decode(entry[0][1])[0]),
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
1334
                       (source_kind, target_kind),
4570.2.1 by Robert Collins
Refactoring of dirstate iter_changes to make it possible to tell changed vs unchanged results internally.
1335
                       (source_exec, target_exec)), changed
3696.4.7 by Robert Collins
More tuning.
1336
        elif source_minikind == c'a' and _versioned_minikind(target_minikind):
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
1337
            # looks like a new file
3696.4.17 by Robert Collins
Review feedback.
1338
            path = self.pathjoin(entry[0][0], entry[0][1])
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
1339
            # parent id is the entry for the path in the target tree
1340
            # TODO: these are the same for an entire directory: cache em.
4005.1.1 by John Arbash Meinel
Related to bug #328674, give a better error for a corrupt dirstate.
1341
            parent_entry = self.state._get_entry(self.target_index,
1342
                                                 path_utf8=entry[0][0])
1343
            if parent_entry is None:
1344
                raise errors.DirstateCorrupt(self.state,
1345
                    "We could not find the parent entry in index %d"
1346
                    " for the entry: %s"
1347
                    % (self.target_index, entry[0]))
1348
            parent_id = parent_entry[0][2]
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
1349
            if parent_id == entry[0][2]:
1350
                parent_id = None
1351
            if path_info is not None:
1352
                # Present on disk:
1353
                if self.use_filesystem_for_exec:
1354
                    # We need S_ISREG here, because we aren't sure if this
1355
                    # is a file or not.
1356
                    target_exec = bool(
1357
                        S_ISREG(path_info[3].st_mode)
1358
                        and S_IXUSR & path_info[3].st_mode)
1359
                else:
1360
                    target_exec = target_details[3]
1361
                return (entry[0][2],
3696.4.6 by Robert Collins
Fixes for the relocated code, and use _update_entry within the C accelerated code, another 8 percent saving.
1362
                       (None, self.utf8_decode(path)[0]),
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
1363
                       True,
1364
                       (False, True),
1365
                       (None, parent_id),
3696.4.6 by Robert Collins
Fixes for the relocated code, and use _update_entry within the C accelerated code, another 8 percent saving.
1366
                       (None, self.utf8_decode(entry[0][1])[0]),
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
1367
                       (None, path_info[2]),
4570.2.1 by Robert Collins
Refactoring of dirstate iter_changes to make it possible to tell changed vs unchanged results internally.
1368
                       (None, target_exec)), True
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
1369
            else:
1370
                # Its a missing file, report it as such.
1371
                return (entry[0][2],
3696.4.6 by Robert Collins
Fixes for the relocated code, and use _update_entry within the C accelerated code, another 8 percent saving.
1372
                       (None, self.utf8_decode(path)[0]),
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
1373
                       False,
1374
                       (False, True),
1375
                       (None, parent_id),
3696.4.6 by Robert Collins
Fixes for the relocated code, and use _update_entry within the C accelerated code, another 8 percent saving.
1376
                       (None, self.utf8_decode(entry[0][1])[0]),
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
1377
                       (None, None),
4570.2.1 by Robert Collins
Refactoring of dirstate iter_changes to make it possible to tell changed vs unchanged results internally.
1378
                       (None, False)), True
3696.4.7 by Robert Collins
More tuning.
1379
        elif _versioned_minikind(source_minikind) and target_minikind == c'a':
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
1380
            # unversioned, possibly, or possibly not deleted: we dont care.
1381
            # if its still on disk, *and* theres no other entry at this
1382
            # path [we dont know this in this routine at the moment -
1383
            # perhaps we should change this - then it would be an unknown.
3696.4.17 by Robert Collins
Review feedback.
1384
            old_path = self.pathjoin(entry[0][0], entry[0][1])
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
1385
            # parent id is the entry for the path in the target tree
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1386
            parent_id = self.state._get_entry(self.source_index, path_utf8=entry[0][0])[0][2]
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
1387
            if parent_id == entry[0][2]:
1388
                parent_id = None
1389
            return (entry[0][2],
3696.4.6 by Robert Collins
Fixes for the relocated code, and use _update_entry within the C accelerated code, another 8 percent saving.
1390
                   (self.utf8_decode(old_path)[0], None),
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
1391
                   True,
1392
                   (True, False),
1393
                   (parent_id, None),
3696.4.6 by Robert Collins
Fixes for the relocated code, and use _update_entry within the C accelerated code, another 8 percent saving.
1394
                   (self.utf8_decode(entry[0][1])[0], None),
3696.4.7 by Robert Collins
More tuning.
1395
                   (_minikind_to_kind(source_minikind), None),
4570.2.1 by Robert Collins
Refactoring of dirstate iter_changes to make it possible to tell changed vs unchanged results internally.
1396
                   (source_details[3], None)), True
3696.4.7 by Robert Collins
More tuning.
1397
        elif _versioned_minikind(source_minikind) and target_minikind == c'r':
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
1398
            # a rename; could be a true rename, or a rename inherited from
1399
            # a renamed parent. TODO: handle this efficiently. Its not
1400
            # common case to rename dirs though, so a correct but slow
1401
            # implementation will do.
4570.2.5 by Robert Collins
Review feedback, including finding a bug with changes at the root.
1402
            if (not self.doing_consistency_expansion and 
4570.2.3 by Robert Collins
Change the way iter_changes treats specific files to prevent InconsistentDeltas.
1403
                not osutils.is_inside_any(self.searched_specific_files,
1404
                    target_details[1])):
3696.4.8 by Robert Collins
Fix up inter_changes with dirstate both C and python.
1405
                self.search_specific_files.add(target_details[1])
4570.2.3 by Robert Collins
Change the way iter_changes treats specific files to prevent InconsistentDeltas.
1406
                # We don't expand the specific files parents list here as
1407
                # the path is absent in target and won't create a delta with
1408
                # missing parent.
3696.4.7 by Robert Collins
More tuning.
1409
        elif ((source_minikind == c'r' or source_minikind == c'a') and
1410
              (target_minikind == c'r' or target_minikind == c'a')):
3696.4.13 by Robert Collins
More Cification, removing redundant string comparisons
1411
            # neither of the selected trees contain this path,
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
1412
            # so skip over it. This is not currently directly tested, but
1413
            # is indirectly via test_too_much.TestCommands.test_conflicts.
1414
            pass
1415
        else:
1416
            raise AssertionError("don't know how to compare "
1417
                "source_minikind=%r, target_minikind=%r"
1418
                % (source_minikind, target_minikind))
1419
            ## import pdb;pdb.set_trace()
4570.2.1 by Robert Collins
Refactoring of dirstate iter_changes to make it possible to tell changed vs unchanged results internally.
1420
        return None, None
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1421
1422
    def __iter__(self):
1423
        return self
1424
1425
    def iter_changes(self):
1426
        return self
1427
4634.117.6 by John Arbash Meinel
Start going through the test failures.
1428
    cdef int _gather_result_for_consistency(self, result) except -1:
4570.2.3 by Robert Collins
Change the way iter_changes treats specific files to prevent InconsistentDeltas.
1429
        """Check a result we will yield to make sure we are consistent later.
1430
        
1431
        This gathers result's parents into a set to output later.
1432
1433
        :param result: A result tuple.
1434
        """
1435
        if not self.partial or not result[0]:
4634.117.6 by John Arbash Meinel
Start going through the test failures.
1436
            return 0
4570.2.3 by Robert Collins
Change the way iter_changes treats specific files to prevent InconsistentDeltas.
1437
        self.seen_ids.add(result[0])
1438
        new_path = result[1][1]
1439
        if new_path:
1440
            # Not the root and not a delete: queue up the parents of the path.
1441
            self.search_specific_file_parents.update(
1442
                osutils.parent_directories(new_path.encode('utf8')))
1443
            # Add the root directory which parent_directories does not
1444
            # provide.
1445
            self.search_specific_file_parents.add('')
4634.117.6 by John Arbash Meinel
Start going through the test failures.
1446
        return 0
4570.2.3 by Robert Collins
Change the way iter_changes treats specific files to prevent InconsistentDeltas.
1447
4634.117.1 by John Arbash Meinel
Fix bug #495023, _update_current_block should not supress exceptions.
1448
    cdef int _update_current_block(self) except -1:
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1449
        if (self.block_index < len(self.state._dirblocks) and
1450
            osutils.is_inside(self.current_root, self.state._dirblocks[self.block_index][0])):
1451
            self.current_block = self.state._dirblocks[self.block_index]
3696.4.12 by Robert Collins
More Cification of iter_changes, smaller functions, explicit type usage.
1452
            self.current_block_list = self.current_block[1]
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1453
            self.current_block_pos = 0
1454
        else:
1455
            self.current_block = None
3696.4.12 by Robert Collins
More Cification of iter_changes, smaller functions, explicit type usage.
1456
            self.current_block_list = None
4634.117.1 by John Arbash Meinel
Fix bug #495023, _update_current_block should not supress exceptions.
1457
        return 0
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1458
1459
    def __next__(self):
1460
        # Simple thunk to allow tail recursion without pyrex confusion
1461
        return self._iter_next()
1462
1463
    cdef _iter_next(self):
1464
        """Iterate over the changes."""
1465
        # This function single steps through an iterator. As such while loops
1466
        # are often exited by 'return' - the code is structured so that the
1467
        # next call into the function will return to the same while loop. Note
1468
        # that all flow control needed to re-reach that step is reexecuted,
1469
        # which can be a performance problem. It has not yet been tuned to
1470
        # minimise this; a state machine is probably the simplest restructuring
1471
        # to both minimise this overhead and make the code considerably more
1472
        # understandable.
1473
1474
        # sketch: 
1475
        # compare source_index and target_index at or under each element of search_specific_files.
1476
        # follow the following comparison table. Note that we only want to do diff operations when
1477
        # the target is fdl because thats when the walkdirs logic will have exposed the pathinfo 
1478
        # for the target.
1479
        # cases:
1480
        # 
1481
        # Source | Target | disk | action
1482
        #   r    | fdlt   |      | add source to search, add id path move and perform
1483
        #        |        |      | diff check on source-target
1484
        #   r    | fdlt   |  a   | dangling file that was present in the basis. 
1485
        #        |        |      | ???
1486
        #   r    |  a     |      | add source to search
1487
        #   r    |  a     |  a   | 
1488
        #   r    |  r     |      | this path is present in a non-examined tree, skip.
1489
        #   r    |  r     |  a   | this path is present in a non-examined tree, skip.
1490
        #   a    | fdlt   |      | add new id
1491
        #   a    | fdlt   |  a   | dangling locally added file, skip
1492
        #   a    |  a     |      | not present in either tree, skip
1493
        #   a    |  a     |  a   | not present in any tree, skip
1494
        #   a    |  r     |      | not present in either tree at this path, skip as it
1495
        #        |        |      | may not be selected by the users list of paths.
1496
        #   a    |  r     |  a   | not present in either tree at this path, skip as it
1497
        #        |        |      | may not be selected by the users list of paths.
1498
        #  fdlt  | fdlt   |      | content in both: diff them
1499
        #  fdlt  | fdlt   |  a   | deleted locally, but not unversioned - show as deleted ?
1500
        #  fdlt  |  a     |      | unversioned: output deleted id for now
1501
        #  fdlt  |  a     |  a   | unversioned and deleted: output deleted id
1502
        #  fdlt  |  r     |      | relocated in this tree, so add target to search.
1503
        #        |        |      | Dont diff, we will see an r,fd; pair when we reach
1504
        #        |        |      | this id at the other path.
1505
        #  fdlt  |  r     |  a   | relocated in this tree, so add target to search.
1506
        #        |        |      | Dont diff, we will see an r,fd; pair when we reach
1507
        #        |        |      | this id at the other path.
1508
1509
        # TODO: jam 20070516 - Avoid the _get_entry lookup overhead by
1510
        #       keeping a cache of directories that we have seen.
1511
        cdef object current_dirname, current_blockname
1512
        cdef char * current_dirname_c, * current_blockname_c
3696.4.11 by Robert Collins
Some Cification of iter_changes, and making the python one actually work.
1513
        cdef int advance_entry, advance_path
3696.4.12 by Robert Collins
More Cification of iter_changes, smaller functions, explicit type usage.
1514
        cdef int path_handled
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1515
        searched_specific_files = self.searched_specific_files
1516
        # Are we walking a root?
1517
        while self.root_entries_pos < self.root_entries_len:
1518
            entry = self.root_entries[self.root_entries_pos]
1519
            self.root_entries_pos = self.root_entries_pos + 1
4570.2.1 by Robert Collins
Refactoring of dirstate iter_changes to make it possible to tell changed vs unchanged results internally.
1520
            result, changed = self._process_entry(entry, self.root_dir_info)
4570.2.3 by Robert Collins
Change the way iter_changes treats specific files to prevent InconsistentDeltas.
1521
            if changed is not None:
1522
                if changed:
1523
                    self._gather_result_for_consistency(result)
1524
                if changed or self.include_unchanged:
1525
                    return result
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1526
        # Have we finished the prior root, or never started one ?
1527
        if self.current_root is None:
1528
            # TODO: the pending list should be lexically sorted?  the
1529
            # interface doesn't require it.
1530
            try:
1531
                self.current_root = self.search_specific_files.pop()
4634.153.1 by John Arbash Meinel
Workaround a bug (#582656) in recent versions of Pyrex.
1532
            except KeyError, _:
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1533
                raise StopIteration()
1534
            self.searched_specific_files.add(self.current_root)
1535
            # process the entries for this containing directory: the rest will be
1536
            # found by their parents recursively.
1537
            self.root_entries = self.state._entries_for_path(self.current_root)
1538
            self.root_entries_len = len(self.root_entries)
4570.2.3 by Robert Collins
Change the way iter_changes treats specific files to prevent InconsistentDeltas.
1539
            self.current_root_unicode = self.current_root.decode('utf8')
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1540
            self.root_abspath = self.tree.abspath(self.current_root_unicode)
1541
            try:
1542
                root_stat = os.lstat(self.root_abspath)
1543
            except OSError, e:
1544
                if e.errno == errno.ENOENT:
1545
                    # the path does not exist: let _process_entry know that.
1546
                    self.root_dir_info = None
1547
                else:
1548
                    # some other random error: hand it up.
1549
                    raise
1550
            else:
1551
                self.root_dir_info = ('', self.current_root,
1552
                    osutils.file_kind_from_stat_mode(root_stat.st_mode), root_stat,
1553
                    self.root_abspath)
1554
                if self.root_dir_info[2] == 'directory':
1555
                    if self.tree._directory_is_tree_reference(
1556
                        self.current_root_unicode):
1557
                        self.root_dir_info = self.root_dir_info[:2] + \
1558
                            ('tree-reference',) + self.root_dir_info[3:]
1559
            if not self.root_entries and not self.root_dir_info:
1560
                # this specified path is not present at all, skip it.
1561
                # (tail recursion, can do a loop once the full structure is
1562
                # known).
1563
                return self._iter_next()
3696.4.12 by Robert Collins
More Cification of iter_changes, smaller functions, explicit type usage.
1564
            path_handled = 0
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1565
            self.root_entries_pos = 0
1566
            # XXX Clarity: This loop is duplicated a out the self.current_root
1567
            # is None guard above: if we return from it, it completes there
1568
            # (and the following if block cannot trigger because
3696.4.12 by Robert Collins
More Cification of iter_changes, smaller functions, explicit type usage.
1569
            # path_handled must be true, so the if block is not # duplicated.
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1570
            while self.root_entries_pos < self.root_entries_len:
1571
                entry = self.root_entries[self.root_entries_pos]
1572
                self.root_entries_pos = self.root_entries_pos + 1
4570.2.1 by Robert Collins
Refactoring of dirstate iter_changes to make it possible to tell changed vs unchanged results internally.
1573
                result, changed = self._process_entry(entry, self.root_dir_info)
1574
                if changed is not None:
3696.4.12 by Robert Collins
More Cification of iter_changes, smaller functions, explicit type usage.
1575
                    path_handled = -1
4570.2.3 by Robert Collins
Change the way iter_changes treats specific files to prevent InconsistentDeltas.
1576
                    if changed:
1577
                        self._gather_result_for_consistency(result)
4570.2.1 by Robert Collins
Refactoring of dirstate iter_changes to make it possible to tell changed vs unchanged results internally.
1578
                    if changed or self.include_unchanged:
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1579
                        return result
1580
            # handle unversioned specified paths:
3696.4.12 by Robert Collins
More Cification of iter_changes, smaller functions, explicit type usage.
1581
            if self.want_unversioned and not path_handled and self.root_dir_info:
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1582
                new_executable = bool(
1583
                    stat.S_ISREG(self.root_dir_info[3].st_mode)
1584
                    and stat.S_IEXEC & self.root_dir_info[3].st_mode)
1585
                return (None,
1586
                       (None, self.current_root_unicode),
1587
                       True,
1588
                       (False, False),
1589
                       (None, None),
1590
                       (None, splitpath(self.current_root_unicode)[-1]),
1591
                       (None, self.root_dir_info[2]),
1592
                       (None, new_executable)
1593
                      )
1594
            # If we reach here, the outer flow continues, which enters into the
1595
            # per-root setup logic.
4570.2.3 by Robert Collins
Change the way iter_changes treats specific files to prevent InconsistentDeltas.
1596
        if (self.current_dir_info is None and self.current_block is None and not
4570.2.5 by Robert Collins
Review feedback, including finding a bug with changes at the root.
1597
            self.doing_consistency_expansion):
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1598
            # setup iteration of this root:
3696.4.12 by Robert Collins
More Cification of iter_changes, smaller functions, explicit type usage.
1599
            self.current_dir_list = None
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1600
            if self.root_dir_info and self.root_dir_info[2] == 'tree-reference':
1601
                self.current_dir_info = None
1602
            else:
1603
                self.dir_iterator = osutils._walkdirs_utf8(self.root_abspath,
1604
                    prefix=self.current_root)
1605
                self.path_index = 0
1606
                try:
1607
                    self.current_dir_info = self.dir_iterator.next()
3696.4.12 by Robert Collins
More Cification of iter_changes, smaller functions, explicit type usage.
1608
                    self.current_dir_list = self.current_dir_info[1]
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1609
                except OSError, e:
1610
                    # there may be directories in the inventory even though
1611
                    # this path is not a file on disk: so mark it as end of
1612
                    # iterator
1613
                    if e.errno in (errno.ENOENT, errno.ENOTDIR, errno.EINVAL):
1614
                        self.current_dir_info = None
1615
                    elif sys.platform == 'win32':
1616
                        # on win32, python2.4 has e.errno == ERROR_DIRECTORY, but
1617
                        # python 2.5 has e.errno == EINVAL,
1618
                        #            and e.winerror == ERROR_DIRECTORY
1619
                        try:
1620
                            e_winerror = e.winerror
4634.153.1 by John Arbash Meinel
Workaround a bug (#582656) in recent versions of Pyrex.
1621
                        except AttributeError, _:
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1622
                            e_winerror = None
1623
                        win_errors = (ERROR_DIRECTORY, ERROR_PATH_NOT_FOUND)
1624
                        if (e.errno in win_errors or e_winerror in win_errors):
1625
                            self.current_dir_info = None
1626
                        else:
1627
                            # Will this really raise the right exception ?
1628
                            raise
1629
                    else:
1630
                        raise
1631
                else:
1632
                    if self.current_dir_info[0][0] == '':
1633
                        # remove .bzr from iteration
3696.4.12 by Robert Collins
More Cification of iter_changes, smaller functions, explicit type usage.
1634
                        bzr_index = self.bisect_left(self.current_dir_list, ('.bzr',))
1635
                        if self.current_dir_list[bzr_index][0] != '.bzr':
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1636
                            raise AssertionError()
3696.4.12 by Robert Collins
More Cification of iter_changes, smaller functions, explicit type usage.
1637
                        del self.current_dir_list[bzr_index]
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1638
            initial_key = (self.current_root, '', '')
1639
            self.block_index, _ = self.state._find_block_index_from_key(initial_key)
1640
            if self.block_index == 0:
1641
                # we have processed the total root already, but because the
1642
                # initial key matched it we should skip it here.
1643
                self.block_index = self.block_index + 1
1644
            self._update_current_block()
1645
        # walk until both the directory listing and the versioned metadata
1646
        # are exhausted. 
1647
        while (self.current_dir_info is not None
1648
            or self.current_block is not None):
3696.4.12 by Robert Collins
More Cification of iter_changes, smaller functions, explicit type usage.
1649
            # Uncommon case - a missing directory or an unversioned directory:
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1650
            if (self.current_dir_info and self.current_block
1651
                and self.current_dir_info[0][0] != self.current_block[0]):
1652
                # Work around pyrex broken heuristic - current_dirname has
1653
                # the same scope as current_dirname_c
1654
                current_dirname = self.current_dir_info[0][0]
1655
                current_dirname_c = PyString_AS_STRING_void(
1656
                    <void *>current_dirname)
1657
                current_blockname = self.current_block[0]
1658
                current_blockname_c = PyString_AS_STRING_void(
1659
                    <void *>current_blockname)
1660
                # In the python generator we evaluate this if block once per
1661
                # dir+block; because we reenter in the pyrex version its being
1662
                # evaluated once per path: we could cache the result before
1663
                # doing the while loop and probably save time.
1664
                if _cmp_by_dirs(current_dirname_c,
1665
                    PyString_Size(current_dirname),
1666
                    current_blockname_c,
1667
                    PyString_Size(current_blockname)) < 0:
1668
                    # filesystem data refers to paths not covered by the
1669
                    # dirblock.  this has two possibilities:
1670
                    # A) it is versioned but empty, so there is no block for it
1671
                    # B) it is not versioned.
1672
1673
                    # if (A) then we need to recurse into it to check for
1674
                    # new unknown files or directories.
1675
                    # if (B) then we should ignore it, because we don't
1676
                    # recurse into unknown directories.
1677
                    # We are doing a loop
3696.4.12 by Robert Collins
More Cification of iter_changes, smaller functions, explicit type usage.
1678
                    while self.path_index < len(self.current_dir_list):
1679
                        current_path_info = self.current_dir_list[self.path_index]
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1680
                        # dont descend into this unversioned path if it is
1681
                        # a dir
1682
                        if current_path_info[2] in ('directory',
1683
                                                    'tree-reference'):
3696.4.12 by Robert Collins
More Cification of iter_changes, smaller functions, explicit type usage.
1684
                            del self.current_dir_list[self.path_index]
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1685
                            self.path_index = self.path_index - 1
1686
                        self.path_index = self.path_index + 1
1687
                        if self.want_unversioned:
1688
                            if current_path_info[2] == 'directory':
1689
                                if self.tree._directory_is_tree_reference(
1690
                                    self.utf8_decode(current_path_info[0])[0]):
1691
                                    current_path_info = current_path_info[:2] + \
1692
                                        ('tree-reference',) + current_path_info[3:]
1693
                            new_executable = bool(
1694
                                stat.S_ISREG(current_path_info[3].st_mode)
1695
                                and stat.S_IEXEC & current_path_info[3].st_mode)
1696
                            return (None,
1697
                                (None, self.utf8_decode(current_path_info[0])[0]),
1698
                                True,
1699
                                (False, False),
1700
                                (None, None),
1701
                                (None, self.utf8_decode(current_path_info[1])[0]),
1702
                                (None, current_path_info[2]),
1703
                                (None, new_executable))
1704
                    # This dir info has been handled, go to the next
1705
                    self.path_index = 0
3696.4.12 by Robert Collins
More Cification of iter_changes, smaller functions, explicit type usage.
1706
                    self.current_dir_list = None
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1707
                    try:
1708
                        self.current_dir_info = self.dir_iterator.next()
3696.4.12 by Robert Collins
More Cification of iter_changes, smaller functions, explicit type usage.
1709
                        self.current_dir_list = self.current_dir_info[1]
4634.153.1 by John Arbash Meinel
Workaround a bug (#582656) in recent versions of Pyrex.
1710
                    except StopIteration, _:
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1711
                        self.current_dir_info = None
1712
                else: #(dircmp > 0)
1713
                    # We have a dirblock entry for this location, but there
1714
                    # is no filesystem path for this. This is most likely
1715
                    # because a directory was removed from the disk.
1716
                    # We don't have to report the missing directory,
1717
                    # because that should have already been handled, but we
1718
                    # need to handle all of the files that are contained
1719
                    # within.
3696.4.12 by Robert Collins
More Cification of iter_changes, smaller functions, explicit type usage.
1720
                    while self.current_block_pos < len(self.current_block_list):
1721
                        current_entry = self.current_block_list[self.current_block_pos]
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1722
                        self.current_block_pos = self.current_block_pos + 1
1723
                        # entry referring to file not present on disk.
1724
                        # advance the entry only, after processing.
4570.2.1 by Robert Collins
Refactoring of dirstate iter_changes to make it possible to tell changed vs unchanged results internally.
1725
                        result, changed = self._process_entry(current_entry, None)
1726
                        if changed is not None:
4570.2.3 by Robert Collins
Change the way iter_changes treats specific files to prevent InconsistentDeltas.
1727
                            if changed:
1728
                                self._gather_result_for_consistency(result)
4570.2.1 by Robert Collins
Refactoring of dirstate iter_changes to make it possible to tell changed vs unchanged results internally.
1729
                            if changed or self.include_unchanged:
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1730
                                return result
1731
                    self.block_index = self.block_index + 1
1732
                    self._update_current_block()
1733
                continue # next loop-on-block/dir
3696.4.12 by Robert Collins
More Cification of iter_changes, smaller functions, explicit type usage.
1734
            result = self._loop_one_block()
1735
            if result is not None:
1736
                return result
1737
        if len(self.search_specific_files):
1738
            # More supplied paths to process
1739
            self.current_root = None
1740
            return self._iter_next()
4570.2.3 by Robert Collins
Change the way iter_changes treats specific files to prevent InconsistentDeltas.
1741
        # Start expanding more conservatively, adding paths the user may not
1742
        # have intended but required for consistent deltas.
4570.2.5 by Robert Collins
Review feedback, including finding a bug with changes at the root.
1743
        self.doing_consistency_expansion = 1
1744
        if not self._pending_consistent_entries:
1745
            self._pending_consistent_entries = self._next_consistent_entries()
1746
        while self._pending_consistent_entries:
1747
            result, changed = self._pending_consistent_entries.pop()
4570.2.3 by Robert Collins
Change the way iter_changes treats specific files to prevent InconsistentDeltas.
1748
            if changed is not None:
1749
                return result
3696.4.12 by Robert Collins
More Cification of iter_changes, smaller functions, explicit type usage.
1750
        raise StopIteration()
1751
1752
    cdef object _maybe_tree_ref(self, current_path_info):
1753
        if self.tree._directory_is_tree_reference(
1754
            self.utf8_decode(current_path_info[0])[0]):
1755
            return current_path_info[:2] + \
1756
                ('tree-reference',) + current_path_info[3:]
1757
        else:
1758
            return current_path_info
1759
1760
    cdef object _loop_one_block(self):
3696.4.11 by Robert Collins
Some Cification of iter_changes, and making the python one actually work.
1761
            # current_dir_info and current_block refer to the same directory -
1762
            # this is the common case code.
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1763
            # Assign local variables for current path and entry:
3696.4.12 by Robert Collins
More Cification of iter_changes, smaller functions, explicit type usage.
1764
            cdef object current_entry
1765
            cdef object current_path_info
1766
            cdef int path_handled
3696.4.13 by Robert Collins
More Cification, removing redundant string comparisons
1767
            cdef char minikind
1768
            cdef int cmp_result
3696.4.12 by Robert Collins
More Cification of iter_changes, smaller functions, explicit type usage.
1769
            # cdef char * temp_str
1770
            # cdef Py_ssize_t temp_str_length
1771
            # PyString_AsStringAndSize(disk_kind, &temp_str, &temp_str_length)
1772
            # if not strncmp(temp_str, "directory", temp_str_length):
1773
            if (self.current_block is not None and
1774
                self.current_block_pos < PyList_GET_SIZE(self.current_block_list)):
1775
                current_entry = PyList_GET_ITEM(self.current_block_list,
1776
                    self.current_block_pos)
1777
                # accomodate pyrex
1778
                Py_INCREF(current_entry)
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1779
            else:
1780
                current_entry = None
3696.4.12 by Robert Collins
More Cification of iter_changes, smaller functions, explicit type usage.
1781
            if (self.current_dir_info is not None and
1782
                self.path_index < PyList_GET_SIZE(self.current_dir_list)):
1783
                current_path_info = PyList_GET_ITEM(self.current_dir_list,
1784
                    self.path_index)
1785
                # accomodate pyrex
1786
                Py_INCREF(current_path_info)
1787
                disk_kind = PyTuple_GET_ITEM(current_path_info, 2)
1788
                # accomodate pyrex
1789
                Py_INCREF(disk_kind)
1790
                if disk_kind == "directory":
1791
                    current_path_info = self._maybe_tree_ref(current_path_info)
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1792
            else:
1793
                current_path_info = None
1794
            while (current_entry is not None or current_path_info is not None):
3696.4.11 by Robert Collins
Some Cification of iter_changes, and making the python one actually work.
1795
                advance_entry = -1
1796
                advance_path = -1
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1797
                result = None
6015.41.2 by Denys Duchier
Fix compatibility with new Cython that doesn't init local vars to None
1798
                changed = None
3696.4.12 by Robert Collins
More Cification of iter_changes, smaller functions, explicit type usage.
1799
                path_handled = 0
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1800
                if current_entry is None:
1801
                    # unversioned -  the check for path_handled when the path
1802
                    # is advanced will yield this path if needed.
1803
                    pass
1804
                elif current_path_info is None:
1805
                    # no path is fine: the per entry code will handle it.
4570.2.1 by Robert Collins
Refactoring of dirstate iter_changes to make it possible to tell changed vs unchanged results internally.
1806
                    result, changed = self._process_entry(current_entry,
1807
                        current_path_info)
3696.4.13 by Robert Collins
More Cification, removing redundant string comparisons
1808
                else:
1809
                    minikind = _minikind_from_string(
1810
                        current_entry[1][self.target_index][0])
1811
                    cmp_result = cmp(current_path_info[1], current_entry[0][1])
1812
                    if (cmp_result or minikind == c'a' or minikind == c'r'):
1813
                        # The current path on disk doesn't match the dirblock
1814
                        # record. Either the dirblock record is marked as
1815
                        # absent/renamed, or the file on disk is not present at all
1816
                        # in the dirblock. Either way, report about the dirblock
1817
                        # entry, and let other code handle the filesystem one.
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1818
3696.4.13 by Robert Collins
More Cification, removing redundant string comparisons
1819
                        # Compare the basename for these files to determine
1820
                        # which comes first
1821
                        if cmp_result < 0:
1822
                            # extra file on disk: pass for now, but only
1823
                            # increment the path, not the entry
1824
                            advance_entry = 0
1825
                        else:
1826
                            # entry referring to file not present on disk.
1827
                            # advance the entry only, after processing.
4570.2.1 by Robert Collins
Refactoring of dirstate iter_changes to make it possible to tell changed vs unchanged results internally.
1828
                            result, changed = self._process_entry(current_entry,
1829
                                None)
3696.4.13 by Robert Collins
More Cification, removing redundant string comparisons
1830
                            advance_path = 0
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1831
                    else:
3696.4.13 by Robert Collins
More Cification, removing redundant string comparisons
1832
                        # paths are the same,and the dirstate entry is not
1833
                        # absent or renamed.
4570.2.1 by Robert Collins
Refactoring of dirstate iter_changes to make it possible to tell changed vs unchanged results internally.
1834
                        result, changed = self._process_entry(current_entry,
1835
                            current_path_info)
1836
                        if changed is not None:
3696.4.13 by Robert Collins
More Cification, removing redundant string comparisons
1837
                            path_handled = -1
4570.2.3 by Robert Collins
Change the way iter_changes treats specific files to prevent InconsistentDeltas.
1838
                            if not changed and not self.include_unchanged:
1839
                                changed = None
3696.4.11 by Robert Collins
Some Cification of iter_changes, and making the python one actually work.
1840
                # >- loop control starts here:
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1841
                # >- entry
1842
                if advance_entry and current_entry is not None:
1843
                    self.current_block_pos = self.current_block_pos + 1
3696.4.12 by Robert Collins
More Cification of iter_changes, smaller functions, explicit type usage.
1844
                    if self.current_block_pos < PyList_GET_SIZE(self.current_block_list):
1845
                        current_entry = self.current_block_list[self.current_block_pos]
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1846
                    else:
1847
                        current_entry = None
1848
                # >- path
1849
                if advance_path and current_path_info is not None:
3696.4.12 by Robert Collins
More Cification of iter_changes, smaller functions, explicit type usage.
1850
                    if not path_handled:
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1851
                        # unversioned in all regards
1852
                        if self.want_unversioned:
1853
                            new_executable = bool(
1854
                                stat.S_ISREG(current_path_info[3].st_mode)
1855
                                and stat.S_IEXEC & current_path_info[3].st_mode)
1856
                            try:
1857
                                relpath_unicode = self.utf8_decode(current_path_info[0])[0]
4634.153.1 by John Arbash Meinel
Workaround a bug (#582656) in recent versions of Pyrex.
1858
                            except UnicodeDecodeError, _:
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1859
                                raise errors.BadFilenameEncoding(
1860
                                    current_path_info[0], osutils._fs_enc)
4570.2.3 by Robert Collins
Change the way iter_changes treats specific files to prevent InconsistentDeltas.
1861
                            if changed is not None:
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1862
                                raise AssertionError(
1863
                                    "result is not None: %r" % result)
1864
                            result = (None,
1865
                                (None, relpath_unicode),
1866
                                True,
1867
                                (False, False),
1868
                                (None, None),
1869
                                (None, self.utf8_decode(current_path_info[1])[0]),
1870
                                (None, current_path_info[2]),
1871
                                (None, new_executable))
4570.2.3 by Robert Collins
Change the way iter_changes treats specific files to prevent InconsistentDeltas.
1872
                            changed = True
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1873
                        # dont descend into this unversioned path if it is
1874
                        # a dir
1875
                        if current_path_info[2] in ('directory'):
3696.4.12 by Robert Collins
More Cification of iter_changes, smaller functions, explicit type usage.
1876
                            del self.current_dir_list[self.path_index]
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1877
                            self.path_index = self.path_index - 1
1878
                    # dont descend the disk iterator into any tree 
1879
                    # paths.
1880
                    if current_path_info[2] == 'tree-reference':
3696.4.12 by Robert Collins
More Cification of iter_changes, smaller functions, explicit type usage.
1881
                        del self.current_dir_list[self.path_index]
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1882
                        self.path_index = self.path_index - 1
1883
                    self.path_index = self.path_index + 1
3696.4.12 by Robert Collins
More Cification of iter_changes, smaller functions, explicit type usage.
1884
                    if self.path_index < len(self.current_dir_list):
1885
                        current_path_info = self.current_dir_list[self.path_index]
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1886
                        if current_path_info[2] == 'directory':
3696.4.12 by Robert Collins
More Cification of iter_changes, smaller functions, explicit type usage.
1887
                            current_path_info = self._maybe_tree_ref(
1888
                                current_path_info)
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1889
                    else:
1890
                        current_path_info = None
4570.2.3 by Robert Collins
Change the way iter_changes treats specific files to prevent InconsistentDeltas.
1891
                if changed is not None:
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1892
                    # Found a result on this pass, yield it
4570.2.3 by Robert Collins
Change the way iter_changes treats specific files to prevent InconsistentDeltas.
1893
                    if changed:
1894
                        self._gather_result_for_consistency(result)
1895
                    if changed or self.include_unchanged:
1896
                        return result
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1897
            if self.current_block is not None:
1898
                self.block_index = self.block_index + 1
1899
                self._update_current_block()
1900
            if self.current_dir_info is not None:
1901
                self.path_index = 0
3696.4.12 by Robert Collins
More Cification of iter_changes, smaller functions, explicit type usage.
1902
                self.current_dir_list = None
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1903
                try:
1904
                    self.current_dir_info = self.dir_iterator.next()
3696.4.12 by Robert Collins
More Cification of iter_changes, smaller functions, explicit type usage.
1905
                    self.current_dir_list = self.current_dir_info[1]
4634.153.1 by John Arbash Meinel
Workaround a bug (#582656) in recent versions of Pyrex.
1906
                except StopIteration, _:
3696.4.10 by Robert Collins
Basic first cut of full-pyrex iter_changes.
1907
                    self.current_dir_info = None
4570.2.3 by Robert Collins
Change the way iter_changes treats specific files to prevent InconsistentDeltas.
1908
4570.2.5 by Robert Collins
Review feedback, including finding a bug with changes at the root.
1909
    cdef object _next_consistent_entries(self):
4570.2.3 by Robert Collins
Change the way iter_changes treats specific files to prevent InconsistentDeltas.
1910
        """Grabs the next specific file parent case to consider.
1911
        
1912
        :return: A list of the results, each of which is as for _process_entry.
1913
        """
1914
        results = []
1915
        while self.search_specific_file_parents:
1916
            # Process the parent directories for the paths we were iterating.
1917
            # Even in extremely large trees this should be modest, so currently
1918
            # no attempt is made to optimise.
1919
            path_utf8 = self.search_specific_file_parents.pop()
4570.2.5 by Robert Collins
Review feedback, including finding a bug with changes at the root.
1920
            if path_utf8 in self.searched_exact_paths:
1921
                # We've examined this path.
1922
                continue
4570.2.3 by Robert Collins
Change the way iter_changes treats specific files to prevent InconsistentDeltas.
1923
            if osutils.is_inside_any(self.searched_specific_files, path_utf8):
1924
                # We've examined this path.
1925
                continue
1926
            path_entries = self.state._entries_for_path(path_utf8)
1927
            # We need either one or two entries. If the path in
1928
            # self.target_index has moved (so the entry in source_index is in
1929
            # 'ar') then we need to also look for the entry for this path in
1930
            # self.source_index, to output the appropriate delete-or-rename.
1931
            selected_entries = []
1932
            found_item = False
1933
            for candidate_entry in path_entries:
1934
                # Find entries present in target at this path:
1935
                if candidate_entry[1][self.target_index][0] not in 'ar':
1936
                    found_item = True
1937
                    selected_entries.append(candidate_entry)
1938
                # Find entries present in source at this path:
1939
                elif (self.source_index is not None and
1940
                    candidate_entry[1][self.source_index][0] not in 'ar'):
1941
                    found_item = True
1942
                    if candidate_entry[1][self.target_index][0] == 'a':
1943
                        # Deleted, emit it here.
1944
                        selected_entries.append(candidate_entry)
1945
                    else:
1946
                        # renamed, emit it when we process the directory it
1947
                        # ended up at.
1948
                        self.search_specific_file_parents.add(
1949
                            candidate_entry[1][self.target_index][1])
1950
            if not found_item:
1951
                raise AssertionError(
1952
                    "Missing entry for specific path parent %r, %r" % (
1953
                    path_utf8, path_entries))
1954
            path_info = self._path_info(path_utf8, path_utf8.decode('utf8'))
1955
            for entry in selected_entries:
1956
                if entry[0][2] in self.seen_ids:
1957
                    continue
1958
                result, changed = self._process_entry(entry, path_info)
1959
                if changed is None:
1960
                    raise AssertionError(
1961
                        "Got entry<->path mismatch for specific path "
1962
                        "%r entry %r path_info %r " % (
1963
                        path_utf8, entry, path_info))
1964
                # Only include changes - we're outside the users requested
1965
                # expansion.
1966
                if changed:
1967
                    self._gather_result_for_consistency(result)
1968
                    if (result[6][0] == 'directory' and
1969
                        result[6][1] != 'directory'):
1970
                        # This stopped being a directory, the old children have
1971
                        # to be included.
1972
                        if entry[1][self.source_index][0] == 'r':
1973
                            # renamed, take the source path
1974
                            entry_path_utf8 = entry[1][self.source_index][1]
1975
                        else:
1976
                            entry_path_utf8 = path_utf8
1977
                        initial_key = (entry_path_utf8, '', '')
1978
                        block_index, _ = self.state._find_block_index_from_key(
1979
                            initial_key)
1980
                        if block_index == 0:
1981
                            # The children of the root are in block index 1.
4570.2.4 by Robert Collins
Older pyrex compatibility.
1982
                            block_index = block_index + 1
4570.2.3 by Robert Collins
Change the way iter_changes treats specific files to prevent InconsistentDeltas.
1983
                        current_block = None
1984
                        if block_index < len(self.state._dirblocks):
1985
                            current_block = self.state._dirblocks[block_index]
1986
                            if not osutils.is_inside(
1987
                                entry_path_utf8, current_block[0]):
1988
                                # No entries for this directory at all.
1989
                                current_block = None
1990
                        if current_block is not None:
1991
                            for entry in current_block[1]:
1992
                                if entry[1][self.source_index][0] in 'ar':
1993
                                    # Not in the source tree, so doesn't have to be
1994
                                    # included.
1995
                                    continue
1996
                                # Path of the entry itself.
1997
                                self.search_specific_file_parents.add(
4570.2.5 by Robert Collins
Review feedback, including finding a bug with changes at the root.
1998
                                    self.pathjoin(*entry[0][:2]))
4570.2.3 by Robert Collins
Change the way iter_changes treats specific files to prevent InconsistentDeltas.
1999
                if changed or self.include_unchanged:
2000
                    results.append((result, changed))
2001
            self.searched_exact_paths.add(path_utf8)
2002
        return results
2003
2004
    cdef object _path_info(self, utf8_path, unicode_path):
2005
        """Generate path_info for unicode_path.
2006
2007
        :return: None if unicode_path does not exist, or a path_info tuple.
2008
        """
2009
        abspath = self.tree.abspath(unicode_path)
2010
        try:
2011
            stat = os.lstat(abspath)
2012
        except OSError, e:
2013
            if e.errno == errno.ENOENT:
2014
                # the path does not exist.
2015
                return None
2016
            else:
2017
                raise
2018
        utf8_basename = utf8_path.rsplit('/', 1)[-1]
2019
        dir_info = (utf8_path, utf8_basename,
2020
            osutils.file_kind_from_stat_mode(stat.st_mode), stat,
2021
            abspath)
2022
        if dir_info[2] == 'directory':
2023
            if self.tree._directory_is_tree_reference(
2024
                unicode_path):
2025
                self.root_dir_info = self.root_dir_info[:2] + \
2026
                    ('tree-reference',) + self.root_dir_info[3:]
2027
        return dir_info