1
# Copyright (C) 2006, 2008, 2009, 2010 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
"""Wrapper for readdir which returns files ordered by inode."""
23
cdef extern from "python-compat.h":
27
cdef extern from 'errno.h':
32
char *strerror(int errno)
33
# not necessarily a real variable, but this should be close enough
36
cdef extern from 'unistd.h':
40
char *getcwd(char *, int size)
42
cdef extern from 'stdlib.h':
47
cdef extern from 'sys/types.h':
49
ctypedef unsigned long size_t
51
ctypedef unsigned long ino_t
52
ctypedef unsigned long long off_t
56
cdef extern from 'sys/stat.h':
64
int lstat(char *path, stat *buf)
69
int S_ISFIFO(int mode)
71
int S_ISSOCK(int mode)
74
cdef extern from 'fcntl.h':
76
int open(char *pathname, int flags, mode_t mode)
79
cdef extern from 'Python.h':
80
int PyErr_CheckSignals() except -1
81
char * PyBytes_AS_STRING(object)
82
ctypedef struct PyObject:
84
Py_ssize_t PyBytes_Size(object s)
85
object PyList_GetItem(object lst, Py_ssize_t index)
86
void *PyList_GetItem_object_void "PyList_GET_ITEM" (object lst, int index)
87
int PyList_Append(object lst, object item) except -1
88
void *PyTuple_GetItem_void_void "PyTuple_GET_ITEM" (void* tpl, int index)
89
int PyTuple_SetItem(void *, Py_ssize_t pos, object item) except -1
90
int PyTuple_SetItem_obj "PyTuple_SetItem" (void *, Py_ssize_t pos, PyObject * item) except -1
91
void Py_INCREF(object o)
92
void Py_DECREF(object o)
93
void PyBytes_Concat(PyObject **string, object newpart)
96
cdef extern from 'dirent.h':
97
ctypedef struct dirent:
100
# the opaque C library DIR type.
102
# should be DIR *, pyrex barfs.
103
DIR * opendir(char * name)
104
int closedir(DIR * dir)
105
dirent *readdir(DIR *dir)
107
cdef object _directory
108
_directory = 'directory'
124
# add a typedef struct dirent dirent to workaround pyrex
125
cdef extern from 'readdir.h':
130
"""Represent a 'stat' result."""
136
return self._st.st_dev
140
return self._st.st_ino
144
return self._st.st_mode
148
return self._st.st_ctime
152
return self._st.st_mtime
156
return self._st.st_size
159
"""Repr is the same as a Stat object.
161
(mode, ino, dev, nlink, uid, gid, size, None(atime), mtime, ctime)
163
return repr((self.st_mode, 0, 0, 0, 0, 0, self.st_size, None,
164
self.st_mtime, self.st_ctime))
167
from . import osutils
169
cdef object _safe_utf8
170
_safe_utf8 = osutils.safe_utf8
172
cdef class UTF8DirReader:
173
"""A dir reader for utf8 file systems."""
175
def kind_from_mode(self, int mode):
176
"""Get the kind of a path from a mode status."""
177
return self._kind_from_mode(mode)
179
cdef _kind_from_mode(self, int mode):
180
# Files and directories are the most common - check them first.
197
def top_prefix_to_starting_dir(self, top, prefix=""):
198
"""See DirReader.top_prefix_to_starting_dir."""
199
return (_safe_utf8(prefix), None, None, None, _safe_utf8(top))
201
def read_dir(self, prefix, top):
202
"""Read a single directory from a utf8 file system.
204
All paths in and out are utf8.
206
This sub-function is called when we know the filesystem is already in utf8
207
encoding. So we don't need to transcode filenames.
209
See DirReader.read_dir for details.
211
#cdef char *_prefix = prefix
212
#cdef char *_top = top
213
# Use C accelerated directory listing.
219
cdef PyObject * new_val_obj
221
if PyBytes_Size(prefix):
222
relprefix = prefix + b'/'
225
top_slash = top + b'/'
227
# read_dir supplies in should-stat order.
228
# for _, name in sorted(_listdir(top)):
229
result = _read_dir(top)
232
for index from 0 <= index < length:
233
atuple = PyList_GetItem_object_void(result, index)
234
name = <object>PyTuple_GetItem_void_void(atuple, 1)
235
# We have a tuple with (inode, name, None, statvalue, None)
237
# inode -> path_from_top
238
# direct concat - faster than operator +.
239
new_val_obj = <PyObject *>relprefix
241
PyBytes_Concat(&new_val_obj, name)
242
if NULL == new_val_obj:
243
# PyBytes_Concat will have setup an exception, but how to get
245
raise Exception("failed to strcat")
246
PyTuple_SetItem_obj(atuple, 0, new_val_obj)
248
newval = self._kind_from_mode(
249
(<_Stat>PyTuple_GetItem_void_void(atuple, 3)).st_mode)
251
PyTuple_SetItem(atuple, 2, newval)
252
# 2nd None -> abspath # for all - the caller may need to stat files
254
# direct concat - faster than operator +.
255
new_val_obj = <PyObject *>top_slash
257
PyBytes_Concat(&new_val_obj, name)
258
if NULL == new_val_obj:
259
# PyBytes_Concat will have setup an exception, but how to get
261
raise Exception("failed to strcat")
262
PyTuple_SetItem_obj(atuple, 4, new_val_obj)
266
cdef raise_os_error(int errnum, char *msg_prefix, path):
269
raise OSError(errnum, msg_prefix + strerror(errnum), path)
272
cdef _read_dir(path):
273
"""Like os.listdir, this reads the contents of a directory.
275
:param path: the directory to list.
276
:return: a list of single-owner (the list) tuples ready for editing into
277
the result tuples walkdirs needs to yield. They contain (inode, name,
278
None, statvalue, None).
281
# currently this needs a fixup - the C code says 'dirent' but should say
291
# Avoid chdir('') because it causes problems on Sun OS, and avoid this if
293
if path != b"" and path != b'.':
294
# we change into the requested directory before reading, and back at the
295
# end, because that turns out to make the stat calls measurably faster than
296
# passing full paths every time.
297
orig_dir_fd = open(".", O_RDONLY, 0)
298
if orig_dir_fd == -1:
299
raise_os_error(errno, "open: ", ".")
300
if -1 == chdir(path):
301
# Ignore the return value, because we are already raising an
304
raise_os_error(errno, "chdir: ", path)
309
the_dir = opendir(b".")
311
raise_os_error(errno, "opendir: ", path)
316
# Unlike most libc functions, readdir needs errno set to 0
317
# beforehand so that eof can be distinguished from errors. See
318
# <https://bugs.launchpad.net/bzr/+bug/279381>
321
entry = readdir(the_dir)
322
if entry == NULL and (errno == EAGAIN or errno == EINTR):
330
if errno == ENOTDIR or errno == 0:
331
# We see ENOTDIR at the end of a normal directory.
332
# As ENOTDIR for read_dir(file) is triggered on opendir,
333
# we consider ENOTDIR to be 'no error'.
336
raise_os_error(errno, "readdir: ", path)
338
if not (name[0] == c"." and (
340
(name[1] == c"." and name[2] == 0))
343
stat_result = lstat(entry.d_name, &statvalue._st)
346
raise_os_error(errno, "lstat: ",
347
path + b"/" + entry.d_name)
349
# the file seems to have disappeared after being
350
# seen by readdir - perhaps a transient temporary
351
# file. there's no point returning it.
353
# We append a 5-tuple that can be modified in-place by the C
355
# inode to sort on (to replace with top_path)
357
# kind (None, to set)
358
# statvalue (to keep)
359
# abspath (None, to set)
360
PyList_Append(result, (entry.d_ino, entry.d_name, None,
363
if -1 == closedir(the_dir):
364
raise_os_error(errno, "closedir: ", path)
366
if -1 != orig_dir_fd:
368
if -1 == fchdir(orig_dir_fd):
369
# try to close the original directory anyhow
371
if -1 == close(orig_dir_fd) or failed:
372
raise_os_error(errno, "return to orig_dir: ", "")
377
# vim: tw=79 ai expandtab sw=4 sts=4