bpo-38073: Make pwd module PEP-384 compatible (GH-15790)

Makes the pwd module PEP-384 compatible


https://bugs.python.org/issue38073



Automerge-Triggered-By: @tiran
This commit is contained in:
Dino Viehland 2019-09-10 13:59:43 +01:00 committed by Miss Islington (bot)
parent 12c122ae95
commit b7f8e52433
2 changed files with 36 additions and 16 deletions

View File

@ -0,0 +1 @@
Make pwd extension module PEP-384 compatible

View File

@ -47,8 +47,13 @@ The uid and gid items are integers, all others are strings. An\n\
exception is raised if the entry asked for cannot be found."); exception is raised if the entry asked for cannot be found.");
static int initialized; typedef struct {
static PyTypeObject StructPwdType; PyTypeObject *StructPwdType;
} pwdmodulestate;
#define modulestate(o) ((pwdmodulestate *)PyModule_GetState(o))
#define modulestate_global modulestate(PyState_FindModule(&pwdmodule))
static struct PyModuleDef pwdmodule;
#define DEFAULT_BUFFER_SIZE 1024 #define DEFAULT_BUFFER_SIZE 1024
@ -69,7 +74,7 @@ static PyObject *
mkpwent(struct passwd *p) mkpwent(struct passwd *p)
{ {
int setIndex = 0; int setIndex = 0;
PyObject *v = PyStructSequence_New(&StructPwdType); PyObject *v = PyStructSequence_New(modulestate_global->StructPwdType);
if (v == NULL) if (v == NULL)
return NULL; return NULL;
@ -310,16 +315,28 @@ static PyMethodDef pwd_methods[] = {
{NULL, NULL} /* sentinel */ {NULL, NULL} /* sentinel */
}; };
static int pwdmodule_traverse(PyObject *m, visitproc visit, void *arg) {
Py_VISIT(modulestate(m)->StructPwdType);
return 0;
}
static int pwdmodule_clear(PyObject *m) {
Py_CLEAR(modulestate(m)->StructPwdType);
return 0;
}
static void pwdmodule_free(void *m) {
pwdmodule_clear((PyObject *)m);
}
static struct PyModuleDef pwdmodule = { static struct PyModuleDef pwdmodule = {
PyModuleDef_HEAD_INIT, PyModuleDef_HEAD_INIT,
"pwd", "pwd",
pwd__doc__, pwd__doc__,
-1, sizeof(pwdmodulestate),
pwd_methods, pwd_methods,
NULL, NULL,
NULL, pwdmodule_traverse,
NULL, pwdmodule_clear,
NULL pwdmodule_free,
}; };
@ -327,17 +344,19 @@ PyMODINIT_FUNC
PyInit_pwd(void) PyInit_pwd(void)
{ {
PyObject *m; PyObject *m;
m = PyModule_Create(&pwdmodule); if ((m = PyState_FindModule(&pwdmodule)) != NULL) {
if (m == NULL) Py_INCREF(m);
return m;
}
if ((m = PyModule_Create(&pwdmodule)) == NULL)
return NULL; return NULL;
if (!initialized) { pwdmodulestate *state = PyModule_GetState(m);
if (PyStructSequence_InitType2(&StructPwdType, state->StructPwdType = PyStructSequence_NewType(&struct_pwd_type_desc);
&struct_pwd_type_desc) < 0) if (state->StructPwdType == NULL) {
return NULL; return NULL;
initialized = 1;
} }
Py_INCREF((PyObject *) &StructPwdType); Py_INCREF(state->StructPwdType);
PyModule_AddObject(m, "struct_passwd", (PyObject *) &StructPwdType); PyModule_AddObject(m, "struct_passwd", (PyObject *) state->StructPwdType);
return m; return m;
} }