~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/_dirstate_helpers_pyx.pyx

(jelmer) Support upgrading between the 2a and development-colo formats.
 (Jelmer Vernooij)

Show diffs side-by-side

added added

removed removed

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