Skip to content

Commit

Permalink
Merge pull request #2694 from Starbuck5/filenotfound
Browse files Browse the repository at this point in the history
More informative FileNotFoundError
  • Loading branch information
illume committed Oct 23, 2021
2 parents 6d50f38 + 8add1aa commit 96b2e06
Showing 1 changed file with 53 additions and 3 deletions.
56 changes: 53 additions & 3 deletions src_c/rwobject.c
Expand Up @@ -46,6 +46,8 @@ typedef struct {
static const char pg_default_encoding[] = "unicode_escape";
static const char pg_default_errors[] = "backslashreplace";

static PyObject* os_module = NULL;

#define PATHLIB "pathlib"
#define PUREPATH "PurePath"

Expand Down Expand Up @@ -769,9 +771,51 @@ _rwops_from_pystr(PyObject *obj)
} else {
#if PY3
if (PyUnicode_Check(obj)) {
SDL_ClearError();
PyErr_SetString(PyExc_FileNotFoundError,
"No such file or directory.");
SDL_ClearError();

if (os_module) {
PyObject* cwd = PyObject_CallMethod(os_module, "getcwd",
NULL);
if (cwd == NULL) {
PyErr_SetString(PyExc_FileNotFoundError,
"No such file or directory.");
return NULL;
}

PyObject* path = PyObject_GetAttrString(os_module, "path");
if (path == NULL) {
Py_DECREF(cwd);
PyErr_SetString(PyExc_FileNotFoundError,
"No such file or directory.");
return NULL;
}

PyObject* isabs = PyObject_CallMethod(path, "isabs", "O", obj);
if (isabs == NULL) {
Py_DECREF(cwd);
Py_DECREF(path);
PyErr_SetString(PyExc_FileNotFoundError,
"No such file or directory.");
return NULL;
}

if (isabs == Py_False) {
PyErr_Format(PyExc_FileNotFoundError,
"No file '%S' found in working directory"
" '%S'.", obj, cwd);
}
else {
PyErr_Format(PyExc_FileNotFoundError,
"No such file or directory: '%S'.", obj);
}
Py_DECREF(cwd);
Py_DECREF(path);
Py_DECREF(isabs);
}
else {
PyErr_Format(PyExc_FileNotFoundError,
"No such file or directory: '%S'.", obj);
}
#else
if (PyUnicode_Check(obj) || PyString_Check(obj)) {
SDL_ClearError();
Expand Down Expand Up @@ -896,5 +940,11 @@ MODINIT_DEFINE(rwobject)
DECREF_MOD(module);
MODINIT_ERROR;
}

/* import os, don't sweat if it errors, it will be checked before use */
os_module = PyImport_ImportModule("os");
if (os_module == NULL)
PyErr_Clear();

MODINIT_RETURN(module);
}

0 comments on commit 96b2e06

Please sign in to comment.