~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/_dirstate_helpers_c.pyx

  • Committer: Ian Clatworthy
  • Date: 2007-08-13 14:33:10 UTC
  • mto: (2733.1.1 ianc-integration)
  • mto: This revision was merged to the branch mainline in revision 2734.
  • Revision ID: ian.clatworthy@internode.on.net-20070813143310-twhj4la0qnupvze8
Added Quick Start Summary

Show diffs side-by-side

added added

removed removed

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