~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/_dirstate_helpers_pyx.pyx

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2009-08-24 21:25:26 UTC
  • mfrom: (4641.1.1 integration)
  • Revision ID: pqm@pqm.ubuntu.com-20090824212526-5j41jw5zsciji66e
(robertc) Back out draft documentation change landed as 'selftest
        improvements'. (Robert Collins)

Show diffs side-by-side

added added

removed removed

Lines of Context:
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
 
from bzrlib import errors
 
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
23
30
from bzrlib.dirstate import DirState
24
 
 
 
31
from bzrlib.osutils import 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)
25
46
 
26
47
# Give Pyrex some function definitions for it to understand.
27
48
# All of these are just hints to Pyrex, so that it can try to convert python
33
54
cdef extern from *:
34
55
    ctypedef unsigned long size_t
35
56
 
36
 
cdef extern from "_dirstate_helpers_c.h":
 
57
cdef extern from "_dirstate_helpers_pyx.h":
37
58
    ctypedef int intptr_t
38
59
 
39
60
 
 
61
 
40
62
cdef extern from "stdlib.h":
41
63
    unsigned long int strtoul(char *nptr, char **endptr, int base)
42
64
 
43
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
 
44
73
# These functions allow us access to a bit of the 'bare metal' of python
45
74
# objects, rather than going through the object abstraction. (For example,
46
75
# PyList_Append, rather than getting the 'append' attribute of the object, and
50
79
# will automatically Py_INCREF and Py_DECREF when appropriate. But for some
51
80
# inner loops, we don't need to do that at all, as the reference only lasts for
52
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.
53
85
cdef extern from "Python.h":
54
86
    ctypedef int Py_ssize_t
 
87
    ctypedef struct PyObject:
 
88
        pass
55
89
    int PyList_Append(object lst, object item) except -1
56
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)
57
93
    int PyList_CheckExact(object)
 
94
    Py_ssize_t PyList_GET_SIZE (object p)
58
95
 
59
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
 
60
100
 
61
101
    char *PyString_AsString(object p)
 
102
    char *PyString_AsString_obj "PyString_AsString" (PyObject *string)
62
103
    char *PyString_AS_STRING_void "PyString_AS_STRING" (void *p)
 
104
    int PyString_AsStringAndSize(object str, char **buffer, Py_ssize_t *length) except -1
63
105
    object PyString_FromString(char *)
64
106
    object PyString_FromStringAndSize(char *, Py_ssize_t)
65
107
    int PyString_Size(object p)
66
108
    int PyString_GET_SIZE_void "PyString_GET_SIZE" (void *p)
67
109
    int PyString_CheckExact(object p)
 
110
    void Py_INCREF(object o)
 
111
    void Py_DECREF(object o)
68
112
 
69
113
 
70
114
cdef extern from "string.h":
114
158
 
115
159
cdef object safe_string_from_size(char *s, Py_ssize_t size):
116
160
    if size < 0:
 
161
        # XXX: On 64-bit machines the <int> cast causes a C compiler warning.
117
162
        raise AssertionError(
118
163
            'tried to create a string with an invalid size: %d @0x%x'
119
164
            % (size, <int>s))
192
237
    return 0
193
238
 
194
239
 
195
 
def cmp_by_dirs_c(path1, path2):
 
240
def cmp_by_dirs(path1, path2):
196
241
    """Compare two paths directory by directory.
197
242
 
198
243
    This is equivalent to doing::
221
266
                        PyString_Size(path2))
222
267
 
223
268
 
224
 
def _cmp_path_by_dirblock_c(path1, path2):
 
269
def _cmp_path_by_dirblock(path1, path2):
225
270
    """Compare two paths based on what directory they are in.
226
271
 
227
272
    This generates a sort order, such that all children of a directory are
243
288
    if not PyString_CheckExact(path2):
244
289
        raise TypeError("'path2' must be a plain string, not %s: %r"
245
290
                        % (type(path2), path2))
246
 
    return _cmp_path_by_dirblock(PyString_AsString(path1),
247
 
                                 PyString_Size(path1),
248
 
                                 PyString_AsString(path2),
249
 
                                 PyString_Size(path2))
250
 
 
251
 
 
252
 
cdef int _cmp_path_by_dirblock(char *path1, int path1_len,
253
 
                               char *path2, int path2_len):
 
291
    return _cmp_path_by_dirblock_intern(PyString_AsString(path1),
 
292
                                        PyString_Size(path1),
 
293
                                        PyString_AsString(path2),
 
294
                                        PyString_Size(path2))
 
295
 
 
296
 
 
297
cdef int _cmp_path_by_dirblock_intern(char *path1, int path1_len,
 
298
                                      char *path2, int path2_len):
254
299
    """Compare two paths by what directory they are in.
255
300
 
256
 
    see ``_cmp_path_by_dirblock_c`` for details.
 
301
    see ``_cmp_path_by_dirblock`` for details.
257
302
    """
258
303
    cdef char *dirname1
259
304
    cdef int dirname1_len
323
368
    return 1
324
369
 
325
370
 
326
 
def _bisect_path_left_c(paths, path):
 
371
def _bisect_path_left(paths, path):
327
372
    """Return the index where to insert path into paths.
328
373
 
329
374
    This uses a path-wise comparison so we get::
368
413
        cur = PyList_GetItem_object_void(paths, _mid)
369
414
        cur_cstr = PyString_AS_STRING_void(cur)
370
415
        cur_size = PyString_GET_SIZE_void(cur)
371
 
        if _cmp_path_by_dirblock(cur_cstr, cur_size, path_cstr, path_size) < 0:
 
416
        if _cmp_path_by_dirblock_intern(cur_cstr, cur_size,
 
417
                                        path_cstr, path_size) < 0:
372
418
            _lo = _mid + 1
373
419
        else:
374
420
            _hi = _mid
375
421
    return _lo
376
422
 
377
423
 
378
 
def _bisect_path_right_c(paths, path):
 
424
def _bisect_path_right(paths, path):
379
425
    """Return the index where to insert path into paths.
380
426
 
381
427
    This uses a path-wise comparison so we get::
420
466
        cur = PyList_GetItem_object_void(paths, _mid)
421
467
        cur_cstr = PyString_AS_STRING_void(cur)
422
468
        cur_size = PyString_GET_SIZE_void(cur)
423
 
        if _cmp_path_by_dirblock(path_cstr, path_size, cur_cstr, cur_size) < 0:
 
469
        if _cmp_path_by_dirblock_intern(path_cstr, path_size,
 
470
                                        cur_cstr, cur_size) < 0:
424
471
            _hi = _mid
425
472
        else:
426
473
            _lo = _mid + 1
427
474
    return _lo
428
475
 
429
476
 
430
 
def bisect_dirblock_c(dirblocks, dirname, lo=0, hi=None, cache=None):
 
477
def bisect_dirblock(dirblocks, dirname, lo=0, hi=None, cache=None):
431
478
    """Return the index where to insert dirname into the dirblocks.
432
479
 
433
480
    The return value idx is such that all directories blocks in dirblock[:idx]
699
746
        self.state._split_root_dirblock_into_contents()
700
747
 
701
748
 
702
 
def _read_dirblocks_c(state):
 
749
def _read_dirblocks(state):
703
750
    """Read in the dirblocks for the given DirState object.
704
751
 
705
752
    This is tightly bound to the DirState internal representation. It should be
719
766
 
720
767
    reader._parse_dirblocks()
721
768
    state._dirblock_state = DirState.IN_MEMORY_UNMODIFIED
 
769
 
 
770
 
 
771
cdef int minikind_from_mode(int mode):
 
772
    # in order of frequency:
 
773
    if S_ISREG(mode):
 
774
        return c"f"
 
775
    if S_ISDIR(mode):
 
776
        return c"d"
 
777
    if S_ISLNK(mode):
 
778
        return c"l"
 
779
    return 0
 
780
 
 
781
 
 
782
_encode = binascii.b2a_base64
 
783
 
 
784
 
 
785
from struct import pack
 
786
cdef _pack_stat(stat_value):
 
787
    """return a string representing the stat value's key fields.
 
788
 
 
789
    :param stat_value: A stat oject with st_size, st_mtime, st_ctime, st_dev,
 
790
        st_ino and st_mode fields.
 
791
    """
 
792
    cdef char result[6*4] # 6 long ints
 
793
    cdef int *aliased
 
794
    aliased = <int *>result
 
795
    aliased[0] = htonl(stat_value.st_size)
 
796
    aliased[1] = htonl(int(stat_value.st_mtime))
 
797
    aliased[2] = htonl(int(stat_value.st_ctime))
 
798
    aliased[3] = htonl(stat_value.st_dev)
 
799
    aliased[4] = htonl(stat_value.st_ino & 0xFFFFFFFF)
 
800
    aliased[5] = htonl(stat_value.st_mode)
 
801
    packed = PyString_FromStringAndSize(result, 6*4)
 
802
    return _encode(packed)[:-1]
 
803
 
 
804
 
 
805
def update_entry(self, entry, abspath, stat_value):
 
806
    """Update the entry based on what is actually on disk.
 
807
 
 
808
    This function only calculates the sha if it needs to - if the entry is
 
809
    uncachable, or clearly different to the first parent's entry, no sha
 
810
    is calculated, and None is returned.
 
811
 
 
812
    :param entry: This is the dirblock entry for the file in question.
 
813
    :param abspath: The path on disk for this file.
 
814
    :param stat_value: (optional) if we already have done a stat on the
 
815
        file, re-use it.
 
816
    :return: None, or The sha1 hexdigest of the file (40 bytes) or link
 
817
        target of a symlink.
 
818
    """
 
819
    return _update_entry(self, entry, abspath, stat_value)
 
820
 
 
821
 
 
822
cdef _update_entry(self, entry, abspath, stat_value):
 
823
    """Update the entry based on what is actually on disk.
 
824
 
 
825
    This function only calculates the sha if it needs to - if the entry is
 
826
    uncachable, or clearly different to the first parent's entry, no sha
 
827
    is calculated, and None is returned.
 
828
 
 
829
    :param self: The dirstate object this is operating on.
 
830
    :param entry: This is the dirblock entry for the file in question.
 
831
    :param abspath: The path on disk for this file.
 
832
    :param stat_value: The stat value done on the path.
 
833
    :return: None, or The sha1 hexdigest of the file (40 bytes) or link
 
834
        target of a symlink.
 
835
    """
 
836
    # TODO - require pyrex 0.9.8, then use a pyd file to define access to the
 
837
    # _st mode of the compiled stat objects.
 
838
    cdef int minikind, saved_minikind
 
839
    cdef void * details
 
840
    minikind = minikind_from_mode(stat_value.st_mode)
 
841
    if 0 == minikind:
 
842
        return None
 
843
    packed_stat = _pack_stat(stat_value)
 
844
    details = PyList_GetItem_void_void(PyTuple_GetItem_void_void(<void *>entry, 1), 0)
 
845
    saved_minikind = PyString_AsString_obj(<PyObject *>PyTuple_GetItem_void_void(details, 0))[0]
 
846
    if minikind == c'd' and saved_minikind == c't':
 
847
        minikind = c't'
 
848
    saved_link_or_sha1 = PyTuple_GetItem_void_object(details, 1)
 
849
    saved_file_size = PyTuple_GetItem_void_object(details, 2)
 
850
    saved_executable = PyTuple_GetItem_void_object(details, 3)
 
851
    saved_packed_stat = PyTuple_GetItem_void_object(details, 4)
 
852
    # Deal with pyrex decrefing the objects
 
853
    Py_INCREF(saved_link_or_sha1)
 
854
    Py_INCREF(saved_file_size)
 
855
    Py_INCREF(saved_executable)
 
856
    Py_INCREF(saved_packed_stat)
 
857
    #(saved_minikind, saved_link_or_sha1, saved_file_size,
 
858
    # saved_executable, saved_packed_stat) = entry[1][0]
 
859
 
 
860
    if (minikind == saved_minikind
 
861
        and packed_stat == saved_packed_stat):
 
862
        # The stat hasn't changed since we saved, so we can re-use the
 
863
        # saved sha hash.
 
864
        if minikind == c'd':
 
865
            return None
 
866
 
 
867
        # size should also be in packed_stat
 
868
        if saved_file_size == stat_value.st_size:
 
869
            return saved_link_or_sha1
 
870
 
 
871
    # If we have gotten this far, that means that we need to actually
 
872
    # process this entry.
 
873
    link_or_sha1 = None
 
874
    if minikind == c'f':
 
875
        executable = self._is_executable(stat_value.st_mode,
 
876
                                         saved_executable)
 
877
        if self._cutoff_time is None:
 
878
            self._sha_cutoff_time()
 
879
        if (stat_value.st_mtime < self._cutoff_time
 
880
            and stat_value.st_ctime < self._cutoff_time
 
881
            and len(entry[1]) > 1
 
882
            and entry[1][1][0] != 'a'):
 
883
                # Could check for size changes for further optimised
 
884
                # avoidance of sha1's. However the most prominent case of
 
885
                # over-shaing is during initial add, which this catches.
 
886
            link_or_sha1 = self._sha1_file(abspath)
 
887
            entry[1][0] = ('f', link_or_sha1, stat_value.st_size,
 
888
                           executable, packed_stat)
 
889
        else:
 
890
            entry[1][0] = ('f', '', stat_value.st_size,
 
891
                           executable, DirState.NULLSTAT)
 
892
    elif minikind == c'd':
 
893
        link_or_sha1 = None
 
894
        entry[1][0] = ('d', '', 0, False, packed_stat)
 
895
        if saved_minikind != c'd':
 
896
            # This changed from something into a directory. Make sure we
 
897
            # have a directory block for it. This doesn't happen very
 
898
            # often, so this doesn't have to be super fast.
 
899
            block_index, entry_index, dir_present, file_present = \
 
900
                self._get_block_entry_index(entry[0][0], entry[0][1], 0)
 
901
            self._ensure_block(block_index, entry_index,
 
902
                               pathjoin(entry[0][0], entry[0][1]))
 
903
    elif minikind == c'l':
 
904
        link_or_sha1 = self._read_link(abspath, saved_link_or_sha1)
 
905
        if self._cutoff_time is None:
 
906
            self._sha_cutoff_time()
 
907
        if (stat_value.st_mtime < self._cutoff_time
 
908
            and stat_value.st_ctime < self._cutoff_time):
 
909
            entry[1][0] = ('l', link_or_sha1, stat_value.st_size,
 
910
                           False, packed_stat)
 
911
        else:
 
912
            entry[1][0] = ('l', '', stat_value.st_size,
 
913
                           False, DirState.NULLSTAT)
 
914
    self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
915
    return link_or_sha1
 
916
 
 
917
 
 
918
cdef char _minikind_from_string(object string):
 
919
    """Convert a python string to a char."""
 
920
    return PyString_AsString(string)[0]
 
921
 
 
922
 
 
923
cdef object _kind_absent
 
924
cdef object _kind_file
 
925
cdef object _kind_directory
 
926
cdef object _kind_symlink
 
927
cdef object _kind_relocated
 
928
cdef object _kind_tree_reference
 
929
_kind_absent = "absent"
 
930
_kind_file = "file"
 
931
_kind_directory = "directory"
 
932
_kind_symlink = "symlink"
 
933
_kind_relocated = "relocated"
 
934
_kind_tree_reference = "tree-reference"
 
935
 
 
936
 
 
937
cdef object _minikind_to_kind(char minikind):
 
938
    """Create a string kind for minikind."""
 
939
    cdef char _minikind[1]
 
940
    if minikind == c'f':
 
941
        return _kind_file
 
942
    elif minikind == c'd':
 
943
        return _kind_directory
 
944
    elif minikind == c'a':
 
945
        return _kind_absent
 
946
    elif minikind == c'r':
 
947
        return _kind_relocated
 
948
    elif minikind == c'l':
 
949
        return _kind_symlink
 
950
    elif minikind == c't':
 
951
        return _kind_tree_reference
 
952
    _minikind[0] = minikind
 
953
    raise KeyError(PyString_FromStringAndSize(_minikind, 1))
 
954
 
 
955
 
 
956
cdef int _versioned_minikind(char minikind):
 
957
    """Return non-zero if minikind is in fltd"""
 
958
    return (minikind == c'f' or
 
959
            minikind == c'd' or
 
960
            minikind == c'l' or
 
961
            minikind == c't')
 
962
 
 
963
 
 
964
cdef class ProcessEntryC:
 
965
 
 
966
    cdef object old_dirname_to_file_id # dict
 
967
    cdef object new_dirname_to_file_id # dict
 
968
    cdef object last_source_parent
 
969
    cdef object last_target_parent
 
970
    cdef object include_unchanged
 
971
    cdef object use_filesystem_for_exec
 
972
    cdef object utf8_decode
 
973
    cdef readonly object searched_specific_files
 
974
    cdef object search_specific_files
 
975
    cdef object state
 
976
    # Current iteration variables:
 
977
    cdef object current_root
 
978
    cdef object current_root_unicode
 
979
    cdef object root_entries
 
980
    cdef int root_entries_pos, root_entries_len
 
981
    cdef object root_abspath
 
982
    cdef int source_index, target_index
 
983
    cdef int want_unversioned
 
984
    cdef object tree
 
985
    cdef object dir_iterator
 
986
    cdef int block_index
 
987
    cdef object current_block
 
988
    cdef int current_block_pos
 
989
    cdef object current_block_list
 
990
    cdef object current_dir_info
 
991
    cdef object current_dir_list
 
992
    cdef int path_index
 
993
    cdef object root_dir_info
 
994
    cdef object bisect_left
 
995
    cdef object pathjoin
 
996
    cdef object fstat
 
997
    cdef object sha_file
 
998
 
 
999
    def __init__(self, include_unchanged, use_filesystem_for_exec,
 
1000
        search_specific_files, state, source_index, target_index,
 
1001
        want_unversioned, tree):
 
1002
        self.old_dirname_to_file_id = {}
 
1003
        self.new_dirname_to_file_id = {}
 
1004
        # Using a list so that we can access the values and change them in
 
1005
        # nested scope. Each one is [path, file_id, entry]
 
1006
        self.last_source_parent = [None, None]
 
1007
        self.last_target_parent = [None, None]
 
1008
        self.include_unchanged = include_unchanged
 
1009
        self.use_filesystem_for_exec = use_filesystem_for_exec
 
1010
        self.utf8_decode = cache_utf8._utf8_decode
 
1011
        # for all search_indexs in each path at or under each element of
 
1012
        # search_specific_files, if the detail is relocated: add the id, and add the
 
1013
        # relocated path as one to search if its not searched already. If the
 
1014
        # detail is not relocated, add the id.
 
1015
        self.searched_specific_files = set()
 
1016
        self.search_specific_files = search_specific_files
 
1017
        self.state = state
 
1018
        self.current_root = None
 
1019
        self.current_root_unicode = None
 
1020
        self.root_entries = None
 
1021
        self.root_entries_pos = 0
 
1022
        self.root_entries_len = 0
 
1023
        self.root_abspath = None
 
1024
        if source_index is None:
 
1025
            self.source_index = -1
 
1026
        else:
 
1027
            self.source_index = source_index
 
1028
        self.target_index = target_index
 
1029
        self.want_unversioned = want_unversioned
 
1030
        self.tree = tree
 
1031
        self.dir_iterator = None
 
1032
        self.block_index = -1
 
1033
        self.current_block = None
 
1034
        self.current_block_list = None
 
1035
        self.current_block_pos = -1
 
1036
        self.current_dir_info = None
 
1037
        self.current_dir_list = None
 
1038
        self.path_index = 0
 
1039
        self.root_dir_info = None
 
1040
        self.bisect_left = bisect.bisect_left
 
1041
        self.pathjoin = osutils.pathjoin
 
1042
        self.fstat = os.fstat
 
1043
        self.sha_file = osutils.sha_file
 
1044
 
 
1045
    cdef _process_entry(self, entry, path_info):
 
1046
        """Compare an entry and real disk to generate delta information.
 
1047
 
 
1048
        :param path_info: top_relpath, basename, kind, lstat, abspath for
 
1049
            the path of entry. If None, then the path is considered absent.
 
1050
            (Perhaps we should pass in a concrete entry for this ?)
 
1051
            Basename is returned as a utf8 string because we expect this
 
1052
            tuple will be ignored, and don't want to take the time to
 
1053
            decode.
 
1054
        :return: (iter_changes_result, changed). If the entry has not been
 
1055
            handled then changed is None. Otherwise it is False if no content
 
1056
            or metadata changes have occured, and None if any content or
 
1057
            metadata change has occured. If self.include_unchanged is True then
 
1058
            if changed is not None, iter_changes_result will always be a result
 
1059
            tuple. Otherwise, iter_changes_result is None unless changed is
 
1060
            True.
 
1061
        """
 
1062
        cdef char target_minikind
 
1063
        cdef char source_minikind
 
1064
        cdef object file_id
 
1065
        cdef int content_change
 
1066
        cdef object details_list
 
1067
        file_id = None
 
1068
        details_list = entry[1]
 
1069
        if -1 == self.source_index:
 
1070
            source_details = DirState.NULL_PARENT_DETAILS
 
1071
        else:
 
1072
            source_details = details_list[self.source_index]
 
1073
        target_details = details_list[self.target_index]
 
1074
        target_minikind = _minikind_from_string(target_details[0])
 
1075
        if path_info is not None and _versioned_minikind(target_minikind):
 
1076
            if self.target_index != 0:
 
1077
                raise AssertionError("Unsupported target index %d" %
 
1078
                                     self.target_index)
 
1079
            link_or_sha1 = _update_entry(self.state, entry, path_info[4], path_info[3])
 
1080
            # The entry may have been modified by update_entry
 
1081
            target_details = details_list[self.target_index]
 
1082
            target_minikind = _minikind_from_string(target_details[0])
 
1083
        else:
 
1084
            link_or_sha1 = None
 
1085
        # the rest of this function is 0.3 seconds on 50K paths, or
 
1086
        # 0.000006 seconds per call.
 
1087
        source_minikind = _minikind_from_string(source_details[0])
 
1088
        if ((_versioned_minikind(source_minikind) or source_minikind == c'r')
 
1089
            and _versioned_minikind(target_minikind)):
 
1090
            # claimed content in both: diff
 
1091
            #   r    | fdlt   |      | add source to search, add id path move and perform
 
1092
            #        |        |      | diff check on source-target
 
1093
            #   r    | fdlt   |  a   | dangling file that was present in the basis.
 
1094
            #        |        |      | ???
 
1095
            if source_minikind != c'r':
 
1096
                old_dirname = entry[0][0]
 
1097
                old_basename = entry[0][1]
 
1098
                old_path = path = None
 
1099
            else:
 
1100
                # add the source to the search path to find any children it
 
1101
                # has.  TODO ? : only add if it is a container ?
 
1102
                if not osutils.is_inside_any(self.searched_specific_files,
 
1103
                                             source_details[1]):
 
1104
                    self.search_specific_files.add(source_details[1])
 
1105
                # generate the old path; this is needed for stating later
 
1106
                # as well.
 
1107
                old_path = source_details[1]
 
1108
                old_dirname, old_basename = os.path.split(old_path)
 
1109
                path = self.pathjoin(entry[0][0], entry[0][1])
 
1110
                old_entry = self.state._get_entry(self.source_index,
 
1111
                                             path_utf8=old_path)
 
1112
                # update the source details variable to be the real
 
1113
                # location.
 
1114
                if old_entry == (None, None):
 
1115
                    raise errors.CorruptDirstate(self.state._filename,
 
1116
                        "entry '%s/%s' is considered renamed from %r"
 
1117
                        " but source does not exist\n"
 
1118
                        "entry: %s" % (entry[0][0], entry[0][1], old_path, entry))
 
1119
                source_details = old_entry[1][self.source_index]
 
1120
                source_minikind = _minikind_from_string(source_details[0])
 
1121
            if path_info is None:
 
1122
                # the file is missing on disk, show as removed.
 
1123
                content_change = 1
 
1124
                target_kind = None
 
1125
                target_exec = False
 
1126
            else:
 
1127
                # source and target are both versioned and disk file is present.
 
1128
                target_kind = path_info[2]
 
1129
                if target_kind == 'directory':
 
1130
                    if path is None:
 
1131
                        old_path = path = self.pathjoin(old_dirname, old_basename)
 
1132
                    file_id = entry[0][2]
 
1133
                    self.new_dirname_to_file_id[path] = file_id
 
1134
                    if source_minikind != c'd':
 
1135
                        content_change = 1
 
1136
                    else:
 
1137
                        # directories have no fingerprint
 
1138
                        content_change = 0
 
1139
                    target_exec = False
 
1140
                elif target_kind == 'file':
 
1141
                    if source_minikind != c'f':
 
1142
                        content_change = 1
 
1143
                    else:
 
1144
                        # Check the sha. We can't just rely on the size as
 
1145
                        # content filtering may mean differ sizes actually
 
1146
                        # map to the same content
 
1147
                        if link_or_sha1 is None:
 
1148
                            # Stat cache miss:
 
1149
                            statvalue, link_or_sha1 = \
 
1150
                                self.state._sha1_provider.stat_and_sha1(
 
1151
                                path_info[4])
 
1152
                            self.state._observed_sha1(entry, link_or_sha1,
 
1153
                                statvalue)
 
1154
                        content_change = (link_or_sha1 != source_details[1])
 
1155
                    # Target details is updated at update_entry time
 
1156
                    if self.use_filesystem_for_exec:
 
1157
                        # We don't need S_ISREG here, because we are sure
 
1158
                        # we are dealing with a file.
 
1159
                        target_exec = bool(S_IXUSR & path_info[3].st_mode)
 
1160
                    else:
 
1161
                        target_exec = target_details[3]
 
1162
                elif target_kind == 'symlink':
 
1163
                    if source_minikind != c'l':
 
1164
                        content_change = 1
 
1165
                    else:
 
1166
                        content_change = (link_or_sha1 != source_details[1])
 
1167
                    target_exec = False
 
1168
                elif target_kind == 'tree-reference':
 
1169
                    if source_minikind != c't':
 
1170
                        content_change = 1
 
1171
                    else:
 
1172
                        content_change = 0
 
1173
                    target_exec = False
 
1174
                else:
 
1175
                    raise Exception, "unknown kind %s" % path_info[2]
 
1176
            if source_minikind == c'd':
 
1177
                if path is None:
 
1178
                    old_path = path = self.pathjoin(old_dirname, old_basename)
 
1179
                if file_id is None:
 
1180
                    file_id = entry[0][2]
 
1181
                self.old_dirname_to_file_id[old_path] = file_id
 
1182
            # parent id is the entry for the path in the target tree
 
1183
            if old_dirname == self.last_source_parent[0]:
 
1184
                source_parent_id = self.last_source_parent[1]
 
1185
            else:
 
1186
                try:
 
1187
                    source_parent_id = self.old_dirname_to_file_id[old_dirname]
 
1188
                except KeyError:
 
1189
                    source_parent_entry = self.state._get_entry(self.source_index,
 
1190
                                                           path_utf8=old_dirname)
 
1191
                    source_parent_id = source_parent_entry[0][2]
 
1192
                if source_parent_id == entry[0][2]:
 
1193
                    # This is the root, so the parent is None
 
1194
                    source_parent_id = None
 
1195
                else:
 
1196
                    self.last_source_parent[0] = old_dirname
 
1197
                    self.last_source_parent[1] = source_parent_id
 
1198
            new_dirname = entry[0][0]
 
1199
            if new_dirname == self.last_target_parent[0]:
 
1200
                target_parent_id = self.last_target_parent[1]
 
1201
            else:
 
1202
                try:
 
1203
                    target_parent_id = self.new_dirname_to_file_id[new_dirname]
 
1204
                except KeyError:
 
1205
                    # TODO: We don't always need to do the lookup, because the
 
1206
                    #       parent entry will be the same as the source entry.
 
1207
                    target_parent_entry = self.state._get_entry(self.target_index,
 
1208
                                                           path_utf8=new_dirname)
 
1209
                    if target_parent_entry == (None, None):
 
1210
                        raise AssertionError(
 
1211
                            "Could not find target parent in wt: %s\nparent of: %s"
 
1212
                            % (new_dirname, entry))
 
1213
                    target_parent_id = target_parent_entry[0][2]
 
1214
                if target_parent_id == entry[0][2]:
 
1215
                    # This is the root, so the parent is None
 
1216
                    target_parent_id = None
 
1217
                else:
 
1218
                    self.last_target_parent[0] = new_dirname
 
1219
                    self.last_target_parent[1] = target_parent_id
 
1220
 
 
1221
            source_exec = source_details[3]
 
1222
            changed = (content_change
 
1223
                or source_parent_id != target_parent_id
 
1224
                or old_basename != entry[0][1]
 
1225
                or source_exec != target_exec
 
1226
                )
 
1227
            if not changed and not self.include_unchanged:
 
1228
                return None, False
 
1229
            else:
 
1230
                if old_path is None:
 
1231
                    path = self.pathjoin(old_dirname, old_basename)
 
1232
                    old_path = path
 
1233
                    old_path_u = self.utf8_decode(old_path)[0]
 
1234
                    path_u = old_path_u
 
1235
                else:
 
1236
                    old_path_u = self.utf8_decode(old_path)[0]
 
1237
                    if old_path == path:
 
1238
                        path_u = old_path_u
 
1239
                    else:
 
1240
                        path_u = self.utf8_decode(path)[0]
 
1241
                source_kind = _minikind_to_kind(source_minikind)
 
1242
                return (entry[0][2],
 
1243
                       (old_path_u, path_u),
 
1244
                       content_change,
 
1245
                       (True, True),
 
1246
                       (source_parent_id, target_parent_id),
 
1247
                       (self.utf8_decode(old_basename)[0], self.utf8_decode(entry[0][1])[0]),
 
1248
                       (source_kind, target_kind),
 
1249
                       (source_exec, target_exec)), changed
 
1250
        elif source_minikind == c'a' and _versioned_minikind(target_minikind):
 
1251
            # looks like a new file
 
1252
            path = self.pathjoin(entry[0][0], entry[0][1])
 
1253
            # parent id is the entry for the path in the target tree
 
1254
            # TODO: these are the same for an entire directory: cache em.
 
1255
            parent_entry = self.state._get_entry(self.target_index,
 
1256
                                                 path_utf8=entry[0][0])
 
1257
            if parent_entry is None:
 
1258
                raise errors.DirstateCorrupt(self.state,
 
1259
                    "We could not find the parent entry in index %d"
 
1260
                    " for the entry: %s"
 
1261
                    % (self.target_index, entry[0]))
 
1262
            parent_id = parent_entry[0][2]
 
1263
            if parent_id == entry[0][2]:
 
1264
                parent_id = None
 
1265
            if path_info is not None:
 
1266
                # Present on disk:
 
1267
                if self.use_filesystem_for_exec:
 
1268
                    # We need S_ISREG here, because we aren't sure if this
 
1269
                    # is a file or not.
 
1270
                    target_exec = bool(
 
1271
                        S_ISREG(path_info[3].st_mode)
 
1272
                        and S_IXUSR & path_info[3].st_mode)
 
1273
                else:
 
1274
                    target_exec = target_details[3]
 
1275
                return (entry[0][2],
 
1276
                       (None, self.utf8_decode(path)[0]),
 
1277
                       True,
 
1278
                       (False, True),
 
1279
                       (None, parent_id),
 
1280
                       (None, self.utf8_decode(entry[0][1])[0]),
 
1281
                       (None, path_info[2]),
 
1282
                       (None, target_exec)), True
 
1283
            else:
 
1284
                # Its a missing file, report it as such.
 
1285
                return (entry[0][2],
 
1286
                       (None, self.utf8_decode(path)[0]),
 
1287
                       False,
 
1288
                       (False, True),
 
1289
                       (None, parent_id),
 
1290
                       (None, self.utf8_decode(entry[0][1])[0]),
 
1291
                       (None, None),
 
1292
                       (None, False)), True
 
1293
        elif _versioned_minikind(source_minikind) and target_minikind == c'a':
 
1294
            # unversioned, possibly, or possibly not deleted: we dont care.
 
1295
            # if its still on disk, *and* theres no other entry at this
 
1296
            # path [we dont know this in this routine at the moment -
 
1297
            # perhaps we should change this - then it would be an unknown.
 
1298
            old_path = self.pathjoin(entry[0][0], entry[0][1])
 
1299
            # parent id is the entry for the path in the target tree
 
1300
            parent_id = self.state._get_entry(self.source_index, path_utf8=entry[0][0])[0][2]
 
1301
            if parent_id == entry[0][2]:
 
1302
                parent_id = None
 
1303
            return (entry[0][2],
 
1304
                   (self.utf8_decode(old_path)[0], None),
 
1305
                   True,
 
1306
                   (True, False),
 
1307
                   (parent_id, None),
 
1308
                   (self.utf8_decode(entry[0][1])[0], None),
 
1309
                   (_minikind_to_kind(source_minikind), None),
 
1310
                   (source_details[3], None)), True
 
1311
        elif _versioned_minikind(source_minikind) and target_minikind == c'r':
 
1312
            # a rename; could be a true rename, or a rename inherited from
 
1313
            # a renamed parent. TODO: handle this efficiently. Its not
 
1314
            # common case to rename dirs though, so a correct but slow
 
1315
            # implementation will do.
 
1316
            if not osutils.is_inside_any(self.searched_specific_files, target_details[1]):
 
1317
                self.search_specific_files.add(target_details[1])
 
1318
        elif ((source_minikind == c'r' or source_minikind == c'a') and
 
1319
              (target_minikind == c'r' or target_minikind == c'a')):
 
1320
            # neither of the selected trees contain this path,
 
1321
            # so skip over it. This is not currently directly tested, but
 
1322
            # is indirectly via test_too_much.TestCommands.test_conflicts.
 
1323
            pass
 
1324
        else:
 
1325
            raise AssertionError("don't know how to compare "
 
1326
                "source_minikind=%r, target_minikind=%r"
 
1327
                % (source_minikind, target_minikind))
 
1328
            ## import pdb;pdb.set_trace()
 
1329
        return None, None
 
1330
 
 
1331
    def __iter__(self):
 
1332
        return self
 
1333
 
 
1334
    def iter_changes(self):
 
1335
        return self
 
1336
 
 
1337
    cdef void _update_current_block(self):
 
1338
        if (self.block_index < len(self.state._dirblocks) and
 
1339
            osutils.is_inside(self.current_root, self.state._dirblocks[self.block_index][0])):
 
1340
            self.current_block = self.state._dirblocks[self.block_index]
 
1341
            self.current_block_list = self.current_block[1]
 
1342
            self.current_block_pos = 0
 
1343
        else:
 
1344
            self.current_block = None
 
1345
            self.current_block_list = None
 
1346
 
 
1347
    def __next__(self):
 
1348
        # Simple thunk to allow tail recursion without pyrex confusion
 
1349
        return self._iter_next()
 
1350
 
 
1351
    cdef _iter_next(self):
 
1352
        """Iterate over the changes."""
 
1353
        # This function single steps through an iterator. As such while loops
 
1354
        # are often exited by 'return' - the code is structured so that the
 
1355
        # next call into the function will return to the same while loop. Note
 
1356
        # that all flow control needed to re-reach that step is reexecuted,
 
1357
        # which can be a performance problem. It has not yet been tuned to
 
1358
        # minimise this; a state machine is probably the simplest restructuring
 
1359
        # to both minimise this overhead and make the code considerably more
 
1360
        # understandable.
 
1361
 
 
1362
        # sketch: 
 
1363
        # compare source_index and target_index at or under each element of search_specific_files.
 
1364
        # follow the following comparison table. Note that we only want to do diff operations when
 
1365
        # the target is fdl because thats when the walkdirs logic will have exposed the pathinfo 
 
1366
        # for the target.
 
1367
        # cases:
 
1368
        # 
 
1369
        # Source | Target | disk | action
 
1370
        #   r    | fdlt   |      | add source to search, add id path move and perform
 
1371
        #        |        |      | diff check on source-target
 
1372
        #   r    | fdlt   |  a   | dangling file that was present in the basis. 
 
1373
        #        |        |      | ???
 
1374
        #   r    |  a     |      | add source to search
 
1375
        #   r    |  a     |  a   | 
 
1376
        #   r    |  r     |      | this path is present in a non-examined tree, skip.
 
1377
        #   r    |  r     |  a   | this path is present in a non-examined tree, skip.
 
1378
        #   a    | fdlt   |      | add new id
 
1379
        #   a    | fdlt   |  a   | dangling locally added file, skip
 
1380
        #   a    |  a     |      | not present in either tree, skip
 
1381
        #   a    |  a     |  a   | not present in any tree, skip
 
1382
        #   a    |  r     |      | not present in either tree at this path, skip as it
 
1383
        #        |        |      | may not be selected by the users list of paths.
 
1384
        #   a    |  r     |  a   | not present in either tree at this path, skip as it
 
1385
        #        |        |      | may not be selected by the users list of paths.
 
1386
        #  fdlt  | fdlt   |      | content in both: diff them
 
1387
        #  fdlt  | fdlt   |  a   | deleted locally, but not unversioned - show as deleted ?
 
1388
        #  fdlt  |  a     |      | unversioned: output deleted id for now
 
1389
        #  fdlt  |  a     |  a   | unversioned and deleted: output deleted id
 
1390
        #  fdlt  |  r     |      | relocated in this tree, so add target to search.
 
1391
        #        |        |      | Dont diff, we will see an r,fd; pair when we reach
 
1392
        #        |        |      | this id at the other path.
 
1393
        #  fdlt  |  r     |  a   | relocated in this tree, so add target to search.
 
1394
        #        |        |      | Dont diff, we will see an r,fd; pair when we reach
 
1395
        #        |        |      | this id at the other path.
 
1396
 
 
1397
        # TODO: jam 20070516 - Avoid the _get_entry lookup overhead by
 
1398
        #       keeping a cache of directories that we have seen.
 
1399
        cdef object current_dirname, current_blockname
 
1400
        cdef char * current_dirname_c, * current_blockname_c
 
1401
        cdef int advance_entry, advance_path
 
1402
        cdef int path_handled
 
1403
        searched_specific_files = self.searched_specific_files
 
1404
        # Are we walking a root?
 
1405
        while self.root_entries_pos < self.root_entries_len:
 
1406
            entry = self.root_entries[self.root_entries_pos]
 
1407
            self.root_entries_pos = self.root_entries_pos + 1
 
1408
            result, changed = self._process_entry(entry, self.root_dir_info)
 
1409
            if changed is not None and changed or self.include_unchanged:
 
1410
                return result
 
1411
        # Have we finished the prior root, or never started one ?
 
1412
        if self.current_root is None:
 
1413
            # TODO: the pending list should be lexically sorted?  the
 
1414
            # interface doesn't require it.
 
1415
            try:
 
1416
                self.current_root = self.search_specific_files.pop()
 
1417
            except KeyError:
 
1418
                raise StopIteration()
 
1419
            self.current_root_unicode = self.current_root.decode('utf8')
 
1420
            self.searched_specific_files.add(self.current_root)
 
1421
            # process the entries for this containing directory: the rest will be
 
1422
            # found by their parents recursively.
 
1423
            self.root_entries = self.state._entries_for_path(self.current_root)
 
1424
            self.root_entries_len = len(self.root_entries)
 
1425
            self.root_abspath = self.tree.abspath(self.current_root_unicode)
 
1426
            try:
 
1427
                root_stat = os.lstat(self.root_abspath)
 
1428
            except OSError, e:
 
1429
                if e.errno == errno.ENOENT:
 
1430
                    # the path does not exist: let _process_entry know that.
 
1431
                    self.root_dir_info = None
 
1432
                else:
 
1433
                    # some other random error: hand it up.
 
1434
                    raise
 
1435
            else:
 
1436
                self.root_dir_info = ('', self.current_root,
 
1437
                    osutils.file_kind_from_stat_mode(root_stat.st_mode), root_stat,
 
1438
                    self.root_abspath)
 
1439
                if self.root_dir_info[2] == 'directory':
 
1440
                    if self.tree._directory_is_tree_reference(
 
1441
                        self.current_root_unicode):
 
1442
                        self.root_dir_info = self.root_dir_info[:2] + \
 
1443
                            ('tree-reference',) + self.root_dir_info[3:]
 
1444
            if not self.root_entries and not self.root_dir_info:
 
1445
                # this specified path is not present at all, skip it.
 
1446
                # (tail recursion, can do a loop once the full structure is
 
1447
                # known).
 
1448
                return self._iter_next()
 
1449
            path_handled = 0
 
1450
            self.root_entries_pos = 0
 
1451
            # XXX Clarity: This loop is duplicated a out the self.current_root
 
1452
            # is None guard above: if we return from it, it completes there
 
1453
            # (and the following if block cannot trigger because
 
1454
            # path_handled must be true, so the if block is not # duplicated.
 
1455
            while self.root_entries_pos < self.root_entries_len:
 
1456
                entry = self.root_entries[self.root_entries_pos]
 
1457
                self.root_entries_pos = self.root_entries_pos + 1
 
1458
                result, changed = self._process_entry(entry, self.root_dir_info)
 
1459
                if changed is not None:
 
1460
                    path_handled = -1
 
1461
                    if changed or self.include_unchanged:
 
1462
                        return result
 
1463
            # handle unversioned specified paths:
 
1464
            if self.want_unversioned and not path_handled and self.root_dir_info:
 
1465
                new_executable = bool(
 
1466
                    stat.S_ISREG(self.root_dir_info[3].st_mode)
 
1467
                    and stat.S_IEXEC & self.root_dir_info[3].st_mode)
 
1468
                return (None,
 
1469
                       (None, self.current_root_unicode),
 
1470
                       True,
 
1471
                       (False, False),
 
1472
                       (None, None),
 
1473
                       (None, splitpath(self.current_root_unicode)[-1]),
 
1474
                       (None, self.root_dir_info[2]),
 
1475
                       (None, new_executable)
 
1476
                      )
 
1477
            # If we reach here, the outer flow continues, which enters into the
 
1478
            # per-root setup logic.
 
1479
        if self.current_dir_info is None and self.current_block is None:
 
1480
            # setup iteration of this root:
 
1481
            self.current_dir_list = None
 
1482
            if self.root_dir_info and self.root_dir_info[2] == 'tree-reference':
 
1483
                self.current_dir_info = None
 
1484
            else:
 
1485
                self.dir_iterator = osutils._walkdirs_utf8(self.root_abspath,
 
1486
                    prefix=self.current_root)
 
1487
                self.path_index = 0
 
1488
                try:
 
1489
                    self.current_dir_info = self.dir_iterator.next()
 
1490
                    self.current_dir_list = self.current_dir_info[1]
 
1491
                except OSError, e:
 
1492
                    # there may be directories in the inventory even though
 
1493
                    # this path is not a file on disk: so mark it as end of
 
1494
                    # iterator
 
1495
                    if e.errno in (errno.ENOENT, errno.ENOTDIR, errno.EINVAL):
 
1496
                        self.current_dir_info = None
 
1497
                    elif sys.platform == 'win32':
 
1498
                        # on win32, python2.4 has e.errno == ERROR_DIRECTORY, but
 
1499
                        # python 2.5 has e.errno == EINVAL,
 
1500
                        #            and e.winerror == ERROR_DIRECTORY
 
1501
                        try:
 
1502
                            e_winerror = e.winerror
 
1503
                        except AttributeError:
 
1504
                            e_winerror = None
 
1505
                        win_errors = (ERROR_DIRECTORY, ERROR_PATH_NOT_FOUND)
 
1506
                        if (e.errno in win_errors or e_winerror in win_errors):
 
1507
                            self.current_dir_info = None
 
1508
                        else:
 
1509
                            # Will this really raise the right exception ?
 
1510
                            raise
 
1511
                    else:
 
1512
                        raise
 
1513
                else:
 
1514
                    if self.current_dir_info[0][0] == '':
 
1515
                        # remove .bzr from iteration
 
1516
                        bzr_index = self.bisect_left(self.current_dir_list, ('.bzr',))
 
1517
                        if self.current_dir_list[bzr_index][0] != '.bzr':
 
1518
                            raise AssertionError()
 
1519
                        del self.current_dir_list[bzr_index]
 
1520
            initial_key = (self.current_root, '', '')
 
1521
            self.block_index, _ = self.state._find_block_index_from_key(initial_key)
 
1522
            if self.block_index == 0:
 
1523
                # we have processed the total root already, but because the
 
1524
                # initial key matched it we should skip it here.
 
1525
                self.block_index = self.block_index + 1
 
1526
            self._update_current_block()
 
1527
        # walk until both the directory listing and the versioned metadata
 
1528
        # are exhausted. 
 
1529
        while (self.current_dir_info is not None
 
1530
            or self.current_block is not None):
 
1531
            # Uncommon case - a missing directory or an unversioned directory:
 
1532
            if (self.current_dir_info and self.current_block
 
1533
                and self.current_dir_info[0][0] != self.current_block[0]):
 
1534
                # Work around pyrex broken heuristic - current_dirname has
 
1535
                # the same scope as current_dirname_c
 
1536
                current_dirname = self.current_dir_info[0][0]
 
1537
                current_dirname_c = PyString_AS_STRING_void(
 
1538
                    <void *>current_dirname)
 
1539
                current_blockname = self.current_block[0]
 
1540
                current_blockname_c = PyString_AS_STRING_void(
 
1541
                    <void *>current_blockname)
 
1542
                # In the python generator we evaluate this if block once per
 
1543
                # dir+block; because we reenter in the pyrex version its being
 
1544
                # evaluated once per path: we could cache the result before
 
1545
                # doing the while loop and probably save time.
 
1546
                if _cmp_by_dirs(current_dirname_c,
 
1547
                    PyString_Size(current_dirname),
 
1548
                    current_blockname_c,
 
1549
                    PyString_Size(current_blockname)) < 0:
 
1550
                    # filesystem data refers to paths not covered by the
 
1551
                    # dirblock.  this has two possibilities:
 
1552
                    # A) it is versioned but empty, so there is no block for it
 
1553
                    # B) it is not versioned.
 
1554
 
 
1555
                    # if (A) then we need to recurse into it to check for
 
1556
                    # new unknown files or directories.
 
1557
                    # if (B) then we should ignore it, because we don't
 
1558
                    # recurse into unknown directories.
 
1559
                    # We are doing a loop
 
1560
                    while self.path_index < len(self.current_dir_list):
 
1561
                        current_path_info = self.current_dir_list[self.path_index]
 
1562
                        # dont descend into this unversioned path if it is
 
1563
                        # a dir
 
1564
                        if current_path_info[2] in ('directory',
 
1565
                                                    'tree-reference'):
 
1566
                            del self.current_dir_list[self.path_index]
 
1567
                            self.path_index = self.path_index - 1
 
1568
                        self.path_index = self.path_index + 1
 
1569
                        if self.want_unversioned:
 
1570
                            if current_path_info[2] == 'directory':
 
1571
                                if self.tree._directory_is_tree_reference(
 
1572
                                    self.utf8_decode(current_path_info[0])[0]):
 
1573
                                    current_path_info = current_path_info[:2] + \
 
1574
                                        ('tree-reference',) + current_path_info[3:]
 
1575
                            new_executable = bool(
 
1576
                                stat.S_ISREG(current_path_info[3].st_mode)
 
1577
                                and stat.S_IEXEC & current_path_info[3].st_mode)
 
1578
                            return (None,
 
1579
                                (None, self.utf8_decode(current_path_info[0])[0]),
 
1580
                                True,
 
1581
                                (False, False),
 
1582
                                (None, None),
 
1583
                                (None, self.utf8_decode(current_path_info[1])[0]),
 
1584
                                (None, current_path_info[2]),
 
1585
                                (None, new_executable))
 
1586
                    # This dir info has been handled, go to the next
 
1587
                    self.path_index = 0
 
1588
                    self.current_dir_list = None
 
1589
                    try:
 
1590
                        self.current_dir_info = self.dir_iterator.next()
 
1591
                        self.current_dir_list = self.current_dir_info[1]
 
1592
                    except StopIteration:
 
1593
                        self.current_dir_info = None
 
1594
                else: #(dircmp > 0)
 
1595
                    # We have a dirblock entry for this location, but there
 
1596
                    # is no filesystem path for this. This is most likely
 
1597
                    # because a directory was removed from the disk.
 
1598
                    # We don't have to report the missing directory,
 
1599
                    # because that should have already been handled, but we
 
1600
                    # need to handle all of the files that are contained
 
1601
                    # within.
 
1602
                    while self.current_block_pos < len(self.current_block_list):
 
1603
                        current_entry = self.current_block_list[self.current_block_pos]
 
1604
                        self.current_block_pos = self.current_block_pos + 1
 
1605
                        # entry referring to file not present on disk.
 
1606
                        # advance the entry only, after processing.
 
1607
                        result, changed = self._process_entry(current_entry, None)
 
1608
                        if changed is not None:
 
1609
                            if changed or self.include_unchanged:
 
1610
                                return result
 
1611
                    self.block_index = self.block_index + 1
 
1612
                    self._update_current_block()
 
1613
                continue # next loop-on-block/dir
 
1614
            result = self._loop_one_block()
 
1615
            if result is not None:
 
1616
                return result
 
1617
        if len(self.search_specific_files):
 
1618
            # More supplied paths to process
 
1619
            self.current_root = None
 
1620
            return self._iter_next()
 
1621
        raise StopIteration()
 
1622
 
 
1623
    cdef object _maybe_tree_ref(self, current_path_info):
 
1624
        if self.tree._directory_is_tree_reference(
 
1625
            self.utf8_decode(current_path_info[0])[0]):
 
1626
            return current_path_info[:2] + \
 
1627
                ('tree-reference',) + current_path_info[3:]
 
1628
        else:
 
1629
            return current_path_info
 
1630
 
 
1631
    cdef object _loop_one_block(self):
 
1632
            # current_dir_info and current_block refer to the same directory -
 
1633
            # this is the common case code.
 
1634
            # Assign local variables for current path and entry:
 
1635
            cdef object current_entry
 
1636
            cdef object current_path_info
 
1637
            cdef int path_handled
 
1638
            cdef char minikind
 
1639
            cdef int cmp_result
 
1640
            # cdef char * temp_str
 
1641
            # cdef Py_ssize_t temp_str_length
 
1642
            # PyString_AsStringAndSize(disk_kind, &temp_str, &temp_str_length)
 
1643
            # if not strncmp(temp_str, "directory", temp_str_length):
 
1644
            if (self.current_block is not None and
 
1645
                self.current_block_pos < PyList_GET_SIZE(self.current_block_list)):
 
1646
                current_entry = PyList_GET_ITEM(self.current_block_list,
 
1647
                    self.current_block_pos)
 
1648
                # accomodate pyrex
 
1649
                Py_INCREF(current_entry)
 
1650
            else:
 
1651
                current_entry = None
 
1652
            if (self.current_dir_info is not None and
 
1653
                self.path_index < PyList_GET_SIZE(self.current_dir_list)):
 
1654
                current_path_info = PyList_GET_ITEM(self.current_dir_list,
 
1655
                    self.path_index)
 
1656
                # accomodate pyrex
 
1657
                Py_INCREF(current_path_info)
 
1658
                disk_kind = PyTuple_GET_ITEM(current_path_info, 2)
 
1659
                # accomodate pyrex
 
1660
                Py_INCREF(disk_kind)
 
1661
                if disk_kind == "directory":
 
1662
                    current_path_info = self._maybe_tree_ref(current_path_info)
 
1663
            else:
 
1664
                current_path_info = None
 
1665
            while (current_entry is not None or current_path_info is not None):
 
1666
                advance_entry = -1
 
1667
                advance_path = -1
 
1668
                result = None
 
1669
                path_handled = 0
 
1670
                if current_entry is None:
 
1671
                    # unversioned -  the check for path_handled when the path
 
1672
                    # is advanced will yield this path if needed.
 
1673
                    pass
 
1674
                elif current_path_info is None:
 
1675
                    # no path is fine: the per entry code will handle it.
 
1676
                    result, changed = self._process_entry(current_entry,
 
1677
                        current_path_info)
 
1678
                else:
 
1679
                    minikind = _minikind_from_string(
 
1680
                        current_entry[1][self.target_index][0])
 
1681
                    cmp_result = cmp(current_path_info[1], current_entry[0][1])
 
1682
                    if (cmp_result or minikind == c'a' or minikind == c'r'):
 
1683
                        # The current path on disk doesn't match the dirblock
 
1684
                        # record. Either the dirblock record is marked as
 
1685
                        # absent/renamed, or the file on disk is not present at all
 
1686
                        # in the dirblock. Either way, report about the dirblock
 
1687
                        # entry, and let other code handle the filesystem one.
 
1688
 
 
1689
                        # Compare the basename for these files to determine
 
1690
                        # which comes first
 
1691
                        if cmp_result < 0:
 
1692
                            # extra file on disk: pass for now, but only
 
1693
                            # increment the path, not the entry
 
1694
                            advance_entry = 0
 
1695
                        else:
 
1696
                            # entry referring to file not present on disk.
 
1697
                            # advance the entry only, after processing.
 
1698
                            result, changed = self._process_entry(current_entry,
 
1699
                                None)
 
1700
                            advance_path = 0
 
1701
                    else:
 
1702
                        # paths are the same,and the dirstate entry is not
 
1703
                        # absent or renamed.
 
1704
                        result, changed = self._process_entry(current_entry,
 
1705
                            current_path_info)
 
1706
                        if changed is not None:
 
1707
                            path_handled = -1
 
1708
                # >- loop control starts here:
 
1709
                # >- entry
 
1710
                if advance_entry and current_entry is not None:
 
1711
                    self.current_block_pos = self.current_block_pos + 1
 
1712
                    if self.current_block_pos < PyList_GET_SIZE(self.current_block_list):
 
1713
                        current_entry = self.current_block_list[self.current_block_pos]
 
1714
                    else:
 
1715
                        current_entry = None
 
1716
                # >- path
 
1717
                if advance_path and current_path_info is not None:
 
1718
                    if not path_handled:
 
1719
                        # unversioned in all regards
 
1720
                        if self.want_unversioned:
 
1721
                            new_executable = bool(
 
1722
                                stat.S_ISREG(current_path_info[3].st_mode)
 
1723
                                and stat.S_IEXEC & current_path_info[3].st_mode)
 
1724
                            try:
 
1725
                                relpath_unicode = self.utf8_decode(current_path_info[0])[0]
 
1726
                            except UnicodeDecodeError:
 
1727
                                raise errors.BadFilenameEncoding(
 
1728
                                    current_path_info[0], osutils._fs_enc)
 
1729
                            if result is not None:
 
1730
                                raise AssertionError(
 
1731
                                    "result is not None: %r" % result)
 
1732
                            result = (None,
 
1733
                                (None, relpath_unicode),
 
1734
                                True,
 
1735
                                (False, False),
 
1736
                                (None, None),
 
1737
                                (None, self.utf8_decode(current_path_info[1])[0]),
 
1738
                                (None, current_path_info[2]),
 
1739
                                (None, new_executable))
 
1740
                        # dont descend into this unversioned path if it is
 
1741
                        # a dir
 
1742
                        if current_path_info[2] in ('directory'):
 
1743
                            del self.current_dir_list[self.path_index]
 
1744
                            self.path_index = self.path_index - 1
 
1745
                    # dont descend the disk iterator into any tree 
 
1746
                    # paths.
 
1747
                    if current_path_info[2] == 'tree-reference':
 
1748
                        del self.current_dir_list[self.path_index]
 
1749
                        self.path_index = self.path_index - 1
 
1750
                    self.path_index = self.path_index + 1
 
1751
                    if self.path_index < len(self.current_dir_list):
 
1752
                        current_path_info = self.current_dir_list[self.path_index]
 
1753
                        if current_path_info[2] == 'directory':
 
1754
                            current_path_info = self._maybe_tree_ref(
 
1755
                                current_path_info)
 
1756
                    else:
 
1757
                        current_path_info = None
 
1758
                if result is not None:
 
1759
                    # Found a result on this pass, yield it
 
1760
                    return result
 
1761
            if self.current_block is not None:
 
1762
                self.block_index = self.block_index + 1
 
1763
                self._update_current_block()
 
1764
            if self.current_dir_info is not None:
 
1765
                self.path_index = 0
 
1766
                self.current_dir_list = None
 
1767
                try:
 
1768
                    self.current_dir_info = self.dir_iterator.next()
 
1769
                    self.current_dir_list = self.current_dir_info[1]
 
1770
                except StopIteration:
 
1771
                    self.current_dir_info = None