/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/_dirstate_helpers_c.pyx

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2008-09-26 05:14:51 UTC
  • mfrom: (3737.1.3 trivial_python_compat)
  • Revision ID: pqm@pqm.ubuntu.com-20080926051451-dvc1qg5inn7msjvr
(jam) Some win32 tweaks for the faster iter_changes code.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2007, 2008 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  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
 
 
28
from bzrlib import cache_utf8, errors, osutils
 
29
from bzrlib.dirstate import DirState
 
30
from bzrlib.osutils import pathjoin, splitpath
 
31
 
 
32
 
 
33
# This is the Windows equivalent of ENOTDIR
 
34
# It is defined in pywin32.winerror, but we don't want a strong dependency for
 
35
# just an error code.
 
36
# XXX: Perhaps we could get it from a windows header ?
 
37
cdef int ERROR_PATH_NOT_FOUND
 
38
ERROR_PATH_NOT_FOUND = 3
 
39
cdef int ERROR_DIRECTORY
 
40
ERROR_DIRECTORY = 267
 
41
 
 
42
#python2.4 support, and other platform-dependent includes
 
43
cdef extern from "python-compat.h":
 
44
    unsigned long htonl(unsigned long)
 
45
 
 
46
# Give Pyrex some function definitions for it to understand.
 
47
# All of these are just hints to Pyrex, so that it can try to convert python
 
48
# objects into similar C objects. (such as PyInt => int).
 
49
# In anything defined 'cdef extern from XXX' the real C header will be
 
50
# imported, and the real definition will be used from there. So these are just
 
51
# hints, and do not need to match exactly to the C definitions.
 
52
 
 
53
cdef extern from *:
 
54
    ctypedef unsigned long size_t
 
55
 
 
56
cdef extern from "_dirstate_helpers_c.h":
 
57
    ctypedef int intptr_t
 
58
 
 
59
 
 
60
 
 
61
cdef extern from "stdlib.h":
 
62
    unsigned long int strtoul(char *nptr, char **endptr, int base)
 
63
 
 
64
 
 
65
cdef extern from 'sys/stat.h':
 
66
    int S_ISDIR(int mode)
 
67
    int S_ISREG(int mode)
 
68
    # On win32, this actually comes from "python-compat.h"
 
69
    int S_ISLNK(int mode)
 
70
    int S_IXUSR
 
71
 
 
72
# These functions allow us access to a bit of the 'bare metal' of python
 
73
# objects, rather than going through the object abstraction. (For example,
 
74
# PyList_Append, rather than getting the 'append' attribute of the object, and
 
75
# creating a tuple, and then using PyCallObject).
 
76
# Functions that return (or take) a void* are meant to grab a C PyObject*. This
 
77
# differs from the Pyrex 'object'. If you declare a variable as 'object' Pyrex
 
78
# will automatically Py_INCREF and Py_DECREF when appropriate. But for some
 
79
# inner loops, we don't need to do that at all, as the reference only lasts for
 
80
# a very short time.
 
81
# Note that the C API GetItem calls borrow references, so pyrex does the wrong
 
82
# thing if you declare e.g. object PyList_GetItem(object lst, int index) - you
 
83
# need to manually Py_INCREF yourself.
 
84
cdef extern from "Python.h":
 
85
    ctypedef int Py_ssize_t
 
86
    ctypedef struct PyObject:
 
87
        pass
 
88
    int PyList_Append(object lst, object item) except -1
 
89
    void *PyList_GetItem_object_void "PyList_GET_ITEM" (object lst, int index)
 
90
    void *PyList_GetItem_void_void "PyList_GET_ITEM" (void * lst, int index)
 
91
    object PyList_GET_ITEM(object lst, Py_ssize_t index)
 
92
    int PyList_CheckExact(object)
 
93
    Py_ssize_t PyList_GET_SIZE (object p)
 
94
 
 
95
    void *PyTuple_GetItem_void_void "PyTuple_GET_ITEM" (void* tpl, int index)
 
96
    object PyTuple_GetItem_void_object "PyTuple_GET_ITEM" (void* tpl, int index)
 
97
    object PyTuple_GET_ITEM(object tpl, Py_ssize_t index)
 
98
 
 
99
 
 
100
    char *PyString_AsString(object p)
 
101
    char *PyString_AsString_obj "PyString_AsString" (PyObject *string)
 
102
    char *PyString_AS_STRING_void "PyString_AS_STRING" (void *p)
 
103
    int PyString_AsStringAndSize(object str, char **buffer, Py_ssize_t *length) except -1
 
104
    object PyString_FromString(char *)
 
105
    object PyString_FromStringAndSize(char *, Py_ssize_t)
 
106
    int PyString_Size(object p)
 
107
    int PyString_GET_SIZE_void "PyString_GET_SIZE" (void *p)
 
108
    int PyString_CheckExact(object p)
 
109
    void Py_INCREF(object o)
 
110
    void Py_DECREF(object o)
 
111
 
 
112
 
 
113
cdef extern from "string.h":
 
114
    int strncmp(char *s1, char *s2, int len)
 
115
    void *memchr(void *s, int c, size_t len)
 
116
    int memcmp(void *b1, void *b2, size_t len)
 
117
    # ??? memrchr is a GNU extension :(
 
118
    # void *memrchr(void *s, int c, size_t len)
 
119
 
 
120
 
 
121
cdef void* _my_memrchr(void *s, int c, size_t n):
 
122
    # memrchr seems to be a GNU extension, so we have to implement it ourselves
 
123
    cdef char *pos
 
124
    cdef char *start
 
125
 
 
126
    start = <char*>s
 
127
    pos = start + n - 1
 
128
    while pos >= start:
 
129
        if pos[0] == c:
 
130
            return <void*>pos
 
131
        pos = pos - 1
 
132
    return NULL
 
133
 
 
134
 
 
135
def _py_memrchr(s, c):
 
136
    """Just to expose _my_memrchr for testing.
 
137
 
 
138
    :param s: The Python string to search
 
139
    :param c: The character to search for
 
140
    :return: The offset to the last instance of 'c' in s
 
141
    """
 
142
    cdef void *_s
 
143
    cdef void *found
 
144
    cdef int length
 
145
    cdef char *_c
 
146
 
 
147
    _s = PyString_AsString(s)
 
148
    length = PyString_Size(s)
 
149
 
 
150
    _c = PyString_AsString(c)
 
151
    assert PyString_Size(c) == 1,\
 
152
        'Must be a single character string, not %s' % (c,)
 
153
    found = _my_memrchr(_s, _c[0], length)
 
154
    if found == NULL:
 
155
        return None
 
156
    return <char*>found - <char*>_s
 
157
 
 
158
cdef object safe_string_from_size(char *s, Py_ssize_t size):
 
159
    if size < 0:
 
160
        # XXX: On 64-bit machines the <int> cast causes a C compiler warning.
 
161
        raise AssertionError(
 
162
            'tried to create a string with an invalid size: %d @0x%x'
 
163
            % (size, <int>s))
 
164
    return PyString_FromStringAndSize(s, size)
 
165
 
 
166
 
 
167
cdef int _is_aligned(void *ptr):
 
168
    """Is this pointer aligned to an integer size offset?
 
169
 
 
170
    :return: 1 if this pointer is aligned, 0 otherwise.
 
171
    """
 
172
    return ((<intptr_t>ptr) & ((sizeof(int))-1)) == 0
 
173
 
 
174
 
 
175
cdef int _cmp_by_dirs(char *path1, int size1, char *path2, int size2):
 
176
    cdef unsigned char *cur1
 
177
    cdef unsigned char *cur2
 
178
    cdef unsigned char *end1
 
179
    cdef unsigned char *end2
 
180
    cdef int *cur_int1
 
181
    cdef int *cur_int2
 
182
    cdef int *end_int1
 
183
    cdef int *end_int2
 
184
 
 
185
    if path1 == path2 and size1 == size2:
 
186
        return 0
 
187
 
 
188
    end1 = <unsigned char*>path1+size1
 
189
    end2 = <unsigned char*>path2+size2
 
190
 
 
191
    # Use 32-bit comparisons for the matching portion of the string.
 
192
    # Almost all CPU's are faster at loading and comparing 32-bit integers,
 
193
    # than they are at 8-bit integers.
 
194
    # 99% of the time, these will be aligned, but in case they aren't just skip
 
195
    # this loop
 
196
    if _is_aligned(path1) and _is_aligned(path2):
 
197
        cur_int1 = <int*>path1
 
198
        cur_int2 = <int*>path2
 
199
        end_int1 = <int*>(path1 + size1 - (size1 % sizeof(int)))
 
200
        end_int2 = <int*>(path2 + size2 - (size2 % sizeof(int)))
 
201
 
 
202
        while cur_int1 < end_int1 and cur_int2 < end_int2:
 
203
            if cur_int1[0] != cur_int2[0]:
 
204
                break
 
205
            cur_int1 = cur_int1 + 1
 
206
            cur_int2 = cur_int2 + 1
 
207
 
 
208
        cur1 = <unsigned char*>cur_int1
 
209
        cur2 = <unsigned char*>cur_int2
 
210
    else:
 
211
        cur1 = <unsigned char*>path1
 
212
        cur2 = <unsigned char*>path2
 
213
 
 
214
    while cur1 < end1 and cur2 < end2:
 
215
        if cur1[0] == cur2[0]:
 
216
            # This character matches, just go to the next one
 
217
            cur1 = cur1 + 1
 
218
            cur2 = cur2 + 1
 
219
            continue
 
220
        # The current characters do not match
 
221
        if cur1[0] == c'/':
 
222
            return -1 # Reached the end of path1 segment first
 
223
        elif cur2[0] == c'/':
 
224
            return 1 # Reached the end of path2 segment first
 
225
        elif cur1[0] < cur2[0]:
 
226
            return -1
 
227
        else:
 
228
            return 1
 
229
 
 
230
    # We reached the end of at least one of the strings
 
231
    if cur1 < end1:
 
232
        return 1 # Not at the end of cur1, must be at the end of cur2
 
233
    if cur2 < end2:
 
234
        return -1 # At the end of cur1, but not at cur2
 
235
    # We reached the end of both strings
 
236
    return 0
 
237
 
 
238
 
 
239
def cmp_by_dirs_c(path1, path2):
 
240
    """Compare two paths directory by directory.
 
241
 
 
242
    This is equivalent to doing::
 
243
 
 
244
       cmp(path1.split('/'), path2.split('/'))
 
245
 
 
246
    The idea is that you should compare path components separately. This
 
247
    differs from plain ``cmp(path1, path2)`` for paths like ``'a-b'`` and
 
248
    ``a/b``. "a-b" comes after "a" but would come before "a/b" lexically.
 
249
 
 
250
    :param path1: first path
 
251
    :param path2: second path
 
252
    :return: negative number if ``path1`` comes first,
 
253
        0 if paths are equal,
 
254
        and positive number if ``path2`` sorts first
 
255
    """
 
256
    if not PyString_CheckExact(path1):
 
257
        raise TypeError("'path1' must be a plain string, not %s: %r"
 
258
                        % (type(path1), path1))
 
259
    if not PyString_CheckExact(path2):
 
260
        raise TypeError("'path2' must be a plain string, not %s: %r"
 
261
                        % (type(path2), path2))
 
262
    return _cmp_by_dirs(PyString_AsString(path1),
 
263
                        PyString_Size(path1),
 
264
                        PyString_AsString(path2),
 
265
                        PyString_Size(path2))
 
266
 
 
267
 
 
268
def _cmp_path_by_dirblock_c(path1, path2):
 
269
    """Compare two paths based on what directory they are in.
 
270
 
 
271
    This generates a sort order, such that all children of a directory are
 
272
    sorted together, and grandchildren are in the same order as the
 
273
    children appear. But all grandchildren come after all children.
 
274
 
 
275
    In other words, all entries in a directory are sorted together, and
 
276
    directorys are sorted in cmp_by_dirs order.
 
277
 
 
278
    :param path1: first path
 
279
    :param path2: the second path
 
280
    :return: negative number if ``path1`` comes first,
 
281
        0 if paths are equal
 
282
        and a positive number if ``path2`` sorts first
 
283
    """
 
284
    if not PyString_CheckExact(path1):
 
285
        raise TypeError("'path1' must be a plain string, not %s: %r"
 
286
                        % (type(path1), path1))
 
287
    if not PyString_CheckExact(path2):
 
288
        raise TypeError("'path2' must be a plain string, not %s: %r"
 
289
                        % (type(path2), path2))
 
290
    return _cmp_path_by_dirblock(PyString_AsString(path1),
 
291
                                 PyString_Size(path1),
 
292
                                 PyString_AsString(path2),
 
293
                                 PyString_Size(path2))
 
294
 
 
295
 
 
296
cdef int _cmp_path_by_dirblock(char *path1, int path1_len,
 
297
                               char *path2, int path2_len):
 
298
    """Compare two paths by what directory they are in.
 
299
 
 
300
    see ``_cmp_path_by_dirblock_c`` for details.
 
301
    """
 
302
    cdef char *dirname1
 
303
    cdef int dirname1_len
 
304
    cdef char *dirname2
 
305
    cdef int dirname2_len
 
306
    cdef char *basename1
 
307
    cdef int basename1_len
 
308
    cdef char *basename2
 
309
    cdef int basename2_len
 
310
    cdef int cur_len
 
311
    cdef int cmp_val
 
312
 
 
313
    if path1_len == 0 and path2_len == 0:
 
314
        return 0
 
315
 
 
316
    if path1 == path2 and path1_len == path2_len:
 
317
        return 0
 
318
 
 
319
    if path1_len == 0:
 
320
        return -1
 
321
 
 
322
    if path2_len == 0:
 
323
        return 1
 
324
 
 
325
    basename1 = <char*>_my_memrchr(path1, c'/', path1_len)
 
326
 
 
327
    if basename1 == NULL:
 
328
        basename1 = path1
 
329
        basename1_len = path1_len
 
330
        dirname1 = ''
 
331
        dirname1_len = 0
 
332
    else:
 
333
        dirname1 = path1
 
334
        dirname1_len = basename1 - path1
 
335
        basename1 = basename1 + 1
 
336
        basename1_len = path1_len - dirname1_len - 1
 
337
 
 
338
    basename2 = <char*>_my_memrchr(path2, c'/', path2_len)
 
339
 
 
340
    if basename2 == NULL:
 
341
        basename2 = path2
 
342
        basename2_len = path2_len
 
343
        dirname2 = ''
 
344
        dirname2_len = 0
 
345
    else:
 
346
        dirname2 = path2
 
347
        dirname2_len = basename2 - path2
 
348
        basename2 = basename2 + 1
 
349
        basename2_len = path2_len - dirname2_len - 1
 
350
 
 
351
    cmp_val = _cmp_by_dirs(dirname1, dirname1_len,
 
352
                           dirname2, dirname2_len)
 
353
    if cmp_val != 0:
 
354
        return cmp_val
 
355
 
 
356
    cur_len = basename1_len
 
357
    if basename2_len < basename1_len:
 
358
        cur_len = basename2_len
 
359
 
 
360
    cmp_val = memcmp(basename1, basename2, cur_len)
 
361
    if cmp_val != 0:
 
362
        return cmp_val
 
363
    if basename1_len == basename2_len:
 
364
        return 0
 
365
    if basename1_len < basename2_len:
 
366
        return -1
 
367
    return 1
 
368
 
 
369
 
 
370
def _bisect_path_left_c(paths, path):
 
371
    """Return the index where to insert path into paths.
 
372
 
 
373
    This uses a path-wise comparison so we get::
 
374
        a
 
375
        a-b
 
376
        a=b
 
377
        a/b
 
378
    Rather than::
 
379
        a
 
380
        a-b
 
381
        a/b
 
382
        a=b
 
383
    :param paths: A list of paths to search through
 
384
    :param path: A single path to insert
 
385
    :return: An offset where 'path' can be inserted.
 
386
    :seealso: bisect.bisect_left
 
387
    """
 
388
    cdef int _lo
 
389
    cdef int _hi
 
390
    cdef int _mid
 
391
    cdef char *path_cstr
 
392
    cdef int path_size
 
393
    cdef char *cur_cstr
 
394
    cdef int cur_size
 
395
    cdef void *cur
 
396
 
 
397
    if not PyList_CheckExact(paths):
 
398
        raise TypeError("you must pass a python list for 'paths' not: %s %r"
 
399
                        % (type(paths), paths))
 
400
    if not PyString_CheckExact(path):
 
401
        raise TypeError("you must pass a string for 'path' not: %s %r"
 
402
                        % (type(path), path))
 
403
 
 
404
    _hi = len(paths)
 
405
    _lo = 0
 
406
 
 
407
    path_cstr = PyString_AsString(path)
 
408
    path_size = PyString_Size(path)
 
409
 
 
410
    while _lo < _hi:
 
411
        _mid = (_lo + _hi) / 2
 
412
        cur = PyList_GetItem_object_void(paths, _mid)
 
413
        cur_cstr = PyString_AS_STRING_void(cur)
 
414
        cur_size = PyString_GET_SIZE_void(cur)
 
415
        if _cmp_path_by_dirblock(cur_cstr, cur_size, path_cstr, path_size) < 0:
 
416
            _lo = _mid + 1
 
417
        else:
 
418
            _hi = _mid
 
419
    return _lo
 
420
 
 
421
 
 
422
def _bisect_path_right_c(paths, path):
 
423
    """Return the index where to insert path into paths.
 
424
 
 
425
    This uses a path-wise comparison so we get::
 
426
        a
 
427
        a-b
 
428
        a=b
 
429
        a/b
 
430
    Rather than::
 
431
        a
 
432
        a-b
 
433
        a/b
 
434
        a=b
 
435
    :param paths: A list of paths to search through
 
436
    :param path: A single path to insert
 
437
    :return: An offset where 'path' can be inserted.
 
438
    :seealso: bisect.bisect_right
 
439
    """
 
440
    cdef int _lo
 
441
    cdef int _hi
 
442
    cdef int _mid
 
443
    cdef char *path_cstr
 
444
    cdef int path_size
 
445
    cdef char *cur_cstr
 
446
    cdef int cur_size
 
447
    cdef void *cur
 
448
 
 
449
    if not PyList_CheckExact(paths):
 
450
        raise TypeError("you must pass a python list for 'paths' not: %s %r"
 
451
                        % (type(paths), paths))
 
452
    if not PyString_CheckExact(path):
 
453
        raise TypeError("you must pass a string for 'path' not: %s %r"
 
454
                        % (type(path), path))
 
455
 
 
456
    _hi = len(paths)
 
457
    _lo = 0
 
458
 
 
459
    path_cstr = PyString_AsString(path)
 
460
    path_size = PyString_Size(path)
 
461
 
 
462
    while _lo < _hi:
 
463
        _mid = (_lo + _hi) / 2
 
464
        cur = PyList_GetItem_object_void(paths, _mid)
 
465
        cur_cstr = PyString_AS_STRING_void(cur)
 
466
        cur_size = PyString_GET_SIZE_void(cur)
 
467
        if _cmp_path_by_dirblock(path_cstr, path_size, cur_cstr, cur_size) < 0:
 
468
            _hi = _mid
 
469
        else:
 
470
            _lo = _mid + 1
 
471
    return _lo
 
472
 
 
473
 
 
474
def bisect_dirblock_c(dirblocks, dirname, lo=0, hi=None, cache=None):
 
475
    """Return the index where to insert dirname into the dirblocks.
 
476
 
 
477
    The return value idx is such that all directories blocks in dirblock[:idx]
 
478
    have names < dirname, and all blocks in dirblock[idx:] have names >=
 
479
    dirname.
 
480
 
 
481
    Optional args lo (default 0) and hi (default len(dirblocks)) bound the
 
482
    slice of a to be searched.
 
483
    """
 
484
    cdef int _lo
 
485
    cdef int _hi
 
486
    cdef int _mid
 
487
    cdef char *dirname_cstr
 
488
    cdef int dirname_size
 
489
    cdef char *cur_cstr
 
490
    cdef int cur_size
 
491
    cdef void *cur
 
492
 
 
493
    if not PyList_CheckExact(dirblocks):
 
494
        raise TypeError("you must pass a python list for 'dirblocks' not: %s %r"
 
495
                        % (type(dirblocks), dirblocks))
 
496
    if not PyString_CheckExact(dirname):
 
497
        raise TypeError("you must pass a string for dirname not: %s %r"
 
498
                        % (type(dirname), dirname))
 
499
    if hi is None:
 
500
        _hi = len(dirblocks)
 
501
    else:
 
502
        _hi = hi
 
503
 
 
504
    _lo = lo
 
505
    dirname_cstr = PyString_AsString(dirname)
 
506
    dirname_size = PyString_Size(dirname)
 
507
 
 
508
    while _lo < _hi:
 
509
        _mid = (_lo + _hi) / 2
 
510
        # Grab the dirname for the current dirblock
 
511
        # cur = dirblocks[_mid][0]
 
512
        cur = PyTuple_GetItem_void_void(
 
513
                PyList_GetItem_object_void(dirblocks, _mid), 0)
 
514
        cur_cstr = PyString_AS_STRING_void(cur)
 
515
        cur_size = PyString_GET_SIZE_void(cur)
 
516
        if _cmp_by_dirs(cur_cstr, cur_size, dirname_cstr, dirname_size) < 0:
 
517
            _lo = _mid + 1
 
518
        else:
 
519
            _hi = _mid
 
520
    return _lo
 
521
 
 
522
 
 
523
cdef class Reader:
 
524
    """Maintain the current location, and return fields as you parse them."""
 
525
 
 
526
    cdef object state # The DirState object
 
527
    cdef object text # The overall string object
 
528
    cdef char *text_cstr # Pointer to the beginning of text
 
529
    cdef int text_size # Length of text
 
530
 
 
531
    cdef char *end_cstr # End of text
 
532
    cdef char *cur_cstr # Pointer to the current record
 
533
    cdef char *next # Pointer to the end of this record
 
534
 
 
535
    def __init__(self, text, state):
 
536
        self.state = state
 
537
        self.text = text
 
538
        self.text_cstr = PyString_AsString(text)
 
539
        self.text_size = PyString_Size(text)
 
540
        self.end_cstr = self.text_cstr + self.text_size
 
541
        self.cur_cstr = self.text_cstr
 
542
 
 
543
    cdef char *get_next(self, int *size) except NULL:
 
544
        """Return a pointer to the start of the next field."""
 
545
        cdef char *next
 
546
        cdef Py_ssize_t extra_len
 
547
 
 
548
        if self.cur_cstr == NULL:
 
549
            raise AssertionError('get_next() called when cur_str is NULL')
 
550
        elif self.cur_cstr >= self.end_cstr:
 
551
            raise AssertionError('get_next() called when there are no chars'
 
552
                                 ' left')
 
553
        next = self.cur_cstr
 
554
        self.cur_cstr = <char*>memchr(next, c'\0', self.end_cstr - next)
 
555
        if self.cur_cstr == NULL:
 
556
            extra_len = self.end_cstr - next
 
557
            raise errors.DirstateCorrupt(self.state,
 
558
                'failed to find trailing NULL (\\0).'
 
559
                ' Trailing garbage: %r'
 
560
                % safe_string_from_size(next, extra_len))
 
561
        size[0] = self.cur_cstr - next
 
562
        self.cur_cstr = self.cur_cstr + 1
 
563
        return next
 
564
 
 
565
    cdef object get_next_str(self):
 
566
        """Get the next field as a Python string."""
 
567
        cdef int size
 
568
        cdef char *next
 
569
        next = self.get_next(&size)
 
570
        return safe_string_from_size(next, size)
 
571
 
 
572
    cdef int _init(self) except -1:
 
573
        """Get the pointer ready.
 
574
 
 
575
        This assumes that the dirstate header has already been read, and we
 
576
        already have the dirblock string loaded into memory.
 
577
        This just initializes our memory pointers, etc for parsing of the
 
578
        dirblock string.
 
579
        """
 
580
        cdef char *first
 
581
        cdef int size
 
582
        # The first field should be an empty string left over from the Header
 
583
        first = self.get_next(&size)
 
584
        if first[0] != c'\0' and size == 0:
 
585
            raise AssertionError('First character should be null not: %s'
 
586
                                 % (first,))
 
587
        return 0
 
588
 
 
589
    cdef object _get_entry(self, int num_trees, void **p_current_dirname,
 
590
                           int *new_block):
 
591
        """Extract the next entry.
 
592
 
 
593
        This parses the next entry based on the current location in
 
594
        ``self.cur_cstr``.
 
595
        Each entry can be considered a "row" in the total table. And each row
 
596
        has a fixed number of columns. It is generally broken up into "key"
 
597
        columns, then "current" columns, and then "parent" columns.
 
598
 
 
599
        :param num_trees: How many parent trees need to be parsed
 
600
        :param p_current_dirname: A pointer to the current PyString
 
601
            representing the directory name.
 
602
            We pass this in as a void * so that pyrex doesn't have to
 
603
            increment/decrement the PyObject reference counter for each
 
604
            _get_entry call.
 
605
            We use a pointer so that _get_entry can update it with the new
 
606
            value.
 
607
        :param new_block: This is to let the caller know that it needs to
 
608
            create a new directory block to store the next entry.
 
609
        """
 
610
        cdef object path_name_file_id_key
 
611
        cdef char *entry_size_cstr
 
612
        cdef unsigned long int entry_size
 
613
        cdef char* executable_cstr
 
614
        cdef int is_executable
 
615
        cdef char* dirname_cstr
 
616
        cdef char* trailing
 
617
        cdef int cur_size
 
618
        cdef int i
 
619
        cdef object minikind
 
620
        cdef object fingerprint
 
621
        cdef object info
 
622
 
 
623
        # Read the 'key' information (dirname, name, file_id)
 
624
        dirname_cstr = self.get_next(&cur_size)
 
625
        # Check to see if we have started a new directory block.
 
626
        # If so, then we need to create a new dirname PyString, so that it can
 
627
        # be used in all of the tuples. This saves time and memory, by re-using
 
628
        # the same object repeatedly.
 
629
 
 
630
        # Do the cheap 'length of string' check first. If the string is a
 
631
        # different length, then we *have* to be a different directory.
 
632
        if (cur_size != PyString_GET_SIZE_void(p_current_dirname[0])
 
633
            or strncmp(dirname_cstr,
 
634
                       # Extract the char* from our current dirname string.  We
 
635
                       # know it is a PyString, so we can use
 
636
                       # PyString_AS_STRING, we use the _void version because
 
637
                       # we are tricking Pyrex by using a void* rather than an
 
638
                       # <object>
 
639
                       PyString_AS_STRING_void(p_current_dirname[0]),
 
640
                       cur_size+1) != 0):
 
641
            dirname = safe_string_from_size(dirname_cstr, cur_size)
 
642
            p_current_dirname[0] = <void*>dirname
 
643
            new_block[0] = 1
 
644
        else:
 
645
            new_block[0] = 0
 
646
 
 
647
        # Build up the key that will be used.
 
648
        # By using <object>(void *) Pyrex will automatically handle the
 
649
        # Py_INCREF that we need.
 
650
        path_name_file_id_key = (<object>p_current_dirname[0],
 
651
                                 self.get_next_str(),
 
652
                                 self.get_next_str(),
 
653
                                )
 
654
 
 
655
        # Parse all of the per-tree information. current has the information in
 
656
        # the same location as parent trees. The only difference is that 'info'
 
657
        # is a 'packed_stat' for current, while it is a 'revision_id' for
 
658
        # parent trees.
 
659
        # minikind, fingerprint, and info will be returned as regular python
 
660
        # strings
 
661
        # entry_size and is_executable will be parsed into a python Long and
 
662
        # python Boolean, respectively.
 
663
        # TODO: jam 20070718 Consider changin the entry_size conversion to
 
664
        #       prefer python Int when possible. They are generally faster to
 
665
        #       work with, and it will be rare that we have a file >2GB.
 
666
        #       Especially since this code is pretty much fixed at a max of
 
667
        #       4GB.
 
668
        trees = []
 
669
        for i from 0 <= i < num_trees:
 
670
            minikind = self.get_next_str()
 
671
            fingerprint = self.get_next_str()
 
672
            entry_size_cstr = self.get_next(&cur_size)
 
673
            entry_size = strtoul(entry_size_cstr, NULL, 10)
 
674
            executable_cstr = self.get_next(&cur_size)
 
675
            is_executable = (executable_cstr[0] == c'y')
 
676
            info = self.get_next_str()
 
677
            PyList_Append(trees, (
 
678
                minikind,     # minikind
 
679
                fingerprint,  # fingerprint
 
680
                entry_size,   # size
 
681
                is_executable,# executable
 
682
                info,         # packed_stat or revision_id
 
683
            ))
 
684
 
 
685
        # The returned tuple is (key, [trees])
 
686
        ret = (path_name_file_id_key, trees)
 
687
        # Ignore the trailing newline, but assert that it does exist, this
 
688
        # ensures that we always finish parsing a line on an end-of-entry
 
689
        # marker.
 
690
        trailing = self.get_next(&cur_size)
 
691
        if cur_size != 1 or trailing[0] != c'\n':
 
692
            raise errors.DirstateCorrupt(self.state,
 
693
                'Bad parse, we expected to end on \\n, not: %d %s: %s'
 
694
                % (cur_size, safe_string_from_size(trailing, cur_size),
 
695
                   ret))
 
696
        return ret
 
697
 
 
698
    def _parse_dirblocks(self):
 
699
        """Parse all dirblocks in the state file."""
 
700
        cdef int num_trees
 
701
        cdef object current_block
 
702
        cdef object entry
 
703
        cdef void * current_dirname
 
704
        cdef int new_block
 
705
        cdef int expected_entry_count
 
706
        cdef int entry_count
 
707
 
 
708
        num_trees = self.state._num_present_parents() + 1
 
709
        expected_entry_count = self.state._num_entries
 
710
 
 
711
        # Ignore the first record
 
712
        self._init()
 
713
 
 
714
        current_block = []
 
715
        dirblocks = [('', current_block), ('', [])]
 
716
        self.state._dirblocks = dirblocks
 
717
        obj = ''
 
718
        current_dirname = <void*>obj
 
719
        new_block = 0
 
720
        entry_count = 0
 
721
 
 
722
        # TODO: jam 2007-05-07 Consider pre-allocating some space for the
 
723
        #       members, and then growing and shrinking from there. If most
 
724
        #       directories have close to 10 entries in them, it would save a
 
725
        #       few mallocs if we default our list size to something
 
726
        #       reasonable. Or we could malloc it to something large (100 or
 
727
        #       so), and then truncate. That would give us a malloc + realloc,
 
728
        #       rather than lots of reallocs.
 
729
        while self.cur_cstr < self.end_cstr:
 
730
            entry = self._get_entry(num_trees, &current_dirname, &new_block)
 
731
            if new_block:
 
732
                # new block - different dirname
 
733
                current_block = []
 
734
                PyList_Append(dirblocks,
 
735
                              (<object>current_dirname, current_block))
 
736
            PyList_Append(current_block, entry)
 
737
            entry_count = entry_count + 1
 
738
        if entry_count != expected_entry_count:
 
739
            raise errors.DirstateCorrupt(self.state,
 
740
                    'We read the wrong number of entries.'
 
741
                    ' We expected to read %s, but read %s'
 
742
                    % (expected_entry_count, entry_count))
 
743
        self.state._split_root_dirblock_into_contents()
 
744
 
 
745
 
 
746
def _read_dirblocks_c(state):
 
747
    """Read in the dirblocks for the given DirState object.
 
748
 
 
749
    This is tightly bound to the DirState internal representation. It should be
 
750
    thought of as a member function, which is only separated out so that we can
 
751
    re-write it in pyrex.
 
752
 
 
753
    :param state: A DirState object.
 
754
    :return: None
 
755
    :postcondition: The dirblocks will be loaded into the appropriate fields in
 
756
        the DirState object.
 
757
    """
 
758
    state._state_file.seek(state._end_of_header)
 
759
    text = state._state_file.read()
 
760
    # TODO: check the crc checksums. crc_measured = zlib.crc32(text)
 
761
 
 
762
    reader = Reader(text, state)
 
763
 
 
764
    reader._parse_dirblocks()
 
765
    state._dirblock_state = DirState.IN_MEMORY_UNMODIFIED
 
766
 
 
767
 
 
768
cdef int minikind_from_mode(int mode):
 
769
    # in order of frequency:
 
770
    if S_ISREG(mode):
 
771
        return c"f"
 
772
    if S_ISDIR(mode):
 
773
        return c"d"
 
774
    if S_ISLNK(mode):
 
775
        return c"l"
 
776
    return 0
 
777
 
 
778
 
 
779
_encode = binascii.b2a_base64
 
780
 
 
781
 
 
782
from struct import pack
 
783
cdef _pack_stat(stat_value):
 
784
    """return a string representing the stat value's key fields.
 
785
 
 
786
    :param stat_value: A stat oject with st_size, st_mtime, st_ctime, st_dev,
 
787
        st_ino and st_mode fields.
 
788
    """
 
789
    cdef char result[6*4] # 6 long ints
 
790
    cdef int *aliased
 
791
    aliased = <int *>result
 
792
    aliased[0] = htonl(stat_value.st_size)
 
793
    aliased[1] = htonl(int(stat_value.st_mtime))
 
794
    aliased[2] = htonl(int(stat_value.st_ctime))
 
795
    aliased[3] = htonl(stat_value.st_dev)
 
796
    aliased[4] = htonl(stat_value.st_ino & 0xFFFFFFFF)
 
797
    aliased[5] = htonl(stat_value.st_mode)
 
798
    packed = PyString_FromStringAndSize(result, 6*4)
 
799
    return _encode(packed)[:-1]
 
800
 
 
801
 
 
802
def update_entry(self, entry, abspath, stat_value):
 
803
    """Update the entry based on what is actually on disk.
 
804
 
 
805
    :param entry: This is the dirblock entry for the file in question.
 
806
    :param abspath: The path on disk for this file.
 
807
    :param stat_value: (optional) if we already have done a stat on the
 
808
        file, re-use it.
 
809
    :return: The sha1 hexdigest of the file (40 bytes) or link target of a
 
810
            symlink.
 
811
    """
 
812
    return _update_entry(self, entry, abspath, stat_value)
 
813
 
 
814
 
 
815
cdef _update_entry(self, entry, abspath, stat_value):
 
816
    """Update the entry based on what is actually on disk.
 
817
 
 
818
    :param self: The dirstate object this is operating on.
 
819
    :param entry: This is the dirblock entry for the file in question.
 
820
    :param abspath: The path on disk for this file.
 
821
    :param stat_value: The stat value done on the path.
 
822
    :return: The sha1 hexdigest of the file (40 bytes) or link target of a
 
823
            symlink.
 
824
    """
 
825
    # TODO - require pyrex 0.9.8, then use a pyd file to define access to the
 
826
    # _st mode of the compiled stat objects.
 
827
    cdef int minikind, saved_minikind
 
828
    cdef void * details
 
829
    minikind = minikind_from_mode(stat_value.st_mode)
 
830
    if 0 == minikind:
 
831
        return None
 
832
    packed_stat = _pack_stat(stat_value)
 
833
    details = PyList_GetItem_void_void(PyTuple_GetItem_void_void(<void *>entry, 1), 0)
 
834
    saved_minikind = PyString_AsString_obj(<PyObject *>PyTuple_GetItem_void_void(details, 0))[0]
 
835
    saved_link_or_sha1 = PyTuple_GetItem_void_object(details, 1)
 
836
    saved_file_size = PyTuple_GetItem_void_object(details, 2)
 
837
    saved_executable = PyTuple_GetItem_void_object(details, 3)
 
838
    saved_packed_stat = PyTuple_GetItem_void_object(details, 4)
 
839
    # Deal with pyrex decrefing the objects
 
840
    Py_INCREF(saved_link_or_sha1)
 
841
    Py_INCREF(saved_file_size)
 
842
    Py_INCREF(saved_executable)
 
843
    Py_INCREF(saved_packed_stat)
 
844
    #(saved_minikind, saved_link_or_sha1, saved_file_size,
 
845
    # saved_executable, saved_packed_stat) = entry[1][0]
 
846
 
 
847
    if (minikind == saved_minikind
 
848
        and packed_stat == saved_packed_stat):
 
849
        # The stat hasn't changed since we saved, so we can re-use the
 
850
        # saved sha hash.
 
851
        if minikind == c'd':
 
852
            return None
 
853
 
 
854
        # size should also be in packed_stat
 
855
        if saved_file_size == stat_value.st_size:
 
856
            return saved_link_or_sha1
 
857
 
 
858
    # If we have gotten this far, that means that we need to actually
 
859
    # process this entry.
 
860
    link_or_sha1 = None
 
861
    if minikind == c'f':
 
862
        link_or_sha1 = self._sha1_file(abspath)
 
863
        executable = self._is_executable(stat_value.st_mode,
 
864
                                         saved_executable)
 
865
        if self._cutoff_time is None:
 
866
            self._sha_cutoff_time()
 
867
        if (stat_value.st_mtime < self._cutoff_time
 
868
            and stat_value.st_ctime < self._cutoff_time):
 
869
            entry[1][0] = ('f', link_or_sha1, stat_value.st_size,
 
870
                           executable, packed_stat)
 
871
        else:
 
872
            entry[1][0] = ('f', '', stat_value.st_size,
 
873
                           executable, DirState.NULLSTAT)
 
874
    elif minikind == c'd':
 
875
        link_or_sha1 = None
 
876
        entry[1][0] = ('d', '', 0, False, packed_stat)
 
877
        if saved_minikind != c'd':
 
878
            # This changed from something into a directory. Make sure we
 
879
            # have a directory block for it. This doesn't happen very
 
880
            # often, so this doesn't have to be super fast.
 
881
            block_index, entry_index, dir_present, file_present = \
 
882
                self._get_block_entry_index(entry[0][0], entry[0][1], 0)
 
883
            self._ensure_block(block_index, entry_index,
 
884
                               pathjoin(entry[0][0], entry[0][1]))
 
885
    elif minikind == c'l':
 
886
        link_or_sha1 = self._read_link(abspath, saved_link_or_sha1)
 
887
        if self._cutoff_time is None:
 
888
            self._sha_cutoff_time()
 
889
        if (stat_value.st_mtime < self._cutoff_time
 
890
            and stat_value.st_ctime < self._cutoff_time):
 
891
            entry[1][0] = ('l', link_or_sha1, stat_value.st_size,
 
892
                           False, packed_stat)
 
893
        else:
 
894
            entry[1][0] = ('l', '', stat_value.st_size,
 
895
                           False, DirState.NULLSTAT)
 
896
    self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
897
    return link_or_sha1
 
898
 
 
899
 
 
900
cdef char _minikind_from_string(object string):
 
901
    """Convert a python string to a char."""
 
902
    return PyString_AsString(string)[0]
 
903
 
 
904
 
 
905
cdef object _kind_absent
 
906
cdef object _kind_file
 
907
cdef object _kind_directory
 
908
cdef object _kind_symlink
 
909
cdef object _kind_relocated
 
910
cdef object _kind_tree_reference
 
911
_kind_absent = "absent"
 
912
_kind_file = "file"
 
913
_kind_directory = "directory"
 
914
_kind_symlink = "symlink"
 
915
_kind_relocated = "relocated"
 
916
_kind_tree_reference = "tree-reference"
 
917
 
 
918
 
 
919
cdef object _minikind_to_kind(char minikind):
 
920
    """Create a string kind for minikind."""
 
921
    cdef char _minikind[1]
 
922
    if minikind == c'f':
 
923
        return _kind_file
 
924
    elif minikind == c'd':
 
925
        return _kind_directory
 
926
    elif minikind == c'a':
 
927
        return _kind_absent
 
928
    elif minikind == c'r':
 
929
        return _kind_relocated
 
930
    elif minikind == c'l':
 
931
        return _kind_symlink
 
932
    elif minikind == c't':
 
933
        return _kind_tree_reference
 
934
    _minikind[0] = minikind
 
935
    raise KeyError(PyString_FromStringAndSize(_minikind, 1))
 
936
 
 
937
 
 
938
cdef int _versioned_minikind(char minikind):
 
939
    """Return non-zero if minikind is in fltd"""
 
940
    return (minikind == c'f' or
 
941
            minikind == c'd' or
 
942
            minikind == c'l' or
 
943
            minikind == c't')
 
944
 
 
945
 
 
946
cdef class ProcessEntryC:
 
947
 
 
948
    cdef object old_dirname_to_file_id # dict
 
949
    cdef object new_dirname_to_file_id # dict
 
950
    cdef readonly object uninteresting
 
951
    cdef object last_source_parent
 
952
    cdef object last_target_parent
 
953
    cdef object include_unchanged
 
954
    cdef object use_filesystem_for_exec
 
955
    cdef object utf8_decode
 
956
    cdef readonly object searched_specific_files
 
957
    cdef object search_specific_files
 
958
    cdef object state
 
959
    # Current iteration variables:
 
960
    cdef object current_root
 
961
    cdef object current_root_unicode
 
962
    cdef object root_entries
 
963
    cdef int root_entries_pos, root_entries_len
 
964
    cdef object root_abspath
 
965
    cdef int source_index, target_index
 
966
    cdef int want_unversioned
 
967
    cdef object tree
 
968
    cdef object dir_iterator
 
969
    cdef int block_index
 
970
    cdef object current_block
 
971
    cdef int current_block_pos
 
972
    cdef object current_block_list
 
973
    cdef object current_dir_info
 
974
    cdef object current_dir_list
 
975
    cdef int path_index
 
976
    cdef object root_dir_info
 
977
    cdef object bisect_left
 
978
    cdef object pathjoin
 
979
 
 
980
    def __init__(self, include_unchanged, use_filesystem_for_exec,
 
981
        search_specific_files, state, source_index, target_index,
 
982
        want_unversioned, tree):
 
983
        self.old_dirname_to_file_id = {}
 
984
        self.new_dirname_to_file_id = {}
 
985
        # Just a sentry, so that _process_entry can say that this
 
986
        # record is handled, but isn't interesting to process (unchanged)
 
987
        self.uninteresting = object()
 
988
        # Using a list so that we can access the values and change them in
 
989
        # nested scope. Each one is [path, file_id, entry]
 
990
        self.last_source_parent = [None, None]
 
991
        self.last_target_parent = [None, None]
 
992
        self.include_unchanged = include_unchanged
 
993
        self.use_filesystem_for_exec = use_filesystem_for_exec
 
994
        self.utf8_decode = cache_utf8._utf8_decode
 
995
        # for all search_indexs in each path at or under each element of
 
996
        # search_specific_files, if the detail is relocated: add the id, and add the
 
997
        # relocated path as one to search if its not searched already. If the
 
998
        # detail is not relocated, add the id.
 
999
        self.searched_specific_files = set()
 
1000
        self.search_specific_files = search_specific_files
 
1001
        self.state = state
 
1002
        self.current_root = None
 
1003
        self.current_root_unicode = None
 
1004
        self.root_entries = None
 
1005
        self.root_entries_pos = 0
 
1006
        self.root_entries_len = 0
 
1007
        self.root_abspath = None
 
1008
        if source_index is None:
 
1009
            self.source_index = -1
 
1010
        else:
 
1011
            self.source_index = source_index
 
1012
        self.target_index = target_index
 
1013
        self.want_unversioned = want_unversioned
 
1014
        self.tree = tree
 
1015
        self.dir_iterator = None
 
1016
        self.block_index = -1
 
1017
        self.current_block = None
 
1018
        self.current_block_list = None
 
1019
        self.current_block_pos = -1
 
1020
        self.current_dir_info = None
 
1021
        self.current_dir_list = None
 
1022
        self.path_index = 0
 
1023
        self.root_dir_info = None
 
1024
        self.bisect_left = bisect.bisect_left
 
1025
        self.pathjoin = osutils.pathjoin
 
1026
 
 
1027
    cdef _process_entry(self, entry, path_info):
 
1028
        """Compare an entry and real disk to generate delta information.
 
1029
 
 
1030
        :param path_info: top_relpath, basename, kind, lstat, abspath for
 
1031
            the path of entry. If None, then the path is considered absent.
 
1032
            (Perhaps we should pass in a concrete entry for this ?)
 
1033
            Basename is returned as a utf8 string because we expect this
 
1034
            tuple will be ignored, and don't want to take the time to
 
1035
            decode.
 
1036
        :return: None if the these don't match
 
1037
                 A tuple of information about the change, or
 
1038
                 the object 'uninteresting' if these match, but are
 
1039
                 basically identical.
 
1040
        """
 
1041
        cdef char target_minikind
 
1042
        cdef char source_minikind
 
1043
        cdef object file_id
 
1044
        cdef int content_change
 
1045
        cdef object details_list
 
1046
        file_id = None
 
1047
        details_list = entry[1]
 
1048
        if -1 == self.source_index:
 
1049
            source_details = DirState.NULL_PARENT_DETAILS
 
1050
        else:
 
1051
            source_details = details_list[self.source_index]
 
1052
        target_details = details_list[self.target_index]
 
1053
        target_minikind = _minikind_from_string(target_details[0])
 
1054
        if path_info is not None and _versioned_minikind(target_minikind):
 
1055
            if self.target_index != 0:
 
1056
                raise AssertionError("Unsupported target index %d" % target_index)
 
1057
            link_or_sha1 = _update_entry(self.state, entry, path_info[4], path_info[3])
 
1058
            # The entry may have been modified by update_entry
 
1059
            target_details = details_list[self.target_index]
 
1060
            target_minikind = _minikind_from_string(target_details[0])
 
1061
        else:
 
1062
            link_or_sha1 = None
 
1063
        # the rest of this function is 0.3 seconds on 50K paths, or
 
1064
        # 0.000006 seconds per call.
 
1065
        source_minikind = _minikind_from_string(source_details[0])
 
1066
        if ((_versioned_minikind(source_minikind) or source_minikind == c'r')
 
1067
            and _versioned_minikind(target_minikind)):
 
1068
            # claimed content in both: diff
 
1069
            #   r    | fdlt   |      | add source to search, add id path move and perform
 
1070
            #        |        |      | diff check on source-target
 
1071
            #   r    | fdlt   |  a   | dangling file that was present in the basis.
 
1072
            #        |        |      | ???
 
1073
            if source_minikind != c'r':
 
1074
                old_dirname = entry[0][0]
 
1075
                old_basename = entry[0][1]
 
1076
                old_path = path = None
 
1077
            else:
 
1078
                # add the source to the search path to find any children it
 
1079
                # has.  TODO ? : only add if it is a container ?
 
1080
                if not osutils.is_inside_any(self.searched_specific_files,
 
1081
                                             source_details[1]):
 
1082
                    self.search_specific_files.add(source_details[1])
 
1083
                # generate the old path; this is needed for stating later
 
1084
                # as well.
 
1085
                old_path = source_details[1]
 
1086
                old_dirname, old_basename = os.path.split(old_path)
 
1087
                path = self.pathjoin(entry[0][0], entry[0][1])
 
1088
                old_entry = self.state._get_entry(self.source_index,
 
1089
                                             path_utf8=old_path)
 
1090
                # update the source details variable to be the real
 
1091
                # location.
 
1092
                if old_entry == (None, None):
 
1093
                    raise errors.CorruptDirstate(self.state._filename,
 
1094
                        "entry '%s/%s' is considered renamed from %r"
 
1095
                        " but source does not exist\n"
 
1096
                        "entry: %s" % (entry[0][0], entry[0][1], old_path, entry))
 
1097
                source_details = old_entry[1][self.source_index]
 
1098
                source_minikind = _minikind_from_string(source_details[0])
 
1099
            if path_info is None:
 
1100
                # the file is missing on disk, show as removed.
 
1101
                content_change = 1
 
1102
                target_kind = None
 
1103
                target_exec = False
 
1104
            else:
 
1105
                # source and target are both versioned and disk file is present.
 
1106
                target_kind = path_info[2]
 
1107
                if target_kind == 'directory':
 
1108
                    if path is None:
 
1109
                        old_path = path = self.pathjoin(old_dirname, old_basename)
 
1110
                    file_id = entry[0][2]
 
1111
                    self.new_dirname_to_file_id[path] = file_id
 
1112
                    if source_minikind != c'd':
 
1113
                        content_change = 1
 
1114
                    else:
 
1115
                        # directories have no fingerprint
 
1116
                        content_change = 0
 
1117
                    target_exec = False
 
1118
                elif target_kind == 'file':
 
1119
                    if source_minikind != c'f':
 
1120
                        content_change = 1
 
1121
                    else:
 
1122
                        # We could check the size, but we already have the
 
1123
                        # sha1 hash.
 
1124
                        content_change = (link_or_sha1 != source_details[1])
 
1125
                    # Target details is updated at update_entry time
 
1126
                    if self.use_filesystem_for_exec:
 
1127
                        # We don't need S_ISREG here, because we are sure
 
1128
                        # we are dealing with a file.
 
1129
                        target_exec = bool(S_IXUSR & path_info[3].st_mode)
 
1130
                    else:
 
1131
                        target_exec = target_details[3]
 
1132
                elif target_kind == 'symlink':
 
1133
                    if source_minikind != c'l':
 
1134
                        content_change = 1
 
1135
                    else:
 
1136
                        content_change = (link_or_sha1 != source_details[1])
 
1137
                    target_exec = False
 
1138
                elif target_kind == 'tree-reference':
 
1139
                    if source_minikind != c't':
 
1140
                        content_change = 1
 
1141
                    else:
 
1142
                        content_change = 0
 
1143
                    target_exec = False
 
1144
                else:
 
1145
                    raise Exception, "unknown kind %s" % path_info[2]
 
1146
            if source_minikind == c'd':
 
1147
                if path is None:
 
1148
                    old_path = path = self.pathjoin(old_dirname, old_basename)
 
1149
                if file_id is None:
 
1150
                    file_id = entry[0][2]
 
1151
                self.old_dirname_to_file_id[old_path] = file_id
 
1152
            # parent id is the entry for the path in the target tree
 
1153
            if old_dirname == self.last_source_parent[0]:
 
1154
                source_parent_id = self.last_source_parent[1]
 
1155
            else:
 
1156
                try:
 
1157
                    source_parent_id = self.old_dirname_to_file_id[old_dirname]
 
1158
                except KeyError:
 
1159
                    source_parent_entry = self.state._get_entry(self.source_index,
 
1160
                                                           path_utf8=old_dirname)
 
1161
                    source_parent_id = source_parent_entry[0][2]
 
1162
                if source_parent_id == entry[0][2]:
 
1163
                    # This is the root, so the parent is None
 
1164
                    source_parent_id = None
 
1165
                else:
 
1166
                    self.last_source_parent[0] = old_dirname
 
1167
                    self.last_source_parent[1] = source_parent_id
 
1168
            new_dirname = entry[0][0]
 
1169
            if new_dirname == self.last_target_parent[0]:
 
1170
                target_parent_id = self.last_target_parent[1]
 
1171
            else:
 
1172
                try:
 
1173
                    target_parent_id = self.new_dirname_to_file_id[new_dirname]
 
1174
                except KeyError:
 
1175
                    # TODO: We don't always need to do the lookup, because the
 
1176
                    #       parent entry will be the same as the source entry.
 
1177
                    target_parent_entry = self.state._get_entry(self.target_index,
 
1178
                                                           path_utf8=new_dirname)
 
1179
                    if target_parent_entry == (None, None):
 
1180
                        raise AssertionError(
 
1181
                            "Could not find target parent in wt: %s\nparent of: %s"
 
1182
                            % (new_dirname, entry))
 
1183
                    target_parent_id = target_parent_entry[0][2]
 
1184
                if target_parent_id == entry[0][2]:
 
1185
                    # This is the root, so the parent is None
 
1186
                    target_parent_id = None
 
1187
                else:
 
1188
                    self.last_target_parent[0] = new_dirname
 
1189
                    self.last_target_parent[1] = target_parent_id
 
1190
 
 
1191
            source_exec = source_details[3]
 
1192
            if (self.include_unchanged
 
1193
                or content_change
 
1194
                or source_parent_id != target_parent_id
 
1195
                or old_basename != entry[0][1]
 
1196
                or source_exec != target_exec
 
1197
                ):
 
1198
                if old_path is None:
 
1199
                    path = self.pathjoin(old_dirname, old_basename)
 
1200
                    old_path = path
 
1201
                    old_path_u = self.utf8_decode(old_path)[0]
 
1202
                    path_u = old_path_u
 
1203
                else:
 
1204
                    old_path_u = self.utf8_decode(old_path)[0]
 
1205
                    if old_path == path:
 
1206
                        path_u = old_path_u
 
1207
                    else:
 
1208
                        path_u = self.utf8_decode(path)[0]
 
1209
                source_kind = _minikind_to_kind(source_minikind)
 
1210
                return (entry[0][2],
 
1211
                       (old_path_u, path_u),
 
1212
                       content_change,
 
1213
                       (True, True),
 
1214
                       (source_parent_id, target_parent_id),
 
1215
                       (self.utf8_decode(old_basename)[0], self.utf8_decode(entry[0][1])[0]),
 
1216
                       (source_kind, target_kind),
 
1217
                       (source_exec, target_exec))
 
1218
            else:
 
1219
                return self.uninteresting
 
1220
        elif source_minikind == c'a' and _versioned_minikind(target_minikind):
 
1221
            # looks like a new file
 
1222
            path = self.pathjoin(entry[0][0], entry[0][1])
 
1223
            # parent id is the entry for the path in the target tree
 
1224
            # TODO: these are the same for an entire directory: cache em.
 
1225
            parent_id = self.state._get_entry(self.target_index,
 
1226
                                         path_utf8=entry[0][0])[0][2]
 
1227
            if parent_id == entry[0][2]:
 
1228
                parent_id = None
 
1229
            if path_info is not None:
 
1230
                # Present on disk:
 
1231
                if self.use_filesystem_for_exec:
 
1232
                    # We need S_ISREG here, because we aren't sure if this
 
1233
                    # is a file or not.
 
1234
                    target_exec = bool(
 
1235
                        S_ISREG(path_info[3].st_mode)
 
1236
                        and S_IXUSR & path_info[3].st_mode)
 
1237
                else:
 
1238
                    target_exec = target_details[3]
 
1239
                return (entry[0][2],
 
1240
                       (None, self.utf8_decode(path)[0]),
 
1241
                       True,
 
1242
                       (False, True),
 
1243
                       (None, parent_id),
 
1244
                       (None, self.utf8_decode(entry[0][1])[0]),
 
1245
                       (None, path_info[2]),
 
1246
                       (None, target_exec))
 
1247
            else:
 
1248
                # Its a missing file, report it as such.
 
1249
                return (entry[0][2],
 
1250
                       (None, self.utf8_decode(path)[0]),
 
1251
                       False,
 
1252
                       (False, True),
 
1253
                       (None, parent_id),
 
1254
                       (None, self.utf8_decode(entry[0][1])[0]),
 
1255
                       (None, None),
 
1256
                       (None, False))
 
1257
        elif _versioned_minikind(source_minikind) and target_minikind == c'a':
 
1258
            # unversioned, possibly, or possibly not deleted: we dont care.
 
1259
            # if its still on disk, *and* theres no other entry at this
 
1260
            # path [we dont know this in this routine at the moment -
 
1261
            # perhaps we should change this - then it would be an unknown.
 
1262
            old_path = self.pathjoin(entry[0][0], entry[0][1])
 
1263
            # parent id is the entry for the path in the target tree
 
1264
            parent_id = self.state._get_entry(self.source_index, path_utf8=entry[0][0])[0][2]
 
1265
            if parent_id == entry[0][2]:
 
1266
                parent_id = None
 
1267
            return (entry[0][2],
 
1268
                   (self.utf8_decode(old_path)[0], None),
 
1269
                   True,
 
1270
                   (True, False),
 
1271
                   (parent_id, None),
 
1272
                   (self.utf8_decode(entry[0][1])[0], None),
 
1273
                   (_minikind_to_kind(source_minikind), None),
 
1274
                   (source_details[3], None))
 
1275
        elif _versioned_minikind(source_minikind) and target_minikind == c'r':
 
1276
            # a rename; could be a true rename, or a rename inherited from
 
1277
            # a renamed parent. TODO: handle this efficiently. Its not
 
1278
            # common case to rename dirs though, so a correct but slow
 
1279
            # implementation will do.
 
1280
            if not osutils.is_inside_any(self.searched_specific_files, target_details[1]):
 
1281
                self.search_specific_files.add(target_details[1])
 
1282
        elif ((source_minikind == c'r' or source_minikind == c'a') and
 
1283
              (target_minikind == c'r' or target_minikind == c'a')):
 
1284
            # neither of the selected trees contain this path,
 
1285
            # so skip over it. This is not currently directly tested, but
 
1286
            # is indirectly via test_too_much.TestCommands.test_conflicts.
 
1287
            pass
 
1288
        else:
 
1289
            raise AssertionError("don't know how to compare "
 
1290
                "source_minikind=%r, target_minikind=%r"
 
1291
                % (source_minikind, target_minikind))
 
1292
            ## import pdb;pdb.set_trace()
 
1293
        return None
 
1294
 
 
1295
    def __iter__(self):
 
1296
        return self
 
1297
 
 
1298
    def iter_changes(self):
 
1299
        return self
 
1300
 
 
1301
    cdef void _update_current_block(self):
 
1302
        if (self.block_index < len(self.state._dirblocks) and
 
1303
            osutils.is_inside(self.current_root, self.state._dirblocks[self.block_index][0])):
 
1304
            self.current_block = self.state._dirblocks[self.block_index]
 
1305
            self.current_block_list = self.current_block[1]
 
1306
            self.current_block_pos = 0
 
1307
        else:
 
1308
            self.current_block = None
 
1309
            self.current_block_list = None
 
1310
 
 
1311
    def __next__(self):
 
1312
        # Simple thunk to allow tail recursion without pyrex confusion
 
1313
        return self._iter_next()
 
1314
 
 
1315
    cdef _iter_next(self):
 
1316
        """Iterate over the changes."""
 
1317
        # This function single steps through an iterator. As such while loops
 
1318
        # are often exited by 'return' - the code is structured so that the
 
1319
        # next call into the function will return to the same while loop. Note
 
1320
        # that all flow control needed to re-reach that step is reexecuted,
 
1321
        # which can be a performance problem. It has not yet been tuned to
 
1322
        # minimise this; a state machine is probably the simplest restructuring
 
1323
        # to both minimise this overhead and make the code considerably more
 
1324
        # understandable.
 
1325
 
 
1326
        # sketch: 
 
1327
        # compare source_index and target_index at or under each element of search_specific_files.
 
1328
        # follow the following comparison table. Note that we only want to do diff operations when
 
1329
        # the target is fdl because thats when the walkdirs logic will have exposed the pathinfo 
 
1330
        # for the target.
 
1331
        # cases:
 
1332
        # 
 
1333
        # Source | Target | disk | action
 
1334
        #   r    | fdlt   |      | add source to search, add id path move and perform
 
1335
        #        |        |      | diff check on source-target
 
1336
        #   r    | fdlt   |  a   | dangling file that was present in the basis. 
 
1337
        #        |        |      | ???
 
1338
        #   r    |  a     |      | add source to search
 
1339
        #   r    |  a     |  a   | 
 
1340
        #   r    |  r     |      | this path is present in a non-examined tree, skip.
 
1341
        #   r    |  r     |  a   | this path is present in a non-examined tree, skip.
 
1342
        #   a    | fdlt   |      | add new id
 
1343
        #   a    | fdlt   |  a   | dangling locally added file, skip
 
1344
        #   a    |  a     |      | not present in either tree, skip
 
1345
        #   a    |  a     |  a   | not present in any tree, skip
 
1346
        #   a    |  r     |      | not present in either tree at this path, skip as it
 
1347
        #        |        |      | may not be selected by the users list of paths.
 
1348
        #   a    |  r     |  a   | not present in either tree at this path, skip as it
 
1349
        #        |        |      | may not be selected by the users list of paths.
 
1350
        #  fdlt  | fdlt   |      | content in both: diff them
 
1351
        #  fdlt  | fdlt   |  a   | deleted locally, but not unversioned - show as deleted ?
 
1352
        #  fdlt  |  a     |      | unversioned: output deleted id for now
 
1353
        #  fdlt  |  a     |  a   | unversioned and deleted: output deleted id
 
1354
        #  fdlt  |  r     |      | relocated in this tree, so add target to search.
 
1355
        #        |        |      | Dont diff, we will see an r,fd; pair when we reach
 
1356
        #        |        |      | this id at the other path.
 
1357
        #  fdlt  |  r     |  a   | relocated in this tree, so add target to search.
 
1358
        #        |        |      | Dont diff, we will see an r,fd; pair when we reach
 
1359
        #        |        |      | this id at the other path.
 
1360
 
 
1361
        # TODO: jam 20070516 - Avoid the _get_entry lookup overhead by
 
1362
        #       keeping a cache of directories that we have seen.
 
1363
        cdef object current_dirname, current_blockname
 
1364
        cdef char * current_dirname_c, * current_blockname_c
 
1365
        cdef int advance_entry, advance_path
 
1366
        cdef int path_handled
 
1367
        uninteresting = self.uninteresting
 
1368
        searched_specific_files = self.searched_specific_files
 
1369
        # Are we walking a root?
 
1370
        while self.root_entries_pos < self.root_entries_len:
 
1371
            entry = self.root_entries[self.root_entries_pos]
 
1372
            self.root_entries_pos = self.root_entries_pos + 1
 
1373
            result = self._process_entry(entry, self.root_dir_info)
 
1374
            if result is not None and result is not self.uninteresting:
 
1375
                return result
 
1376
        # Have we finished the prior root, or never started one ?
 
1377
        if self.current_root is None:
 
1378
            # TODO: the pending list should be lexically sorted?  the
 
1379
            # interface doesn't require it.
 
1380
            try:
 
1381
                self.current_root = self.search_specific_files.pop()
 
1382
            except KeyError:
 
1383
                raise StopIteration()
 
1384
            self.current_root_unicode = self.current_root.decode('utf8')
 
1385
            self.searched_specific_files.add(self.current_root)
 
1386
            # process the entries for this containing directory: the rest will be
 
1387
            # found by their parents recursively.
 
1388
            self.root_entries = self.state._entries_for_path(self.current_root)
 
1389
            self.root_entries_len = len(self.root_entries)
 
1390
            self.root_abspath = self.tree.abspath(self.current_root_unicode)
 
1391
            try:
 
1392
                root_stat = os.lstat(self.root_abspath)
 
1393
            except OSError, e:
 
1394
                if e.errno == errno.ENOENT:
 
1395
                    # the path does not exist: let _process_entry know that.
 
1396
                    self.root_dir_info = None
 
1397
                else:
 
1398
                    # some other random error: hand it up.
 
1399
                    raise
 
1400
            else:
 
1401
                self.root_dir_info = ('', self.current_root,
 
1402
                    osutils.file_kind_from_stat_mode(root_stat.st_mode), root_stat,
 
1403
                    self.root_abspath)
 
1404
                if self.root_dir_info[2] == 'directory':
 
1405
                    if self.tree._directory_is_tree_reference(
 
1406
                        self.current_root_unicode):
 
1407
                        self.root_dir_info = self.root_dir_info[:2] + \
 
1408
                            ('tree-reference',) + self.root_dir_info[3:]
 
1409
            if not self.root_entries and not self.root_dir_info:
 
1410
                # this specified path is not present at all, skip it.
 
1411
                # (tail recursion, can do a loop once the full structure is
 
1412
                # known).
 
1413
                return self._iter_next()
 
1414
            path_handled = 0
 
1415
            self.root_entries_pos = 0
 
1416
            # XXX Clarity: This loop is duplicated a out the self.current_root
 
1417
            # is None guard above: if we return from it, it completes there
 
1418
            # (and the following if block cannot trigger because
 
1419
            # path_handled must be true, so the if block is not # duplicated.
 
1420
            while self.root_entries_pos < self.root_entries_len:
 
1421
                entry = self.root_entries[self.root_entries_pos]
 
1422
                self.root_entries_pos = self.root_entries_pos + 1
 
1423
                result = self._process_entry(entry, self.root_dir_info)
 
1424
                if result is not None:
 
1425
                    path_handled = -1
 
1426
                    if result is not self.uninteresting:
 
1427
                        return result
 
1428
            # handle unversioned specified paths:
 
1429
            if self.want_unversioned and not path_handled and self.root_dir_info:
 
1430
                new_executable = bool(
 
1431
                    stat.S_ISREG(self.root_dir_info[3].st_mode)
 
1432
                    and stat.S_IEXEC & self.root_dir_info[3].st_mode)
 
1433
                return (None,
 
1434
                       (None, self.current_root_unicode),
 
1435
                       True,
 
1436
                       (False, False),
 
1437
                       (None, None),
 
1438
                       (None, splitpath(self.current_root_unicode)[-1]),
 
1439
                       (None, self.root_dir_info[2]),
 
1440
                       (None, new_executable)
 
1441
                      )
 
1442
            # If we reach here, the outer flow continues, which enters into the
 
1443
            # per-root setup logic.
 
1444
        if self.current_dir_info is None and self.current_block is None:
 
1445
            # setup iteration of this root:
 
1446
            self.current_dir_list = None
 
1447
            if self.root_dir_info and self.root_dir_info[2] == 'tree-reference':
 
1448
                self.current_dir_info = None
 
1449
            else:
 
1450
                self.dir_iterator = osutils._walkdirs_utf8(self.root_abspath,
 
1451
                    prefix=self.current_root)
 
1452
                self.path_index = 0
 
1453
                try:
 
1454
                    self.current_dir_info = self.dir_iterator.next()
 
1455
                    self.current_dir_list = self.current_dir_info[1]
 
1456
                except OSError, e:
 
1457
                    # there may be directories in the inventory even though
 
1458
                    # this path is not a file on disk: so mark it as end of
 
1459
                    # iterator
 
1460
                    if e.errno in (errno.ENOENT, errno.ENOTDIR, errno.EINVAL):
 
1461
                        self.current_dir_info = None
 
1462
                    elif sys.platform == 'win32':
 
1463
                        # on win32, python2.4 has e.errno == ERROR_DIRECTORY, but
 
1464
                        # python 2.5 has e.errno == EINVAL,
 
1465
                        #            and e.winerror == ERROR_DIRECTORY
 
1466
                        try:
 
1467
                            e_winerror = e.winerror
 
1468
                        except AttributeError:
 
1469
                            e_winerror = None
 
1470
                        win_errors = (ERROR_DIRECTORY, ERROR_PATH_NOT_FOUND)
 
1471
                        if (e.errno in win_errors or e_winerror in win_errors):
 
1472
                            self.current_dir_info = None
 
1473
                        else:
 
1474
                            # Will this really raise the right exception ?
 
1475
                            raise
 
1476
                    else:
 
1477
                        raise
 
1478
                else:
 
1479
                    if self.current_dir_info[0][0] == '':
 
1480
                        # remove .bzr from iteration
 
1481
                        bzr_index = self.bisect_left(self.current_dir_list, ('.bzr',))
 
1482
                        if self.current_dir_list[bzr_index][0] != '.bzr':
 
1483
                            raise AssertionError()
 
1484
                        del self.current_dir_list[bzr_index]
 
1485
            initial_key = (self.current_root, '', '')
 
1486
            self.block_index, _ = self.state._find_block_index_from_key(initial_key)
 
1487
            if self.block_index == 0:
 
1488
                # we have processed the total root already, but because the
 
1489
                # initial key matched it we should skip it here.
 
1490
                self.block_index = self.block_index + 1
 
1491
            self._update_current_block()
 
1492
        # walk until both the directory listing and the versioned metadata
 
1493
        # are exhausted. 
 
1494
        while (self.current_dir_info is not None
 
1495
            or self.current_block is not None):
 
1496
            # Uncommon case - a missing directory or an unversioned directory:
 
1497
            if (self.current_dir_info and self.current_block
 
1498
                and self.current_dir_info[0][0] != self.current_block[0]):
 
1499
                # Work around pyrex broken heuristic - current_dirname has
 
1500
                # the same scope as current_dirname_c
 
1501
                current_dirname = self.current_dir_info[0][0]
 
1502
                current_dirname_c = PyString_AS_STRING_void(
 
1503
                    <void *>current_dirname)
 
1504
                current_blockname = self.current_block[0]
 
1505
                current_blockname_c = PyString_AS_STRING_void(
 
1506
                    <void *>current_blockname)
 
1507
                # In the python generator we evaluate this if block once per
 
1508
                # dir+block; because we reenter in the pyrex version its being
 
1509
                # evaluated once per path: we could cache the result before
 
1510
                # doing the while loop and probably save time.
 
1511
                if _cmp_by_dirs(current_dirname_c,
 
1512
                    PyString_Size(current_dirname),
 
1513
                    current_blockname_c,
 
1514
                    PyString_Size(current_blockname)) < 0:
 
1515
                    # filesystem data refers to paths not covered by the
 
1516
                    # dirblock.  this has two possibilities:
 
1517
                    # A) it is versioned but empty, so there is no block for it
 
1518
                    # B) it is not versioned.
 
1519
 
 
1520
                    # if (A) then we need to recurse into it to check for
 
1521
                    # new unknown files or directories.
 
1522
                    # if (B) then we should ignore it, because we don't
 
1523
                    # recurse into unknown directories.
 
1524
                    # We are doing a loop
 
1525
                    while self.path_index < len(self.current_dir_list):
 
1526
                        current_path_info = self.current_dir_list[self.path_index]
 
1527
                        # dont descend into this unversioned path if it is
 
1528
                        # a dir
 
1529
                        if current_path_info[2] in ('directory',
 
1530
                                                    'tree-reference'):
 
1531
                            del self.current_dir_list[self.path_index]
 
1532
                            self.path_index = self.path_index - 1
 
1533
                        self.path_index = self.path_index + 1
 
1534
                        if self.want_unversioned:
 
1535
                            if current_path_info[2] == 'directory':
 
1536
                                if self.tree._directory_is_tree_reference(
 
1537
                                    self.utf8_decode(current_path_info[0])[0]):
 
1538
                                    current_path_info = current_path_info[:2] + \
 
1539
                                        ('tree-reference',) + current_path_info[3:]
 
1540
                            new_executable = bool(
 
1541
                                stat.S_ISREG(current_path_info[3].st_mode)
 
1542
                                and stat.S_IEXEC & current_path_info[3].st_mode)
 
1543
                            return (None,
 
1544
                                (None, self.utf8_decode(current_path_info[0])[0]),
 
1545
                                True,
 
1546
                                (False, False),
 
1547
                                (None, None),
 
1548
                                (None, self.utf8_decode(current_path_info[1])[0]),
 
1549
                                (None, current_path_info[2]),
 
1550
                                (None, new_executable))
 
1551
                    # This dir info has been handled, go to the next
 
1552
                    self.path_index = 0
 
1553
                    self.current_dir_list = None
 
1554
                    try:
 
1555
                        self.current_dir_info = self.dir_iterator.next()
 
1556
                        self.current_dir_list = self.current_dir_info[1]
 
1557
                    except StopIteration:
 
1558
                        self.current_dir_info = None
 
1559
                else: #(dircmp > 0)
 
1560
                    # We have a dirblock entry for this location, but there
 
1561
                    # is no filesystem path for this. This is most likely
 
1562
                    # because a directory was removed from the disk.
 
1563
                    # We don't have to report the missing directory,
 
1564
                    # because that should have already been handled, but we
 
1565
                    # need to handle all of the files that are contained
 
1566
                    # within.
 
1567
                    while self.current_block_pos < len(self.current_block_list):
 
1568
                        current_entry = self.current_block_list[self.current_block_pos]
 
1569
                        self.current_block_pos = self.current_block_pos + 1
 
1570
                        # entry referring to file not present on disk.
 
1571
                        # advance the entry only, after processing.
 
1572
                        result = self._process_entry(current_entry, None)
 
1573
                        if result is not None:
 
1574
                            if result is not self.uninteresting:
 
1575
                                return result
 
1576
                    self.block_index = self.block_index + 1
 
1577
                    self._update_current_block()
 
1578
                continue # next loop-on-block/dir
 
1579
            result = self._loop_one_block()
 
1580
            if result is not None:
 
1581
                return result
 
1582
        if len(self.search_specific_files):
 
1583
            # More supplied paths to process
 
1584
            self.current_root = None
 
1585
            return self._iter_next()
 
1586
        raise StopIteration()
 
1587
 
 
1588
    cdef object _maybe_tree_ref(self, current_path_info):
 
1589
        if self.tree._directory_is_tree_reference(
 
1590
            self.utf8_decode(current_path_info[0])[0]):
 
1591
            return current_path_info[:2] + \
 
1592
                ('tree-reference',) + current_path_info[3:]
 
1593
        else:
 
1594
            return current_path_info
 
1595
 
 
1596
    cdef object _loop_one_block(self):
 
1597
            # current_dir_info and current_block refer to the same directory -
 
1598
            # this is the common case code.
 
1599
            # Assign local variables for current path and entry:
 
1600
            cdef object current_entry
 
1601
            cdef object current_path_info
 
1602
            cdef int path_handled
 
1603
            cdef char minikind
 
1604
            cdef int cmp_result
 
1605
            # cdef char * temp_str
 
1606
            # cdef Py_ssize_t temp_str_length
 
1607
            # PyString_AsStringAndSize(disk_kind, &temp_str, &temp_str_length)
 
1608
            # if not strncmp(temp_str, "directory", temp_str_length):
 
1609
            if (self.current_block is not None and
 
1610
                self.current_block_pos < PyList_GET_SIZE(self.current_block_list)):
 
1611
                current_entry = PyList_GET_ITEM(self.current_block_list,
 
1612
                    self.current_block_pos)
 
1613
                # accomodate pyrex
 
1614
                Py_INCREF(current_entry)
 
1615
            else:
 
1616
                current_entry = None
 
1617
            if (self.current_dir_info is not None and
 
1618
                self.path_index < PyList_GET_SIZE(self.current_dir_list)):
 
1619
                current_path_info = PyList_GET_ITEM(self.current_dir_list,
 
1620
                    self.path_index)
 
1621
                # accomodate pyrex
 
1622
                Py_INCREF(current_path_info)
 
1623
                disk_kind = PyTuple_GET_ITEM(current_path_info, 2)
 
1624
                # accomodate pyrex
 
1625
                Py_INCREF(disk_kind)
 
1626
                if disk_kind == "directory":
 
1627
                    current_path_info = self._maybe_tree_ref(current_path_info)
 
1628
            else:
 
1629
                current_path_info = None
 
1630
            while (current_entry is not None or current_path_info is not None):
 
1631
                advance_entry = -1
 
1632
                advance_path = -1
 
1633
                result = None
 
1634
                path_handled = 0
 
1635
                if current_entry is None:
 
1636
                    # unversioned -  the check for path_handled when the path
 
1637
                    # is advanced will yield this path if needed.
 
1638
                    pass
 
1639
                elif current_path_info is None:
 
1640
                    # no path is fine: the per entry code will handle it.
 
1641
                    result = self._process_entry(current_entry, current_path_info)
 
1642
                    if result is not None:
 
1643
                        if result is self.uninteresting:
 
1644
                            result = None
 
1645
                else:
 
1646
                    minikind = _minikind_from_string(
 
1647
                        current_entry[1][self.target_index][0])
 
1648
                    cmp_result = cmp(current_path_info[1], current_entry[0][1])
 
1649
                    if (cmp_result or minikind == c'a' or minikind == c'r'):
 
1650
                        # The current path on disk doesn't match the dirblock
 
1651
                        # record. Either the dirblock record is marked as
 
1652
                        # absent/renamed, or the file on disk is not present at all
 
1653
                        # in the dirblock. Either way, report about the dirblock
 
1654
                        # entry, and let other code handle the filesystem one.
 
1655
 
 
1656
                        # Compare the basename for these files to determine
 
1657
                        # which comes first
 
1658
                        if cmp_result < 0:
 
1659
                            # extra file on disk: pass for now, but only
 
1660
                            # increment the path, not the entry
 
1661
                            advance_entry = 0
 
1662
                        else:
 
1663
                            # entry referring to file not present on disk.
 
1664
                            # advance the entry only, after processing.
 
1665
                            result = self._process_entry(current_entry, None)
 
1666
                            if result is not None:
 
1667
                                if result is self.uninteresting:
 
1668
                                    result = None
 
1669
                            advance_path = 0
 
1670
                    else:
 
1671
                        # paths are the same,and the dirstate entry is not
 
1672
                        # absent or renamed.
 
1673
                        result = self._process_entry(current_entry, current_path_info)
 
1674
                        if result is not None:
 
1675
                            path_handled = -1
 
1676
                            if result is self.uninteresting:
 
1677
                                result = None
 
1678
                # >- loop control starts here:
 
1679
                # >- entry
 
1680
                if advance_entry and current_entry is not None:
 
1681
                    self.current_block_pos = self.current_block_pos + 1
 
1682
                    if self.current_block_pos < PyList_GET_SIZE(self.current_block_list):
 
1683
                        current_entry = self.current_block_list[self.current_block_pos]
 
1684
                    else:
 
1685
                        current_entry = None
 
1686
                # >- path
 
1687
                if advance_path and current_path_info is not None:
 
1688
                    if not path_handled:
 
1689
                        # unversioned in all regards
 
1690
                        if self.want_unversioned:
 
1691
                            new_executable = bool(
 
1692
                                stat.S_ISREG(current_path_info[3].st_mode)
 
1693
                                and stat.S_IEXEC & current_path_info[3].st_mode)
 
1694
                            try:
 
1695
                                relpath_unicode = self.utf8_decode(current_path_info[0])[0]
 
1696
                            except UnicodeDecodeError:
 
1697
                                raise errors.BadFilenameEncoding(
 
1698
                                    current_path_info[0], osutils._fs_enc)
 
1699
                            if result is not None:
 
1700
                                raise AssertionError(
 
1701
                                    "result is not None: %r" % result)
 
1702
                            result = (None,
 
1703
                                (None, relpath_unicode),
 
1704
                                True,
 
1705
                                (False, False),
 
1706
                                (None, None),
 
1707
                                (None, self.utf8_decode(current_path_info[1])[0]),
 
1708
                                (None, current_path_info[2]),
 
1709
                                (None, new_executable))
 
1710
                        # dont descend into this unversioned path if it is
 
1711
                        # a dir
 
1712
                        if current_path_info[2] in ('directory'):
 
1713
                            del self.current_dir_list[self.path_index]
 
1714
                            self.path_index = self.path_index - 1
 
1715
                    # dont descend the disk iterator into any tree 
 
1716
                    # paths.
 
1717
                    if current_path_info[2] == 'tree-reference':
 
1718
                        del self.current_dir_list[self.path_index]
 
1719
                        self.path_index = self.path_index - 1
 
1720
                    self.path_index = self.path_index + 1
 
1721
                    if self.path_index < len(self.current_dir_list):
 
1722
                        current_path_info = self.current_dir_list[self.path_index]
 
1723
                        if current_path_info[2] == 'directory':
 
1724
                            current_path_info = self._maybe_tree_ref(
 
1725
                                current_path_info)
 
1726
                    else:
 
1727
                        current_path_info = None
 
1728
                if result is not None:
 
1729
                    # Found a result on this pass, yield it
 
1730
                    return result
 
1731
            if self.current_block is not None:
 
1732
                self.block_index = self.block_index + 1
 
1733
                self._update_current_block()
 
1734
            if self.current_dir_info is not None:
 
1735
                self.path_index = 0
 
1736
                self.current_dir_list = None
 
1737
                try:
 
1738
                    self.current_dir_info = self.dir_iterator.next()
 
1739
                    self.current_dir_list = self.current_dir_info[1]
 
1740
                except StopIteration:
 
1741
                    self.current_dir_info = None