Debian Codegraph @

pypy/module/posix/interp_scandir.py

raw symbols SCIP
1 import stat
2 import sys
3 from errno import ENOENT, ENOTDIR
4 from rpython.rlib import rgc
5 from rpython.rlib import rposix, rposix_scandir, rposix_stat
6
7 from pypy.interpreter.gateway import unwrap_spec, WrappedDefault, interp2app
8 from pypy.interpreter.error import (OperationError, oefmt, wrap_oserror,
9 wrap_oserror2)
10 from pypy.interpreter.typedef import TypeDef, GetSetProperty
11 from pypy.interpreter.baseobjspace import W_Root
12 from pypy.interpreter.buffer import BufferInterfaceNotFound
13 from pypy.objspace.std.util import generic_alias_class_getitem
14
15 from pypy.module.posix.interp_posix import (path_or_fd, build_stat_result,
16 _WIN32, dup, FileEncoder)
17
18
19 # XXX: update os.supports_fd when fd support is implemented
20 @unwrap_spec(path=path_or_fd(allow_fd=rposix.HAVE_FDOPENDIR, nullable=True))
21 def scandir(space, path=None):
22 "scandir(path='.') -> iterator of DirEntry objects for given path"
23 try:
24 space._try_buffer_w(path.w_path, space.BUF_FULL_RO)
25 except BufferInterfaceNotFound:
26 as_bytes = (path.as_unicode is None)
27 result_is_bytes = False
28 else:
29 as_bytes = True
30 result_is_bytes = True
31 if path.as_fd != -1:
32 if not rposix.HAVE_FDOPENDIR:
33 # needed for translation, in practice this is dead code
34 raise oefmt(space.w_TypeError,
35 "scandir: illegal type for path argument")
36 try:
37 dirfd = rposix.dup(path.as_fd, inheritable=False)
38 except OSError as e:
39 raise wrap_oserror(space, e, eintr_retry=False)
40 dirp = rposix.c_fdopendir(dirfd)
41 if not dirp:
42 rposix.c_close(dirfd)
43 e = rposix.get_saved_errno()
44 if e == ENOTDIR:
45 w_type = space.w_NotADirectoryError
46 else:
47 w_type = space.w_ValueError
48 raise oefmt(w_type, "invalid fd %d", path.as_fd)
49 path_prefix = ''
50 elif as_bytes:
51 path_prefix = path.as_bytes
52 try:
53 name = path.as_bytes
54 dirp = rposix_scandir.opendir(name, len(name))
55 except OSError as e:
56 raise wrap_oserror2(space, e, space.newbytes(path.as_bytes), eintr_retry=False)
57 else:
58 w_path = path.w_path
59 path_prefix = space.utf8_w(w_path)
60 lgt = len(path_prefix)
61 try:
62 dirp = rposix_scandir.opendir(path_prefix, lgt)
63 except OSError as e:
64 raise wrap_oserror2(space, e, w_path, eintr_retry=False)
65 if not _WIN32:
66 if len(path_prefix) > 0 and path_prefix[-1] != '/':
67 path_prefix += '/'
68 w_path_prefix = space.newbytes(path_prefix)
69 if not result_is_bytes:
70 w_path_prefix = space.fsdecode(w_path_prefix)
71 else:
72 if len(path_prefix) > 0 and path_prefix[-1] not in ('\\', '/', ':'):
73 path_prefix += '\\'
74 if result_is_bytes:
75 w_path_prefix = space.newbytes(path_prefix)
76 else:
77 w_path_prefix = space.newtext(path_prefix)
78 if rposix.HAVE_FSTATAT:
79 dirfd = rposix.c_dirfd(dirp)
80 else:
81 dirfd = -1
82 return W_ScandirIterator(space, dirp, dirfd, w_path_prefix, result_is_bytes, path.as_fd)
83
84
85 class W_ScandirIterator(W_Root):
86 _in_next = False
87
88 def __init__(self, space, dirp, dirfd, w_path_prefix, result_is_bytes, orig_fd):
89 self.space = space
90 self.dirp = dirp
91 self.dirfd = dirfd
92 self.orig_fd = orig_fd
93 self.w_path_prefix = w_path_prefix
94 self.result_is_bytes = result_is_bytes
95 self.register_finalizer(space)
96
97 def _finalize_(self):
98 if not self.dirp:
99 return
100 space = self.space
101 try:
102 msg = ("unclosed scandir iterator %s" %
103 space.text_w(space.repr(self)))
104 space.warn(space.newtext(msg), space.w_ResourceWarning)
105 except OperationError as e:
106 # Spurious errors can appear at shutdown
107 if e.match(space, space.w_Warning):
108 e.write_unraisable(space, '', self)
109 self._close()
110
111 def _close(self):
112 dirp = self.dirp
113 if dirp:
114 self.dirp = rposix_scandir.NULL_DIRP
115 if not _WIN32 and self.dirfd != -1:
116 rposix.c_rewinddir(dirp)
117 rposix_scandir.closedir(dirp)
118 self.dirfd = -1
119
120 def iter_w(self):
121 return self
122
123 def fail(self, err=None):
124 self._close()
125 if err is None:
126 raise OperationError(self.space.w_StopIteration, self.space.w_None)
127 else:
128 raise err
129
130 def next_w(self):
131 if not self.dirp:
132 raise self.fail()
133 if self._in_next:
134 raise self.fail(oefmt(self.space.w_RuntimeError,
135 "cannot use ScandirIterator from multiple threads concurrently"))
136 self._in_next = True
137 try:
138 #
139 space = self.space
140 while True:
141 try:
142 entry = rposix_scandir.nextentry(self.dirp)
143 except OSError as e:
144 raise self.fail(wrap_oserror2(space, e, self.w_path_prefix,
145 eintr_retry=False))
146 if not entry:
147 raise self.fail()
148 name = rposix_scandir.get_name_bytes(entry)
149 if name != '.' and name != '..':
150 break
151 #
152 known_type = rposix_scandir.get_known_type(entry)
153 inode = rposix_scandir.get_inode(entry)
154 except:
155 self._close()
156 raise
157 finally:
158 self._in_next = False
159 direntry = W_DirEntry(self, name, known_type, inode)
160 return direntry
161
162 def close_w(self):
163 self._close()
164
165 def enter_w(self):
166 return self
167
168 def exit_w(self, space, __args__):
169 self._close()
170
171
172 W_ScandirIterator.typedef = TypeDef(
173 'posix.ScandirIterator',
174 __iter__ = interp2app(W_ScandirIterator.iter_w),
175 __next__ = interp2app(W_ScandirIterator.next_w),
176 __enter__ = interp2app(W_ScandirIterator.enter_w),
177 __exit__ = interp2app(W_ScandirIterator.exit_w),
178 close = interp2app(W_ScandirIterator.close_w),
179 )
180 W_ScandirIterator.typedef.acceptable_as_base_class = False
181
182
183 class FileNotFound(Exception):
184 pass
185
186 if not _WIN32:
187 assert 0 <= rposix_scandir.DT_UNKNOWN <= 255
188 assert 0 <= rposix_scandir.DT_REG <= 255
189 assert 0 <= rposix_scandir.DT_DIR <= 255
190 assert 0 <= rposix_scandir.DT_LNK <= 255
191 FLAG_STAT = 256
192 FLAG_LSTAT = 512
193
194 else:
195 # The highest used bit by Windows for file attributes is 0x00400000 according to
196 # <https://learn.microsoft.com/en-us/windows/win32/fileio/file-attribute-constants>.
197 # Using the 0x40000000 and 0x80000000 bits should be safe.
198 assert 0 <= rposix_scandir.win32traits.FILE_ATTRIBUTE_READONLY <= 0x3FFFFFFF
199 assert 0 <= rposix_scandir.win32traits.FILE_ATTRIBUTE_DIRECTORY <= 0x3FFFFFFF
200 assert 0 <= rposix_scandir.win32traits.FILE_ATTRIBUTE_NORMAL <= 0x3FFFFFFF
201 assert 0 <= rposix_scandir.win32traits.FILE_ATTRIBUTE_REPARSE_POINT <= 0x3FFFFFFF
202 FLAG_STAT = 0x40000000
203 FLAG_LSTAT = 0x80000000
204
205
206 class W_DirEntry(W_Root):
207 w_path = None
208
209 def __init__(self, scandir_iterator, name, known_type, inode):
210 self.space = scandir_iterator.space
211 self.scandir_iterator = scandir_iterator
212 self.name = name # always bytes, used only on posix
213 self.inode = inode
214 self.flags = known_type
215 #
216 if not _WIN32:
217 assert known_type == (known_type & 255)
218 w_name = self.space.newbytes(name)
219 if not scandir_iterator.result_is_bytes:
220 w_name = self.space.fsdecode(w_name)
221 else:
222 if not scandir_iterator.result_is_bytes:
223 w_name = self.space.newtext(name)
224 else:
225 w_name = self.space.newbytes(name)
226 self.w_name = w_name
227
228 def descr_repr(self, space):
229 u = space.utf8_w(space.repr(self.w_name))
230 return space.newtext(b"<DirEntry %s>" % u)
231
232 def fget_name(self, space):
233 return self.w_name
234
235 def fget_path(self, space):
236 w_path = self.w_path
237 if w_path is None:
238 w_path_prefix = self.scandir_iterator.w_path_prefix
239 w_path = space.add(w_path_prefix, self.w_name)
240 self.w_path = w_path
241 return w_path
242
243 # The internal methods, used to implement the public methods at
244 # the end of the class. Every method only calls methods *before*
245 # it in program order, so there is no cycle.
246
247 if not _WIN32:
248 def get_lstat(self):
249 """Get the lstat() of the direntry."""
250 if (self.flags & FLAG_LSTAT) == 0:
251 # Unlike CPython, try to use fstatat() if possible
252 dirfd = self.scandir_iterator.orig_fd
253 if rposix.HAVE_FSTATAT and dirfd != -1:
254 st = rposix_stat.fstatat(self.name, dirfd,
255 follow_symlinks=False)
256 else:
257 path = self.space.fsencode_w(self.fget_path(self.space))
258 st = rposix_stat.lstat(path)
259 self.d_lstat = st
260 self.flags |= FLAG_LSTAT
261 return self.d_lstat
262
263 def get_stat(self):
264 """Get the stat() of the direntry. This is implemented in
265 such a way that it won't do both a stat() and a lstat().
266 """
267 if (self.flags & FLAG_STAT) == 0:
268 # We don't have the 'd_stat'. If the known_type says the
269 # direntry is not a DT_LNK, then try to get and cache the
270 # 'd_lstat' instead. Then, or if we already have a
271 # 'd_lstat' from before, *and* if the 'd_lstat' is not a
272 # S_ISLNK, we can reuse it unchanged for 'd_stat'.
273 #
274 # Note how, in the common case where the known_type says
275 # it is a DT_REG or DT_DIR, then we call and cache lstat()
276 # and that's it. Also note that in a d_type-less OS or on
277 # a filesystem that always answer DT_UNKNOWN, this method
278 # will instead only call at most stat(), but not cache it
279 # as 'd_lstat'.
280 known_type = self.flags & 255
281 if (known_type != rposix_scandir.DT_UNKNOWN and
282 known_type != rposix_scandir.DT_LNK):
283 self.get_lstat() # fill the 'd_lstat' cache
284 have_lstat = True
285 else:
286 have_lstat = (self.flags & FLAG_LSTAT) != 0
287
288 if have_lstat:
289 # We have the lstat() but not the stat(). They are
290 # the same, unless the 'd_lstat' is a S_IFLNK.
291 must_call_stat = stat.S_ISLNK(self.d_lstat.st_mode)
292 else:
293 must_call_stat = True
294
295 if must_call_stat:
296 # Must call stat(). Try to use fstatat() if possible
297 dirfd = self.scandir_iterator.orig_fd
298 if dirfd != -1 and rposix.HAVE_FSTATAT:
299 st = rposix_stat.fstatat(self.name, dirfd,
300 follow_symlinks=True)
301 else:
302 path = self.space.fsencode_w(self.fget_path(self.space))
303 st = rposix_stat.stat(path)
304 else:
305 st = self.d_lstat
306
307 self.d_stat = st
308 self.flags |= FLAG_STAT
309 return self.d_stat
310
311 def get_stat_or_lstat(self, follow_symlinks):
312 if follow_symlinks:
313 return self.get_stat()
314 else:
315 return self.get_lstat()
316
317 def check_mode(self, follow_symlinks):
318 """Get the stat() or lstat() of the direntry, and return the
319 S_IFMT. If calling stat()/lstat() gives us ENOENT, return -1
320 instead; it is better to give up and answer "no, not this type"
321 to requests, rather than propagate the error.
322 """
323 try:
324 st = self.get_stat_or_lstat(follow_symlinks)
325 except OSError as e:
326 if e.errno == ENOENT: # not found
327 return -1
328 raise wrap_oserror2(self.space, e, self.fget_path(self.space),
329 eintr_retry=False)
330 return stat.S_IFMT(st.st_mode)
331
332 else:
333 # Win32
334
335 def get_lstat(self):
336 """Get the lstat() of the direntry."""
337 if (self.flags & FLAG_LSTAT) == 0:
338 path = FileEncoder(self.space, self.fget_path(self.space))
339 st = rposix_stat.lstat(path)
340 self.d_lstat = st
341 self.flags |= FLAG_LSTAT
342 return self.d_lstat
343
344 def get_stat(self):
345 """Get the stat() of the direntry."""
346 if (self.flags & FLAG_STAT) == 0:
347 # We don't have the 'd_stat'. Try to get and cache the
348 # 'd_lstat'. Then, or if we already have a 'd_lstat' from
349 # before, *and* if the 'd_lstat' is not a S_ISLNK, we can
350 # reuse it unchanged for 'd_stat'.
351 if (self.flags & FLAG_LSTAT) == 0:
352 self.get_lstat() # fill the 'd_lstat' cache
353
354 # We have the lstat() but not the stat(). They are the same,
355 # unless the 'd_lstat' is a S_IFLNK.
356 must_call_stat = stat.S_ISLNK(self.d_lstat.st_mode)
357
358 if must_call_stat:
359 path = FileEncoder(self.space, self.fget_path(self.space))
360 st = rposix_stat.stat(path)
361 else:
362 st = self.d_lstat
363
364 self.d_stat = st
365 self.flags |= FLAG_STAT
366 return self.d_stat
367
368 def get_stat_or_lstat(self, follow_symlinks):
369 if follow_symlinks:
370 return self.get_stat()
371 else:
372 return self.get_lstat()
373
374 def check_mode(self, follow_symlinks):
375 """Get the stat() or lstat() of the direntry, and return the
376 S_IFMT. If calling stat()/lstat() gives us ENOENT, return -1
377 instead; it is better to give up and answer "no, not this type"
378 to requests, rather than propagate the error.
379 """
380 try:
381 st = self.get_stat_or_lstat(follow_symlinks)
382 except WindowsError as e:
383 if e.winerror == 2:
384 # ERROR_FILE_NOT_FOUND is 2 according to
385 # <https://learn.microsoft.com/en-us/windows/win32/debug/system-error-codes--0-499->.
386 # This is coincidentally the same value as ENOENT (2), but
387 # winerror and errno values are not interchangeable.
388 return -1
389 raise wrap_oserror2(self.space, e, self.fget_path(self.space),
390 eintr_retry=False)
391 except OSError as e:
392 if e.errno == ENOENT: # not found
393 return -1
394 raise wrap_oserror2(self.space, e, self.fget_path(self.space),
395 eintr_retry=False)
396 return stat.S_IFMT(st.st_mode)
397
398
399 def is_dir(self, follow_symlinks):
400 known_type = self.flags & 255
401 if not _WIN32 and known_type != rposix_scandir.DT_UNKNOWN:
402 if known_type == rposix_scandir.DT_DIR:
403 return True
404 elif follow_symlinks and known_type == rposix_scandir.DT_LNK:
405 pass # don't know in this case
406 else:
407 return False
408 return self.check_mode(follow_symlinks) == stat.S_IFDIR
409
410 def is_file(self, follow_symlinks):
411 known_type = self.flags & 255
412 if not _WIN32 and known_type != rposix_scandir.DT_UNKNOWN:
413 if known_type == rposix_scandir.DT_REG:
414 return True
415 elif follow_symlinks and known_type == rposix_scandir.DT_LNK:
416 pass # don't know in this case
417 else:
418 return False
419 return self.check_mode(follow_symlinks) == stat.S_IFREG
420
421 def is_symlink(self):
422 """Check if the direntry is a symlink. May get the lstat()."""
423 known_type = self.flags & 255
424 if not _WIN32 and known_type != rposix_scandir.DT_UNKNOWN:
425 return known_type == rposix_scandir.DT_LNK
426 return self.check_mode(follow_symlinks=False) == stat.S_IFLNK
427
428 @unwrap_spec(follow_symlinks=bool)
429 def descr_is_dir(self, space, __kwonly__, follow_symlinks=True):
430 """return True if the entry is a directory; cached per entry"""
431 return space.newbool(self.is_dir(follow_symlinks))
432
433 @unwrap_spec(follow_symlinks=bool)
434 def descr_is_file(self, space, __kwonly__, follow_symlinks=True):
435 """return True if the entry is a file; cached per entry"""
436 return space.newbool(self.is_file(follow_symlinks))
437
438 def descr_is_symlink(self, space):
439 """return True if the entry is a symbolic link; cached per entry"""
440 return space.newbool(self.is_symlink())
441
442 @unwrap_spec(follow_symlinks=bool)
443 def descr_stat(self, space, __kwonly__, follow_symlinks=True):
444 """return stat_result object for the entry; cached per entry"""
445 try:
446 st = self.get_stat_or_lstat(follow_symlinks)
447 except OSError as e:
448 raise wrap_oserror2(space, e, self.fget_path(space),
449 eintr_retry=False)
450 return build_stat_result(space, st)
451
452 def descr_inode(self, space):
453 inode = self.inode
454 if inode is None: # _WIN32
455 try:
456 st = self.get_stat_or_lstat(follow_symlinks=False)
457 except OSError as e:
458 raise wrap_oserror2(space, e, self.fget_path(space),
459 eintr_retry=False)
460 inode = st.st_ino
461 return space.newint(inode)
462
463 def descr_reduce_ex(self, space, w_protocol):
464 raise oefmt(space.w_TypeError,
465 "cannot pickle '%T' object", self)
466
467
468 W_DirEntry.typedef = TypeDef(
469 'posix.DirEntry',
470 __repr__ = interp2app(W_DirEntry.descr_repr),
471 name = GetSetProperty(W_DirEntry.fget_name,
472 doc="the entry's base filename, relative to "
473 'scandir() "path" argument'),
474 path = GetSetProperty(W_DirEntry.fget_path,
475 doc="the entry's full path name; equivalent to "
476 "os.path.join(scandir_path, entry.name)"),
477 __fspath__ = interp2app(W_DirEntry.fget_path),
478 is_dir = interp2app(W_DirEntry.descr_is_dir),
479 is_file = interp2app(W_DirEntry.descr_is_file),
480 is_symlink = interp2app(W_DirEntry.descr_is_symlink),
481 stat = interp2app(W_DirEntry.descr_stat),
482 inode = interp2app(W_DirEntry.descr_inode),
483 __class_getitem__ = interp2app(
484 generic_alias_class_getitem, as_classmethod=True),
485 __reduce_ex__ = interp2app(W_DirEntry.descr_reduce_ex),
486 )
487 W_DirEntry.typedef.acceptable_as_base_class = False