From 410bf68fd41a6b8c98e48ca77e093f2f6c6bda75 Mon Sep 17 00:00:00 2001 From: Panu Matilainen Date: Thu, 15 Oct 2009 10:11:37 +0300 Subject: Accept rpm.fd() types file objects everywhere in python bindings - turn rpmfdFromPyObject() into a python-level object converter, add a separate C-level getter for the fd pointer itself - take advantage of python refcounting to handle differences between native vs converted rpm.fd in callers so we can simply decref the rpmfdFromPyObject() result without having to worry whether it was converted or not (ie should we close it or not) --- python/rpmfd-py.c | 51 +++++++++++++++++++++++++++++++-------------------- 1 file changed, 31 insertions(+), 20 deletions(-) (limited to 'python/rpmfd-py.c') diff --git a/python/rpmfd-py.c b/python/rpmfd-py.c index 8b4f2b1a0..8458410d0 100644 --- a/python/rpmfd-py.c +++ b/python/rpmfd-py.c @@ -3,25 +3,36 @@ #include #include "rpmfd-py.h" -int rpmFdFromPyObject(PyObject *obj, FD_t *fdp) +struct rpmfdObject_s { + PyObject_HEAD + PyObject *md_dict; + FD_t fd; +}; + +FD_t rpmfdGetFd(rpmfdObject *fdo) { - FD_t fd = NULL; + return fdo->fd; +} - if (PyInt_Check(obj)) { - fd = fdDup(PyInt_AsLong(obj)); - } else if (PyFile_Check(obj)) { - FILE *fp = PyFile_AsFile(obj); - fd = fdDup(fileno(fp)); +int rpmfdFromPyObject(PyObject *obj, rpmfdObject **fdop) +{ + rpmfdObject *fdo = NULL; + + if (rpmfdObject_Check(obj)) { + Py_INCREF(obj); + fdo = (rpmfdObject *) obj; } else { - PyErr_SetString(PyExc_TypeError, "integer or file object expected"); - return 0; + fdo = (rpmfdObject *) PyObject_Call((PyObject *)&rpmfd_Type, + Py_BuildValue("(O)", obj), NULL); } - if (Ferror(fd)) { - PyErr_SetString(PyExc_IOError, Fstrerror(fd)); - if (fd) Fclose(fd); + if (fdo == NULL) return 0; + + if (Ferror(fdo->fd)) { + Py_DECREF(fdo); + PyErr_SetString(PyExc_IOError, Fstrerror(fdo->fd)); return 0; } - *fdp = fd; + *fdop = fdo; return 1; } @@ -31,12 +42,6 @@ static PyObject *err_closed(void) return NULL; } -struct rpmfdObject_s { - PyObject_HEAD - PyObject *md_dict; - FD_t fd; -}; - static PyObject *rpmfd_new(PyTypeObject *subtype, PyObject *args, PyObject *kwds) { @@ -57,7 +62,13 @@ static PyObject *rpmfd_new(PyTypeObject *subtype, fd = Fopen(PyString_AsString(fo), m); Py_END_ALLOW_THREADS free(m); - } else if (!rpmFdFromPyObject(fo, &fd)) { + } else if (PyInt_Check(fo)) { + fd = fdDup(PyInt_AsLong(fo)); + } else if (PyFile_Check(fo)) { + FILE *fp = PyFile_AsFile(fo); + fd = fdDup(fileno(fp)); + } else { + PyErr_SetString(PyExc_TypeError, "path or file object expected"); return NULL; } -- cgit v1.2.3