1from _bsdopendirtype import ffi, lib
2
3
4def _posix_error():
5    raise OSError(ffi.errno, os.strerror(ffi.errno))
6
7_dtype_to_smode = {
8    lib.DT_BLK:  0o060000,
9    lib.DT_CHR:  0o020000,
10    lib.DT_DIR:  0o040000,
11    lib.DT_FIFO: 0o010000,
12    lib.DT_LNK:  0o120000,
13    lib.DT_REG:  0o100000,
14    lib.DT_SOCK: 0o140000,
15}
16
17def opendir(dir):
18    if len(dir) == 0:
19        dir = b'.'
20    dirname = dir
21    if not dirname.endswith(b'/'):
22        dirname += b'/'
23    dirp = lib.opendir(dir)
24    if dirp == ffi.NULL:
25        raise _posix_error()
26    try:
27        while True:
28            ffi.errno = 0
29            dirent = lib.readdir(dirp)
30            if dirent == ffi.NULL:
31                if ffi.errno != 0:
32                    raise _posix_error()
33                return
34            name = ffi.string(dirent.d_name)
35            if name == b'.' or name == b'..':
36                continue
37            name = dirname + name
38            try:
39                smode = _dtype_to_smode[dirent.d_type]
40            except KeyError:
41                smode = os.lstat(name).st_mode
42            yield name, smode
43    finally:
44        lib.closedir(dirp)
45
46if __name__ == '__main__':
47    for name, smode in opendir(b'/tmp'):
48        print(hex(smode), name)
49