Skip to content

Commit 40a3566

Browse files
author
Victor Stinner
committed
Issue #9425: Create private _Py_stat() function
Use stat() or _wstat() depending on the OS.
1 parent 6aa55e3 commit 40a3566

2 files changed

Lines changed: 38 additions & 0 deletions

File tree

Include/Python.h

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,11 @@ PyAPI_FUNC(wchar_t *) _Py_char2wchar(char *);
135135
PyAPI_FUNC(char*) _Py_wchar2char(const wchar_t *text);
136136
PyAPI_FUNC(FILE *) _Py_wfopen(const wchar_t *path, const wchar_t *mode);
137137

138+
/* _Py_stat lives in import.c */
139+
#ifdef HAVE_STAT
140+
int _Py_stat(PyObject *unicode, struct stat *statbuf);
141+
#endif
142+
138143
#ifdef __cplusplus
139144
}
140145
#endif

Python/import.c

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1962,6 +1962,39 @@ case_ok(char *buf, Py_ssize_t len, Py_ssize_t namelen, char *name)
19621962

19631963

19641964
#ifdef HAVE_STAT
1965+
1966+
/* Call _wstat() on Windows, or stat() otherwise. Only fill st_mode
1967+
attribute on Windows. Return 0 on success, -1 on stat error or (if
1968+
PyErr_Occurred()) unicode error. */
1969+
1970+
int
1971+
_Py_stat(PyObject *unicode, struct stat *statbuf)
1972+
{
1973+
#ifdef MS_WINDOWS
1974+
wchar_t path[MAXPATHLEN+1];
1975+
Py_ssize_t len;
1976+
int err;
1977+
struct _stat wstatbuf;
1978+
1979+
len = PyUnicode_AsWideChar((PyUnicodeObject*)unicode, path,
1980+
sizeof(path) / sizeof(path[0]));
1981+
if (len == -1)
1982+
return -1;
1983+
err = _wstat(path, &wstatbuf);
1984+
if (!err)
1985+
statbuf->st_mode = wstatbuf.st_mode;
1986+
return err;
1987+
#else
1988+
int ret;
1989+
PyObject *bytes = PyUnicode_EncodeFSDefault(unicode);
1990+
if (bytes == NULL)
1991+
return -1;
1992+
ret = stat(PyBytes_AS_STRING(bytes), statbuf);
1993+
Py_DECREF(bytes);
1994+
return ret;
1995+
#endif
1996+
}
1997+
19651998
/* Helper to look for __init__.py or __init__.py[co] in potential package */
19661999
static int
19672000
find_init_module(char *buf)

0 commit comments

Comments
 (0)