~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/_dirstate_helpers_pyx.pyx

  • Committer: Patch Queue Manager
  • Date: 2016-01-15 09:21:49 UTC
  • mfrom: (6606.2.1 autodoc-unicode)
  • Revision ID: pqm@pqm.ubuntu.com-20160115092149-z5f4sfq3jvaz0enb
(vila) Fix autodoc runner when LANG=C. (Jelmer Vernooij)

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2007-2010 Canonical Ltd
 
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
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
 
17
"""Helper functions for DirState.
 
18
 
 
19
This is the python implementation for DirState functions.
 
20
"""
 
21
 
 
22
import binascii
 
23
import bisect
 
24
import errno
 
25
import os
 
26
import stat
 
27
import sys
 
28
 
 
29
from bzrlib import cache_utf8, errors, osutils
 
30
from bzrlib.dirstate import DirState
 
31
from bzrlib.osutils import parent_directories, pathjoin, splitpath
 
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
 
42
 
 
43
#python2.4 support, and other platform-dependent includes
 
44
cdef extern from "python-compat.h":
 
45
    unsigned long htonl(unsigned long)
 
46
 
 
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
 
 
54
cdef extern from *:
 
55
    ctypedef unsigned long size_t
 
56
 
 
57
cdef extern from "_dirstate_helpers_pyx.h":
 
58
    ctypedef int intptr_t
 
59
 
 
60
 
 
61
 
 
62
cdef extern from "stdlib.h":
 
63
    unsigned long int strtoul(char *nptr, char **endptr, int base)
 
64
 
 
65
 
 
66
cdef extern from 'sys/stat.h':
 
67
    int S_ISDIR(int mode)
 
68
    int S_ISREG(int mode)
 
69
    # On win32, this actually comes from "python-compat.h"
 
70
    int S_ISLNK(int mode)
 
71
    int S_IXUSR
 
72
 
 
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.
 
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.
 
85
cdef extern from "Python.h":
 
86
    ctypedef int Py_ssize_t
 
87
    ctypedef struct PyObject:
 
88
        pass
 
89
    int PyList_Append(object lst, object item) except -1
 
90
    void *PyList_GetItem_object_void "PyList_GET_ITEM" (object lst, int index)
 
91
    void *PyList_GetItem_void_void "PyList_GET_ITEM" (void * lst, int index)
 
92
    object PyList_GET_ITEM(object lst, Py_ssize_t index)
 
93
    int PyList_CheckExact(object)
 
94
    Py_ssize_t PyList_GET_SIZE (object p)
 
95
 
 
96
    void *PyTuple_GetItem_void_void "PyTuple_GET_ITEM" (void* tpl, int index)
 
97
    object PyTuple_GetItem_void_object "PyTuple_GET_ITEM" (void* tpl, int index)
 
98
    object PyTuple_GET_ITEM(object tpl, Py_ssize_t index)
 
99
 
 
100
    unsigned long PyInt_AsUnsignedLongMask(object number) except? -1
 
101
 
 
102
    char *PyString_AsString(object p)
 
103
    char *PyString_AsString_obj "PyString_AsString" (PyObject *string)
 
104
    char *PyString_AS_STRING_void "PyString_AS_STRING" (void *p)
 
105
    int PyString_AsStringAndSize(object str, char **buffer, Py_ssize_t *length) except -1
 
106
    object PyString_FromString(char *)
 
107
    object PyString_FromStringAndSize(char *, Py_ssize_t)
 
108
    int PyString_Size(object p)
 
109
    int PyString_GET_SIZE_void "PyString_GET_SIZE" (void *p)
 
110
    int PyString_CheckExact(object p)
 
111
    void Py_INCREF(object o)
 
112
    void Py_DECREF(object o)
 
113
 
 
114
 
 
115
cdef extern from "string.h":
 
116
    int strncmp(char *s1, char *s2, int len)
 
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
 
 
122
# cimport all of the definitions we will need to access
 
123
from _static_tuple_c cimport import_static_tuple_c, StaticTuple, \
 
124
    StaticTuple_New, StaticTuple_SET_ITEM
 
125
 
 
126
import_static_tuple_c()
 
127
 
 
128
cdef void* _my_memrchr(void *s, int c, size_t n): # cannot_raise
 
129
    # memrchr seems to be a GNU extension, so we have to implement it ourselves
 
130
    cdef char *pos
 
131
    cdef char *start
 
132
 
 
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
 
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
 
163
    return <char*>found - <char*>_s
 
164
 
 
165
 
 
166
cdef object safe_string_from_size(char *s, Py_ssize_t size):
 
167
    if size < 0:
 
168
        raise AssertionError(
 
169
            'tried to create a string with an invalid size: %d'
 
170
            % (size))
 
171
    return PyString_FromStringAndSize(s, size)
 
172
 
 
173
 
 
174
cdef int _is_aligned(void *ptr): # cannot_raise
 
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
 
 
182
cdef int _cmp_by_dirs(char *path1, int size1, char *path2, int size2): # cannot_raise
 
183
    cdef unsigned char *cur1
 
184
    cdef unsigned char *cur2
 
185
    cdef unsigned char *end1
 
186
    cdef unsigned char *end2
 
187
    cdef int *cur_int1
 
188
    cdef int *cur_int2
 
189
    cdef int *end_int1
 
190
    cdef int *end_int2
 
191
 
 
192
    if path1 == path2 and size1 == size2:
 
193
        return 0
 
194
 
 
195
    end1 = <unsigned char*>path1+size1
 
196
    end2 = <unsigned char*>path2+size2
 
197
 
 
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.
 
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
 
206
        end_int1 = <int*>(path1 + size1 - (size1 % sizeof(int)))
 
207
        end_int2 = <int*>(path2 + size2 - (size2 % sizeof(int)))
 
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
 
 
215
        cur1 = <unsigned char*>cur_int1
 
216
        cur2 = <unsigned char*>cur_int2
 
217
    else:
 
218
        cur1 = <unsigned char*>path1
 
219
        cur2 = <unsigned char*>path2
 
220
 
 
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'/':
 
229
            return -1 # Reached the end of path1 segment first
 
230
        elif cur2[0] == c'/':
 
231
            return 1 # Reached the end of path2 segment first
 
232
        elif cur1[0] < cur2[0]:
 
233
            return -1
 
234
        else:
 
235
            return 1
 
236
 
 
237
    # We reached the end of at least one of the strings
 
238
    if cur1 < end1:
 
239
        return 1 # Not at the end of cur1, must be at the end of cur2
 
240
    if cur2 < end2:
 
241
        return -1 # At the end of cur1, but not at cur2
 
242
    # We reached the end of both strings
 
243
    return 0
 
244
 
 
245
 
 
246
def cmp_by_dirs(path1, path2):
 
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
 
259
    :return: negative number if ``path1`` comes first,
 
260
        0 if paths are equal,
 
261
        and positive number if ``path2`` sorts first
 
262
    """
 
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))
 
269
    return _cmp_by_dirs(PyString_AsString(path1),
 
270
                        PyString_Size(path1),
 
271
                        PyString_AsString(path2),
 
272
                        PyString_Size(path2))
 
273
 
 
274
 
 
275
def _cmp_path_by_dirblock(path1, path2):
 
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
 
 
282
    In other words, all entries in a directory are sorted together, and
 
283
    directorys are sorted in cmp_by_dirs order.
 
284
 
 
285
    :param path1: first path
 
286
    :param path2: the second path
 
287
    :return: negative number if ``path1`` comes first,
 
288
        0 if paths are equal
 
289
        and a positive number if ``path2`` sorts first
 
290
    """
 
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))
 
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,
 
304
                                      char *path2, int path2_len): # cannot_raise
 
305
    """Compare two paths by what directory they are in.
 
306
 
 
307
    see ``_cmp_path_by_dirblock`` for details.
 
308
    """
 
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
 
 
323
    if path1 == path2 and path1_len == path2_len:
 
324
        return 0
 
325
 
 
326
    if path1_len == 0:
 
327
        return -1
 
328
 
 
329
    if path2_len == 0:
 
330
        return 1
 
331
 
 
332
    basename1 = <char*>_my_memrchr(path1, c'/', path1_len)
 
333
 
 
334
    if basename1 == NULL:
 
335
        basename1 = path1
 
336
        basename1_len = path1_len
 
337
        dirname1 = ''
 
338
        dirname1_len = 0
 
339
    else:
 
340
        dirname1 = path1
 
341
        dirname1_len = basename1 - path1
 
342
        basename1 = basename1 + 1
 
343
        basename1_len = path1_len - dirname1_len - 1
 
344
 
 
345
    basename2 = <char*>_my_memrchr(path2, c'/', path2_len)
 
346
 
 
347
    if basename2 == NULL:
 
348
        basename2 = path2
 
349
        basename2_len = path2_len
 
350
        dirname2 = ''
 
351
        dirname2_len = 0
 
352
    else:
 
353
        dirname2 = path2
 
354
        dirname2_len = basename2 - path2
 
355
        basename2 = basename2 + 1
 
356
        basename2_len = path2_len - dirname2_len - 1
 
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
 
 
377
def _bisect_path_left(paths, path):
 
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
 
398
    cdef char *path_cstr
 
399
    cdef int path_size
 
400
    cdef char *cur_cstr
 
401
    cdef int cur_size
 
402
    cdef void *cur
 
403
 
 
404
    if not PyList_CheckExact(paths):
 
405
        raise TypeError("you must pass a python list for 'paths' not: %s %r"
 
406
                        % (type(paths), paths))
 
407
    if not PyString_CheckExact(path):
 
408
        raise TypeError("you must pass a string for 'path' not: %s %r"
 
409
                        % (type(path), path))
 
410
 
 
411
    _hi = len(paths)
 
412
    _lo = 0
 
413
 
 
414
    path_cstr = PyString_AsString(path)
 
415
    path_size = PyString_Size(path)
 
416
 
 
417
    while _lo < _hi:
 
418
        _mid = (_lo + _hi) / 2
 
419
        cur = PyList_GetItem_object_void(paths, _mid)
 
420
        cur_cstr = PyString_AS_STRING_void(cur)
 
421
        cur_size = PyString_GET_SIZE_void(cur)
 
422
        if _cmp_path_by_dirblock_intern(cur_cstr, cur_size,
 
423
                                        path_cstr, path_size) < 0:
 
424
            _lo = _mid + 1
 
425
        else:
 
426
            _hi = _mid
 
427
    return _lo
 
428
 
 
429
 
 
430
def _bisect_path_right(paths, path):
 
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
 
451
    cdef char *path_cstr
 
452
    cdef int path_size
 
453
    cdef char *cur_cstr
 
454
    cdef int cur_size
 
455
    cdef void *cur
 
456
 
 
457
    if not PyList_CheckExact(paths):
 
458
        raise TypeError("you must pass a python list for 'paths' not: %s %r"
 
459
                        % (type(paths), paths))
 
460
    if not PyString_CheckExact(path):
 
461
        raise TypeError("you must pass a string for 'path' not: %s %r"
 
462
                        % (type(path), path))
 
463
 
 
464
    _hi = len(paths)
 
465
    _lo = 0
 
466
 
 
467
    path_cstr = PyString_AsString(path)
 
468
    path_size = PyString_Size(path)
 
469
 
 
470
    while _lo < _hi:
 
471
        _mid = (_lo + _hi) / 2
 
472
        cur = PyList_GetItem_object_void(paths, _mid)
 
473
        cur_cstr = PyString_AS_STRING_void(cur)
 
474
        cur_size = PyString_GET_SIZE_void(cur)
 
475
        if _cmp_path_by_dirblock_intern(path_cstr, path_size,
 
476
                                        cur_cstr, cur_size) < 0:
 
477
            _hi = _mid
 
478
        else:
 
479
            _lo = _mid + 1
 
480
    return _lo
 
481
 
 
482
 
 
483
def bisect_dirblock(dirblocks, dirname, lo=0, hi=None, cache=None):
 
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
 
496
    cdef char *dirname_cstr
 
497
    cdef int dirname_size
 
498
    cdef char *cur_cstr
 
499
    cdef int cur_size
 
500
    cdef void *cur
 
501
 
 
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))
 
508
    if hi is None:
 
509
        _hi = len(dirblocks)
 
510
    else:
 
511
        _hi = hi
 
512
 
 
513
    _lo = lo
 
514
    dirname_cstr = PyString_AsString(dirname)
 
515
    dirname_size = PyString_Size(dirname)
 
516
 
 
517
    while _lo < _hi:
 
518
        _mid = (_lo + _hi) / 2
 
519
        # Grab the dirname for the current dirblock
 
520
        # cur = dirblocks[_mid][0]
 
521
        cur = PyTuple_GetItem_void_void(
 
522
                PyList_GetItem_object_void(dirblocks, _mid), 0)
 
523
        cur_cstr = PyString_AS_STRING_void(cur)
 
524
        cur_size = PyString_GET_SIZE_void(cur)
 
525
        if _cmp_by_dirs(cur_cstr, cur_size, dirname_cstr, dirname_size) < 0:
 
526
            _lo = _mid + 1
 
527
        else:
 
528
            _hi = _mid
 
529
    return _lo
 
530
 
 
531
 
 
532
cdef class Reader:
 
533
    """Maintain the current location, and return fields as you parse them."""
 
534
 
 
535
    cdef object state # The DirState object
 
536
    cdef object text # The overall string object
 
537
    cdef char *text_cstr # Pointer to the beginning of text
 
538
    cdef int text_size # Length of text
 
539
 
 
540
    cdef char *end_cstr # End of text
 
541
    cdef char *cur_cstr # Pointer to the current record
 
542
    cdef char *next # Pointer to the end of this record
 
543
 
 
544
    def __init__(self, text, state):
 
545
        self.state = state
 
546
        self.text = text
 
547
        self.text_cstr = PyString_AsString(text)
 
548
        self.text_size = PyString_Size(text)
 
549
        self.end_cstr = self.text_cstr + self.text_size
 
550
        self.cur_cstr = self.text_cstr
 
551
 
 
552
    cdef char *get_next(self, int *size) except NULL:
 
553
        """Return a pointer to the start of the next field."""
 
554
        cdef char *next
 
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')
 
562
        next = self.cur_cstr
 
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
 
566
            raise errors.DirstateCorrupt(self.state,
 
567
                'failed to find trailing NULL (\\0).'
 
568
                ' Trailing garbage: %r'
 
569
                % safe_string_from_size(next, extra_len))
 
570
        size[0] = self.cur_cstr - next
 
571
        self.cur_cstr = self.cur_cstr + 1
 
572
        return next
 
573
 
 
574
    cdef object get_next_str(self):
 
575
        """Get the next field as a Python string."""
 
576
        cdef int size
 
577
        cdef char *next
 
578
        next = self.get_next(&size)
 
579
        return safe_string_from_size(next, size)
 
580
 
 
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
        """
 
589
        cdef char *first
 
590
        cdef int size
 
591
        # The first field should be an empty string left over from the Header
 
592
        first = self.get_next(&size)
 
593
        if first[0] != c'\0' and size == 0:
 
594
            raise AssertionError('First character should be null not: %s'
 
595
                                 % (first,))
 
596
        return 0
 
597
 
 
598
    cdef object _get_entry(self, int num_trees, void **p_current_dirname,
 
599
                           int *new_block):
 
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
        """
 
619
        cdef StaticTuple path_name_file_id_key
 
620
        cdef StaticTuple tmp
 
621
        cdef char *entry_size_cstr
 
622
        cdef unsigned long int entry_size
 
623
        cdef char* executable_cstr
 
624
        cdef int is_executable
 
625
        cdef char* dirname_cstr
 
626
        cdef char* trailing
 
627
        cdef int cur_size
 
628
        cdef int i
 
629
        cdef object minikind
 
630
        cdef object fingerprint
 
631
        cdef object info
 
632
 
 
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):
 
651
            dirname = safe_string_from_size(dirname_cstr, cur_size)
 
652
            p_current_dirname[0] = <void*>dirname
 
653
            new_block[0] = 1
 
654
        else:
 
655
            new_block[0] = 0
 
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.
 
660
        cur_dirname = <object>p_current_dirname[0]
 
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
        #                         )
 
667
        tmp = StaticTuple_New(3)
 
668
        Py_INCREF(cur_dirname); StaticTuple_SET_ITEM(tmp, 0, cur_dirname)
 
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)
 
673
        path_name_file_id_key = tmp
 
674
 
 
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.
 
688
        trees = []
 
689
        for i from 0 <= i < num_trees:
 
690
            minikind = self.get_next_str()
 
691
            fingerprint = self.get_next_str()
 
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')
 
696
            info = self.get_next_str()
 
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.
 
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)
 
710
            PyList_Append(trees, StaticTuple(
 
711
                minikind,     # minikind
 
712
                fingerprint,  # fingerprint
 
713
                entry_size,   # size
 
714
                is_executable,# executable
 
715
                info,         # packed_stat or revision_id
 
716
            ))
 
717
 
 
718
        # The returned tuple is (key, [trees])
 
719
        ret = (path_name_file_id_key, trees)
 
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.
 
723
        trailing = self.get_next(&cur_size)
 
724
        if cur_size != 1 or trailing[0] != c'\n':
 
725
            raise errors.DirstateCorrupt(self.state,
 
726
                'Bad parse, we expected to end on \\n, not: %d %s: %s'
 
727
                % (cur_size, safe_string_from_size(trailing, cur_size),
 
728
                   ret))
 
729
        return ret
 
730
 
 
731
    def _parse_dirblocks(self):
 
732
        """Parse all dirblocks in the state file."""
 
733
        cdef int num_trees
 
734
        cdef object current_block
 
735
        cdef object entry
 
736
        cdef void * current_dirname
 
737
        cdef int new_block
 
738
        cdef int expected_entry_count
 
739
        cdef int entry_count
 
740
 
 
741
        num_trees = self.state._num_present_parents() + 1
 
742
        expected_entry_count = self.state._num_entries
 
743
 
 
744
        # Ignore the first record
 
745
        self._init()
 
746
 
 
747
        current_block = []
 
748
        dirblocks = [('', current_block), ('', [])]
 
749
        self.state._dirblocks = dirblocks
 
750
        obj = ''
 
751
        current_dirname = <void*>obj
 
752
        new_block = 0
 
753
        entry_count = 0
 
754
 
 
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.
 
762
        while self.cur_cstr < self.end_cstr:
 
763
            entry = self._get_entry(num_trees, &current_dirname, &new_block)
 
764
            if new_block:
 
765
                # new block - different dirname
 
766
                current_block = []
 
767
                PyList_Append(dirblocks,
 
768
                              (<object>current_dirname, current_block))
 
769
            PyList_Append(current_block, entry)
 
770
            entry_count = entry_count + 1
 
771
        if entry_count != expected_entry_count:
 
772
            raise errors.DirstateCorrupt(self.state,
 
773
                    'We read the wrong number of entries.'
 
774
                    ' We expected to read %s, but read %s'
 
775
                    % (expected_entry_count, entry_count))
 
776
        self.state._split_root_dirblock_into_contents()
 
777
 
 
778
 
 
779
def _read_dirblocks(state):
 
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
 
788
    :postcondition: The dirblocks will be loaded into the appropriate fields in
 
789
        the DirState object.
 
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
 
 
795
    reader = Reader(text, state)
 
796
 
 
797
    reader._parse_dirblocks()
 
798
    state._dirblock_state = DirState.IN_MEMORY_UNMODIFIED
 
799
 
 
800
 
 
801
cdef int minikind_from_mode(int mode): # cannot_raise
 
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
 
 
814
 
 
815
cdef _pack_stat(stat_value):
 
816
    """return a string representing the stat value's key fields.
 
817
 
 
818
    :param stat_value: A stat oject with st_size, st_mtime, st_ctime, st_dev,
 
819
        st_ino and st_mode fields.
 
820
    """
 
821
    cdef char result[6*4] # 6 long ints
 
822
    cdef int *aliased
 
823
    aliased = <int *>result
 
824
    aliased[0] = htonl(PyInt_AsUnsignedLongMask(stat_value.st_size))
 
825
    # mtime and ctime will often be floats but get converted to PyInt within
 
826
    aliased[1] = htonl(PyInt_AsUnsignedLongMask(stat_value.st_mtime))
 
827
    aliased[2] = htonl(PyInt_AsUnsignedLongMask(stat_value.st_ctime))
 
828
    aliased[3] = htonl(PyInt_AsUnsignedLongMask(stat_value.st_dev))
 
829
    aliased[4] = htonl(PyInt_AsUnsignedLongMask(stat_value.st_ino))
 
830
    aliased[5] = htonl(PyInt_AsUnsignedLongMask(stat_value.st_mode))
 
831
    packed = PyString_FromStringAndSize(result, 6*4)
 
832
    return _encode(packed)[:-1]
 
833
 
 
834
 
 
835
def pack_stat(stat_value):
 
836
    """Convert stat value into a packed representation quickly with pyrex"""
 
837
    return _pack_stat(stat_value)
 
838
 
 
839
 
 
840
def update_entry(self, entry, abspath, stat_value):
 
841
    """Update the entry based on what is actually on disk.
 
842
 
 
843
    This function only calculates the sha if it needs to - if the entry is
 
844
    uncachable, or clearly different to the first parent's entry, no sha
 
845
    is calculated, and None is returned.
 
846
 
 
847
    :param entry: This is the dirblock entry for the file in question.
 
848
    :param abspath: The path on disk for this file.
 
849
    :param stat_value: (optional) if we already have done a stat on the
 
850
        file, re-use it.
 
851
    :return: None, or The sha1 hexdigest of the file (40 bytes) or link
 
852
        target of a symlink.
 
853
    """
 
854
    return _update_entry(self, entry, abspath, stat_value)
 
855
 
 
856
 
 
857
cdef _update_entry(self, entry, abspath, stat_value):
 
858
    """Update the entry based on what is actually on disk.
 
859
 
 
860
    This function only calculates the sha if it needs to - if the entry is
 
861
    uncachable, or clearly different to the first parent's entry, no sha
 
862
    is calculated, and None is returned.
 
863
 
 
864
    :param self: The dirstate object this is operating on.
 
865
    :param entry: This is the dirblock entry for the file in question.
 
866
    :param abspath: The path on disk for this file.
 
867
    :param stat_value: The stat value done on the path.
 
868
    :return: None, or The sha1 hexdigest of the file (40 bytes) or link
 
869
        target of a symlink.
 
870
    """
 
871
    # TODO - require pyrex 0.9.8, then use a pyd file to define access to the
 
872
    # _st mode of the compiled stat objects.
 
873
    cdef int minikind, saved_minikind
 
874
    cdef void * details
 
875
    cdef int worth_saving
 
876
    minikind = minikind_from_mode(stat_value.st_mode)
 
877
    if 0 == minikind:
 
878
        return None
 
879
    packed_stat = _pack_stat(stat_value)
 
880
    details = PyList_GetItem_void_void(PyTuple_GetItem_void_void(<void *>entry, 1), 0)
 
881
    saved_minikind = PyString_AsString_obj(<PyObject *>PyTuple_GetItem_void_void(details, 0))[0]
 
882
    if minikind == c'd' and saved_minikind == c't':
 
883
        minikind = c't'
 
884
    saved_link_or_sha1 = PyTuple_GetItem_void_object(details, 1)
 
885
    saved_file_size = PyTuple_GetItem_void_object(details, 2)
 
886
    saved_executable = PyTuple_GetItem_void_object(details, 3)
 
887
    saved_packed_stat = PyTuple_GetItem_void_object(details, 4)
 
888
    # Deal with pyrex decrefing the objects
 
889
    Py_INCREF(saved_link_or_sha1)
 
890
    Py_INCREF(saved_file_size)
 
891
    Py_INCREF(saved_executable)
 
892
    Py_INCREF(saved_packed_stat)
 
893
    #(saved_minikind, saved_link_or_sha1, saved_file_size,
 
894
    # saved_executable, saved_packed_stat) = entry[1][0]
 
895
 
 
896
    if (minikind == saved_minikind
 
897
        and packed_stat == saved_packed_stat):
 
898
        # The stat hasn't changed since we saved, so we can re-use the
 
899
        # saved sha hash.
 
900
        if minikind == c'd':
 
901
            return None
 
902
 
 
903
        # size should also be in packed_stat
 
904
        if saved_file_size == stat_value.st_size:
 
905
            return saved_link_or_sha1
 
906
 
 
907
    # If we have gotten this far, that means that we need to actually
 
908
    # process this entry.
 
909
    link_or_sha1 = None
 
910
    worth_saving = 1
 
911
    if minikind == c'f':
 
912
        executable = self._is_executable(stat_value.st_mode,
 
913
                                         saved_executable)
 
914
        if self._cutoff_time is None:
 
915
            self._sha_cutoff_time()
 
916
        if (stat_value.st_mtime < self._cutoff_time
 
917
            and stat_value.st_ctime < self._cutoff_time
 
918
            and len(entry[1]) > 1
 
919
            and entry[1][1][0] != 'a'):
 
920
                # Could check for size changes for further optimised
 
921
                # avoidance of sha1's. However the most prominent case of
 
922
                # over-shaing is during initial add, which this catches.
 
923
            link_or_sha1 = self._sha1_file(abspath)
 
924
            entry[1][0] = ('f', link_or_sha1, stat_value.st_size,
 
925
                           executable, packed_stat)
 
926
        else:
 
927
            # This file is not worth caching the sha1. Either it is too new, or
 
928
            # it is newly added. Regardless, the only things we are changing
 
929
            # are derived from the stat, and so are not worth caching. So we do
 
930
            # *not* set the IN_MEMORY_MODIFIED flag. (But we'll save the
 
931
            # updated values if there is *other* data worth saving.)
 
932
            entry[1][0] = ('f', '', stat_value.st_size, executable,
 
933
                           DirState.NULLSTAT)
 
934
            worth_saving = 0
 
935
    elif minikind == c'd':
 
936
        entry[1][0] = ('d', '', 0, False, packed_stat)
 
937
        if saved_minikind != c'd':
 
938
            # This changed from something into a directory. Make sure we
 
939
            # have a directory block for it. This doesn't happen very
 
940
            # often, so this doesn't have to be super fast.
 
941
            block_index, entry_index, dir_present, file_present = \
 
942
                self._get_block_entry_index(entry[0][0], entry[0][1], 0)
 
943
            self._ensure_block(block_index, entry_index,
 
944
                               pathjoin(entry[0][0], entry[0][1]))
 
945
        else:
 
946
            # Any changes are derived trivially from the stat object, not worth
 
947
            # re-writing a dirstate for just this
 
948
            worth_saving = 0
 
949
    elif minikind == c'l':
 
950
        if saved_minikind == c'l':
 
951
            # If the object hasn't changed kind, it isn't worth saving the
 
952
            # dirstate just for a symlink. The default is 'fast symlinks' which
 
953
            # save the target in the inode entry, rather than separately. So to
 
954
            # stat, we've already read everything off disk.
 
955
            worth_saving = 0
 
956
        link_or_sha1 = self._read_link(abspath, saved_link_or_sha1)
 
957
        if self._cutoff_time is None:
 
958
            self._sha_cutoff_time()
 
959
        if (stat_value.st_mtime < self._cutoff_time
 
960
            and stat_value.st_ctime < self._cutoff_time):
 
961
            entry[1][0] = ('l', link_or_sha1, stat_value.st_size,
 
962
                           False, packed_stat)
 
963
        else:
 
964
            entry[1][0] = ('l', '', stat_value.st_size,
 
965
                           False, DirState.NULLSTAT)
 
966
    if worth_saving:
 
967
        # Note, even though _mark_modified will only set
 
968
        # IN_MEMORY_HASH_MODIFIED, it still isn't worth 
 
969
        self._mark_modified([entry])
 
970
    return link_or_sha1
 
971
 
 
972
 
 
973
# TODO: Do we want to worry about exceptions here?
 
974
cdef char _minikind_from_string(object string) except? -1:
 
975
    """Convert a python string to a char."""
 
976
    return PyString_AsString(string)[0]
 
977
 
 
978
 
 
979
cdef object _kind_absent
 
980
cdef object _kind_file
 
981
cdef object _kind_directory
 
982
cdef object _kind_symlink
 
983
cdef object _kind_relocated
 
984
cdef object _kind_tree_reference
 
985
_kind_absent = "absent"
 
986
_kind_file = "file"
 
987
_kind_directory = "directory"
 
988
_kind_symlink = "symlink"
 
989
_kind_relocated = "relocated"
 
990
_kind_tree_reference = "tree-reference"
 
991
 
 
992
 
 
993
cdef object _minikind_to_kind(char minikind):
 
994
    """Create a string kind for minikind."""
 
995
    cdef char _minikind[1]
 
996
    if minikind == c'f':
 
997
        return _kind_file
 
998
    elif minikind == c'd':
 
999
        return _kind_directory
 
1000
    elif minikind == c'a':
 
1001
        return _kind_absent
 
1002
    elif minikind == c'r':
 
1003
        return _kind_relocated
 
1004
    elif minikind == c'l':
 
1005
        return _kind_symlink
 
1006
    elif minikind == c't':
 
1007
        return _kind_tree_reference
 
1008
    _minikind[0] = minikind
 
1009
    raise KeyError(PyString_FromStringAndSize(_minikind, 1))
 
1010
 
 
1011
 
 
1012
cdef int _versioned_minikind(char minikind): # cannot_raise
 
1013
    """Return non-zero if minikind is in fltd"""
 
1014
    return (minikind == c'f' or
 
1015
            minikind == c'd' or
 
1016
            minikind == c'l' or
 
1017
            minikind == c't')
 
1018
 
 
1019
 
 
1020
cdef class ProcessEntryC:
 
1021
 
 
1022
    cdef int doing_consistency_expansion
 
1023
    cdef object old_dirname_to_file_id # dict
 
1024
    cdef object new_dirname_to_file_id # dict
 
1025
    cdef object last_source_parent
 
1026
    cdef object last_target_parent
 
1027
    cdef int include_unchanged
 
1028
    cdef int partial
 
1029
    cdef object use_filesystem_for_exec
 
1030
    cdef object utf8_decode
 
1031
    cdef readonly object searched_specific_files
 
1032
    cdef readonly object searched_exact_paths
 
1033
    cdef object search_specific_files
 
1034
    # The parents up to the root of the paths we are searching.
 
1035
    # After all normal paths are returned, these specific items are returned.
 
1036
    cdef object search_specific_file_parents
 
1037
    cdef object state
 
1038
    # Current iteration variables:
 
1039
    cdef object current_root
 
1040
    cdef object current_root_unicode
 
1041
    cdef object root_entries
 
1042
    cdef int root_entries_pos, root_entries_len
 
1043
    cdef object root_abspath
 
1044
    cdef int source_index, target_index
 
1045
    cdef int want_unversioned
 
1046
    cdef object tree
 
1047
    cdef object dir_iterator
 
1048
    cdef int block_index
 
1049
    cdef object current_block
 
1050
    cdef int current_block_pos
 
1051
    cdef object current_block_list
 
1052
    cdef object current_dir_info
 
1053
    cdef object current_dir_list
 
1054
    cdef object _pending_consistent_entries # list
 
1055
    cdef int path_index
 
1056
    cdef object root_dir_info
 
1057
    cdef object bisect_left
 
1058
    cdef object pathjoin
 
1059
    cdef object fstat
 
1060
    # A set of the ids we've output when doing partial output.
 
1061
    cdef object seen_ids
 
1062
    cdef object sha_file
 
1063
 
 
1064
    def __init__(self, include_unchanged, use_filesystem_for_exec,
 
1065
        search_specific_files, state, source_index, target_index,
 
1066
        want_unversioned, tree):
 
1067
        self.doing_consistency_expansion = 0
 
1068
        self.old_dirname_to_file_id = {}
 
1069
        self.new_dirname_to_file_id = {}
 
1070
        # Are we doing a partial iter_changes?
 
1071
        self.partial = set(['']).__ne__(search_specific_files)
 
1072
        # Using a list so that we can access the values and change them in
 
1073
        # nested scope. Each one is [path, file_id, entry]
 
1074
        self.last_source_parent = [None, None]
 
1075
        self.last_target_parent = [None, None]
 
1076
        if include_unchanged is None:
 
1077
            self.include_unchanged = False
 
1078
        else:
 
1079
            self.include_unchanged = int(include_unchanged)
 
1080
        self.use_filesystem_for_exec = use_filesystem_for_exec
 
1081
        self.utf8_decode = cache_utf8._utf8_decode
 
1082
        # for all search_indexs in each path at or under each element of
 
1083
        # search_specific_files, if the detail is relocated: add the id, and
 
1084
        # add the relocated path as one to search if its not searched already.
 
1085
        # If the detail is not relocated, add the id.
 
1086
        self.searched_specific_files = set()
 
1087
        # When we search exact paths without expanding downwards, we record
 
1088
        # that here.
 
1089
        self.searched_exact_paths = set()
 
1090
        self.search_specific_files = search_specific_files
 
1091
        # The parents up to the root of the paths we are searching.
 
1092
        # After all normal paths are returned, these specific items are returned.
 
1093
        self.search_specific_file_parents = set()
 
1094
        # The ids we've sent out in the delta.
 
1095
        self.seen_ids = set()
 
1096
        self.state = state
 
1097
        self.current_root = None
 
1098
        self.current_root_unicode = None
 
1099
        self.root_entries = None
 
1100
        self.root_entries_pos = 0
 
1101
        self.root_entries_len = 0
 
1102
        self.root_abspath = None
 
1103
        if source_index is None:
 
1104
            self.source_index = -1
 
1105
        else:
 
1106
            self.source_index = source_index
 
1107
        self.target_index = target_index
 
1108
        self.want_unversioned = want_unversioned
 
1109
        self.tree = tree
 
1110
        self.dir_iterator = None
 
1111
        self.block_index = -1
 
1112
        self.current_block = None
 
1113
        self.current_block_list = None
 
1114
        self.current_block_pos = -1
 
1115
        self.current_dir_info = None
 
1116
        self.current_dir_list = None
 
1117
        self._pending_consistent_entries = []
 
1118
        self.path_index = 0
 
1119
        self.root_dir_info = None
 
1120
        self.bisect_left = bisect.bisect_left
 
1121
        self.pathjoin = osutils.pathjoin
 
1122
        self.fstat = os.fstat
 
1123
        self.sha_file = osutils.sha_file
 
1124
        if target_index != 0:
 
1125
            # A lot of code in here depends on target_index == 0
 
1126
            raise errors.BzrError('unsupported target index')
 
1127
 
 
1128
    cdef _process_entry(self, entry, path_info):
 
1129
        """Compare an entry and real disk to generate delta information.
 
1130
 
 
1131
        :param path_info: top_relpath, basename, kind, lstat, abspath for
 
1132
            the path of entry. If None, then the path is considered absent in 
 
1133
            the target (Perhaps we should pass in a concrete entry for this ?)
 
1134
            Basename is returned as a utf8 string because we expect this
 
1135
            tuple will be ignored, and don't want to take the time to
 
1136
            decode.
 
1137
        :return: (iter_changes_result, changed). If the entry has not been
 
1138
            handled then changed is None. Otherwise it is False if no content
 
1139
            or metadata changes have occured, and True if any content or
 
1140
            metadata change has occurred. If self.include_unchanged is True then
 
1141
            if changed is not None, iter_changes_result will always be a result
 
1142
            tuple. Otherwise, iter_changes_result is None unless changed is
 
1143
            True.
 
1144
        """
 
1145
        cdef char target_minikind
 
1146
        cdef char source_minikind
 
1147
        cdef object file_id
 
1148
        cdef int content_change
 
1149
        cdef object details_list
 
1150
        file_id = None
 
1151
        details_list = entry[1]
 
1152
        if -1 == self.source_index:
 
1153
            source_details = DirState.NULL_PARENT_DETAILS
 
1154
        else:
 
1155
            source_details = details_list[self.source_index]
 
1156
        target_details = details_list[self.target_index]
 
1157
        target_minikind = _minikind_from_string(target_details[0])
 
1158
        if path_info is not None and _versioned_minikind(target_minikind):
 
1159
            if self.target_index != 0:
 
1160
                raise AssertionError("Unsupported target index %d" %
 
1161
                                     self.target_index)
 
1162
            link_or_sha1 = _update_entry(self.state, entry, path_info[4], path_info[3])
 
1163
            # The entry may have been modified by update_entry
 
1164
            target_details = details_list[self.target_index]
 
1165
            target_minikind = _minikind_from_string(target_details[0])
 
1166
        else:
 
1167
            link_or_sha1 = None
 
1168
        # the rest of this function is 0.3 seconds on 50K paths, or
 
1169
        # 0.000006 seconds per call.
 
1170
        source_minikind = _minikind_from_string(source_details[0])
 
1171
        if ((_versioned_minikind(source_minikind) or source_minikind == c'r')
 
1172
            and _versioned_minikind(target_minikind)):
 
1173
            # claimed content in both: diff
 
1174
            #   r    | fdlt   |      | add source to search, add id path move and perform
 
1175
            #        |        |      | diff check on source-target
 
1176
            #   r    | fdlt   |  a   | dangling file that was present in the basis.
 
1177
            #        |        |      | ???
 
1178
            if source_minikind != c'r':
 
1179
                old_dirname = entry[0][0]
 
1180
                old_basename = entry[0][1]
 
1181
                old_path = path = None
 
1182
            else:
 
1183
                # add the source to the search path to find any children it
 
1184
                # has.  TODO ? : only add if it is a container ?
 
1185
                if (not self.doing_consistency_expansion and 
 
1186
                    not osutils.is_inside_any(self.searched_specific_files,
 
1187
                                             source_details[1])):
 
1188
                    self.search_specific_files.add(source_details[1])
 
1189
                    # expanding from a user requested path, parent expansion
 
1190
                    # for delta consistency happens later.
 
1191
                # generate the old path; this is needed for stating later
 
1192
                # as well.
 
1193
                old_path = source_details[1]
 
1194
                old_dirname, old_basename = os.path.split(old_path)
 
1195
                path = self.pathjoin(entry[0][0], entry[0][1])
 
1196
                old_entry = self.state._get_entry(self.source_index,
 
1197
                                             path_utf8=old_path)
 
1198
                # update the source details variable to be the real
 
1199
                # location.
 
1200
                if old_entry == (None, None):
 
1201
                    raise errors.CorruptDirstate(self.state._filename,
 
1202
                        "entry '%s/%s' is considered renamed from %r"
 
1203
                        " but source does not exist\n"
 
1204
                        "entry: %s" % (entry[0][0], entry[0][1], old_path, entry))
 
1205
                source_details = old_entry[1][self.source_index]
 
1206
                source_minikind = _minikind_from_string(source_details[0])
 
1207
            if path_info is None:
 
1208
                # the file is missing on disk, show as removed.
 
1209
                content_change = 1
 
1210
                target_kind = None
 
1211
                target_exec = False
 
1212
            else:
 
1213
                # source and target are both versioned and disk file is present.
 
1214
                target_kind = path_info[2]
 
1215
                if target_kind == 'directory':
 
1216
                    if path is None:
 
1217
                        old_path = path = self.pathjoin(old_dirname, old_basename)
 
1218
                    file_id = entry[0][2]
 
1219
                    self.new_dirname_to_file_id[path] = file_id
 
1220
                    if source_minikind != c'd':
 
1221
                        content_change = 1
 
1222
                    else:
 
1223
                        # directories have no fingerprint
 
1224
                        content_change = 0
 
1225
                    target_exec = False
 
1226
                elif target_kind == 'file':
 
1227
                    if source_minikind != c'f':
 
1228
                        content_change = 1
 
1229
                    else:
 
1230
                        # Check the sha. We can't just rely on the size as
 
1231
                        # content filtering may mean differ sizes actually
 
1232
                        # map to the same content
 
1233
                        if link_or_sha1 is None:
 
1234
                            # Stat cache miss:
 
1235
                            statvalue, link_or_sha1 = \
 
1236
                                self.state._sha1_provider.stat_and_sha1(
 
1237
                                path_info[4])
 
1238
                            self.state._observed_sha1(entry, link_or_sha1,
 
1239
                                statvalue)
 
1240
                        content_change = (link_or_sha1 != source_details[1])
 
1241
                    # Target details is updated at update_entry time
 
1242
                    if self.use_filesystem_for_exec:
 
1243
                        # We don't need S_ISREG here, because we are sure
 
1244
                        # we are dealing with a file.
 
1245
                        target_exec = bool(S_IXUSR & path_info[3].st_mode)
 
1246
                    else:
 
1247
                        target_exec = target_details[3]
 
1248
                elif target_kind == 'symlink':
 
1249
                    if source_minikind != c'l':
 
1250
                        content_change = 1
 
1251
                    else:
 
1252
                        content_change = (link_or_sha1 != source_details[1])
 
1253
                    target_exec = False
 
1254
                elif target_kind == 'tree-reference':
 
1255
                    if source_minikind != c't':
 
1256
                        content_change = 1
 
1257
                    else:
 
1258
                        content_change = 0
 
1259
                    target_exec = False
 
1260
                else:
 
1261
                    if path is None:
 
1262
                        path = self.pathjoin(old_dirname, old_basename)
 
1263
                    raise errors.BadFileKindError(path, path_info[2])
 
1264
            if source_minikind == c'd':
 
1265
                if path is None:
 
1266
                    old_path = path = self.pathjoin(old_dirname, old_basename)
 
1267
                if file_id is None:
 
1268
                    file_id = entry[0][2]
 
1269
                self.old_dirname_to_file_id[old_path] = file_id
 
1270
            # parent id is the entry for the path in the target tree
 
1271
            if old_basename and old_dirname == self.last_source_parent[0]:
 
1272
                # use a cached hit for non-root source entries.
 
1273
                source_parent_id = self.last_source_parent[1]
 
1274
            else:
 
1275
                try:
 
1276
                    source_parent_id = self.old_dirname_to_file_id[old_dirname]
 
1277
                except KeyError, _:
 
1278
                    source_parent_entry = self.state._get_entry(self.source_index,
 
1279
                                                           path_utf8=old_dirname)
 
1280
                    source_parent_id = source_parent_entry[0][2]
 
1281
                if source_parent_id == entry[0][2]:
 
1282
                    # This is the root, so the parent is None
 
1283
                    source_parent_id = None
 
1284
                else:
 
1285
                    self.last_source_parent[0] = old_dirname
 
1286
                    self.last_source_parent[1] = source_parent_id
 
1287
            new_dirname = entry[0][0]
 
1288
            if entry[0][1] and new_dirname == self.last_target_parent[0]:
 
1289
                # use a cached hit for non-root target entries.
 
1290
                target_parent_id = self.last_target_parent[1]
 
1291
            else:
 
1292
                try:
 
1293
                    target_parent_id = self.new_dirname_to_file_id[new_dirname]
 
1294
                except KeyError, _:
 
1295
                    # TODO: We don't always need to do the lookup, because the
 
1296
                    #       parent entry will be the same as the source entry.
 
1297
                    target_parent_entry = self.state._get_entry(self.target_index,
 
1298
                                                           path_utf8=new_dirname)
 
1299
                    if target_parent_entry == (None, None):
 
1300
                        raise AssertionError(
 
1301
                            "Could not find target parent in wt: %s\nparent of: %s"
 
1302
                            % (new_dirname, entry))
 
1303
                    target_parent_id = target_parent_entry[0][2]
 
1304
                if target_parent_id == entry[0][2]:
 
1305
                    # This is the root, so the parent is None
 
1306
                    target_parent_id = None
 
1307
                else:
 
1308
                    self.last_target_parent[0] = new_dirname
 
1309
                    self.last_target_parent[1] = target_parent_id
 
1310
 
 
1311
            source_exec = source_details[3]
 
1312
            changed = (content_change
 
1313
                or source_parent_id != target_parent_id
 
1314
                or old_basename != entry[0][1]
 
1315
                or source_exec != target_exec
 
1316
                )
 
1317
            if not changed and not self.include_unchanged:
 
1318
                return None, False
 
1319
            else:
 
1320
                if old_path is None:
 
1321
                    path = self.pathjoin(old_dirname, old_basename)
 
1322
                    old_path = path
 
1323
                    old_path_u = self.utf8_decode(old_path)[0]
 
1324
                    path_u = old_path_u
 
1325
                else:
 
1326
                    old_path_u = self.utf8_decode(old_path)[0]
 
1327
                    if old_path == path:
 
1328
                        path_u = old_path_u
 
1329
                    else:
 
1330
                        path_u = self.utf8_decode(path)[0]
 
1331
                source_kind = _minikind_to_kind(source_minikind)
 
1332
                return (entry[0][2],
 
1333
                       (old_path_u, path_u),
 
1334
                       content_change,
 
1335
                       (True, True),
 
1336
                       (source_parent_id, target_parent_id),
 
1337
                       (self.utf8_decode(old_basename)[0], self.utf8_decode(entry[0][1])[0]),
 
1338
                       (source_kind, target_kind),
 
1339
                       (source_exec, target_exec)), changed
 
1340
        elif source_minikind == c'a' and _versioned_minikind(target_minikind):
 
1341
            # looks like a new file
 
1342
            path = self.pathjoin(entry[0][0], entry[0][1])
 
1343
            # parent id is the entry for the path in the target tree
 
1344
            # TODO: these are the same for an entire directory: cache em.
 
1345
            parent_entry = self.state._get_entry(self.target_index,
 
1346
                                                 path_utf8=entry[0][0])
 
1347
            if parent_entry is None:
 
1348
                raise errors.DirstateCorrupt(self.state,
 
1349
                    "We could not find the parent entry in index %d"
 
1350
                    " for the entry: %s"
 
1351
                    % (self.target_index, entry[0]))
 
1352
            parent_id = parent_entry[0][2]
 
1353
            if parent_id == entry[0][2]:
 
1354
                parent_id = None
 
1355
            if path_info is not None:
 
1356
                # Present on disk:
 
1357
                if self.use_filesystem_for_exec:
 
1358
                    # We need S_ISREG here, because we aren't sure if this
 
1359
                    # is a file or not.
 
1360
                    target_exec = bool(
 
1361
                        S_ISREG(path_info[3].st_mode)
 
1362
                        and S_IXUSR & path_info[3].st_mode)
 
1363
                else:
 
1364
                    target_exec = target_details[3]
 
1365
                return (entry[0][2],
 
1366
                       (None, self.utf8_decode(path)[0]),
 
1367
                       True,
 
1368
                       (False, True),
 
1369
                       (None, parent_id),
 
1370
                       (None, self.utf8_decode(entry[0][1])[0]),
 
1371
                       (None, path_info[2]),
 
1372
                       (None, target_exec)), True
 
1373
            else:
 
1374
                # Its a missing file, report it as such.
 
1375
                return (entry[0][2],
 
1376
                       (None, self.utf8_decode(path)[0]),
 
1377
                       False,
 
1378
                       (False, True),
 
1379
                       (None, parent_id),
 
1380
                       (None, self.utf8_decode(entry[0][1])[0]),
 
1381
                       (None, None),
 
1382
                       (None, False)), True
 
1383
        elif _versioned_minikind(source_minikind) and target_minikind == c'a':
 
1384
            # unversioned, possibly, or possibly not deleted: we dont care.
 
1385
            # if its still on disk, *and* theres no other entry at this
 
1386
            # path [we dont know this in this routine at the moment -
 
1387
            # perhaps we should change this - then it would be an unknown.
 
1388
            old_path = self.pathjoin(entry[0][0], entry[0][1])
 
1389
            # parent id is the entry for the path in the target tree
 
1390
            parent_id = self.state._get_entry(self.source_index, path_utf8=entry[0][0])[0][2]
 
1391
            if parent_id == entry[0][2]:
 
1392
                parent_id = None
 
1393
            return (entry[0][2],
 
1394
                   (self.utf8_decode(old_path)[0], None),
 
1395
                   True,
 
1396
                   (True, False),
 
1397
                   (parent_id, None),
 
1398
                   (self.utf8_decode(entry[0][1])[0], None),
 
1399
                   (_minikind_to_kind(source_minikind), None),
 
1400
                   (source_details[3], None)), True
 
1401
        elif _versioned_minikind(source_minikind) and target_minikind == c'r':
 
1402
            # a rename; could be a true rename, or a rename inherited from
 
1403
            # a renamed parent. TODO: handle this efficiently. Its not
 
1404
            # common case to rename dirs though, so a correct but slow
 
1405
            # implementation will do.
 
1406
            if (not self.doing_consistency_expansion and 
 
1407
                not osutils.is_inside_any(self.searched_specific_files,
 
1408
                    target_details[1])):
 
1409
                self.search_specific_files.add(target_details[1])
 
1410
                # We don't expand the specific files parents list here as
 
1411
                # the path is absent in target and won't create a delta with
 
1412
                # missing parent.
 
1413
        elif ((source_minikind == c'r' or source_minikind == c'a') and
 
1414
              (target_minikind == c'r' or target_minikind == c'a')):
 
1415
            # neither of the selected trees contain this path,
 
1416
            # so skip over it. This is not currently directly tested, but
 
1417
            # is indirectly via test_too_much.TestCommands.test_conflicts.
 
1418
            pass
 
1419
        else:
 
1420
            raise AssertionError("don't know how to compare "
 
1421
                "source_minikind=%r, target_minikind=%r"
 
1422
                % (source_minikind, target_minikind))
 
1423
            ## import pdb;pdb.set_trace()
 
1424
        return None, None
 
1425
 
 
1426
    def __iter__(self):
 
1427
        return self
 
1428
 
 
1429
    def iter_changes(self):
 
1430
        return self
 
1431
 
 
1432
    cdef int _gather_result_for_consistency(self, result) except -1:
 
1433
        """Check a result we will yield to make sure we are consistent later.
 
1434
        
 
1435
        This gathers result's parents into a set to output later.
 
1436
 
 
1437
        :param result: A result tuple.
 
1438
        """
 
1439
        if not self.partial or not result[0]:
 
1440
            return 0
 
1441
        self.seen_ids.add(result[0])
 
1442
        new_path = result[1][1]
 
1443
        if new_path:
 
1444
            # Not the root and not a delete: queue up the parents of the path.
 
1445
            self.search_specific_file_parents.update(
 
1446
                osutils.parent_directories(new_path.encode('utf8')))
 
1447
            # Add the root directory which parent_directories does not
 
1448
            # provide.
 
1449
            self.search_specific_file_parents.add('')
 
1450
        return 0
 
1451
 
 
1452
    cdef int _update_current_block(self) except -1:
 
1453
        if (self.block_index < len(self.state._dirblocks) and
 
1454
            osutils.is_inside(self.current_root, self.state._dirblocks[self.block_index][0])):
 
1455
            self.current_block = self.state._dirblocks[self.block_index]
 
1456
            self.current_block_list = self.current_block[1]
 
1457
            self.current_block_pos = 0
 
1458
        else:
 
1459
            self.current_block = None
 
1460
            self.current_block_list = None
 
1461
        return 0
 
1462
 
 
1463
    def __next__(self):
 
1464
        # Simple thunk to allow tail recursion without pyrex confusion
 
1465
        return self._iter_next()
 
1466
 
 
1467
    cdef _iter_next(self):
 
1468
        """Iterate over the changes."""
 
1469
        # This function single steps through an iterator. As such while loops
 
1470
        # are often exited by 'return' - the code is structured so that the
 
1471
        # next call into the function will return to the same while loop. Note
 
1472
        # that all flow control needed to re-reach that step is reexecuted,
 
1473
        # which can be a performance problem. It has not yet been tuned to
 
1474
        # minimise this; a state machine is probably the simplest restructuring
 
1475
        # to both minimise this overhead and make the code considerably more
 
1476
        # understandable.
 
1477
 
 
1478
        # sketch: 
 
1479
        # compare source_index and target_index at or under each element of search_specific_files.
 
1480
        # follow the following comparison table. Note that we only want to do diff operations when
 
1481
        # the target is fdl because thats when the walkdirs logic will have exposed the pathinfo 
 
1482
        # for the target.
 
1483
        # cases:
 
1484
        # 
 
1485
        # Source | Target | disk | action
 
1486
        #   r    | fdlt   |      | add source to search, add id path move and perform
 
1487
        #        |        |      | diff check on source-target
 
1488
        #   r    | fdlt   |  a   | dangling file that was present in the basis. 
 
1489
        #        |        |      | ???
 
1490
        #   r    |  a     |      | add source to search
 
1491
        #   r    |  a     |  a   | 
 
1492
        #   r    |  r     |      | this path is present in a non-examined tree, skip.
 
1493
        #   r    |  r     |  a   | this path is present in a non-examined tree, skip.
 
1494
        #   a    | fdlt   |      | add new id
 
1495
        #   a    | fdlt   |  a   | dangling locally added file, skip
 
1496
        #   a    |  a     |      | not present in either tree, skip
 
1497
        #   a    |  a     |  a   | not present in any tree, skip
 
1498
        #   a    |  r     |      | not present in either tree at this path, skip as it
 
1499
        #        |        |      | may not be selected by the users list of paths.
 
1500
        #   a    |  r     |  a   | not present in either tree at this path, skip as it
 
1501
        #        |        |      | may not be selected by the users list of paths.
 
1502
        #  fdlt  | fdlt   |      | content in both: diff them
 
1503
        #  fdlt  | fdlt   |  a   | deleted locally, but not unversioned - show as deleted ?
 
1504
        #  fdlt  |  a     |      | unversioned: output deleted id for now
 
1505
        #  fdlt  |  a     |  a   | unversioned and deleted: output deleted id
 
1506
        #  fdlt  |  r     |      | relocated in this tree, so add target to search.
 
1507
        #        |        |      | Dont diff, we will see an r,fd; pair when we reach
 
1508
        #        |        |      | this id at the other path.
 
1509
        #  fdlt  |  r     |  a   | relocated in this tree, so add target to search.
 
1510
        #        |        |      | Dont diff, we will see an r,fd; pair when we reach
 
1511
        #        |        |      | this id at the other path.
 
1512
 
 
1513
        # TODO: jam 20070516 - Avoid the _get_entry lookup overhead by
 
1514
        #       keeping a cache of directories that we have seen.
 
1515
        cdef object current_dirname, current_blockname
 
1516
        cdef char * current_dirname_c, * current_blockname_c
 
1517
        cdef int advance_entry, advance_path
 
1518
        cdef int path_handled
 
1519
        searched_specific_files = self.searched_specific_files
 
1520
        # Are we walking a root?
 
1521
        while self.root_entries_pos < self.root_entries_len:
 
1522
            entry = self.root_entries[self.root_entries_pos]
 
1523
            self.root_entries_pos = self.root_entries_pos + 1
 
1524
            result, changed = self._process_entry(entry, self.root_dir_info)
 
1525
            if changed is not None:
 
1526
                if changed:
 
1527
                    self._gather_result_for_consistency(result)
 
1528
                if changed or self.include_unchanged:
 
1529
                    return result
 
1530
        # Have we finished the prior root, or never started one ?
 
1531
        if self.current_root is None:
 
1532
            # TODO: the pending list should be lexically sorted?  the
 
1533
            # interface doesn't require it.
 
1534
            try:
 
1535
                self.current_root = self.search_specific_files.pop()
 
1536
            except KeyError, _:
 
1537
                raise StopIteration()
 
1538
            self.searched_specific_files.add(self.current_root)
 
1539
            # process the entries for this containing directory: the rest will be
 
1540
            # found by their parents recursively.
 
1541
            self.root_entries = self.state._entries_for_path(self.current_root)
 
1542
            self.root_entries_len = len(self.root_entries)
 
1543
            self.current_root_unicode = self.current_root.decode('utf8')
 
1544
            self.root_abspath = self.tree.abspath(self.current_root_unicode)
 
1545
            try:
 
1546
                root_stat = os.lstat(self.root_abspath)
 
1547
            except OSError, e:
 
1548
                if e.errno == errno.ENOENT:
 
1549
                    # the path does not exist: let _process_entry know that.
 
1550
                    self.root_dir_info = None
 
1551
                else:
 
1552
                    # some other random error: hand it up.
 
1553
                    raise
 
1554
            else:
 
1555
                self.root_dir_info = ('', self.current_root,
 
1556
                    osutils.file_kind_from_stat_mode(root_stat.st_mode), root_stat,
 
1557
                    self.root_abspath)
 
1558
                if self.root_dir_info[2] == 'directory':
 
1559
                    if self.tree._directory_is_tree_reference(
 
1560
                        self.current_root_unicode):
 
1561
                        self.root_dir_info = self.root_dir_info[:2] + \
 
1562
                            ('tree-reference',) + self.root_dir_info[3:]
 
1563
            if not self.root_entries and not self.root_dir_info:
 
1564
                # this specified path is not present at all, skip it.
 
1565
                # (tail recursion, can do a loop once the full structure is
 
1566
                # known).
 
1567
                return self._iter_next()
 
1568
            path_handled = 0
 
1569
            self.root_entries_pos = 0
 
1570
            # XXX Clarity: This loop is duplicated a out the self.current_root
 
1571
            # is None guard above: if we return from it, it completes there
 
1572
            # (and the following if block cannot trigger because
 
1573
            # path_handled must be true, so the if block is not # duplicated.
 
1574
            while self.root_entries_pos < self.root_entries_len:
 
1575
                entry = self.root_entries[self.root_entries_pos]
 
1576
                self.root_entries_pos = self.root_entries_pos + 1
 
1577
                result, changed = self._process_entry(entry, self.root_dir_info)
 
1578
                if changed is not None:
 
1579
                    path_handled = -1
 
1580
                    if changed:
 
1581
                        self._gather_result_for_consistency(result)
 
1582
                    if changed or self.include_unchanged:
 
1583
                        return result
 
1584
            # handle unversioned specified paths:
 
1585
            if self.want_unversioned and not path_handled and self.root_dir_info:
 
1586
                new_executable = bool(
 
1587
                    stat.S_ISREG(self.root_dir_info[3].st_mode)
 
1588
                    and stat.S_IEXEC & self.root_dir_info[3].st_mode)
 
1589
                return (None,
 
1590
                       (None, self.current_root_unicode),
 
1591
                       True,
 
1592
                       (False, False),
 
1593
                       (None, None),
 
1594
                       (None, splitpath(self.current_root_unicode)[-1]),
 
1595
                       (None, self.root_dir_info[2]),
 
1596
                       (None, new_executable)
 
1597
                      )
 
1598
            # If we reach here, the outer flow continues, which enters into the
 
1599
            # per-root setup logic.
 
1600
        if (self.current_dir_info is None and self.current_block is None and not
 
1601
            self.doing_consistency_expansion):
 
1602
            # setup iteration of this root:
 
1603
            self.current_dir_list = None
 
1604
            if self.root_dir_info and self.root_dir_info[2] == 'tree-reference':
 
1605
                self.current_dir_info = None
 
1606
            else:
 
1607
                self.dir_iterator = osutils._walkdirs_utf8(self.root_abspath,
 
1608
                    prefix=self.current_root)
 
1609
                self.path_index = 0
 
1610
                try:
 
1611
                    self.current_dir_info = self.dir_iterator.next()
 
1612
                    self.current_dir_list = self.current_dir_info[1]
 
1613
                except OSError, e:
 
1614
                    # there may be directories in the inventory even though
 
1615
                    # this path is not a file on disk: so mark it as end of
 
1616
                    # iterator
 
1617
                    if e.errno in (errno.ENOENT, errno.ENOTDIR, errno.EINVAL):
 
1618
                        self.current_dir_info = None
 
1619
                    elif sys.platform == 'win32':
 
1620
                        # on win32, python2.4 has e.errno == ERROR_DIRECTORY, but
 
1621
                        # python 2.5 has e.errno == EINVAL,
 
1622
                        #            and e.winerror == ERROR_DIRECTORY
 
1623
                        try:
 
1624
                            e_winerror = e.winerror
 
1625
                        except AttributeError, _:
 
1626
                            e_winerror = None
 
1627
                        win_errors = (ERROR_DIRECTORY, ERROR_PATH_NOT_FOUND)
 
1628
                        if (e.errno in win_errors or e_winerror in win_errors):
 
1629
                            self.current_dir_info = None
 
1630
                        else:
 
1631
                            # Will this really raise the right exception ?
 
1632
                            raise
 
1633
                    else:
 
1634
                        raise
 
1635
                else:
 
1636
                    if self.current_dir_info[0][0] == '':
 
1637
                        # remove .bzr from iteration
 
1638
                        bzr_index = self.bisect_left(self.current_dir_list, ('.bzr',))
 
1639
                        if self.current_dir_list[bzr_index][0] != '.bzr':
 
1640
                            raise AssertionError()
 
1641
                        del self.current_dir_list[bzr_index]
 
1642
            initial_key = (self.current_root, '', '')
 
1643
            self.block_index, _ = self.state._find_block_index_from_key(initial_key)
 
1644
            if self.block_index == 0:
 
1645
                # we have processed the total root already, but because the
 
1646
                # initial key matched it we should skip it here.
 
1647
                self.block_index = self.block_index + 1
 
1648
            self._update_current_block()
 
1649
        # walk until both the directory listing and the versioned metadata
 
1650
        # are exhausted. 
 
1651
        while (self.current_dir_info is not None
 
1652
            or self.current_block is not None):
 
1653
            # Uncommon case - a missing directory or an unversioned directory:
 
1654
            if (self.current_dir_info and self.current_block
 
1655
                and self.current_dir_info[0][0] != self.current_block[0]):
 
1656
                # Work around pyrex broken heuristic - current_dirname has
 
1657
                # the same scope as current_dirname_c
 
1658
                current_dirname = self.current_dir_info[0][0]
 
1659
                current_dirname_c = PyString_AS_STRING_void(
 
1660
                    <void *>current_dirname)
 
1661
                current_blockname = self.current_block[0]
 
1662
                current_blockname_c = PyString_AS_STRING_void(
 
1663
                    <void *>current_blockname)
 
1664
                # In the python generator we evaluate this if block once per
 
1665
                # dir+block; because we reenter in the pyrex version its being
 
1666
                # evaluated once per path: we could cache the result before
 
1667
                # doing the while loop and probably save time.
 
1668
                if _cmp_by_dirs(current_dirname_c,
 
1669
                    PyString_Size(current_dirname),
 
1670
                    current_blockname_c,
 
1671
                    PyString_Size(current_blockname)) < 0:
 
1672
                    # filesystem data refers to paths not covered by the
 
1673
                    # dirblock.  this has two possibilities:
 
1674
                    # A) it is versioned but empty, so there is no block for it
 
1675
                    # B) it is not versioned.
 
1676
 
 
1677
                    # if (A) then we need to recurse into it to check for
 
1678
                    # new unknown files or directories.
 
1679
                    # if (B) then we should ignore it, because we don't
 
1680
                    # recurse into unknown directories.
 
1681
                    # We are doing a loop
 
1682
                    while self.path_index < len(self.current_dir_list):
 
1683
                        current_path_info = self.current_dir_list[self.path_index]
 
1684
                        # dont descend into this unversioned path if it is
 
1685
                        # a dir
 
1686
                        if current_path_info[2] in ('directory',
 
1687
                                                    'tree-reference'):
 
1688
                            del self.current_dir_list[self.path_index]
 
1689
                            self.path_index = self.path_index - 1
 
1690
                        self.path_index = self.path_index + 1
 
1691
                        if self.want_unversioned:
 
1692
                            if current_path_info[2] == 'directory':
 
1693
                                if self.tree._directory_is_tree_reference(
 
1694
                                    self.utf8_decode(current_path_info[0])[0]):
 
1695
                                    current_path_info = current_path_info[:2] + \
 
1696
                                        ('tree-reference',) + current_path_info[3:]
 
1697
                            new_executable = bool(
 
1698
                                stat.S_ISREG(current_path_info[3].st_mode)
 
1699
                                and stat.S_IEXEC & current_path_info[3].st_mode)
 
1700
                            return (None,
 
1701
                                (None, self.utf8_decode(current_path_info[0])[0]),
 
1702
                                True,
 
1703
                                (False, False),
 
1704
                                (None, None),
 
1705
                                (None, self.utf8_decode(current_path_info[1])[0]),
 
1706
                                (None, current_path_info[2]),
 
1707
                                (None, new_executable))
 
1708
                    # This dir info has been handled, go to the next
 
1709
                    self.path_index = 0
 
1710
                    self.current_dir_list = None
 
1711
                    try:
 
1712
                        self.current_dir_info = self.dir_iterator.next()
 
1713
                        self.current_dir_list = self.current_dir_info[1]
 
1714
                    except StopIteration, _:
 
1715
                        self.current_dir_info = None
 
1716
                else: #(dircmp > 0)
 
1717
                    # We have a dirblock entry for this location, but there
 
1718
                    # is no filesystem path for this. This is most likely
 
1719
                    # because a directory was removed from the disk.
 
1720
                    # We don't have to report the missing directory,
 
1721
                    # because that should have already been handled, but we
 
1722
                    # need to handle all of the files that are contained
 
1723
                    # within.
 
1724
                    while self.current_block_pos < len(self.current_block_list):
 
1725
                        current_entry = self.current_block_list[self.current_block_pos]
 
1726
                        self.current_block_pos = self.current_block_pos + 1
 
1727
                        # entry referring to file not present on disk.
 
1728
                        # advance the entry only, after processing.
 
1729
                        result, changed = self._process_entry(current_entry, None)
 
1730
                        if changed is not None:
 
1731
                            if changed:
 
1732
                                self._gather_result_for_consistency(result)
 
1733
                            if changed or self.include_unchanged:
 
1734
                                return result
 
1735
                    self.block_index = self.block_index + 1
 
1736
                    self._update_current_block()
 
1737
                continue # next loop-on-block/dir
 
1738
            result = self._loop_one_block()
 
1739
            if result is not None:
 
1740
                return result
 
1741
        if len(self.search_specific_files):
 
1742
            # More supplied paths to process
 
1743
            self.current_root = None
 
1744
            return self._iter_next()
 
1745
        # Start expanding more conservatively, adding paths the user may not
 
1746
        # have intended but required for consistent deltas.
 
1747
        self.doing_consistency_expansion = 1
 
1748
        if not self._pending_consistent_entries:
 
1749
            self._pending_consistent_entries = self._next_consistent_entries()
 
1750
        while self._pending_consistent_entries:
 
1751
            result, changed = self._pending_consistent_entries.pop()
 
1752
            if changed is not None:
 
1753
                return result
 
1754
        raise StopIteration()
 
1755
 
 
1756
    cdef object _maybe_tree_ref(self, current_path_info):
 
1757
        if self.tree._directory_is_tree_reference(
 
1758
            self.utf8_decode(current_path_info[0])[0]):
 
1759
            return current_path_info[:2] + \
 
1760
                ('tree-reference',) + current_path_info[3:]
 
1761
        else:
 
1762
            return current_path_info
 
1763
 
 
1764
    cdef object _loop_one_block(self):
 
1765
            # current_dir_info and current_block refer to the same directory -
 
1766
            # this is the common case code.
 
1767
            # Assign local variables for current path and entry:
 
1768
            cdef object current_entry
 
1769
            cdef object current_path_info
 
1770
            cdef int path_handled
 
1771
            cdef char minikind
 
1772
            cdef int cmp_result
 
1773
            # cdef char * temp_str
 
1774
            # cdef Py_ssize_t temp_str_length
 
1775
            # PyString_AsStringAndSize(disk_kind, &temp_str, &temp_str_length)
 
1776
            # if not strncmp(temp_str, "directory", temp_str_length):
 
1777
            if (self.current_block is not None and
 
1778
                self.current_block_pos < PyList_GET_SIZE(self.current_block_list)):
 
1779
                current_entry = PyList_GET_ITEM(self.current_block_list,
 
1780
                    self.current_block_pos)
 
1781
                # accomodate pyrex
 
1782
                Py_INCREF(current_entry)
 
1783
            else:
 
1784
                current_entry = None
 
1785
            if (self.current_dir_info is not None and
 
1786
                self.path_index < PyList_GET_SIZE(self.current_dir_list)):
 
1787
                current_path_info = PyList_GET_ITEM(self.current_dir_list,
 
1788
                    self.path_index)
 
1789
                # accomodate pyrex
 
1790
                Py_INCREF(current_path_info)
 
1791
                disk_kind = PyTuple_GET_ITEM(current_path_info, 2)
 
1792
                # accomodate pyrex
 
1793
                Py_INCREF(disk_kind)
 
1794
                if disk_kind == "directory":
 
1795
                    current_path_info = self._maybe_tree_ref(current_path_info)
 
1796
            else:
 
1797
                current_path_info = None
 
1798
            while (current_entry is not None or current_path_info is not None):
 
1799
                advance_entry = -1
 
1800
                advance_path = -1
 
1801
                result = None
 
1802
                changed = None
 
1803
                path_handled = 0
 
1804
                if current_entry is None:
 
1805
                    # unversioned -  the check for path_handled when the path
 
1806
                    # is advanced will yield this path if needed.
 
1807
                    pass
 
1808
                elif current_path_info is None:
 
1809
                    # no path is fine: the per entry code will handle it.
 
1810
                    result, changed = self._process_entry(current_entry,
 
1811
                        current_path_info)
 
1812
                else:
 
1813
                    minikind = _minikind_from_string(
 
1814
                        current_entry[1][self.target_index][0])
 
1815
                    cmp_result = cmp(current_path_info[1], current_entry[0][1])
 
1816
                    if (cmp_result or minikind == c'a' or minikind == c'r'):
 
1817
                        # The current path on disk doesn't match the dirblock
 
1818
                        # record. Either the dirblock record is marked as
 
1819
                        # absent/renamed, or the file on disk is not present at all
 
1820
                        # in the dirblock. Either way, report about the dirblock
 
1821
                        # entry, and let other code handle the filesystem one.
 
1822
 
 
1823
                        # Compare the basename for these files to determine
 
1824
                        # which comes first
 
1825
                        if cmp_result < 0:
 
1826
                            # extra file on disk: pass for now, but only
 
1827
                            # increment the path, not the entry
 
1828
                            advance_entry = 0
 
1829
                        else:
 
1830
                            # entry referring to file not present on disk.
 
1831
                            # advance the entry only, after processing.
 
1832
                            result, changed = self._process_entry(current_entry,
 
1833
                                None)
 
1834
                            advance_path = 0
 
1835
                    else:
 
1836
                        # paths are the same,and the dirstate entry is not
 
1837
                        # absent or renamed.
 
1838
                        result, changed = self._process_entry(current_entry,
 
1839
                            current_path_info)
 
1840
                        if changed is not None:
 
1841
                            path_handled = -1
 
1842
                            if not changed and not self.include_unchanged:
 
1843
                                changed = None
 
1844
                # >- loop control starts here:
 
1845
                # >- entry
 
1846
                if advance_entry and current_entry is not None:
 
1847
                    self.current_block_pos = self.current_block_pos + 1
 
1848
                    if self.current_block_pos < PyList_GET_SIZE(self.current_block_list):
 
1849
                        current_entry = self.current_block_list[self.current_block_pos]
 
1850
                    else:
 
1851
                        current_entry = None
 
1852
                # >- path
 
1853
                if advance_path and current_path_info is not None:
 
1854
                    if not path_handled:
 
1855
                        # unversioned in all regards
 
1856
                        if self.want_unversioned:
 
1857
                            new_executable = bool(
 
1858
                                stat.S_ISREG(current_path_info[3].st_mode)
 
1859
                                and stat.S_IEXEC & current_path_info[3].st_mode)
 
1860
                            try:
 
1861
                                relpath_unicode = self.utf8_decode(current_path_info[0])[0]
 
1862
                            except UnicodeDecodeError, _:
 
1863
                                raise errors.BadFilenameEncoding(
 
1864
                                    current_path_info[0], osutils._fs_enc)
 
1865
                            if changed is not None:
 
1866
                                raise AssertionError(
 
1867
                                    "result is not None: %r" % result)
 
1868
                            result = (None,
 
1869
                                (None, relpath_unicode),
 
1870
                                True,
 
1871
                                (False, False),
 
1872
                                (None, None),
 
1873
                                (None, self.utf8_decode(current_path_info[1])[0]),
 
1874
                                (None, current_path_info[2]),
 
1875
                                (None, new_executable))
 
1876
                            changed = True
 
1877
                        # dont descend into this unversioned path if it is
 
1878
                        # a dir
 
1879
                        if current_path_info[2] in ('directory'):
 
1880
                            del self.current_dir_list[self.path_index]
 
1881
                            self.path_index = self.path_index - 1
 
1882
                    # dont descend the disk iterator into any tree 
 
1883
                    # paths.
 
1884
                    if current_path_info[2] == 'tree-reference':
 
1885
                        del self.current_dir_list[self.path_index]
 
1886
                        self.path_index = self.path_index - 1
 
1887
                    self.path_index = self.path_index + 1
 
1888
                    if self.path_index < len(self.current_dir_list):
 
1889
                        current_path_info = self.current_dir_list[self.path_index]
 
1890
                        if current_path_info[2] == 'directory':
 
1891
                            current_path_info = self._maybe_tree_ref(
 
1892
                                current_path_info)
 
1893
                    else:
 
1894
                        current_path_info = None
 
1895
                if changed is not None:
 
1896
                    # Found a result on this pass, yield it
 
1897
                    if changed:
 
1898
                        self._gather_result_for_consistency(result)
 
1899
                    if changed or self.include_unchanged:
 
1900
                        return result
 
1901
            if self.current_block is not None:
 
1902
                self.block_index = self.block_index + 1
 
1903
                self._update_current_block()
 
1904
            if self.current_dir_info is not None:
 
1905
                self.path_index = 0
 
1906
                self.current_dir_list = None
 
1907
                try:
 
1908
                    self.current_dir_info = self.dir_iterator.next()
 
1909
                    self.current_dir_list = self.current_dir_info[1]
 
1910
                except StopIteration, _:
 
1911
                    self.current_dir_info = None
 
1912
 
 
1913
    cdef object _next_consistent_entries(self):
 
1914
        """Grabs the next specific file parent case to consider.
 
1915
        
 
1916
        :return: A list of the results, each of which is as for _process_entry.
 
1917
        """
 
1918
        results = []
 
1919
        while self.search_specific_file_parents:
 
1920
            # Process the parent directories for the paths we were iterating.
 
1921
            # Even in extremely large trees this should be modest, so currently
 
1922
            # no attempt is made to optimise.
 
1923
            path_utf8 = self.search_specific_file_parents.pop()
 
1924
            if path_utf8 in self.searched_exact_paths:
 
1925
                # We've examined this path.
 
1926
                continue
 
1927
            if osutils.is_inside_any(self.searched_specific_files, path_utf8):
 
1928
                # We've examined this path.
 
1929
                continue
 
1930
            path_entries = self.state._entries_for_path(path_utf8)
 
1931
            # We need either one or two entries. If the path in
 
1932
            # self.target_index has moved (so the entry in source_index is in
 
1933
            # 'ar') then we need to also look for the entry for this path in
 
1934
            # self.source_index, to output the appropriate delete-or-rename.
 
1935
            selected_entries = []
 
1936
            found_item = False
 
1937
            for candidate_entry in path_entries:
 
1938
                # Find entries present in target at this path:
 
1939
                if candidate_entry[1][self.target_index][0] not in 'ar':
 
1940
                    found_item = True
 
1941
                    selected_entries.append(candidate_entry)
 
1942
                # Find entries present in source at this path:
 
1943
                elif (self.source_index is not None and
 
1944
                    candidate_entry[1][self.source_index][0] not in 'ar'):
 
1945
                    found_item = True
 
1946
                    if candidate_entry[1][self.target_index][0] == 'a':
 
1947
                        # Deleted, emit it here.
 
1948
                        selected_entries.append(candidate_entry)
 
1949
                    else:
 
1950
                        # renamed, emit it when we process the directory it
 
1951
                        # ended up at.
 
1952
                        self.search_specific_file_parents.add(
 
1953
                            candidate_entry[1][self.target_index][1])
 
1954
            if not found_item:
 
1955
                raise AssertionError(
 
1956
                    "Missing entry for specific path parent %r, %r" % (
 
1957
                    path_utf8, path_entries))
 
1958
            path_info = self._path_info(path_utf8, path_utf8.decode('utf8'))
 
1959
            for entry in selected_entries:
 
1960
                if entry[0][2] in self.seen_ids:
 
1961
                    continue
 
1962
                result, changed = self._process_entry(entry, path_info)
 
1963
                if changed is None:
 
1964
                    raise AssertionError(
 
1965
                        "Got entry<->path mismatch for specific path "
 
1966
                        "%r entry %r path_info %r " % (
 
1967
                        path_utf8, entry, path_info))
 
1968
                # Only include changes - we're outside the users requested
 
1969
                # expansion.
 
1970
                if changed:
 
1971
                    self._gather_result_for_consistency(result)
 
1972
                    if (result[6][0] == 'directory' and
 
1973
                        result[6][1] != 'directory'):
 
1974
                        # This stopped being a directory, the old children have
 
1975
                        # to be included.
 
1976
                        if entry[1][self.source_index][0] == 'r':
 
1977
                            # renamed, take the source path
 
1978
                            entry_path_utf8 = entry[1][self.source_index][1]
 
1979
                        else:
 
1980
                            entry_path_utf8 = path_utf8
 
1981
                        initial_key = (entry_path_utf8, '', '')
 
1982
                        block_index, _ = self.state._find_block_index_from_key(
 
1983
                            initial_key)
 
1984
                        if block_index == 0:
 
1985
                            # The children of the root are in block index 1.
 
1986
                            block_index = block_index + 1
 
1987
                        current_block = None
 
1988
                        if block_index < len(self.state._dirblocks):
 
1989
                            current_block = self.state._dirblocks[block_index]
 
1990
                            if not osutils.is_inside(
 
1991
                                entry_path_utf8, current_block[0]):
 
1992
                                # No entries for this directory at all.
 
1993
                                current_block = None
 
1994
                        if current_block is not None:
 
1995
                            for entry in current_block[1]:
 
1996
                                if entry[1][self.source_index][0] in 'ar':
 
1997
                                    # Not in the source tree, so doesn't have to be
 
1998
                                    # included.
 
1999
                                    continue
 
2000
                                # Path of the entry itself.
 
2001
                                self.search_specific_file_parents.add(
 
2002
                                    self.pathjoin(*entry[0][:2]))
 
2003
                if changed or self.include_unchanged:
 
2004
                    results.append((result, changed))
 
2005
            self.searched_exact_paths.add(path_utf8)
 
2006
        return results
 
2007
 
 
2008
    cdef object _path_info(self, utf8_path, unicode_path):
 
2009
        """Generate path_info for unicode_path.
 
2010
 
 
2011
        :return: None if unicode_path does not exist, or a path_info tuple.
 
2012
        """
 
2013
        abspath = self.tree.abspath(unicode_path)
 
2014
        try:
 
2015
            stat = os.lstat(abspath)
 
2016
        except OSError, e:
 
2017
            if e.errno == errno.ENOENT:
 
2018
                # the path does not exist.
 
2019
                return None
 
2020
            else:
 
2021
                raise
 
2022
        utf8_basename = utf8_path.rsplit('/', 1)[-1]
 
2023
        dir_info = (utf8_path, utf8_basename,
 
2024
            osutils.file_kind_from_stat_mode(stat.st_mode), stat,
 
2025
            abspath)
 
2026
        if dir_info[2] == 'directory':
 
2027
            if self.tree._directory_is_tree_reference(
 
2028
                unicode_path):
 
2029
                self.root_dir_info = self.root_dir_info[:2] + \
 
2030
                    ('tree-reference',) + self.root_dir_info[3:]
 
2031
        return dir_info