~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/_readdir_pyx.pyx

Merge bzr.dev and tree-file-ids-as-tuples.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006, 2008 Canonical Ltd
 
1
# Copyright (C) 2006, 2008, 2009, 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
"""Wrapper for readdir which returns files ordered by inode."""
18
18
 
25
25
    pass
26
26
 
27
27
 
28
 
# the opaque C library DIR type.
29
28
cdef extern from 'errno.h':
30
29
    int ENOENT
31
30
    int ENOTDIR
32
31
    int EAGAIN
 
32
    int EINTR
 
33
    char *strerror(int errno)
 
34
    # not necessarily a real variable, but this should be close enough
33
35
    int errno
34
 
    char *strerror(int errno)
35
36
 
36
37
cdef extern from 'unistd.h':
37
38
    int chdir(char *path)
 
39
    int close(int fd)
 
40
    int fchdir(int fd)
38
41
    char *getcwd(char *, int size)
39
42
 
40
43
cdef extern from 'stdlib.h':
48
51
    ctypedef long time_t
49
52
    ctypedef unsigned long ino_t
50
53
    ctypedef unsigned long long off_t
 
54
    ctypedef int mode_t
51
55
 
52
56
 
53
57
cdef extern from 'sys/stat.h':
68
72
    int S_ISSOCK(int mode)
69
73
 
70
74
 
 
75
cdef extern from 'fcntl.h':
 
76
    int O_RDONLY
 
77
    int open(char *pathname, int flags, mode_t mode)
 
78
 
 
79
 
71
80
cdef extern from 'Python.h':
 
81
    int PyErr_CheckSignals() except -1
72
82
    char * PyString_AS_STRING(object)
73
83
    ctypedef int Py_ssize_t # Required for older pyrex versions
74
84
    ctypedef struct PyObject:
89
99
    ctypedef struct dirent:
90
100
        char d_name[256]
91
101
        ino_t d_ino
 
102
    # the opaque C library DIR type.
92
103
    ctypedef struct DIR
93
104
    # should be DIR *, pyrex barfs.
94
105
    DIR * opendir(char * name)
95
106
    int closedir(DIR * dir)
96
107
    dirent *readdir(DIR *dir)
97
108
 
 
109
cdef object _directory
98
110
_directory = 'directory'
 
111
cdef object _chardev
99
112
_chardev = 'chardev'
 
113
cdef object _block
100
114
_block = 'block'
 
115
cdef object _file
101
116
_file = 'file'
 
117
cdef object _fifo
102
118
_fifo = 'fifo'
 
119
cdef object _symlink
103
120
_symlink = 'symlink'
 
121
cdef object _socket
104
122
_socket = 'socket'
 
123
cdef object _unknown
105
124
_unknown = 'unknown'
106
 
_missing = 'missing'
107
125
 
108
126
# add a typedef struct dirent dirent to workaround pyrex
109
127
cdef extern from 'readdir.h':
145
163
        (mode, ino, dev, nlink, uid, gid, size, None(atime), mtime, ctime)
146
164
        """
147
165
        return repr((self.st_mode, 0, 0, 0, 0, 0, self.st_size, None,
148
 
                     self._mtime, self._ctime))
 
166
                     self.st_mtime, self.st_ctime))
149
167
 
150
168
 
151
169
from bzrlib import osutils
152
170
 
 
171
cdef object _safe_utf8
 
172
_safe_utf8 = osutils.safe_utf8
153
173
 
154
174
cdef class UTF8DirReader:
155
175
    """A dir reader for utf8 file systems."""
156
176
 
157
 
    cdef readonly object _safe_utf8
158
 
    cdef _directory, _chardev, _block, _file, _fifo, _symlink
159
 
    cdef _socket, _unknown
160
 
 
161
 
    def __init__(self):
162
 
        self._safe_utf8 = osutils.safe_utf8
163
 
        self._directory = _directory
164
 
        self._chardev = _chardev
165
 
        self._block = _block
166
 
        self._file = _file
167
 
        self._fifo = _fifo
168
 
        self._symlink = _symlink
169
 
        self._socket = _socket
170
 
        self._unknown = _unknown
171
 
 
172
177
    def kind_from_mode(self, int mode):
173
178
        """Get the kind of a path from a mode status."""
174
179
        return self._kind_from_mode(mode)
176
181
    cdef _kind_from_mode(self, int mode):
177
182
        # Files and directories are the most common - check them first.
178
183
        if S_ISREG(mode):
179
 
            return self._file
 
184
            return _file
180
185
        if S_ISDIR(mode):
181
 
            return self._directory
 
186
            return _directory
182
187
        if S_ISCHR(mode):
183
 
            return self._chardev
 
188
            return _chardev
184
189
        if S_ISBLK(mode):
185
 
            return self._block
 
190
            return _block
186
191
        if S_ISLNK(mode):
187
 
            return self._symlink
 
192
            return _symlink
188
193
        if S_ISFIFO(mode):
189
 
            return self._fifo
 
194
            return _fifo
190
195
        if S_ISSOCK(mode):
191
 
            return self._socket
192
 
        return self._unknown
 
196
            return _socket
 
197
        return _unknown
193
198
 
194
199
    def top_prefix_to_starting_dir(self, top, prefix=""):
195
200
        """See DirReader.top_prefix_to_starting_dir."""
196
 
        return (self._safe_utf8(prefix), None, None, None,
197
 
            self._safe_utf8(top))
 
201
        return (_safe_utf8(prefix), None, None, None, _safe_utf8(top))
198
202
 
199
203
    def read_dir(self, prefix, top):
200
204
        """Read a single directory from a utf8 file system.
261
265
        return result
262
266
 
263
267
 
 
268
cdef raise_os_error(int errnum, char *msg_prefix, path):
 
269
    if errnum == EINTR:
 
270
        PyErr_CheckSignals()
 
271
    raise OSError(errnum, msg_prefix + strerror(errnum), path)
 
272
 
 
273
 
264
274
cdef _read_dir(path):
265
275
    """Like os.listdir, this reads the contents of a directory.
266
276
 
277
287
    cdef char *name
278
288
    cdef int stat_result
279
289
    cdef _Stat statvalue
280
 
    cdef char *cwd
281
 
 
282
 
    cwd = getcwd(NULL, 0)
283
 
    if -1 == chdir(path):
284
 
        raise OSError(errno, strerror(errno))
285
 
    the_dir = opendir(".")
286
 
    if NULL == the_dir:
287
 
        raise OSError(errno, strerror(errno))
288
 
    result = []
 
290
    global errno
 
291
    cdef int orig_dir_fd
 
292
 
 
293
    # Avoid chdir('') because it causes problems on Sun OS, and avoid this if
 
294
    # staying in .
 
295
    if path != "" and path != '.':
 
296
        # we change into the requested directory before reading, and back at the
 
297
        # end, because that turns out to make the stat calls measurably faster than
 
298
        # passing full paths every time.
 
299
        orig_dir_fd = open(".", O_RDONLY, 0)
 
300
        if orig_dir_fd == -1:
 
301
            raise_os_error(errno, "open: ", ".")
 
302
        if -1 == chdir(path):
 
303
            # Ignore the return value, because we are already raising an
 
304
            # exception
 
305
            close(orig_dir_fd)
 
306
            raise_os_error(errno, "chdir: ", path)
 
307
    else:
 
308
        orig_dir_fd = -1
 
309
 
289
310
    try:
290
 
        entry = &sentinel
291
 
        while entry != NULL:
292
 
            entry = readdir(the_dir)
293
 
            if entry == NULL:
294
 
                if errno == EAGAIN:
295
 
                    # try again
296
 
                    continue
297
 
                elif errno != ENOTDIR and errno != ENOENT and errno != 0:
298
 
                    # We see ENOTDIR at the end of a normal directory.
299
 
                    # As ENOTDIR for read_dir(file) is triggered on opendir,
300
 
                    # we consider ENOTDIR to be 'no error'.
301
 
                    # ENOENT is listed as 'invalid position in the dir stream' for
302
 
                    # readdir. We swallow this for now and just keep reading.
303
 
                    raise OSError(errno, strerror(errno))
304
 
                else:
305
 
                    # done
306
 
                    continue
307
 
            name = entry.d_name
308
 
            if not (name[0] == c"." and (
309
 
                (name[1] == 0) or 
310
 
                (name[1] == c"." and name[2] == 0))
311
 
                ):
312
 
                statvalue = _Stat()
313
 
                stat_result = lstat(entry.d_name, &statvalue._st)
314
 
                if stat_result != 0:
315
 
                    if errno != ENOENT:
316
 
                        raise OSError(errno, strerror(errno))
317
 
                    else:
318
 
                        kind = _missing
319
 
                        statvalue = None
320
 
                # We append a 5-tuple that can be modified in-place by the C
321
 
                # api:
322
 
                # inode to sort on (to replace with top_path)
323
 
                # name (to keep)
324
 
                # kind (None, to set)
325
 
                # statvalue (to keep)
326
 
                # abspath (None, to set)
327
 
                PyList_Append(result, (entry.d_ino, entry.d_name, None,
328
 
                    statvalue, None))
 
311
        the_dir = opendir(".")
 
312
        if NULL == the_dir:
 
313
            raise_os_error(errno, "opendir: ", path)
 
314
        try:
 
315
            result = []
 
316
            entry = &sentinel
 
317
            while entry != NULL:
 
318
                # Unlike most libc functions, readdir needs errno set to 0
 
319
                # beforehand so that eof can be distinguished from errors.  See
 
320
                # <https://bugs.launchpad.net/bzr/+bug/279381>
 
321
                while True:
 
322
                    errno = 0
 
323
                    entry = readdir(the_dir)
 
324
                    if entry == NULL and (errno == EAGAIN or errno == EINTR):
 
325
                        if errno == EINTR:
 
326
                            PyErr_CheckSignals()
 
327
                        # try again
 
328
                        continue
 
329
                    else:
 
330
                        break
 
331
                if entry == NULL:
 
332
                    if errno == ENOTDIR or errno == 0:
 
333
                        # We see ENOTDIR at the end of a normal directory.
 
334
                        # As ENOTDIR for read_dir(file) is triggered on opendir,
 
335
                        # we consider ENOTDIR to be 'no error'.
 
336
                        continue
 
337
                    else:
 
338
                        raise_os_error(errno, "readdir: ", path)
 
339
                name = entry.d_name
 
340
                if not (name[0] == c"." and (
 
341
                    (name[1] == 0) or 
 
342
                    (name[1] == c"." and name[2] == 0))
 
343
                    ):
 
344
                    statvalue = _Stat()
 
345
                    stat_result = lstat(entry.d_name, &statvalue._st)
 
346
                    if stat_result != 0:
 
347
                        if errno != ENOENT:
 
348
                            raise_os_error(errno, "lstat: ",
 
349
                                path + "/" + entry.d_name)
 
350
                        else:
 
351
                            # the file seems to have disappeared after being
 
352
                            # seen by readdir - perhaps a transient temporary
 
353
                            # file.  there's no point returning it.
 
354
                            continue
 
355
                    # We append a 5-tuple that can be modified in-place by the C
 
356
                    # api:
 
357
                    # inode to sort on (to replace with top_path)
 
358
                    # name (to keep)
 
359
                    # kind (None, to set)
 
360
                    # statvalue (to keep)
 
361
                    # abspath (None, to set)
 
362
                    PyList_Append(result, (entry.d_ino, entry.d_name, None,
 
363
                        statvalue, None))
 
364
        finally:
 
365
            if -1 == closedir(the_dir):
 
366
                raise_os_error(errno, "closedir: ", path)
329
367
    finally:
330
 
        if -1 == chdir(cwd):
331
 
            free(cwd)
332
 
            raise OSError(errno, strerror(errno))
333
 
        free(cwd)
334
 
        if -1 == closedir(the_dir):
335
 
            raise OSError(errno, strerror(errno))
 
368
        if -1 != orig_dir_fd:
 
369
            failed = False
 
370
            if -1 == fchdir(orig_dir_fd):
 
371
                # try to close the original directory anyhow
 
372
                failed = True
 
373
            if -1 == close(orig_dir_fd) or failed:
 
374
                raise_os_error(errno, "return to orig_dir: ", "")
 
375
 
336
376
    return result
337
377
 
338
378