From 506cb021d62e643fba38ddb4b84572a86cb3a3ba Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Mon, 13 Apr 2009 18:27:43 +0200 Subject: * python/tag.cc: Support 'key in mapping' for TagSections Support the replacement of mapping.has_key() for sections, and update the usage in apt/package.py and apt/debfile accordingly. This is implemented by extending the TagSecType with sequence methods, but only settings the contains method there. The TagSecGetAttr() function has been removed and replaced by the use of the tp_methods slot. --- python/apt_pkgmodule.cc | 4 ++++ python/tag.cc | 47 +++++++++++++++++++++++++++++++---------------- 2 files changed, 35 insertions(+), 16 deletions(-) (limited to 'python') diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index 86732781..34669fd5 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -472,6 +472,10 @@ static void AddInt(PyObject *Dict,const char *Itm,unsigned long I) extern "C" void initapt_pkg() { + // Finalize our types to add slots, etc. + if (PyType_Ready(&TagSecType) == -1) return; + + // Initialize the module PyObject *Module = Py_InitModule("apt_pkg",methods); PyObject *Dict = PyModule_GetDict(Module); diff --git a/python/tag.cc b/python/tag.cc index 217be290..cab32370 100644 --- a/python/tag.cc +++ b/python/tag.cc @@ -174,6 +174,16 @@ static PyObject *TagSecExists(PyObject *Self,PyObject *Args) return Py_BuildValue("i",1); } +static int TagSecContains(PyObject *Self,PyObject *Arg) +{ + char *Name = PyString_AsString(Arg); + const char *Start; + const char *Stop; + if (GetCpp(Self).Find(Name,Start,Stop) == false) + return 0; + return 1; +} + static char *doc_Bytes = "Bytes() -> integer"; static PyObject *TagSecBytes(PyObject *Self,PyObject *Args) { @@ -365,36 +375,41 @@ static PyMethodDef TagSecMethods[] = {} }; -// TagSecGetAttr - Get an attribute - variable/method /*{{{*/ -// --------------------------------------------------------------------- -/* */ -static PyObject *TagSecGetAttr(PyObject *Self,char *Name) -{ - return Py_FindMethod(TagSecMethods,Self,Name); -} - /*}}}*/ -// Type for a Tag Section + +PySequenceMethods TagSecSeqMeth = {0,0,0,0,0,0,0,TagSecContains,0,0}; PyMappingMethods TagSecMapMeth = {TagSecLength,TagSecMap,0}; PyTypeObject TagSecType = { PyObject_HEAD_INIT(&PyType_Type) - 0, // ob_size - "TagSection", // tp_name + 0, // ob_size + "TagSection", // tp_name sizeof(TagSecData), // tp_basicsize 0, // tp_itemsize // Methods TagSecFree, // tp_dealloc - 0, // tp_print - TagSecGetAttr, // tp_getattr + 0, // tp_print + 0, // tp_getattr 0, // tp_setattr 0, // tp_compare 0, // tp_repr 0, // tp_as_number - 0, // tp_as_sequence + &TagSecSeqMeth, // tp_as_sequence &TagSecMapMeth, // tp_as_mapping 0, // tp_hash - 0, // tp_call - TagSecStr, // tp_str + 0, // tp_call + TagSecStr, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + Py_TPFLAGS_DEFAULT, // tp_flags + "TagSection Object", // tp_doc + 0, // tp_traverse + 0, // tp_clear + 0, // tp_richcompare + 0, // tp_weaklistoffset + 0, // tp_iter + 0, // tp_iternext + TagSecMethods // tp_methods }; // Method table for the Tag File object -- cgit v1.2.3 From eaefd2f4cb97ed069375f18fb67d8570dc5eaed8 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Mon, 13 Apr 2009 18:41:05 +0200 Subject: * apt/tag.cc: Rework TagFile using tp_methods and tp_getset By using tp_methods and tp_getset instead of a function for tp_getattr, the resulting object is easier to understand and access to attributes and methods is faster. It also helps the port to Python 3, where Py_FindMethod does not exist anymore. --- python/apt_pkgmodule.cc | 1 + python/tag.cc | 47 ++++++++++++++++++++++++++++++----------------- 2 files changed, 31 insertions(+), 17 deletions(-) (limited to 'python') diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index 34669fd5..1417e5d0 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -474,6 +474,7 @@ extern "C" void initapt_pkg() { // Finalize our types to add slots, etc. if (PyType_Ready(&TagSecType) == -1) return; + if (PyType_Ready(&TagFileType) == -1) return; // Initialize the module PyObject *Module = Py_InitModule("apt_pkg",methods); diff --git a/python/tag.cc b/python/tag.cc index cab32370..f3fb2e6c 100644 --- a/python/tag.cc +++ b/python/tag.cc @@ -423,38 +423,51 @@ static PyMethodDef TagFileMethods[] = {} }; -// TagFileGetAttr - Get an attribute - variable/method /*{{{*/ -// --------------------------------------------------------------------- -/* */ -static PyObject *TagFileGetAttr(PyObject *Self,char *Name) -{ - if (strcmp("Section",Name) == 0) - { - PyObject *Obj = ((TagFileData *)Self)->Section; - Py_INCREF(Obj); - return Obj; - } - - return Py_FindMethod(TagFileMethods,Self,Name); +// Return the current section. +static PyObject *TagFileGetSection(PyObject *Self,void*) { + PyObject *Obj = ((TagFileData *)Self)->Section; + Py_INCREF(Obj); + return Obj; } +static PyGetSetDef TagFileGetSet[] = { + {"Section",TagFileGetSection,0,"Return a TagSection.",0}, + {} +}; + // Type for a Tag File PyTypeObject TagFileType = { PyObject_HEAD_INIT(&PyType_Type) - 0, // ob_size - "TagFile", // tp_name + 0, // ob_size + "TagFile", // tp_name sizeof(TagFileData), // tp_basicsize 0, // tp_itemsize // Methods TagFileFree, // tp_dealloc 0, // tp_print - TagFileGetAttr, // tp_getattr + 0, // tp_getattr 0, // tp_setattr 0, // tp_compare 0, // tp_repr 0, // tp_as_number 0, // tp_as_sequence - 0, // tp_as_mapping + 0, // tp_as_mapping 0, // tp_hash + 0, // tp_call + 0, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + Py_TPFLAGS_DEFAULT, // tp_flags + "TagFile Object", // tp_doc + 0, // tp_traverse + 0, // tp_clear + 0, // tp_richcompare + 0, // tp_weaklistoffset + 0, // tp_iter + 0, // tp_iternext + TagFileMethods, // tp_methods + 0, // tp_members + TagFileGetSet // tp_getset }; -- cgit v1.2.3 From 62d7f4b80d56ef1e27039441cd6584cfb71d6502 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Mon, 13 Apr 2009 19:13:25 +0200 Subject: * python/*.cc: Use PyObject_AsFileDescriptor instead of fileno(PyFile_AsFile) Replace support for file objects with a more generic support for any object providing a fileno() method and for file descriptors (integers). This also helps us to port to Python 3, where the previously used PyFile_ functions are not available anymore. --- debian/changelog | 2 ++ python/apt_instmodule.cc | 21 +++++++++++++++------ python/apt_pkgmodule.cc | 12 ++++++------ python/tag.cc | 7 +++++-- python/tar.cc | 17 +++++++++++------ 5 files changed, 39 insertions(+), 20 deletions(-) (limited to 'python') diff --git a/debian/changelog b/debian/changelog index f623254e..dc8d1545 100644 --- a/debian/changelog +++ b/debian/changelog @@ -2,6 +2,8 @@ python-apt (0.7.11) UNRELEASED; urgency=low * python/tag.cc: - Support 'key in mapping' for TagSections + * Replace support for file objects with a more generic support for any object + providing a fileno() method and for file descriptors (integers). -- Julian Andres Klode Mon, 13 Apr 2009 18:08:10 +0200 diff --git a/python/apt_instmodule.cc b/python/apt_instmodule.cc index 48868d86..a9d81be4 100644 --- a/python/apt_instmodule.cc +++ b/python/apt_instmodule.cc @@ -35,14 +35,17 @@ static PyObject *debExtractControl(PyObject *Self,PyObject *Args) { char *Member = "control"; PyObject *File; - if (PyArg_ParseTuple(Args,"O!|s",&PyFile_Type,&File,&Member) == 0) + if (PyArg_ParseTuple(Args,"O|s",&File,&Member) == 0) return 0; // Subscope makes sure any clean up errors are properly handled. PyObject *Res = 0; { // Open the file and associate the .deb - FileFd Fd(fileno(PyFile_AsFile(File)),false); + int fileno = PyObject_AsFileDescriptor(File); + if (fileno == -1) + return 0; + FileFd Fd(fileno,false); debDebFile Deb(Fd); if (_error->PendingError() == true) return HandleErrors(); @@ -76,7 +79,7 @@ static PyObject *debExtractArchive(PyObject *Self,PyObject *Args) char *Rootdir = NULL; char cwd[512]; PyObject *File; - if (PyArg_ParseTuple(Args,"O!|s",&PyFile_Type,&File,&Rootdir) == 0) + if (PyArg_ParseTuple(Args,"O|s",&File,&Rootdir) == 0) return 0; // Subscope makes sure any clean up errors are properly handled. @@ -89,7 +92,10 @@ static PyObject *debExtractArchive(PyObject *Self,PyObject *Args) } // Open the file and associate the .deb - FileFd Fd(fileno(PyFile_AsFile(File)),false); + int fileno = PyObject_AsFileDescriptor(File); + if (fileno == -1) + return 0; + FileFd Fd(fileno,false); debDebFile Deb(Fd); if (_error->PendingError() == true) { if (Rootdir != NULL) @@ -118,11 +124,14 @@ static PyObject *arCheckMember(PyObject *Self,PyObject *Args) char *Member = NULL; bool res = false; PyObject *File; - if (PyArg_ParseTuple(Args,"O!s",&PyFile_Type,&File,&Member) == 0) + if (PyArg_ParseTuple(Args,"Os",&File,&Member) == 0) return 0; // Open the file and associate the .deb - FileFd Fd(fileno(PyFile_AsFile(File)),false); + int fileno = PyObject_AsFileDescriptor(File); + if (fileno == -1) + return 0; + FileFd Fd(fileno,false); ARArchive AR(Fd); if (_error->PendingError() == true) return HandleErrors(Py_BuildValue("b",res)); diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index 1417e5d0..10d98911 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -184,10 +184,10 @@ static PyObject *md5sum(PyObject *Self,PyObject *Args) } // Digest of a file - if (PyFile_Check(Obj) != 0) + int Fd = PyObject_AsFileDescriptor(Obj); + if (Fd != -1) { MD5Summation Sum; - int Fd = fileno(PyFile_AsFile(Obj)); struct stat St; if (fstat(Fd,&St) != 0 || Sum.AddFD(Fd,St.st_size) == false) @@ -224,10 +224,10 @@ static PyObject *sha1sum(PyObject *Self,PyObject *Args) } // Digest of a file - if (PyFile_Check(Obj) != 0) + int Fd = PyObject_AsFileDescriptor(Obj); + if (Fd != -1) { SHA1Summation Sum; - int Fd = fileno(PyFile_AsFile(Obj)); struct stat St; if (fstat(Fd,&St) != 0 || Sum.AddFD(Fd,St.st_size) == false) @@ -264,10 +264,10 @@ static PyObject *sha256sum(PyObject *Self,PyObject *Args) } // Digest of a file - if (PyFile_Check(Obj) != 0) + int Fd = PyObject_AsFileDescriptor(Obj); + if (Fd != -1) { SHA256Summation Sum; - int Fd = fileno(PyFile_AsFile(Obj)); struct stat St; if (fstat(Fd,&St) != 0 || Sum.AddFD(Fd,St.st_size) == false) diff --git a/python/tag.cc b/python/tag.cc index f3fb2e6c..baf97b59 100644 --- a/python/tag.cc +++ b/python/tag.cc @@ -272,11 +272,14 @@ char *doc_ParseTagFile = "ParseTagFile(File) -> TagFile"; PyObject *ParseTagFile(PyObject *self,PyObject *Args) { PyObject *File; - if (PyArg_ParseTuple(Args,"O!",&PyFile_Type,&File) == 0) + if (PyArg_ParseTuple(Args,"O",&File) == 0) + return 0; + int fileno = PyObject_AsFileDescriptor(File); + if (fileno == -1) return 0; TagFileData *New = PyObject_NEW(TagFileData,&TagFileType); - new (&New->Fd) FileFd(fileno(PyFile_AsFile(File)),false); + new (&New->Fd) FileFd(fileno,false); New->File = File; Py_INCREF(New->File); new (&New->Object) pkgTagFile(&New->Fd); diff --git a/python/tar.cc b/python/tar.cc index e5aaee6f..f0d57823 100644 --- a/python/tar.cc +++ b/python/tar.cc @@ -97,8 +97,7 @@ PyObject *tarExtract(PyObject *Self,PyObject *Args) PyObject *Function; char *Comp; - if (PyArg_ParseTuple(Args,"O!Os",&PyFile_Type,&File, - &Function,&Comp) == 0) + if (PyArg_ParseTuple(Args,"OOs",&File, &Function,&Comp) == 0) return 0; if (PyCallable_Check(Function) == 0) @@ -109,7 +108,11 @@ PyObject *tarExtract(PyObject *Self,PyObject *Args) { // Open the file and associate the tar - FileFd Fd(fileno(PyFile_AsFile(File)),false); + int fileno = PyObject_AsFileDescriptor(File); + if (fileno == -1) + return 0; + + FileFd Fd(fileno,false); ExtractTar Tar(Fd,0xFFFFFFFF,Comp); if (_error->PendingError() == true) return HandleErrors(); @@ -139,8 +142,7 @@ PyObject *debExtract(PyObject *Self,PyObject *Args) char *Chunk; const char *Comp = "gzip"; - if (PyArg_ParseTuple(Args,"O!Os",&PyFile_Type,&File, - &Function,&Chunk) == 0) + if (PyArg_ParseTuple(Args,"OOs",&File,&Function,&Chunk) == 0) return 0; if (PyCallable_Check(Function) == 0) @@ -149,10 +151,13 @@ PyObject *debExtract(PyObject *Self,PyObject *Args) return 0; } + int fileno = PyObject_AsFileDescriptor(File); + if (fileno == -1) + return 0; { // Open the file and associate the tar // Open the file and associate the .deb - FileFd Fd(fileno(PyFile_AsFile(File)),false); + FileFd Fd(fileno,false); debDebFile Deb(Fd); if (_error->PendingError() == true) return HandleErrors(); -- cgit v1.2.3 From ebedf54fd4c72bfbf5c5e60d3d908cd66acace95 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Mon, 13 Apr 2009 19:28:33 +0200 Subject: * python/cache.cc: Add support for the Breaks fields This also fixes problems on packages with Breaks field, where the lookup of the field name leads to some unprintable characters (because the index exceeds the number of items). --- debian/changelog | 1 + python/cache.cc | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) (limited to 'python') diff --git a/debian/changelog b/debian/changelog index dc8d1545..29927989 100644 --- a/debian/changelog +++ b/debian/changelog @@ -4,6 +4,7 @@ python-apt (0.7.11) UNRELEASED; urgency=low - Support 'key in mapping' for TagSections * Replace support for file objects with a more generic support for any object providing a fileno() method and for file descriptors (integers). + * Add support for the Breaks fields -- Julian Andres Klode Mon, 13 Apr 2009 18:08:10 +0200 diff --git a/python/cache.cc b/python/cache.cc index 0c59f561..4db097c7 100644 --- a/python/cache.cc +++ b/python/cache.cc @@ -502,7 +502,7 @@ static PyObject *MakeDepends(PyObject *Owner,pkgCache::VerIterator &Ver, { "", "Depends","PreDepends","Suggests", "Recommends","Conflicts","Replaces", - "Obsoletes" + "Obsoletes", "Breaks" }; PyObject *Dep = PyString_FromString(Types[Start->Type]); LastDepType = Start->Type; -- cgit v1.2.3 From ccd98916ba50c7583f354e0d3487ffb0830103f0 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Mon, 13 Apr 2009 20:00:09 +0200 Subject: * python/configuration.cc: Support the 'in' operator for Configuration Support the replacement of mapping.has_key() for Configuration,ConfigurationPtr and ConfigurationSub objects. This is implemented by extending the various types with the tp_as_sequence slot, which refers to a PySequenceMethods containing only this method. The CnfGetAttr() function has been removed and replaced by the use of the tp_method slot. This helps the py3k port because the previously used Py_FindMethod() is not avilable anymore. This completes the support of the 'in' operator in all python-apt objects, which makes it even easier to convert python-apt-using applications to py3k once python-apt supports it, as 2to3 converts 'm.has_key(k)' to 'k in m'. Also finalize the types in apt_pkgmodule.cc and add the new 'key in conf' description to the documentation. --- debian/changelog | 4 +-- doc/source/apt_pkg/cache.rst | 4 +++ python/apt_pkgmodule.cc | 3 ++ python/configuration.cc | 70 ++++++++++++++++++++++++++++++++++---------- 4 files changed, 64 insertions(+), 17 deletions(-) (limited to 'python') diff --git a/debian/changelog b/debian/changelog index 29927989..261ff7bd 100644 --- a/debian/changelog +++ b/debian/changelog @@ -1,7 +1,7 @@ python-apt (0.7.11) UNRELEASED; urgency=low - * python/tag.cc: - - Support 'key in mapping' for TagSections + * Support the 'in' operator (e.g. "k in d") in Configuration{,Ptr,Sub} + objects (e.g. apt_pkg.Config) and in TagSections (apt_pkg.ParseSection()) * Replace support for file objects with a more generic support for any object providing a fileno() method and for file descriptors (integers). * Add support for the Breaks fields diff --git a/doc/source/apt_pkg/cache.rst b/doc/source/apt_pkg/cache.rst index 146c2c2a..3ecbf069 100644 --- a/doc/source/apt_pkg/cache.rst +++ b/doc/source/apt_pkg/cache.rst @@ -117,6 +117,10 @@ Classes in apt_pkg The Configuration objects store the configuration of apt. + .. describe:: key in conf + + Return ``True`` if *conf* has a key *key*, else ``False``. + .. describe:: conf[key] Return the value of the option given key *key*. If it does not diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index 10d98911..3d043179 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -475,6 +475,9 @@ extern "C" void initapt_pkg() // Finalize our types to add slots, etc. if (PyType_Ready(&TagSecType) == -1) return; if (PyType_Ready(&TagFileType) == -1) return; + if (PyType_Ready(&ConfigurationType) == -1) return; + if (PyType_Ready(&ConfigurationPtrType) == -1) return; + if (PyType_Ready(&ConfigurationSubType) == -1) return; // Initialize the module PyObject *Module = Py_InitModule("apt_pkg",methods); diff --git a/python/configuration.cc b/python/configuration.cc index 21f70bc1..a95ac029 100644 --- a/python/configuration.cc +++ b/python/configuration.cc @@ -128,6 +128,11 @@ static PyObject *CnfExists(PyObject *Self,PyObject *Args) return Py_BuildValue("i",(int)GetSelf(Self).Exists(Name)); } +static int CnfContains(PyObject *Self,PyObject *Arg) +{ + return (int)GetSelf(Self).Exists(PyString_AsString(Arg)); +} + static char *doc_Clear = "Clear(Name) -> None"; static PyObject *CnfClear(PyObject *Self,PyObject *Args) { @@ -470,34 +475,41 @@ static PyMethodDef CnfMethods[] = {} }; -// CnfGetAttr - Get an attribute - variable/method /*{{{*/ -// --------------------------------------------------------------------- -/* */ -static PyObject *CnfGetAttr(PyObject *Self,char *Name) -{ - return Py_FindMethod(CnfMethods,Self,Name); -} - // Type for a Normal Configuration object +static PySequenceMethods ConfigurationSeq = {0,0,0,0,0,0,0,CnfContains,0,0}; static PyMappingMethods ConfigurationMap = {0,CnfMap,CnfMapSet}; PyTypeObject ConfigurationType = { PyObject_HEAD_INIT(&PyType_Type) - 0, // ob_size + 0, // ob_size "Configuration", // tp_name sizeof(CppPyObject), // tp_basicsize 0, // tp_itemsize // Methods CppDealloc, // tp_dealloc 0, // tp_print - CnfGetAttr, // tp_getattr + 0, // tp_getattr 0, // tp_setattr 0, // tp_compare 0, // tp_repr 0, // tp_as_number - 0, // tp_as_sequence + &ConfigurationSeq, // tp_as_sequence &ConfigurationMap, // tp_as_mapping 0, // tp_hash + 0, // tp_call + 0, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + Py_TPFLAGS_DEFAULT, // tp_flags + "Configuration Object", // tp_doc + 0, // tp_traverse + 0, // tp_clear + 0, // tp_richcompare + 0, // tp_weaklistoffset + 0, // tp_iter + 0, // tp_iternext + CnfMethods, // tp_methods }; PyTypeObject ConfigurationPtrType = @@ -510,14 +522,28 @@ PyTypeObject ConfigurationPtrType = // Methods (destructor)PyObject_Free, // tp_dealloc 0, // tp_print - CnfGetAttr, // tp_getattr + 0, // tp_getattr 0, // tp_setattr 0, // tp_compare 0, // tp_repr 0, // tp_as_number - 0, // tp_as_sequence + &ConfigurationSeq, // tp_as_sequence &ConfigurationMap, // tp_as_mapping 0, // tp_hash + 0, // tp_call + 0, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + Py_TPFLAGS_DEFAULT, // tp_flags + "ConfigurationPtr Object", // tp_doc + 0, // tp_traverse + 0, // tp_clear + 0, // tp_richcompare + 0, // tp_weaklistoffset + 0, // tp_iter + 0, // tp_iternext + CnfMethods, // tp_methods }; PyTypeObject ConfigurationSubType = @@ -530,13 +556,27 @@ PyTypeObject ConfigurationSubType = // Methods CnfSubFree, // tp_dealloc 0, // tp_print - CnfGetAttr, // tp_getattr + 0, // tp_getattr 0, // tp_setattr 0, // tp_compare 0, // tp_repr 0, // tp_as_number - 0, // tp_as_sequence + &ConfigurationSeq, // tp_as_sequence &ConfigurationMap, // tp_as_mapping 0, // tp_hash + 0, // tp_call + 0, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + Py_TPFLAGS_DEFAULT, // tp_flags + "ConfigurationSub Object", // tp_doc + 0, // tp_traverse + 0, // tp_clear + 0, // tp_richcompare + 0, // tp_weaklistoffset + 0, // tp_iter + 0, // tp_iternext + CnfMethods, // tp_methods }; -- cgit v1.2.3 From daaa814658b6d2b8e3e2437fcc625096c46395dd Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Mon, 13 Apr 2009 23:24:42 +0200 Subject: * python/cdrom.cc, python/depcache.cc: Use tp_methods for Cdrom, ProblemResolver, ActionGroup --- python/apt_pkgmodule.cc | 4 ++++ python/apt_pkgmodule.h | 1 + python/cdrom.cc | 32 +++++++++++++++++-------------- python/depcache.cc | 50 +++++++++++++++++++++++++++++-------------------- 4 files changed, 53 insertions(+), 34 deletions(-) (limited to 'python') diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index 3d043179..5d0b2c0a 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -478,6 +478,10 @@ extern "C" void initapt_pkg() if (PyType_Ready(&ConfigurationType) == -1) return; if (PyType_Ready(&ConfigurationPtrType) == -1) return; if (PyType_Ready(&ConfigurationSubType) == -1) return; + if (PyType_Ready(&PkgCdromType) == -1) return; + if (PyType_Ready(&PkgProblemResolverType) == -1) return; + if (PyType_Ready(&PkgActionGroupType) == -1) return; + // Initialize the module PyObject *Module = Py_InitModule("apt_pkg",methods); diff --git a/python/apt_pkgmodule.h b/python/apt_pkgmodule.h index e047bcd8..ea8e33df 100644 --- a/python/apt_pkgmodule.h +++ b/python/apt_pkgmodule.h @@ -71,6 +71,7 @@ extern PyTypeObject PkgProblemResolverType; PyObject *GetPkgProblemResolver(PyObject *Self, PyObject *Args); PyObject *GetPkgActionGroup(PyObject *Self, PyObject *Args); +extern PyTypeObject PkgActionGroupType; // cdrom extern PyTypeObject PkgCdromType; PyObject *GetCdrom(PyObject *Self,PyObject *Args); diff --git a/python/cdrom.cc b/python/cdrom.cc index 0831548e..1278d6b7 100644 --- a/python/cdrom.cc +++ b/python/cdrom.cc @@ -64,27 +64,17 @@ static PyMethodDef PkgCdromMethods[] = }; -static PyObject *CdromAttr(PyObject *Self,char *Name) -{ - PkgCdromStruct &Struct = GetCpp(Self); - - return Py_FindMethod(PkgCdromMethods,Self,Name); -} - - - - PyTypeObject PkgCdromType = { PyObject_HEAD_INIT(&PyType_Type) - 0, // ob_size - "Cdrom", // tp_name + 0, // ob_size + "Cdrom", // tp_name sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize // Methods - CppOwnedDealloc, // tp_dealloc + CppOwnedDealloc, // tp_dealloc 0, // tp_print - CdromAttr, // tp_getattr + 0, // tp_getattr 0, // tp_setattr 0, // tp_compare 0, // tp_repr @@ -92,6 +82,20 @@ PyTypeObject PkgCdromType = 0, // tp_as_sequence 0, // tp_as_mapping 0, // tp_hash + 0, // tp_call + 0, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + Py_TPFLAGS_DEFAULT, // tp_flags + "Cdrom Object", // tp_doc + 0, // tp_traverse + 0, // tp_clear + 0, // tp_richcompare + 0, // tp_weaklistoffset + 0, // tp_iter + 0, // tp_iternext + PkgCdromMethods, // tp_methods }; PyObject *GetCdrom(PyObject *Self,PyObject *Args) diff --git a/python/depcache.cc b/python/depcache.cc index 0e83c956..b23eecd9 100644 --- a/python/depcache.cc +++ b/python/depcache.cc @@ -749,15 +749,6 @@ static PyMethodDef PkgProblemResolverMethods[] = {} }; - -static PyObject *ProblemResolverAttr(PyObject *Self,char *Name) -{ - pkgProblemResolver *fixer = GetCpp(Self); - - return Py_FindMethod(PkgProblemResolverMethods,Self,Name); -} - - PyTypeObject PkgProblemResolverType = { PyObject_HEAD_INIT(&PyType_Type) @@ -768,7 +759,7 @@ PyTypeObject PkgProblemResolverType = // Methods CppOwnedDealloc, // tp_dealloc 0, // tp_print - ProblemResolverAttr, // tp_getattr + 0, // tp_getattr 0, // tp_setattr 0, // tp_compare 0, // tp_repr @@ -776,6 +767,20 @@ PyTypeObject PkgProblemResolverType = 0, // tp_as_sequence 0, // tp_as_mapping 0, // tp_hash + 0, // tp_call + 0, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + Py_TPFLAGS_DEFAULT, // tp_flags + "ProblemResolver Object", // tp_doc + 0, // tp_traverse + 0, // tp_clear + 0, // tp_richcompare + 0, // tp_weaklistoffset + 0, // tp_iter + 0, // tp_iternext + PkgProblemResolverMethods, // tp_methods }; /*}}}*/ @@ -800,15 +805,6 @@ static PyMethodDef PkgActionGroupMethods[] = {} }; - -static PyObject *ActionGroupAttr(PyObject *Self,char *Name) -{ - pkgDepCache::ActionGroup *ag = GetCpp(Self); - - return Py_FindMethod(PkgActionGroupMethods,Self,Name); -} - - PyTypeObject PkgActionGroupType = { PyObject_HEAD_INIT(&PyType_Type) @@ -819,7 +815,7 @@ PyTypeObject PkgActionGroupType = // Methods CppOwnedDealloc, // tp_dealloc 0, // tp_print - ActionGroupAttr, // tp_getattr + 0, // tp_getattr 0, // tp_setattr 0, // tp_compare 0, // tp_repr @@ -827,6 +823,20 @@ PyTypeObject PkgActionGroupType = 0, // tp_as_sequence 0, // tp_as_mapping 0, // tp_hash + 0, // tp_call + 0, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + Py_TPFLAGS_DEFAULT, // tp_flags + "ActionGroup Object", // tp_doc + 0, // tp_traverse + 0, // tp_clear + 0, // tp_richcompare + 0, // tp_weaklistoffset + 0, // tp_iter + 0, // tp_iternext + PkgActionGroupMethods, // tp_methods }; PyObject *GetPkgActionGroup(PyObject *Self,PyObject *Args) -- cgit v1.2.3 From 8413810c46f802490280b0be1beebaaadf1aa9f2 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Tue, 14 Apr 2009 00:47:23 +0200 Subject: * Remove any trailing whitespace --- apt/package.py | 3 +-- doc/source/apt_pkg/index.rst | 2 +- python/apt_pkgmodule.cc | 2 +- python/cache.cc | 2 +- python/cdrom.cc | 6 +++--- python/configuration.cc | 18 +++++++++--------- python/depcache.cc | 12 ++++++------ python/progress.cc | 2 +- python/tag.cc | 12 ++++++------ python/tar.cc | 2 +- tests/getcache_mem_corruption.py | 6 +++--- 11 files changed, 33 insertions(+), 34 deletions(-) (limited to 'python') diff --git a/apt/package.py b/apt/package.py index 5adef15c..3ea1105d 100644 --- a/apt/package.py +++ b/apt/package.py @@ -639,7 +639,6 @@ class Package(object): def installedPriority(self): """Return the priority (of the installed version). - .. deprecated:: 0.7.9 """ return getattr(self.installed, 'priority', None) @@ -800,7 +799,7 @@ class Package(object): contain multiple named variables which will be substitued. These variables are (src_section, prefix, src_pkg, src_ver). An example is the Ubuntu changelog:: - + "http://changelogs.ubuntu.com/changelogs/pool" \\ "/%(src_section)s/%(prefix)s/%(src_pkg)s" \\ "/%(src_pkg)s_%(src_ver)s/changelog" diff --git a/doc/source/apt_pkg/index.rst b/doc/source/apt_pkg/index.rst index 38310bb5..60c3ba9b 100644 --- a/doc/source/apt_pkg/index.rst +++ b/doc/source/apt_pkg/index.rst @@ -252,7 +252,7 @@ Dependencies >>> apt_pkg.ParseDepends("PkgA (>= VerA) | PkgB (>= VerB)") [[('PkgA', 'VerA', '>='), ('PkgB', 'VerB', '>=')]] - + Furthemore, this function also supports to limit the architectures, as used in e.g. Build-Depends:: diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index 5d0b2c0a..145a2bab 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -481,7 +481,7 @@ extern "C" void initapt_pkg() if (PyType_Ready(&PkgCdromType) == -1) return; if (PyType_Ready(&PkgProblemResolverType) == -1) return; if (PyType_Ready(&PkgActionGroupType) == -1) return; - + // Initialize the module PyObject *Module = Py_InitModule("apt_pkg",methods); diff --git a/python/cache.cc b/python/cache.cc index 4db097c7..31d8c45d 100644 --- a/python/cache.cc +++ b/python/cache.cc @@ -951,7 +951,7 @@ PyObject *TmpGetCache(PyObject *Self,PyObject *Args) progress.setCallbackInst(pyCallbackInst); if (Cache->Open(progress,false) == false) return HandleErrors(); - } + } else { OpTextProgress Prog; if (Cache->Open(Prog,false) == false) diff --git a/python/cdrom.cc b/python/cdrom.cc index 1278d6b7..0816d93e 100644 --- a/python/cdrom.cc +++ b/python/cdrom.cc @@ -84,16 +84,16 @@ PyTypeObject PkgCdromType = 0, // tp_hash 0, // tp_call 0, // tp_str - 0, // tp_getattro + 0, // tp_getattro 0, // tp_setattro - 0, // tp_as_buffer + 0, // tp_as_buffer Py_TPFLAGS_DEFAULT, // tp_flags "Cdrom Object", // tp_doc 0, // tp_traverse 0, // tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset - 0, // tp_iter + 0, // tp_iter 0, // tp_iternext PkgCdromMethods, // tp_methods }; diff --git a/python/configuration.cc b/python/configuration.cc index a95ac029..b4adf357 100644 --- a/python/configuration.cc +++ b/python/configuration.cc @@ -498,16 +498,16 @@ PyTypeObject ConfigurationType = 0, // tp_hash 0, // tp_call 0, // tp_str - 0, // tp_getattro + 0, // tp_getattro 0, // tp_setattro - 0, // tp_as_buffer + 0, // tp_as_buffer Py_TPFLAGS_DEFAULT, // tp_flags "Configuration Object", // tp_doc 0, // tp_traverse 0, // tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset - 0, // tp_iter + 0, // tp_iter 0, // tp_iternext CnfMethods, // tp_methods }; @@ -532,16 +532,16 @@ PyTypeObject ConfigurationPtrType = 0, // tp_hash 0, // tp_call 0, // tp_str - 0, // tp_getattro + 0, // tp_getattro 0, // tp_setattro - 0, // tp_as_buffer + 0, // tp_as_buffer Py_TPFLAGS_DEFAULT, // tp_flags "ConfigurationPtr Object", // tp_doc 0, // tp_traverse 0, // tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset - 0, // tp_iter + 0, // tp_iter 0, // tp_iternext CnfMethods, // tp_methods }; @@ -566,16 +566,16 @@ PyTypeObject ConfigurationSubType = 0, // tp_hash 0, // tp_call 0, // tp_str - 0, // tp_getattro + 0, // tp_getattro 0, // tp_setattro - 0, // tp_as_buffer + 0, // tp_as_buffer Py_TPFLAGS_DEFAULT, // tp_flags "ConfigurationSub Object", // tp_doc 0, // tp_traverse 0, // tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset - 0, // tp_iter + 0, // tp_iter 0, // tp_iternext CnfMethods, // tp_methods }; diff --git a/python/depcache.cc b/python/depcache.cc index b23eecd9..2c73a1a9 100644 --- a/python/depcache.cc +++ b/python/depcache.cc @@ -769,16 +769,16 @@ PyTypeObject PkgProblemResolverType = 0, // tp_hash 0, // tp_call 0, // tp_str - 0, // tp_getattro + 0, // tp_getattro 0, // tp_setattro - 0, // tp_as_buffer + 0, // tp_as_buffer Py_TPFLAGS_DEFAULT, // tp_flags "ProblemResolver Object", // tp_doc 0, // tp_traverse 0, // tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset - 0, // tp_iter + 0, // tp_iter 0, // tp_iternext PkgProblemResolverMethods, // tp_methods }; @@ -825,16 +825,16 @@ PyTypeObject PkgActionGroupType = 0, // tp_hash 0, // tp_call 0, // tp_str - 0, // tp_getattro + 0, // tp_getattro 0, // tp_setattro - 0, // tp_as_buffer + 0, // tp_as_buffer Py_TPFLAGS_DEFAULT, // tp_flags "ActionGroup Object", // tp_doc 0, // tp_traverse 0, // tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset - 0, // tp_iter + 0, // tp_iter 0, // tp_iternext PkgActionGroupMethods, // tp_methods }; diff --git a/python/progress.cc b/python/progress.cc index c5a1c138..bec40ce9 100644 --- a/python/progress.cc +++ b/python/progress.cc @@ -185,7 +185,7 @@ bool PyFetchProgress::Pulse(pkgAcquire * Owner) bool res = true; if(!PyArg_Parse(result, "b", &res)) { - // most of the time the user who subclasses the pulse() + // most of the time the user who subclasses the pulse() // method forgot to add a return {True,False} so we just // assume he wants a True return true; diff --git a/python/tag.cc b/python/tag.cc index baf97b59..cdea3e03 100644 --- a/python/tag.cc +++ b/python/tag.cc @@ -401,16 +401,16 @@ PyTypeObject TagSecType = 0, // tp_hash 0, // tp_call TagSecStr, // tp_str - 0, // tp_getattro + 0, // tp_getattro 0, // tp_setattro - 0, // tp_as_buffer + 0, // tp_as_buffer Py_TPFLAGS_DEFAULT, // tp_flags "TagSection Object", // tp_doc 0, // tp_traverse 0, // tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset - 0, // tp_iter + 0, // tp_iter 0, // tp_iternext TagSecMethods // tp_methods }; @@ -459,16 +459,16 @@ PyTypeObject TagFileType = 0, // tp_hash 0, // tp_call 0, // tp_str - 0, // tp_getattro + 0, // tp_getattro 0, // tp_setattro - 0, // tp_as_buffer + 0, // tp_as_buffer Py_TPFLAGS_DEFAULT, // tp_flags "TagFile Object", // tp_doc 0, // tp_traverse 0, // tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset - 0, // tp_iter + 0, // tp_iter 0, // tp_iternext TagFileMethods, // tp_methods 0, // tp_members diff --git a/python/tar.cc b/python/tar.cc index f0d57823..217554c2 100644 --- a/python/tar.cc +++ b/python/tar.cc @@ -111,7 +111,7 @@ PyObject *tarExtract(PyObject *Self,PyObject *Args) int fileno = PyObject_AsFileDescriptor(File); if (fileno == -1) return 0; - + FileFd Fd(fileno,false); ExtractTar Tar(Fd,0xFFFFFFFF,Comp); if (_error->PendingError() == true) diff --git a/tests/getcache_mem_corruption.py b/tests/getcache_mem_corruption.py index 42e9af00..c3f6eff3 100644 --- a/tests/getcache_mem_corruption.py +++ b/tests/getcache_mem_corruption.py @@ -6,16 +6,16 @@ import re import unittest class TestGetCache(unittest.TestCase): - + def setUp(self): apt_pkg.InitConfig() apt_pkg.InitSystem() - + def testWrongInvocation(self): # wrongly invoke GetCache() rather than GetDepCache() apt_cache = apt_pkg.GetCache() self.assertRaises(ValueError, apt_pkg.GetCache, apt_cache) - + def testProperInvocation(self): apt_cache = apt_pkg.GetCache(apt.progress.OpTextProgress()) apt_depcache = apt_pkg.GetDepCache(apt_cache) -- cgit v1.2.3 From fef39284798154b3fd2548f0311ee5da73b26ec8 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Tue, 14 Apr 2009 16:38:03 +0200 Subject: * python/acquire.cc, python/sourcelist.cc: Type cleanup Use GetSet for PkgSourceListType and remove tp_getattr from PkgAcquireFileType. --- python/acquire.cc | 19 +------------------ python/apt_pkgmodule.cc | 1 + python/sourcelist.cc | 47 ++++++++++++++++++++++++++++++++--------------- 3 files changed, 34 insertions(+), 33 deletions(-) (limited to 'python') diff --git a/python/acquire.cc b/python/acquire.cc index 1ecf55a5..eb1f7418 100644 --- a/python/acquire.cc +++ b/python/acquire.cc @@ -205,23 +205,6 @@ PyObject *GetAcquire(PyObject *Self,PyObject *Args) return FetcherObj; } - - - - -// pkgAcquireFile - -static PyObject *AcquireFileAttr(PyObject *Self,char *Name) -{ - pkgAcqFile *acqFile = GetCpp(Self); - - PyErr_SetString(PyExc_AttributeError,Name); - return 0; -} - - - - PyTypeObject PkgAcquireFileType = { PyObject_HEAD_INIT(&PyType_Type) @@ -232,7 +215,7 @@ PyTypeObject PkgAcquireFileType = // Methods CppDealloc, // tp_dealloc 0, // tp_print - AcquireFileAttr, // tp_getattr + 0, // tp_getattr 0, // tp_setattr 0, // tp_compare 0, // tp_repr diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index 145a2bab..b2b20c20 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -481,6 +481,7 @@ extern "C" void initapt_pkg() if (PyType_Ready(&PkgCdromType) == -1) return; if (PyType_Ready(&PkgProblemResolverType) == -1) return; if (PyType_Ready(&PkgActionGroupType) == -1) return; + if (PyType_Ready(&PkgSourceListType) == -1) return; // Initialize the module diff --git a/python/sourcelist.cc b/python/sourcelist.cc index 5dcaf86b..9f8f8878 100644 --- a/python/sourcelist.cc +++ b/python/sourcelist.cc @@ -74,28 +74,29 @@ static PyMethodDef PkgSourceListMethods[] = { {"FindIndex",PkgSourceListFindIndex,METH_VARARGS,doc_PkgSourceListFindIndex}, {"ReadMainList",PkgSourceListReadMainList,METH_VARARGS,doc_PkgSourceListReadMainList}, - {"GetIndexes",PkgSourceListGetIndexes,METH_VARARGS,doc_PkgSourceListReadMainList}, + {"GetIndexes",PkgSourceListGetIndexes,METH_VARARGS,doc_PkgSourceListGetIndexes}, {} }; -static PyObject *PkgSourceListAttr(PyObject *Self,char *Name) +static PyObject *PkgSourceListGetList(PyObject *Self,void*) { pkgSourceList *list = GetCpp(Self); - - if (strcmp("List",Name) == 0) + PyObject *List = PyList_New(0); + for (vector::const_iterator I = list->begin(); + I != list->end(); I++) { - PyObject *List = PyList_New(0); - for (vector::const_iterator I = list->begin(); - I != list->end(); I++) - { - PyObject *Obj; - Obj = CppPyObject_NEW(&MetaIndexType,*I); - PyList_Append(List,Obj); - } - return List; + PyObject *Obj; + Obj = CppPyObject_NEW(&MetaIndexType,*I); + PyList_Append(List,Obj); } - return Py_FindMethod(PkgSourceListMethods,Self,Name); + return List; } + +static PyGetSetDef PkgSourceListGetSet[] = { + {"List",PkgSourceListGetList,0,"A list of MetaIndex() objects.",0}, + {} +}; + PyTypeObject PkgSourceListType = { PyObject_HEAD_INIT(&PyType_Type) @@ -106,7 +107,7 @@ PyTypeObject PkgSourceListType = // Methods CppDealloc, // tp_dealloc 0, // tp_print - PkgSourceListAttr, // tp_getattr + 0, // tp_getattr 0, // tp_setattr 0, // tp_compare 0, // tp_repr @@ -114,6 +115,22 @@ PyTypeObject PkgSourceListType = 0, // tp_as_sequence 0, // tp_as_mapping 0, // tp_hash + 0, // tp_call + 0, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + Py_TPFLAGS_DEFAULT, // tp_flags + "pkgSourceList Object", // tp_doc + 0, // tp_traverse + 0, // tp_clear + 0, // tp_richcompare + 0, // tp_weaklistoffset + 0, // tp_iter + 0, // tp_iternext + PkgSourceListMethods, // tp_methods + 0, // tp_members + PkgSourceListGetSet, // tp_getset }; PyObject *GetPkgSourceList(PyObject *Self,PyObject *Args) -- cgit v1.2.3 From 9aa8bce9463d813823893d6f611b5bb9682f75ef Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Tue, 14 Apr 2009 18:42:36 +0200 Subject: * python/cache.cc: Use tp_methods and tp_getset for PkgCacheType --- python/apt_pkgmodule.cc | 1 + python/cache.cc | 99 ++++++++++++++++++++++++++++++++++--------------- 2 files changed, 71 insertions(+), 29 deletions(-) (limited to 'python') diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index b2b20c20..ef687dd1 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -482,6 +482,7 @@ extern "C" void initapt_pkg() if (PyType_Ready(&PkgProblemResolverType) == -1) return; if (PyType_Ready(&PkgActionGroupType) == -1) return; if (PyType_Ready(&PkgSourceListType) == -1) return; + if (PyType_Ready(&PkgCacheType) == -1) return; // Initialize the module diff --git a/python/cache.cc b/python/cache.cc index 31d8c45d..87b625c0 100644 --- a/python/cache.cc +++ b/python/cache.cc @@ -142,40 +142,65 @@ static PyMethodDef PkgCacheMethods[] = {} }; -static PyObject *CacheAttr(PyObject *Self,char *Name) -{ +static PyObject *PkgCacheGetPackages(PyObject *Self, void*) { pkgCache *Cache = GetCpp(Self); + return CppOwnedPyObject_NEW(Self,&PkgListType,Cache->PkgBegin()); +} - if (strcmp("Packages",Name) == 0) - return CppOwnedPyObject_NEW(Self,&PkgListType,Cache->PkgBegin()); - else if (strcmp("PackageCount",Name) == 0) - return Py_BuildValue("i",Cache->HeaderP->PackageCount); - else if (strcmp("VersionCount",Name) == 0) - return Py_BuildValue("i",Cache->HeaderP->VersionCount); - else if (strcmp("DependsCount",Name) == 0) - return Py_BuildValue("i",Cache->HeaderP->DependsCount); - else if (strcmp("PackageFileCount",Name) == 0) - return Py_BuildValue("i",Cache->HeaderP->PackageFileCount); - else if (strcmp("VerFileCount",Name) == 0) - return Py_BuildValue("i",Cache->HeaderP->VerFileCount); - else if (strcmp("ProvidesCount",Name) == 0) - return Py_BuildValue("i",Cache->HeaderP->ProvidesCount); - else if (strcmp("FileList",Name) == 0) +static PyObject *PkgCacheGetPackageCount(PyObject *Self, void*) { + pkgCache *Cache = GetCpp(Self); + return Py_BuildValue("i",Cache->HeaderP->PackageCount); +} + +static PyObject *PkgCacheGetVersionCount(PyObject *Self, void*) { + pkgCache *Cache = GetCpp(Self); + return Py_BuildValue("i",Cache->HeaderP->VersionCount); +} +static PyObject *PkgCacheGetDependsCount(PyObject *Self, void*) { + pkgCache *Cache = GetCpp(Self); + return Py_BuildValue("i",Cache->HeaderP->DependsCount); +} + +static PyObject *PkgCacheGetPackageFileCount(PyObject *Self, void*) { + pkgCache *Cache = GetCpp(Self); + return Py_BuildValue("i",Cache->HeaderP->PackageFileCount); +} + +static PyObject *PkgCacheGetVerFileCount(PyObject *Self, void*) { + pkgCache *Cache = GetCpp(Self); + return Py_BuildValue("i",Cache->HeaderP->VerFileCount); +} + +static PyObject *PkgCacheGetProvidesCount(PyObject *Self, void*) { + pkgCache *Cache = GetCpp(Self); + return Py_BuildValue("i",Cache->HeaderP->ProvidesCount); +} + +static PyObject *PkgCacheGetFileList(PyObject *Self, void*) { + pkgCache *Cache = GetCpp(Self); + PyObject *List = PyList_New(0); + for (pkgCache::PkgFileIterator I = Cache->FileBegin(); I.end() == false; I++) { - PyObject *List = PyList_New(0); - for (pkgCache::PkgFileIterator I = Cache->FileBegin(); I.end() == false; I++) - { - PyObject *Obj; - Obj = CppOwnedPyObject_NEW(Self,&PackageFileType,I); - PyList_Append(List,Obj); - Py_DECREF(Obj); - } - return List; + PyObject *Obj; + Obj = CppOwnedPyObject_NEW(Self,&PackageFileType,I); + PyList_Append(List,Obj); + Py_DECREF(Obj); } - - return Py_FindMethod(PkgCacheMethods,Self,Name); + return List; } +static PyGetSetDef PkgCacheGetSet[] = { + {"DependsCount",PkgCacheGetDependsCount}, + {"FileList",PkgCacheGetFileList}, + {"PackageCount",PkgCacheGetPackageCount}, + {"PackageFileCount",PkgCacheGetPackageFileCount}, + {"Packages",PkgCacheGetPackages}, + {"ProvidesCount",PkgCacheGetProvidesCount}, + {"VerFileCount",PkgCacheGetVerFileCount}, + {"VersionCount",PkgCacheGetVersionCount}, + {} +}; + // Map access, operator [] static PyObject *CacheMapOp(PyObject *Self,PyObject *Arg) { @@ -221,7 +246,7 @@ PyTypeObject PkgCacheType = // Methods PkgCacheFileDealloc, // tp_dealloc 0, // tp_print - CacheAttr, // tp_getattr + 0, // tp_getattr 0, // tp_setattr 0, // tp_compare 0, // tp_repr @@ -229,6 +254,22 @@ PyTypeObject PkgCacheType = 0, // tp_as_sequence &CacheMap, // tp_as_mapping 0, // tp_hash + 0, // tp_call + 0, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + Py_TPFLAGS_DEFAULT , // tp_flags + "Cache Object", // tp_doc + 0, // tp_traverse + 0, // tp_clear + 0, // tp_richcompare + 0, // tp_weaklistoffset + 0, // tp_iter + 0, // tp_iternext + PkgCacheMethods, // tp_methods + 0, // tp_members + PkgCacheGetSet, // tp_getset }; /*}}}*/ // PkgCacheFile Class /*{{{*/ -- cgit v1.2.3 From 5a02a12e788f2bda845d5ab5fde8118375bcae47 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Tue, 14 Apr 2009 18:53:15 +0200 Subject: * python/cache.cc: Add tp_getset and tp_methods to DependencyType. --- python/apt_pkgmodule.cc | 1 + python/cache.cc | 97 +++++++++++++++++++++++++++++++++++++------------ 2 files changed, 74 insertions(+), 24 deletions(-) (limited to 'python') diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index ef687dd1..49b6a35f 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -483,6 +483,7 @@ extern "C" void initapt_pkg() if (PyType_Ready(&PkgActionGroupType) == -1) return; if (PyType_Ready(&PkgSourceListType) == -1) return; if (PyType_Ready(&PkgCacheType) == -1) return; + if (PyType_Ready(&DependencyType) == -1) return; // Initialize the module diff --git a/python/cache.cc b/python/cache.cc index 87b625c0..2d8b8db7 100644 --- a/python/cache.cc +++ b/python/cache.cc @@ -840,35 +840,68 @@ static PyMethodDef DependencyMethods[] = // Dependency Class /*{{{*/ // --------------------------------------------------------------------- -static PyObject *DependencyAttr(PyObject *Self,char *Name) +static PyObject *DependencyGetTargetVer(PyObject *Self,void*) +{ + pkgCache::DepIterator &Dep = GetCpp(Self); + if (Dep->Version == 0) + return PyString_FromString(""); + return PyString_FromString(Dep.TargetVer()); +} + +static PyObject *DependencyGetTargetPkg(PyObject *Self,void*) { pkgCache::DepIterator &Dep = GetCpp(Self); PyObject *Owner = GetOwner(Self); + return CppOwnedPyObject_NEW(Owner,&PackageType, + Dep.TargetPkg()); +} - if (strcmp("TargetVer",Name) == 0) - { - if (Dep->Version == 0) - return PyString_FromString(""); - return PyString_FromString(Dep.TargetVer()); - } - else if (strcmp("TargetPkg",Name) == 0) - return CppOwnedPyObject_NEW(Owner,&PackageType, - Dep.TargetPkg()); - else if (strcmp("ParentVer",Name) == 0) - return CppOwnedPyObject_NEW(Owner,&VersionType, - Dep.ParentVer()); - else if (strcmp("ParentPkg",Name) == 0) - return CppOwnedPyObject_NEW(Owner,&PackageType, Dep.ParentPkg()); - else if (strcmp("CompType",Name) == 0) - return PyString_FromString(Dep.CompType()); - else if (strcmp("DepType",Name) == 0) - return PyString_FromString(Dep.DepType()); - else if (strcmp("ID",Name) == 0) - return Py_BuildValue("i",Dep->ID); +static PyObject *DependencyGetParentVer(PyObject *Self,void*) +{ + pkgCache::DepIterator &Dep = GetCpp(Self); + PyObject *Owner = GetOwner(Self); + return CppOwnedPyObject_NEW(Owner,&VersionType, + Dep.ParentVer()); +} + +static PyObject *DependencyGetParentPkg(PyObject *Self,void*) +{ + pkgCache::DepIterator &Dep = GetCpp(Self); + PyObject *Owner = GetOwner(Self); + return CppOwnedPyObject_NEW(Owner,&PackageType, + Dep.ParentPkg()); +} - return Py_FindMethod(DependencyMethods,Self,Name); +static PyObject *DependencyGetCompType(PyObject *Self,void*) +{ + pkgCache::DepIterator &Dep = GetCpp(Self); + return PyString_FromString(Dep.CompType()); } +static PyObject *DependencyGetDepType(PyObject *Self,void*) +{ + pkgCache::DepIterator &Dep = GetCpp(Self); + return PyString_FromString(Dep.DepType()); +} + +static PyObject *DependencyGetID(PyObject *Self,void*) +{ + pkgCache::DepIterator &Dep = GetCpp(Self); + return Py_BuildValue("i",Dep->ID); +} + +static PyGetSetDef DependencyGetSet[] = { + {"CompType",DependencyGetCompType}, + {"DepType",DependencyGetDepType}, + {"ID",DependencyGetID}, + {"ParentPkg",DependencyGetParentPkg}, + {"ParentVer",DependencyGetParentVer}, + {"TargetPkg",DependencyGetTargetPkg}, + {"TargetVer",DependencyGetTargetVer}, + {} +}; + + PyTypeObject DependencyType = { PyObject_HEAD_INIT(&PyType_Type) @@ -879,14 +912,30 @@ PyTypeObject DependencyType = // Methods CppOwnedDealloc, // tp_dealloc 0, // tp_print - DependencyAttr, // tp_getattr + 0, // tp_getattr 0, // tp_setattr 0, // tp_compare - DependencyRepr, // tp_repr + DependencyRepr, // tp_repr 0, // tp_as_number 0, // tp_as_sequence 0, // tp_as_mapping 0, // tp_hash + 0, // tp_call + 0, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + Py_TPFLAGS_DEFAULT, // tp_flags + "Dependency Object", // tp_doc + 0, // tp_traverse + 0, // tp_clear + 0, // tp_richcompare + 0, // tp_weaklistoffset + 0, // tp_iter + 0, // tp_iternext + DependencyMethods, // tp_methods + 0, // tp_members + DependencyGetSet, // tp_getset }; /*}}}*/ -- cgit v1.2.3 From caef6ff047586413cbd2daef969f29c38481fa86 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Tue, 14 Apr 2009 19:07:07 +0200 Subject: * python/depcache.cc: Use tp_methods and tp_getset for PkgDepCacheType --- python/apt_pkgmodule.cc | 1 + python/depcache.cc | 77 +++++++++++++++++++++++++++++++------------------ 2 files changed, 50 insertions(+), 28 deletions(-) (limited to 'python') diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index 49b6a35f..8ed3e599 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -484,6 +484,7 @@ extern "C" void initapt_pkg() if (PyType_Ready(&PkgSourceListType) == -1) return; if (PyType_Ready(&PkgCacheType) == -1) return; if (PyType_Ready(&DependencyType) == -1) return; + if (PyType_Ready(&PkgDepCacheType) == -1) return; // Initialize the module diff --git a/python/depcache.cc b/python/depcache.cc index 2c73a1a9..ade3d4f5 100644 --- a/python/depcache.cc +++ b/python/depcache.cc @@ -560,50 +560,71 @@ static PyMethodDef PkgDepCacheMethods[] = {} }; - -static PyObject *DepCacheAttr(PyObject *Self,char *Name) -{ - pkgDepCache *depcache = GetCpp(Self); - - // size querries - if(strcmp("KeepCount",Name) == 0) - return Py_BuildValue("l", depcache->KeepCount()); - else if(strcmp("InstCount",Name) == 0) - return Py_BuildValue("l", depcache->InstCount()); - else if(strcmp("DelCount",Name) == 0) - return Py_BuildValue("l", depcache->DelCount()); - else if(strcmp("BrokenCount",Name) == 0) - return Py_BuildValue("l", depcache->BrokenCount()); - else if(strcmp("UsrSize",Name) == 0) - return Py_BuildValue("d", depcache->UsrSize()); - else if(strcmp("DebSize",Name) == 0) - return Py_BuildValue("d", depcache->DebSize()); - - - return Py_FindMethod(PkgDepCacheMethods,Self,Name); +#define depcache (GetCpp(Self)) +static PyObject *PkgDepCacheGetKeepCount(PyObject *Self,void*) { + return Py_BuildValue("l", depcache->KeepCount()); } +static PyObject *PkgDepCacheGetInstCount(PyObject *Self,void*) { + return Py_BuildValue("l", depcache->InstCount()); +} +static PyObject *PkgDepCacheGetDelCount(PyObject *Self,void*) { + return Py_BuildValue("l", depcache->DelCount()); +} +static PyObject *PkgDepCacheGetBrokenCount(PyObject *Self,void*) { + return Py_BuildValue("l", depcache->BrokenCount()); +} +static PyObject *PkgDepCacheGetUsrSize(PyObject *Self,void*) { + return Py_BuildValue("d", depcache->UsrSize()); +} +static PyObject *PkgDepCacheGetDebSize(PyObject *Self,void*) { + return Py_BuildValue("d", depcache->DebSize()); +} +#undef depcache - - +static PyGetSetDef PkgDepCacheGetSet[] = { + {"BrokenCount",PkgDepCacheGetBrokenCount}, + {"DebSize",PkgDepCacheGetDebSize}, + {"DelCount",PkgDepCacheGetDelCount}, + {"InstCount",PkgDepCacheGetInstCount}, + {"KeepCount",PkgDepCacheGetKeepCount}, + {"UsrSize",PkgDepCacheGetUsrSize}, + {} +}; PyTypeObject PkgDepCacheType = { PyObject_HEAD_INIT(&PyType_Type) - 0, // ob_size - "pkgDepCache", // tp_name + 0, // ob_size + "pkgDepCache", // tp_name sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize // Methods - CppOwnedDealloc, // tp_dealloc + CppOwnedDealloc, // tp_dealloc 0, // tp_print - DepCacheAttr, // tp_getattr + 0, // tp_getattr 0, // tp_setattr 0, // tp_compare 0, // tp_repr 0, // tp_as_number 0, // tp_as_sequence - 0, // tp_as_mapping + 0, // tp_as_mapping 0, // tp_hash + 0, // tp_call + 0, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + Py_TPFLAGS_DEFAULT, // tp_flags + "pkgDepCache Object", // tp_doc + 0, // tp_traverse + 0, // tp_clear + 0, // tp_richcompare + 0, // tp_weaklistoffset + 0, // tp_iter + 0, // tp_iternext + PkgDepCacheMethods, // tp_methods + 0, // tp_members + PkgDepCacheGetSet, // tp_getset }; -- cgit v1.2.3 From 5b74e72b35b82e60dbe7109fc60988c02c7d7676 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Tue, 14 Apr 2009 19:22:48 +0200 Subject: * python/acquire.cc: Use tp_methods and tp_getset for PkgAcquireType --- python/acquire.cc | 96 +++++++++++++++++++++++++++++++------------------ python/apt_pkgmodule.cc | 1 + 2 files changed, 62 insertions(+), 35 deletions(-) (limited to 'python') diff --git a/python/acquire.cc b/python/acquire.cc index eb1f7418..d39ee495 100644 --- a/python/acquire.cc +++ b/python/acquire.cc @@ -123,63 +123,89 @@ static PyMethodDef PkgAcquireMethods[] = {} }; - -static PyObject *AcquireAttr(PyObject *Self,char *Name) +#define fetcher (GetCpp(Self)) +static PyObject *PkgAcquireGetTotalNeeded(PyObject *Self,void*) { + return Py_BuildValue("d", fetcher->TotalNeeded()); +} +static PyObject *PkgAcquireGetFetchNeeded(PyObject *Self,void*) { + return Py_BuildValue("d", fetcher->FetchNeeded()); +} +static PyObject *PkgAcquireGetPartialPresent(PyObject *Self,void*) { + return Py_BuildValue("d", fetcher->PartialPresent()); +} +#undef fetcher +static PyObject *PkgAcquireGetItems(PyObject *Self,void*) { pkgAcquire *fetcher = GetCpp(Self); - - if(strcmp("TotalNeeded",Name) == 0) - return Py_BuildValue("d", fetcher->TotalNeeded()); - if(strcmp("FetchNeeded",Name) == 0) - return Py_BuildValue("d", fetcher->FetchNeeded()); - if(strcmp("PartialPresent",Name) == 0) - return Py_BuildValue("d", fetcher->PartialPresent()); - if(strcmp("Items",Name) == 0) + PyObject *List = PyList_New(0); + for (pkgAcquire::ItemIterator I = fetcher->ItemsBegin(); + I != fetcher->ItemsEnd(); I++) { - PyObject *List = PyList_New(0); - for (pkgAcquire::ItemIterator I = fetcher->ItemsBegin(); - I != fetcher->ItemsEnd(); I++) - { - PyObject *Obj; - Obj = CppOwnedPyObject_NEW(Self,&AcquireItemType,I); - PyList_Append(List,Obj); - Py_DECREF(Obj); - - } - return List; + PyObject *Obj; + Obj = CppOwnedPyObject_NEW(Self, + &AcquireItemType,I); + PyList_Append(List,Obj); + Py_DECREF(Obj); + } - // some constants - if(strcmp("ResultContinue",Name) == 0) + return List; +} +// some constants +static PyObject *PkgAcquireGetResultContinue(PyObject *Self,void*) { return Py_BuildValue("i", pkgAcquire::Continue); - if(strcmp("ResultFailed",Name) == 0) +} +static PyObject *PkgAcquireGetResultFailed(PyObject *Self,void*) { return Py_BuildValue("i", pkgAcquire::Failed); - if(strcmp("ResultCancelled",Name) == 0) +} +static PyObject *PkgAcquireGetResultCancelled(PyObject *Self,void*) { return Py_BuildValue("i", pkgAcquire::Cancelled); - - return Py_FindMethod(PkgAcquireMethods,Self,Name); } - - +static PyGetSetDef PkgAcquireGetSet[] = { + {"FetchNeeded",PkgAcquireGetFetchNeeded}, + {"Items",PkgAcquireGetItems}, + {"PartialPresent",PkgAcquireGetPartialPresent}, + {"ResultCancelled",PkgAcquireGetResultCancelled}, + {"ResultContinue",PkgAcquireGetResultContinue}, + {"ResultFailed",PkgAcquireGetResultFailed}, + {"TotalNeeded",PkgAcquireGetTotalNeeded}, + {} +}; PyTypeObject PkgAcquireType = { PyObject_HEAD_INIT(&PyType_Type) - 0, // ob_size - "Acquire", // tp_name - sizeof(CppPyObject), // tp_basicsize + 0, // ob_size + "Acquire", // tp_name + sizeof(CppPyObject), // tp_basicsize 0, // tp_itemsize // Methods - CppDealloc, // tp_dealloc + CppDealloc, // tp_dealloc 0, // tp_print - AcquireAttr, // tp_getattr + 0, // tp_getattr 0, // tp_setattr 0, // tp_compare 0, // tp_repr 0, // tp_as_number 0, // tp_as_sequence - 0, // tp_as_mapping + 0, // tp_as_mapping 0, // tp_hash + 0, // tp_call + 0, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + Py_TPFLAGS_DEFAULT, // tp_flags + "pkgAcquire Object", // tp_doc + 0, // tp_traverse + 0, // tp_clear + 0, // tp_richcompare + 0, // tp_weaklistoffset + 0, // tp_iter + 0, // tp_iternext + PkgAcquireMethods, // tp_methods + 0, // tp_members + PkgAcquireGetSet, // tp_getset }; PyObject *GetAcquire(PyObject *Self,PyObject *Args) diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index 8ed3e599..299ca609 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -485,6 +485,7 @@ extern "C" void initapt_pkg() if (PyType_Ready(&PkgCacheType) == -1) return; if (PyType_Ready(&DependencyType) == -1) return; if (PyType_Ready(&PkgDepCacheType) == -1) return; + if (PyType_Ready(&PkgAcquireType) == -1) return; // Initialize the module -- cgit v1.2.3 From 87df0bb1e114d2bf0972b899ac6cfd25dd032dab Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Tue, 14 Apr 2009 20:21:06 +0200 Subject: * python/indexfile.cc: Use tp_methods and tp_getset for PackageIndexFileType --- python/apt_pkgmodule.cc | 1 + python/indexfile.cc | 77 +++++++++++++++++++++++++++++++++---------------- 2 files changed, 53 insertions(+), 25 deletions(-) (limited to 'python') diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index 299ca609..aa01cc2a 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -486,6 +486,7 @@ extern "C" void initapt_pkg() if (PyType_Ready(&DependencyType) == -1) return; if (PyType_Ready(&PkgDepCacheType) == -1) return; if (PyType_Ready(&PkgAcquireType) == -1) return; + if (PyType_Ready(&PackageIndexFileType) == -1) return; // Initialize the module diff --git a/python/indexfile.cc b/python/indexfile.cc index 107eae27..dc55634f 100644 --- a/python/indexfile.cc +++ b/python/indexfile.cc @@ -32,25 +32,26 @@ static PyMethodDef PackageIndexFileMethods[] = {} }; - -static PyObject *PackageIndexFileAttr(PyObject *Self,char *Name) -{ - pkgIndexFile *File = GetCpp(Self); - if (strcmp("Label",Name) == 0) - return Safe_FromString(File->GetType()->Label); - else if (strcmp("Describe",Name) == 0) - return Safe_FromString(File->Describe().c_str()); - else if (strcmp("Exists",Name) == 0) - return Py_BuildValue("i",(File->Exists())); - else if (strcmp("HasPackages",Name) == 0) - return Py_BuildValue("i",(File->HasPackages())); - else if (strcmp("Size",Name) == 0) - return Py_BuildValue("i",(File->Size())); - else if (strcmp("IsTrusted",Name) == 0) - return Py_BuildValue("i",(File->IsTrusted())); - - return Py_FindMethod(PackageIndexFileMethods,Self,Name); +#define File (GetCpp(Self)) +static PyObject *PackageIndexFileGetLabel(PyObject *Self,void*) { + return Safe_FromString(File->GetType()->Label); +} +static PyObject *PackageIndexFileGetDescribe(PyObject *Self,void*) { + return Safe_FromString(File->Describe().c_str()); +} +static PyObject *PackageIndexFileGetExists(PyObject *Self,void*) { + return Py_BuildValue("i",(File->Exists())); } +static PyObject *PackageIndexFileGetHasPackages(PyObject *Self,void*) { + return Py_BuildValue("i",(File->HasPackages())); +} +static PyObject *PackageIndexFileGetSize(PyObject *Self,void*) { + return Py_BuildValue("i",(File->Size())); +} +static PyObject *PackageIndexFileGetIsTrusted(PyObject *Self,void*) { + return Py_BuildValue("i",(File->IsTrusted())); +} +#undef File static PyObject *PackageIndexFileRepr(PyObject *Self) { @@ -67,24 +68,50 @@ static PyObject *PackageIndexFileRepr(PyObject *Self) return PyString_FromString(S); } +static PyGetSetDef PackageIndexFileGetSet[] = { + {"Describe",PackageIndexFileGetDescribe}, + {"Exists",PackageIndexFileGetExists}, + {"HasPackages",PackageIndexFileGetHasPackages}, + {"IsTrusted",PackageIndexFileGetIsTrusted}, + {"Label",PackageIndexFileGetLabel}, + {"Size",PackageIndexFileGetSize}, + {} +}; + PyTypeObject PackageIndexFileType = { PyObject_HEAD_INIT(&PyType_Type) - 0, // ob_size - "pkgIndexFile", // tp_name + 0, // ob_size + "pkgIndexFile", // tp_name sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize // Methods - CppOwnedDealloc, // tp_dealloc + CppOwnedDealloc, // tp_dealloc 0, // tp_print - PackageIndexFileAttr, // tp_getattr + 0, // tp_getattr 0, // tp_setattr 0, // tp_compare - PackageIndexFileRepr, // tp_repr + PackageIndexFileRepr, // tp_repr 0, // tp_as_number - 0, // tp_as_sequence - 0, // tp_as_mapping + 0, // tp_as_sequence + 0, // tp_as_mapping 0, // tp_hash + 0, // tp_call + 0, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + Py_TPFLAGS_DEFAULT, // tp_flags + "pkgIndexFile Object", // tp_doc + 0, // tp_traverse + 0, // tp_clear + 0, // tp_richcompare + 0, // tp_weaklistoffset + 0, // tp_iter + 0, // tp_iternext + PackageIndexFileMethods, // tp_methods + 0, // tp_members + PackageIndexFileGetSet, // tp_getset }; -- cgit v1.2.3 From 444b2afea3b58cc55fbf4b9deb6d20c4475c8fef Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Tue, 14 Apr 2009 20:27:49 +0200 Subject: * python/pkgmanager.cc: Use tp_methods and tp_getset for PkgManagerType --- python/apt_pkgmodule.cc | 1 + python/pkgmanager.cc | 52 ++++++++++++++++++++++++++++++++----------------- 2 files changed, 35 insertions(+), 18 deletions(-) (limited to 'python') diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index aa01cc2a..4e718ffa 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -487,6 +487,7 @@ extern "C" void initapt_pkg() if (PyType_Ready(&PkgDepCacheType) == -1) return; if (PyType_Ready(&PkgAcquireType) == -1) return; if (PyType_Ready(&PackageIndexFileType) == -1) return; + if (PyType_Ready(&PkgManagerType) == -1) return; // Initialize the module diff --git a/python/pkgmanager.cc b/python/pkgmanager.cc index 0eaa28cd..52f86228 100644 --- a/python/pkgmanager.cc +++ b/python/pkgmanager.cc @@ -75,41 +75,57 @@ static PyMethodDef PkgManagerMethods[] = }; -static PyObject *PkgManagerAttr(PyObject *Self,char *Name) -{ - //PkgManagerStruct &Struct = GetCpp(Self); - pkgPackageManager *pm = GetCpp(Self); - - // some constants - if(strcmp("ResultCompleted",Name) == 0) - return Py_BuildValue("i", pkgPackageManager::Completed); - if(strcmp("ResultFailed",Name) == 0) - return Py_BuildValue("i", pkgPackageManager::Failed); - if(strcmp("ResultIncomplete",Name) == 0) - return Py_BuildValue("i", pkgPackageManager::Incomplete); - - return Py_FindMethod(PkgManagerMethods,Self,Name); +static PyObject *PkgManagerGetResultCompleted(PyObject *Self,void*) { + return Py_BuildValue("i", pkgPackageManager::Completed); +} +static PyObject *PkgManagerGetResultFailed(PyObject *Self,void*) { + return Py_BuildValue("i", pkgPackageManager::Failed); +} +static PyObject *PkgManagerGetResultIncomplete(PyObject *Self,void*) { + return Py_BuildValue("i", pkgPackageManager::Incomplete); } +static PyGetSetDef PkgManagerGetSet[] = { + {"ResultCompleted",PkgManagerGetResultCompleted}, + {"ResultFailed",PkgManagerGetResultFailed}, + {"ResultIncomplete",PkgManagerGetResultIncomplete}, + {} +}; PyTypeObject PkgManagerType = { PyObject_HEAD_INIT(&PyType_Type) - 0, // ob_size + 0, // ob_size "PackageManager", // tp_name sizeof(CppPyObject), // tp_basicsize 0, // tp_itemsize // Methods - CppDealloc, // tp_dealloc + CppDealloc, // tp_dealloc 0, // tp_print - PkgManagerAttr, // tp_getattr + 0, // tp_getattr 0, // tp_setattr 0, // tp_compare 0, // tp_repr 0, // tp_as_number 0, // tp_as_sequence - 0, // tp_as_mapping + 0, // tp_as_mapping 0, // tp_hash + 0, // tp_call + 0, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + Py_TPFLAGS_DEFAULT, // tp_flags + "PackageManager Object", // tp_doc + 0, // tp_traverse + 0, // tp_clear + 0, // tp_richcompare + 0, // tp_weaklistoffset + 0, // tp_iter + 0, // tp_iternext + PkgManagerMethods, // tp_methods + 0, // tp_members + PkgManagerGetSet, // tp_getset }; #include -- cgit v1.2.3 From 3caa05aa8e295d338be4bfbe7fdd2e825a59d947 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Tue, 14 Apr 2009 22:14:10 +0200 Subject: * python/pkgsrcrecords.cc: Use GetSet properties for PkgSrcRecordsType This time, it is a bit more complicated because we have to raise an AttributeError when no package has been looked up. --- python/apt_pkgmodule.cc | 1 + python/apt_pkgmodule.h | 1 + python/pkgsrcrecords.cc | 178 +++++++++++++++++++++++++++++++----------------- 3 files changed, 119 insertions(+), 61 deletions(-) (limited to 'python') diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index 4e718ffa..92727b6f 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -488,6 +488,7 @@ extern "C" void initapt_pkg() if (PyType_Ready(&PkgAcquireType) == -1) return; if (PyType_Ready(&PackageIndexFileType) == -1) return; if (PyType_Ready(&PkgManagerType) == -1) return; + if (PyType_Ready(&PkgSrcRecordsType) == -1) return; // Initialize the module diff --git a/python/apt_pkgmodule.h b/python/apt_pkgmodule.h index ea8e33df..d2631864 100644 --- a/python/apt_pkgmodule.h +++ b/python/apt_pkgmodule.h @@ -89,6 +89,7 @@ PyObject *GetPkgManager(PyObject *Self,PyObject *Args); // PkgRecords Stuff extern PyTypeObject PkgRecordsType; +extern PyTypeObject PkgSrcRecordsType; PyObject *GetPkgRecords(PyObject *Self,PyObject *Args); PyObject *GetPkgSrcRecords(PyObject *Self,PyObject *Args); diff --git a/python/pkgsrcrecords.cc b/python/pkgsrcrecords.cc index f7f5d7a2..c830f8d2 100644 --- a/python/pkgsrcrecords.cc +++ b/python/pkgsrcrecords.cc @@ -75,71 +75,111 @@ static PyMethodDef PkgSrcRecordsMethods[] = {} }; -static PyObject *PkgSrcRecordsAttr(PyObject *Self,char *Name) -{ +/** + * Get the PkgSrcRecordsStruct from a PyObject. If no package has been looked + * up, set an AttributeError using the given name. + */ +static inline PkgSrcRecordsStruct &GetStruct(PyObject *Self,char *name) { PkgSrcRecordsStruct &Struct = GetCpp(Self); + if (Struct.Last == 0) + PyErr_SetString(PyExc_AttributeError,name); + return Struct; +} + +static PyObject *PkgSrcRecordsGetPackage(PyObject *Self,void*) { + PkgSrcRecordsStruct &Struct = GetStruct(Self,"Package"); + return (Struct.Last != 0) ? CppPyString(Struct.Last->Package()) : 0; +} +static PyObject *PkgSrcRecordsGetVersion(PyObject *Self,void*) { + PkgSrcRecordsStruct &Struct = GetStruct(Self,"Version"); + return (Struct.Last != 0) ? CppPyString(Struct.Last->Version()) : 0; +} +static PyObject *PkgSrcRecordsGetMaintainer(PyObject *Self,void*) { + PkgSrcRecordsStruct &Struct = GetStruct(Self,"Maintainer"); + return (Struct.Last != 0) ? CppPyString(Struct.Last->Maintainer()) : 0; +} +static PyObject *PkgSrcRecordsGetSection(PyObject *Self,void*) { + PkgSrcRecordsStruct &Struct = GetStruct(Self,"Section"); + return (Struct.Last != 0) ? CppPyString(Struct.Last->Section()) : 0; +} +static PyObject *PkgSrcRecordsGetRecord(PyObject *Self,void*) { + PkgSrcRecordsStruct &Struct = GetStruct(Self,"Record"); + return (Struct.Last != 0) ? CppPyString(Struct.Last->AsStr()) : 0; +} +static PyObject *PkgSrcRecordsGetBinaries(PyObject *Self,void*) { + PkgSrcRecordsStruct &Struct = GetStruct(Self,"Binaries"); + if (Struct.Last == 0) + return 0; + PyObject *List = PyList_New(0); + for(const char **b = Struct.Last->Binaries(); *b != 0; ++b) + PyList_Append(List, CppPyString(*b)); + return List; // todo +} +static PyObject *PkgSrcRecordsGetIndex(PyObject *Self,void*) { + PkgSrcRecordsStruct &Struct = GetStruct(Self,"Index"); + if (Struct.Last == 0) + return 0; + const pkgIndexFile &tmp = Struct.Last->Index(); + return CppOwnedPyObject_NEW(Self,&PackageIndexFileType, + (pkgIndexFile*)&tmp); +} - if (Struct.Last != 0) - { - if (strcmp("Package",Name) == 0) - return CppPyString(Struct.Last->Package()); - else if (strcmp("Version",Name) == 0) - return CppPyString(Struct.Last->Version()); - else if (strcmp("Maintainer",Name) == 0) - return CppPyString(Struct.Last->Maintainer()); - else if (strcmp("Section",Name) == 0) - return CppPyString(Struct.Last->Section()); - else if (strcmp("Record",Name) == 0) - return CppPyString(Struct.Last->AsStr()); - else if (strcmp("Binaries",Name) == 0) { - PyObject *List = PyList_New(0); - - for(const char **b = Struct.Last->Binaries(); - *b != 0; - ++b) - PyList_Append(List, CppPyString(*b)); - return List; // todo - } else if (strcmp("Index",Name) == 0) { - const pkgIndexFile &tmp = Struct.Last->Index(); - return CppOwnedPyObject_NEW(Self,&PackageIndexFileType, (pkgIndexFile*)&tmp); - } else if (strcmp("Files",Name) == 0) { - PyObject *List = PyList_New(0); - - vector f; - if(!Struct.Last->Files(f)) - return NULL; // error - - PyObject *v; - for(unsigned int i=0;i bd; - if(!Struct.Last->BuildDepends(bd, false /* arch-only*/)) - return NULL; // error - - PyObject *v; - for(unsigned int i=0;i f; + if(!Struct.Last->Files(f)) + return NULL; // error + + PyObject *v; + for(unsigned int i=0;i bd; + if(!Struct.Last->BuildDepends(bd, false /* arch-only*/)) + return NULL; // error + + PyObject *v; + for(unsigned int i=0;i, // tp_dealloc 0, // tp_print - PkgSrcRecordsAttr, // tp_getattr + 0, // tp_getattr 0, // tp_setattr 0, // tp_compare 0, // tp_repr @@ -158,6 +198,22 @@ PyTypeObject PkgSrcRecordsType = 0, // tp_as_sequence 0, // tp_as_mapping 0, // tp_hash + 0, // tp_call + 0, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + Py_TPFLAGS_DEFAULT, // tp_flags + "SourceRecords Object", // tp_doc + 0, // tp_traverse + 0, // tp_clear + 0, // tp_richcompare + 0, // tp_weaklistoffset + 0, // tp_iter + 0, // tp_iternext + PkgSrcRecordsMethods, // tp_methods + 0, // tp_members + PkgSrcRecordsGetSet, // tp_getset }; /*}}}*/ -- cgit v1.2.3 From 97d985d73d12da5578628418aa787d78a33b652d Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Wed, 15 Apr 2009 15:00:33 +0200 Subject: * python/pkgrecords.cc: Use GetSet for PkgRecordsType --- python/apt_pkgmodule.cc | 1 + python/pkgrecords.cc | 129 ++++++++++++++++++++++++++++++++++-------------- 2 files changed, 94 insertions(+), 36 deletions(-) (limited to 'python') diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index 92727b6f..fe6a739e 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -489,6 +489,7 @@ extern "C" void initapt_pkg() if (PyType_Ready(&PackageIndexFileType) == -1) return; if (PyType_Ready(&PkgManagerType) == -1) return; if (PyType_Ready(&PkgSrcRecordsType) == -1) return; + if (PyType_Ready(&PkgRecordsType) == -1) return; // Initialize the module diff --git a/python/pkgrecords.cc b/python/pkgrecords.cc index 5359ee6f..577aaf1c 100644 --- a/python/pkgrecords.cc +++ b/python/pkgrecords.cc @@ -53,44 +53,85 @@ static PyMethodDef PkgRecordsMethods[] = {} }; -static PyObject *PkgRecordsAttr(PyObject *Self,char *Name) -{ +/** + * Get the PkgSrcRecordsStruct from a PyObject. If no package has been looked + * up, set an AttributeError using the given name. + */ +static inline PkgRecordsStruct &GetStruct(PyObject *Self,char *name) { PkgRecordsStruct &Struct = GetCpp(Self); + if (Struct.Last == 0) + PyErr_SetString(PyExc_AttributeError,name); + return Struct; +} - if (Struct.Last != 0) - { - if (strcmp("FileName",Name) == 0) - return CppPyString(Struct.Last->FileName()); - else if (strcmp("MD5Hash",Name) == 0) - return CppPyString(Struct.Last->MD5Hash()); - else if (strcmp("SHA1Hash",Name) == 0) - return CppPyString(Struct.Last->SHA1Hash()); - else if (strcmp("SHA256Hash",Name) == 0) - return CppPyString(Struct.Last->SHA256Hash()); - else if (strcmp("SourcePkg",Name) == 0) - return CppPyString(Struct.Last->SourcePkg()); - else if (strcmp("SourceVer",Name) == 0) - return CppPyString(Struct.Last->SourceVer()); - else if (strcmp("Maintainer",Name) == 0) - return CppPyString(Struct.Last->Maintainer()); - else if (strcmp("ShortDesc",Name) == 0) - return CppPyString(Struct.Last->ShortDesc()); - else if (strcmp("LongDesc",Name) == 0) - return CppPyString(Struct.Last->LongDesc()); - else if (strcmp("Name",Name) == 0) - return CppPyString(Struct.Last->Name()); - else if (strcmp("Homepage",Name) == 0) - return CppPyString(Struct.Last->Homepage()); - else if (strcmp("Record", Name) == 0) - { - const char *start, *stop; - Struct.Last->GetRec(start, stop); - return PyString_FromStringAndSize(start,stop-start); - } - } - - return Py_FindMethod(PkgRecordsMethods,Self,Name); +static PyObject *PkgRecordsGetFileName(PyObject *Self,void*) { + PkgRecordsStruct &Struct = GetStruct(Self,"FileName"); + return (Struct.Last != 0) ? CppPyString(Struct.Last->FileName()) : 0; +} +static PyObject *PkgRecordsGetMD5Hash(PyObject *Self,void*) { + PkgRecordsStruct &Struct = GetStruct(Self,"MD5Hash"); + return (Struct.Last != 0) ? CppPyString(Struct.Last->MD5Hash()) : 0; +} +static PyObject *PkgRecordsGetSHA1Hash(PyObject *Self,void*) { + PkgRecordsStruct &Struct = GetStruct(Self,"SHA1Hash"); + return (Struct.Last != 0) ? CppPyString(Struct.Last->SHA1Hash()) : 0; +} +static PyObject *PkgRecordsGetSHA256Hash(PyObject *Self,void*) { + PkgRecordsStruct &Struct = GetStruct(Self,"SHA256Hash"); + return (Struct.Last != 0) ? CppPyString(Struct.Last->SHA256Hash()) : 0; +} +static PyObject *PkgRecordsGetSourcePkg(PyObject *Self,void*) { + PkgRecordsStruct &Struct = GetStruct(Self,"SourcePkg"); + return (Struct.Last != 0) ? CppPyString(Struct.Last->SourcePkg()) : 0; +} +static PyObject *PkgRecordsGetSourceVer(PyObject *Self,void*) { + PkgRecordsStruct &Struct = GetStruct(Self,"SourceVer"); + return (Struct.Last != 0) ? CppPyString(Struct.Last->SourceVer()) : 0; } +static PyObject *PkgRecordsGetMaintainer(PyObject *Self,void*) { + PkgRecordsStruct &Struct = GetStruct(Self,"Maintainer"); + return (Struct.Last != 0) ? CppPyString(Struct.Last->Maintainer()) : 0; +} +static PyObject *PkgRecordsGetShortDesc(PyObject *Self,void*) { + PkgRecordsStruct &Struct = GetStruct(Self,"ShortDesc"); + return (Struct.Last != 0) ? CppPyString(Struct.Last->ShortDesc()) : 0; +} +static PyObject *PkgRecordsGetLongDesc(PyObject *Self,void*) { + PkgRecordsStruct &Struct = GetStruct(Self,"LongDesc"); + return (Struct.Last != 0) ? CppPyString(Struct.Last->LongDesc()) : 0; +} +static PyObject *PkgRecordsGetName(PyObject *Self,void*) { + PkgRecordsStruct &Struct = GetStruct(Self,"Name"); + return (Struct.Last != 0) ? CppPyString(Struct.Last->Name()) : 0; +} +static PyObject *PkgRecordsGetHomepage(PyObject *Self,void*) { + PkgRecordsStruct &Struct = GetStruct(Self,"Homepage"); + return (Struct.Last != 0) ? CppPyString(Struct.Last->Homepage()) : 0; +} +static PyObject *PkgRecordsGetRecord(PyObject *Self,void*) { + const char *start, *stop; + PkgRecordsStruct &Struct = GetStruct(Self,"Record"); + if (Struct.Last == 0) + return 0; + Struct.Last->GetRec(start, stop); + return PyString_FromStringAndSize(start,stop-start); +} +static PyGetSetDef PkgRecordsGetSet[] = { + {"FileName",PkgRecordsGetFileName}, + {"Homepage",PkgRecordsGetHomepage}, + {"LongDesc",PkgRecordsGetLongDesc}, + {"MD5Hash",PkgRecordsGetMD5Hash}, + {"Maintainer",PkgRecordsGetMaintainer}, + {"Name",PkgRecordsGetName}, + {"Record",PkgRecordsGetRecord}, + {"SHA1Hash",PkgRecordsGetSHA1Hash}, + {"SHA256Hash",PkgRecordsGetSHA256Hash}, + {"ShortDesc",PkgRecordsGetShortDesc}, + {"SourcePkg",PkgRecordsGetSourcePkg}, + {"SourceVer",PkgRecordsGetSourceVer}, + {} +}; + PyTypeObject PkgRecordsType = { PyObject_HEAD_INIT(&PyType_Type) @@ -101,7 +142,7 @@ PyTypeObject PkgRecordsType = // Methods CppOwnedDealloc, // tp_dealloc 0, // tp_print - PkgRecordsAttr, // tp_getattr + 0, // tp_getattr 0, // tp_setattr 0, // tp_compare 0, // tp_repr @@ -109,6 +150,22 @@ PyTypeObject PkgRecordsType = 0, // tp_as_sequence 0, // tp_as_mapping 0, // tp_hash + 0, // tp_call + 0, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + Py_TPFLAGS_DEFAULT, // tp_flags + "Records Object", // tp_doc + 0, // tp_traverse + 0, // tp_clear + 0, // tp_richcompare + 0, // tp_weaklistoffset + 0, // tp_iter + 0, // tp_iternext + PkgRecordsMethods, // tp_methods + 0, // tp_members + PkgRecordsGetSet, // tp_getset }; /*}}}*/ -- cgit v1.2.3 From c876c5095673a2f1c0f2c0eef6eadef2ce200e19 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Wed, 15 Apr 2009 16:19:12 +0200 Subject: * Introduce support for Python 3 (Closes: #523645) This is the first initial port to Python 3. The API is almost completely identical to the one found in Python 2, except that functions working with binary data require bytes (md5sum,sha1sum,sha256sum,Base64Encode). Using setup3.py to install the modules will not work, because the apt package still has to be converted to Python 3. For the package, we call 2to3-3.1 in debian/rules to do this automatically. --- apt/package.py | 6 +++- debian/changelog | 2 ++ debian/control | 2 ++ debian/rules | 26 +++++++++++++-- po/python-apt.pot | 10 +++--- python/acquire.cc | 6 ++++ python/apt_instmodule.cc | 35 ++++++++++++++++++- python/apt_pkgmodule.cc | 87 +++++++++++++++++++++++++++++++++++------------- python/cache.cc | 18 ++++++++++ python/cdrom.cc | 2 ++ python/configuration.cc | 6 ++++ python/depcache.cc | 6 ++++ python/generic.h | 25 ++++++++++++++ python/indexfile.cc | 2 ++ python/metaindex.cc | 2 ++ python/pkgmanager.cc | 2 ++ python/pkgrecords.cc | 2 ++ python/pkgsrcrecords.cc | 2 ++ python/sourcelist.cc | 2 ++ python/string.cc | 16 ++++++++- python/tag.cc | 4 +++ setup3.py | 77 ++++++++++++++++++++++++++++++++++++++++++ 22 files changed, 307 insertions(+), 33 deletions(-) create mode 100644 setup3.py (limited to 'python') diff --git a/apt/package.py b/apt/package.py index 3ea1105d..f12f5559 100644 --- a/apt/package.py +++ b/apt/package.py @@ -272,8 +272,12 @@ class Version(object): """ self.summary # This does the lookup for us. desc = '' + + dsc = self.package._pcache._records.LongDesc try: - dsc = unicode(self.package._pcache._records.LongDesc, "utf-8") + if not isinstance(dsc, unicode): + # Only convert where needed (i.e. Python 2.X) + dsc = unicode(dsc, "utf-8") except UnicodeDecodeError, err: return _("Invalid unicode in description for '%s' (%s). " "Please report.") % (self.package.name, err) diff --git a/debian/changelog b/debian/changelog index 6cbdaac7..a9518d7d 100644 --- a/debian/changelog +++ b/debian/changelog @@ -1,5 +1,7 @@ python-apt (0.7.11) UNRELEASED; urgency=low + * Introduce support for Python 3 (Closes: #523645) + * Support the 'in' operator (e.g. "k in d") in Configuration{,Ptr,Sub} objects (e.g. apt_pkg.Config) and in TagSections (apt_pkg.ParseSection()) * Replace support for file objects with a more generic support for any object diff --git a/debian/control b/debian/control index 72476c58..08ee329f 100644 --- a/debian/control +++ b/debian/control @@ -11,6 +11,8 @@ Build-Depends: apt-utils, libapt-pkg-dev (>= 0.7.10), python-all-dbg, python-all-dev, + python3.1-dev, + python3.1-dbg, python-central (>= 0.5), python-distutils-extra (>= 1.9.0), python-gtk2, diff --git a/debian/rules b/debian/rules index 6d709ecd..7de945f2 100755 --- a/debian/rules +++ b/debian/rules @@ -11,22 +11,44 @@ DEB_PYTHON_PACKAGES_EXCLUDE=python-apt-dbg include /usr/share/cdbs/1/rules/debhelper.mk include /usr/share/cdbs/1/class/python-distutils.mk +PY3K = y PKG=python-apt DEBVER=$(shell dpkg-parsechangelog |sed -n -e '/^Version:/s/^Version: //p') DEB_COMPRESS_EXCLUDE:=.html .js _static/* _sources/* _sources/*/* .inv DEB_BUILD_PROG:=debuild --preserve-envvar PATH --preserve-envvar CCACHE_DIR -us -uc $(DEB_BUILD_PROG_OPTS) export DEBVER + +ifeq ($(PY3K),y) +build/python-apt:: + python3.1 setup3.py build + +install/python-apt:: + python3.1 ./setup3.py install --root $(CURDIR)/debian/python-apt \ + --install-layout=deb --no-compile + + find $(CURDIR)/debian/python-apt/usr/lib/python3.1/dist-packages/ -name '*.py' \ + | xargs 2to3-3.1 | patch -p0 +endif + build/python-apt-dbg:: set -e; \ for i in $(cdbs_python_build_versions); do \ python$$i-dbg ./setup.py build; \ done + ifeq($(PY3K),y) + python3.1-dbg ./setup3.py build + endif install/python-apt-dbg:: for i in $(cdbs_python_build_versions); do \ - python$$i-dbg ./setup.py install --root $(CURDIR)/debian/python-apt-dbg; \ + python$$i-dbg ./setup.py install --root $(CURDIR)/debian/python-apt-dbg \ + --no-compile; \ done + ifeq($(PY3K),y) + python3.1-dbg ./setup3.py install --root $(CURDIR)/debian/python-apt-dbg \ + --install-layout=deb --no-compile + endif find debian/python-apt-dbg \ ! -type d ! -name '*_d.so' | xargs rm -f find debian/python-apt-dbg -depth -empty -exec rmdir {} \; @@ -39,4 +61,4 @@ binary-predeb/python-apt-dbg:: ln -s python-apt debian/python-apt-dbg/usr/share/doc/python-apt-dbg clean:: - rm -rf build/lib* build/temp* + rm -rf build/lib* build/temp* build diff --git a/po/python-apt.pot b/po/python-apt.pot index 9c23c579..d12ae967 100644 --- a/po/python-apt.pot +++ b/po/python-apt.pot @@ -8,7 +8,7 @@ msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2009-04-12 19:07+0200\n" +"POT-Creation-Date: 2009-04-15 16:10+0200\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" @@ -354,16 +354,16 @@ msgstr "" msgid "Complete" msgstr "" -#: ../apt/package.py:278 +#: ../apt/package.py:282 #, python-format msgid "Invalid unicode in description for '%s' (%s). Please report." msgstr "" -#: ../apt/package.py:745 ../apt/package.py:849 +#: ../apt/package.py:830 ../apt/package.py:934 msgid "The list of changes is not available" msgstr "" -#: ../apt/package.py:853 +#: ../apt/package.py:938 #, python-format msgid "" "The list of changes is not available yet.\n" @@ -372,7 +372,7 @@ msgid "" "until the changes become available or try again later." msgstr "" -#: ../apt/package.py:859 +#: ../apt/package.py:944 msgid "" "Failed to download the list of changes. \n" "Please check your Internet connection." diff --git a/python/acquire.cc b/python/acquire.cc index d39ee495..053753cd 100644 --- a/python/acquire.cc +++ b/python/acquire.cc @@ -72,7 +72,9 @@ static PyObject *AcquireItemRepr(PyObject *Self) PyTypeObject AcquireItemType = { PyObject_HEAD_INIT(&PyType_Type) + #if PY_MAJOR_VERSION < 3 0, // ob_size + #endif "pkgAcquire::ItemIterator", // tp_name sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize @@ -175,7 +177,9 @@ static PyGetSetDef PkgAcquireGetSet[] = { PyTypeObject PkgAcquireType = { PyObject_HEAD_INIT(&PyType_Type) + #if PY_MAJOR_VERSION < 3 0, // ob_size + #endif "Acquire", // tp_name sizeof(CppPyObject), // tp_basicsize 0, // tp_itemsize @@ -234,7 +238,9 @@ PyObject *GetAcquire(PyObject *Self,PyObject *Args) PyTypeObject PkgAcquireFileType = { PyObject_HEAD_INIT(&PyType_Type) + #if PY_MAJOR_VERSION < 3 0, // ob_size + #endif "pkgAcquireFile", // tp_name sizeof(CppPyObject),// tp_basicsize 0, // tp_itemsize diff --git a/python/apt_instmodule.cc b/python/apt_instmodule.cc index a9d81be4..09e3937e 100644 --- a/python/apt_instmodule.cc +++ b/python/apt_instmodule.cc @@ -162,8 +162,41 @@ static PyMethodDef methods[] = {} }; +#if PY_MAJOR_VERSION >= 3 +struct module_state { + PyObject *error; +}; +#define GETSTATE(m) ((struct module_state*)PyModule_GetState(m)) + +static int apt_inst_traverse(PyObject *m, visitproc visit, void *arg) { + Py_VISIT(GETSTATE(m)->error); + return 0; +} + +static int apt_inst_clear(PyObject *m) { + Py_CLEAR(GETSTATE(m)->error); + return 0; +} + +static struct PyModuleDef moduledef = { + PyModuleDef_HEAD_INIT, + "apt_inst", + NULL, + sizeof(struct module_state), + methods, + NULL, + apt_inst_traverse, + apt_inst_clear, + NULL +}; + +extern "C" PyObject * PyInit_apt_inst() +{ + return PyModule_Create(&moduledef); +} +#else extern "C" void initapt_inst() { Py_InitModule("apt_inst",methods); } - /*}}}*/ +#endif /*}}}*/ diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index fe6a739e..e71d8ee6 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -173,12 +173,12 @@ static PyObject *md5sum(PyObject *Self,PyObject *Args) return 0; // Digest of a string. - if (PyString_Check(Obj) != 0) + if (PyBytes_Check(Obj) != 0) { char *s; Py_ssize_t len; MD5Summation Sum; - PyString_AsStringAndSize(Obj, &s, &len); + PyBytes_AsStringAndSize(Obj, &s, &len); Sum.Add((const unsigned char*)s, len); return CppPyString(Sum.Result().Value()); } @@ -213,12 +213,12 @@ static PyObject *sha1sum(PyObject *Self,PyObject *Args) return 0; // Digest of a string. - if (PyString_Check(Obj) != 0) + if (PyBytes_Check(Obj) != 0) { char *s; Py_ssize_t len; SHA1Summation Sum; - PyString_AsStringAndSize(Obj, &s, &len); + PyBytes_AsStringAndSize(Obj, &s, &len); Sum.Add((const unsigned char*)s, len); return CppPyString(Sum.Result().Value()); } @@ -253,12 +253,12 @@ static PyObject *sha256sum(PyObject *Self,PyObject *Args) return 0; // Digest of a string. - if (PyString_Check(Obj) != 0) + if (PyBytes_Check(Obj) != 0) { char *s; Py_ssize_t len; SHA256Summation Sum; - PyString_AsStringAndSize(Obj, &s, &len); + PyBytes_AsStringAndSize(Obj, &s, &len); Sum.Add((const unsigned char*)s, len); return CppPyString(Sum.Result().Value()); } @@ -470,30 +470,68 @@ static void AddInt(PyObject *Dict,const char *Itm,unsigned long I) Py_DECREF(Obj); } +#if PY_MAJOR_VERSION >= 3 +struct module_state { + PyObject *error; +}; + +#define GETSTATE(m) ((struct module_state*)PyModule_GetState(m)) + +static int apt_inst_traverse(PyObject *m, visitproc visit, void *arg) { + Py_VISIT(GETSTATE(m)->error); + return 0; +} + +static int apt_inst_clear(PyObject *m) { + Py_CLEAR(GETSTATE(m)->error); + return 0; +} + +static struct PyModuleDef moduledef = { + PyModuleDef_HEAD_INIT, + "apt_inst", + NULL, + sizeof(struct module_state), + methods, + NULL, + apt_inst_traverse, + apt_inst_clear, + NULL +}; + +#define INIT_ERROR return 0 +extern "C" PyObject * PyInit_apt_pkg() +#else +#define INIT_ERROR return extern "C" void initapt_pkg() +#endif { // Finalize our types to add slots, etc. - if (PyType_Ready(&TagSecType) == -1) return; - if (PyType_Ready(&TagFileType) == -1) return; - if (PyType_Ready(&ConfigurationType) == -1) return; - if (PyType_Ready(&ConfigurationPtrType) == -1) return; - if (PyType_Ready(&ConfigurationSubType) == -1) return; - if (PyType_Ready(&PkgCdromType) == -1) return; - if (PyType_Ready(&PkgProblemResolverType) == -1) return; - if (PyType_Ready(&PkgActionGroupType) == -1) return; - if (PyType_Ready(&PkgSourceListType) == -1) return; - if (PyType_Ready(&PkgCacheType) == -1) return; - if (PyType_Ready(&DependencyType) == -1) return; - if (PyType_Ready(&PkgDepCacheType) == -1) return; - if (PyType_Ready(&PkgAcquireType) == -1) return; - if (PyType_Ready(&PackageIndexFileType) == -1) return; - if (PyType_Ready(&PkgManagerType) == -1) return; - if (PyType_Ready(&PkgSrcRecordsType) == -1) return; - if (PyType_Ready(&PkgRecordsType) == -1) return; + if (PyType_Ready(&TagSecType) == -1) INIT_ERROR; + if (PyType_Ready(&TagFileType) == -1) INIT_ERROR; + if (PyType_Ready(&ConfigurationType) == -1) INIT_ERROR; + if (PyType_Ready(&ConfigurationPtrType) == -1) INIT_ERROR; + if (PyType_Ready(&ConfigurationSubType) == -1) INIT_ERROR; + if (PyType_Ready(&PkgCdromType) == -1) INIT_ERROR; + if (PyType_Ready(&PkgProblemResolverType) == -1) INIT_ERROR; + if (PyType_Ready(&PkgActionGroupType) == -1) INIT_ERROR; + if (PyType_Ready(&PkgSourceListType) == -1) INIT_ERROR; + if (PyType_Ready(&PkgCacheType) == -1) INIT_ERROR; + if (PyType_Ready(&DependencyType) == -1) INIT_ERROR; + if (PyType_Ready(&PkgDepCacheType) == -1) INIT_ERROR; + if (PyType_Ready(&PkgAcquireType) == -1) INIT_ERROR; + if (PyType_Ready(&PackageIndexFileType) == -1) INIT_ERROR; + if (PyType_Ready(&PkgManagerType) == -1) INIT_ERROR; + if (PyType_Ready(&PkgSrcRecordsType) == -1) INIT_ERROR; + if (PyType_Ready(&PkgRecordsType) == -1) INIT_ERROR; // Initialize the module + #if PY_MAJOR_VERSION >= 3 + PyObject *Module = PyModule_Create(&moduledef); + #else PyObject *Module = Py_InitModule("apt_pkg",methods); + #endif PyObject *Dict = PyModule_GetDict(Module); // Global variable linked to the global configuration class @@ -549,6 +587,9 @@ extern "C" void initapt_pkg() AddInt(Dict,"InstStateReInstReq",pkgCache::State::ReInstReq); AddInt(Dict,"InstStateHold",pkgCache::State::Hold); AddInt(Dict,"InstStateHoldReInstReq",pkgCache::State::HoldReInstReq); + #if PY_MAJOR_VERSION >= 3 + return Module; + #endif } /*}}}*/ diff --git a/python/cache.cc b/python/cache.cc index 2d8b8db7..957681ba 100644 --- a/python/cache.cc +++ b/python/cache.cc @@ -239,7 +239,9 @@ static PyMappingMethods CacheMap = {0,CacheMapOp,0}; PyTypeObject PkgCacheType = { PyObject_HEAD_INIT(&PyType_Type) + #if PY_MAJOR_VERSION < 3 0, // ob_size + #endif "pkgCache", // tp_name sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize @@ -277,7 +279,9 @@ PyTypeObject PkgCacheType = PyTypeObject PkgCacheFileType = { PyObject_HEAD_INIT(&PyType_Type) + #if PY_MAJOR_VERSION < 3 0, // ob_size + #endif "pkgCacheFile", // tp_name sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize @@ -345,7 +349,9 @@ static PySequenceMethods PkgListSeq = PyTypeObject PkgListType = { PyObject_HEAD_INIT(&PyType_Type) + #if PY_MAJOR_VERSION < 3 0, // ob_size + #endif "pkgCache::PkgIterator", // tp_name sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize @@ -435,7 +441,9 @@ static PyObject *PackageRepr(PyObject *Self) PyTypeObject PackageType = { PyObject_HEAD_INIT(&PyType_Type) + #if PY_MAJOR_VERSION < 3 0, // ob_size + #endif "pkgCache::Package", // tp_name sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize @@ -498,7 +506,9 @@ static PyObject *DescriptionRepr(PyObject *Self) PyTypeObject DescriptionType = { PyObject_HEAD_INIT(&PyType_Type) + #if PY_MAJOR_VERSION < 3 0, // ob_size + #endif "pkgCache::DescIterator", // tp_name sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize @@ -684,7 +694,9 @@ static PyObject *VersionRepr(PyObject *Self) PyTypeObject VersionType = { PyObject_HEAD_INIT(&PyType_Type) + #if PY_MAJOR_VERSION < 3 0, // ob_size + #endif "pkgCache::VerIterator", // tp_name sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize @@ -759,7 +771,9 @@ static PyObject *PackageFileRepr(PyObject *Self) PyTypeObject PackageFileType = { PyObject_HEAD_INIT(&PyType_Type) + #if PY_MAJOR_VERSION < 3 0, // ob_size + #endif "pkgCache::PkgFileIterator", // tp_name sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize @@ -905,7 +919,9 @@ static PyGetSetDef DependencyGetSet[] = { PyTypeObject DependencyType = { PyObject_HEAD_INIT(&PyType_Type) + #if PY_MAJOR_VERSION < 3 0, // ob_size + #endif "pkgCache::DepIterator", // tp_name sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize @@ -991,7 +1007,9 @@ static PySequenceMethods RDepListSeq = PyTypeObject RDepListType = { PyObject_HEAD_INIT(&PyType_Type) + #if PY_MAJOR_VERSION < 3 0, // ob_size + #endif "pkgCache::DepIterator", // tp_name sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize diff --git a/python/cdrom.cc b/python/cdrom.cc index 0816d93e..b3a38438 100644 --- a/python/cdrom.cc +++ b/python/cdrom.cc @@ -67,7 +67,9 @@ static PyMethodDef PkgCdromMethods[] = PyTypeObject PkgCdromType = { PyObject_HEAD_INIT(&PyType_Type) + #if PY_MAJOR_VERSION < 3 0, // ob_size + #endif "Cdrom", // tp_name sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize diff --git a/python/configuration.cc b/python/configuration.cc index b4adf357..eaac48ec 100644 --- a/python/configuration.cc +++ b/python/configuration.cc @@ -481,7 +481,9 @@ static PyMappingMethods ConfigurationMap = {0,CnfMap,CnfMapSet}; PyTypeObject ConfigurationType = { PyObject_HEAD_INIT(&PyType_Type) + #if PY_MAJOR_VERSION < 3 0, // ob_size + #endif "Configuration", // tp_name sizeof(CppPyObject), // tp_basicsize 0, // tp_itemsize @@ -515,7 +517,9 @@ PyTypeObject ConfigurationType = PyTypeObject ConfigurationPtrType = { PyObject_HEAD_INIT(&PyType_Type) + #if PY_MAJOR_VERSION < 3 0, // ob_size + #endif "ConfigurationPtr", // tp_name sizeof(CppPyObject), // tp_basicsize 0, // tp_itemsize @@ -549,7 +553,9 @@ PyTypeObject ConfigurationPtrType = PyTypeObject ConfigurationSubType = { PyObject_HEAD_INIT(&PyType_Type) + #if PY_MAJOR_VERSION < 3 0, // ob_size + #endif "ConfigurationSub", // tp_name sizeof(SubConfiguration), // tp_basicsize 0, // tp_itemsize diff --git a/python/depcache.cc b/python/depcache.cc index ade3d4f5..1c9eeff7 100644 --- a/python/depcache.cc +++ b/python/depcache.cc @@ -594,7 +594,9 @@ static PyGetSetDef PkgDepCacheGetSet[] = { PyTypeObject PkgDepCacheType = { PyObject_HEAD_INIT(&PyType_Type) + #if PY_MAJOR_VERSION < 3 0, // ob_size + #endif "pkgDepCache", // tp_name sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize @@ -773,7 +775,9 @@ static PyMethodDef PkgProblemResolverMethods[] = PyTypeObject PkgProblemResolverType = { PyObject_HEAD_INIT(&PyType_Type) + #if PY_MAJOR_VERSION < 3 0, // ob_size + #endif "pkgProblemResolver", // tp_name sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize @@ -829,7 +833,9 @@ static PyMethodDef PkgActionGroupMethods[] = PyTypeObject PkgActionGroupType = { PyObject_HEAD_INIT(&PyType_Type) + #if PY_MAJOR_VERSION < 3 0, // ob_size + #endif "pkgActionGroup", // tp_name sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize diff --git a/python/generic.h b/python/generic.h index ce79a54c..6e66d24c 100644 --- a/python/generic.h +++ b/python/generic.h @@ -35,6 +35,31 @@ typedef int Py_ssize_t; #endif +/* Define compatibility for Python 3. + * + * We will use the names PyString_* to refer to the default string type + * of the current Python version (PyString on 2.X, PyUnicode on 3.X). + * + * When we really need unicode strings, we will use PyUnicode_* directly, as + * long as it exists in Python 2 and Python 3. + * + * When we want bytes in Python 3, we use PyBytes*_ instead of PyString_* and + * define aliases from PyBytes_* to PyString_* for Python 2. + */ + +#if PY_MAJOR_VERSION >= 3 +#define PyString_Check PyUnicode_Check +#define PyString_FromString PyUnicode_FromString +#define PyString_FromStringAndSize PyUnicode_FromStringAndSize +#define PyString_AsString(op) PyBytes_AsString(PyUnicode_AsUTF8String(op)) +#define PyInt_Check PyLong_Check +#define PyInt_AsLong PyLong_AsLong +#else +#define PyBytes_Check PyString_Check +#define PyBytes_AsString PyString_AsString +#define PyBytes_AsStringAndSize PyString_AsStringAndSize +#endif + template struct CppPyObject : public PyObject { // We are only using CppPyObject and friends as dumb structs only, ie the diff --git a/python/indexfile.cc b/python/indexfile.cc index dc55634f..bb40cdd0 100644 --- a/python/indexfile.cc +++ b/python/indexfile.cc @@ -81,7 +81,9 @@ static PyGetSetDef PackageIndexFileGetSet[] = { PyTypeObject PackageIndexFileType = { PyObject_HEAD_INIT(&PyType_Type) + #if PY_MAJOR_VERSION < 3 0, // ob_size + #endif "pkgIndexFile", // tp_name sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize diff --git a/python/metaindex.cc b/python/metaindex.cc index efbc38af..cbaeafbd 100644 --- a/python/metaindex.cc +++ b/python/metaindex.cc @@ -59,7 +59,9 @@ static PyObject *MetaIndexRepr(PyObject *Self) PyTypeObject MetaIndexType = { PyObject_HEAD_INIT(&PyType_Type) + #if PY_MAJOR_VERSION < 3 0, // ob_size + #endif "metaIndex", // tp_name sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize diff --git a/python/pkgmanager.cc b/python/pkgmanager.cc index 52f86228..8f56cddc 100644 --- a/python/pkgmanager.cc +++ b/python/pkgmanager.cc @@ -95,7 +95,9 @@ static PyGetSetDef PkgManagerGetSet[] = { PyTypeObject PkgManagerType = { PyObject_HEAD_INIT(&PyType_Type) + #if PY_MAJOR_VERSION < 3 0, // ob_size + #endif "PackageManager", // tp_name sizeof(CppPyObject), // tp_basicsize 0, // tp_itemsize diff --git a/python/pkgrecords.cc b/python/pkgrecords.cc index 577aaf1c..978de6b7 100644 --- a/python/pkgrecords.cc +++ b/python/pkgrecords.cc @@ -135,7 +135,9 @@ static PyGetSetDef PkgRecordsGetSet[] = { PyTypeObject PkgRecordsType = { PyObject_HEAD_INIT(&PyType_Type) + #if PY_MAJOR_VERSION < 3 0, // ob_size + #endif "pkgRecords", // tp_name sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize diff --git a/python/pkgsrcrecords.cc b/python/pkgsrcrecords.cc index c830f8d2..97667d7a 100644 --- a/python/pkgsrcrecords.cc +++ b/python/pkgsrcrecords.cc @@ -183,7 +183,9 @@ static PyGetSetDef PkgSrcRecordsGetSet[] = { PyTypeObject PkgSrcRecordsType = { PyObject_HEAD_INIT(&PyType_Type) + #if PY_MAJOR_VERSION < 3 0, // ob_size + #endif "pkgSrcRecords", // tp_name sizeof(CppPyObject), // tp_basicsize 0, // tp_itemsize diff --git a/python/sourcelist.cc b/python/sourcelist.cc index 9f8f8878..48b3b7c8 100644 --- a/python/sourcelist.cc +++ b/python/sourcelist.cc @@ -100,7 +100,9 @@ static PyGetSetDef PkgSourceListGetSet[] = { PyTypeObject PkgSourceListType = { PyObject_HEAD_INIT(&PyType_Type) + #if PY_MAJOR_VERSION < 3 0, // ob_size + #endif "pkgSourceList", // tp_name sizeof(CppPyObject), // tp_basicsize 0, // tp_itemsize diff --git a/python/string.cc b/python/string.cc index 8168ea5b..b95ee3eb 100644 --- a/python/string.cc +++ b/python/string.cc @@ -38,7 +38,21 @@ PyObject *Python(PyObject *Self,PyObject *Args) \ } MkStr(StrDeQuote,DeQuoteString); -MkStr(StrBase64Encode,Base64Encode); + +/* + * Input bytes(Py3k)/str(Py2), output str. + */ +PyObject *StrBase64Encode(PyObject *Self,PyObject *Args) { + char *Str = 0; + #if PY_MAJOR_VERSION >= 3 + if (PyArg_ParseTuple(Args,"y",&Str) == 0) + #else + if (PyArg_ParseTuple(Args,"s",&Str) == 0) + #endif + return 0; + return CppPyString(Base64Encode(Str)); +} + MkStr(StrURItoFileName,URItoFileName); //MkFloat(StrSizeToStr,SizeToStr); diff --git a/python/tag.cc b/python/tag.cc index cdea3e03..18d08580 100644 --- a/python/tag.cc +++ b/python/tag.cc @@ -384,7 +384,9 @@ PyMappingMethods TagSecMapMeth = {TagSecLength,TagSecMap,0}; PyTypeObject TagSecType = { PyObject_HEAD_INIT(&PyType_Type) + #if PY_MAJOR_VERSION < 3 0, // ob_size + #endif "TagSection", // tp_name sizeof(TagSecData), // tp_basicsize 0, // tp_itemsize @@ -442,7 +444,9 @@ static PyGetSetDef TagFileGetSet[] = { PyTypeObject TagFileType = { PyObject_HEAD_INIT(&PyType_Type) + #if PY_MAJOR_VERSION < 3 0, // ob_size + #endif "TagFile", // tp_name sizeof(TagFileData), // tp_basicsize 0, // tp_itemsize diff --git a/setup3.py b/setup3.py new file mode 100644 index 00000000..a3cbdc8e --- /dev/null +++ b/setup3.py @@ -0,0 +1,77 @@ +#! /usr/bin/env python3 +# $Id: setup.py,v 1.2 2002/01/08 07:13:21 jgg Exp $ +import glob +import os +import shutil +import sys + +from distutils.core import setup, Extension +from distutils.sysconfig import parse_makefile +#from DistUtilsExtra.command import build_extra, build_i18n + + +# The apt_pkg module +files = ["python/"+source for source in parse_makefile("python/makefile")["APT_PKG_SRC"].split()] +apt_pkg = Extension("apt_pkg", files, libraries=["apt-pkg"]) + +# The apt_inst module +files = ["python/"+source for source in parse_makefile("python/makefile")["APT_INST_SRC"].split()] +apt_inst = Extension("apt_inst", files, libraries=["apt-pkg", "apt-inst"]) + +# Replace the leading _ that is used in the templates for translation +templates = [] + +# build doc +if len(sys.argv) > 1 and sys.argv[1] == "build": + if not os.path.exists("build/data/templates/"): + os.makedirs("build/data/templates") + for template in glob.glob('data/templates/*.info.in'): + source = open(template, "r") + build = open(os.path.join("build", template[:-3]), "w") + lines = source.readlines() + for line in lines: + build.write(line.lstrip("_")) + source.close() + build.close() + + +if len(sys.argv) > 1 and sys.argv[1] == "clean" and '-a' in sys.argv: + for dirname in "build/doc", "doc/build", "build/data", "build/mo": + if os.path.exists(dirname): + print("Removing", dirname) + shutil.rmtree(dirname) + else: + print("Not removing", dirname, "because it does not exist") + +setup(name="python-apt", + description="Python bindings for APT", + version=os.environ.get('DEBVER'), + author="APT Development Team", + author_email="deity@lists.debian.org", + ext_modules=[apt_pkg, apt_inst], + packages=['apt', 'apt.progress', 'aptsources'], + data_files = [('share/python-apt/templates', + glob.glob('build/data/templates/*.info')), + ('share/python-apt/templates', + glob.glob('data/templates/*.mirrors'))], +# cmdclass = {"build": build_extra.build_extra, +# "build_i18n": build_i18n.build_i18n}, + license = 'GNU GPL', + platforms = 'posix') + +if len(sys.argv) > 1 and sys.argv[1] == "build": + try: + import sphinx + except ImportError: + print(('W: Sphinx not available - Not building' + 'documentation'), file=sys.stderr) + try: + import pygtk + except ImportError: + print(('W: Not building documentation because python-' + 'gtk2 is not available at the moment.'), file=sys.stderr) + sys.exit(0) + sphinx.main(["sphinx", "-b", "html", "-d", "build/doc/doctrees", + os.path.abspath("doc/source"), "build/doc/html"]) + sphinx.main(["sphinx", "-b", "text", "-d", "build/doc/doctrees", + os.path.abspath("doc/source"), "build/doc/text"]) -- cgit v1.2.3 From 7a901ee79863eb812cba6e87feadc0a548f920e7 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Wed, 15 Apr 2009 18:21:44 +0200 Subject: * python: Port AcquireItem,Package,Description to GetSet --- python/acquire.cc | 102 +++++++++++++++---------- python/apt_pkgmodule.cc | 4 +- python/apt_pkgmodule.h | 2 + python/cache.cc | 198 +++++++++++++++++++++++++++++------------------- 4 files changed, 188 insertions(+), 118 deletions(-) (limited to 'python') diff --git a/python/acquire.cc b/python/acquire.cc index 053753cd..abd3884d 100644 --- a/python/acquire.cc +++ b/python/acquire.cc @@ -12,46 +12,50 @@ #include -// pkgAcquire::Item -static PyObject *AcquireItemAttr(PyObject *Self,char *Name) -{ - pkgAcquire::ItemIterator &I = GetCpp(Self); - - if (strcmp("ID",Name) == 0) - return Py_BuildValue("i",(*I)->ID); - else if (strcmp("Status",Name) == 0) - return Py_BuildValue("i",(*I)->Status); - else if (strcmp("Complete",Name) == 0) - return Py_BuildValue("i",(*I)->Complete); - else if (strcmp("Local",Name) == 0) - return Py_BuildValue("i",(*I)->Local); - else if (strcmp("IsTrusted",Name) == 0) - return Py_BuildValue("i",(*I)->IsTrusted()); - else if (strcmp("FileSize",Name) == 0) - return Py_BuildValue("i",(*I)->FileSize); - else if (strcmp("ErrorText",Name) == 0) - return Safe_FromString((*I)->ErrorText.c_str()); - else if (strcmp("DestFile",Name) == 0) - return Safe_FromString((*I)->DestFile.c_str()); - else if (strcmp("DescURI",Name) == 0) - return Safe_FromString((*I)->DescURI().c_str()); - // constants - else if (strcmp("StatIdle",Name) == 0) - return Py_BuildValue("i", pkgAcquire::Item::StatIdle); - else if (strcmp("StatFetching",Name) == 0) - return Py_BuildValue("i", pkgAcquire::Item::StatFetching); - else if (strcmp("StatDone",Name) == 0) - return Py_BuildValue("i", pkgAcquire::Item::StatDone); - else if (strcmp("StatError",Name) == 0) - return Py_BuildValue("i", pkgAcquire::Item::StatError); - else if (strcmp("StatAuthError",Name) == 0) - return Py_BuildValue("i", pkgAcquire::Item::StatAuthError); - - - PyErr_SetString(PyExc_AttributeError,Name); - return 0; +#define MkGet(PyFunc,Ret) static PyObject *PyFunc(PyObject *Self,void*) \ +{ \ + pkgAcquire::ItemIterator &I = GetCpp(Self); \ + return Ret; \ } +// Define our getters +MkGet(AcquireItemGetComplete,Py_BuildValue("i",(*I)->Complete)); +MkGet(AcquireItemGetDescURI,Safe_FromString((*I)->DescURI().c_str())); +MkGet(AcquireItemGetDestFile,Safe_FromString((*I)->DestFile.c_str())); +MkGet(AcquireItemGetErrorText,Safe_FromString((*I)->ErrorText.c_str())); +MkGet(AcquireItemGetFileSize,Py_BuildValue("i",(*I)->FileSize)); +MkGet(AcquireItemGetID,Py_BuildValue("i",(*I)->ID)); +MkGet(AcquireItemGetIsTrusted,Py_BuildValue("i",(*I)->IsTrusted())); +MkGet(AcquireItemGetLocal,Py_BuildValue("i",(*I)->Local)); +MkGet(AcquireItemGetStatus,Py_BuildValue("i",(*I)->Status)); + +// Constants +MkGet(AcquireItemGetStatIdle,Py_BuildValue("i", pkgAcquire::Item::StatIdle)); +MkGet(AcquireItemGetStatFetching,Py_BuildValue("i", pkgAcquire::Item::StatFetching)); +MkGet(AcquireItemGetStatDone,Py_BuildValue("i", pkgAcquire::Item::StatDone)); +MkGet(AcquireItemGetStatError,Py_BuildValue("i", pkgAcquire::Item::StatError)); +MkGet(AcquireItemGetStatAuthError,Py_BuildValue("i", pkgAcquire::Item::StatAuthError)); +#undef MkGet + +static PyGetSetDef AcquireItemGetSet[] = { + {"Complete",AcquireItemGetComplete}, + {"DescURI",AcquireItemGetDescURI}, + {"DestFile",AcquireItemGetDestFile}, + {"ErrorText",AcquireItemGetErrorText}, + {"FileSize",AcquireItemGetFileSize}, + {"ID",AcquireItemGetID}, + {"IsTrusted",AcquireItemGetIsTrusted}, + {"Local",AcquireItemGetLocal}, + {"Status",AcquireItemGetStatus}, + {"StatIdle",AcquireItemGetStatIdle}, + {"StatFetching",AcquireItemGetStatFetching}, + {"StatDone",AcquireItemGetStatDone}, + {"StatError",AcquireItemGetStatError}, + {"StatAuthError",AcquireItemGetStatAuthError}, + {} +}; + + static PyObject *AcquireItemRepr(PyObject *Self) { @@ -81,14 +85,30 @@ PyTypeObject AcquireItemType = // Methods CppOwnedDealloc, // tp_dealloc 0, // tp_print - AcquireItemAttr, // tp_getattr + 0, // tp_getattr 0, // tp_setattr 0, // tp_compare AcquireItemRepr, // tp_repr 0, // tp_as_number - 0, // tp_as_sequence - 0, // tp_as_mapping + 0, // tp_as_sequence + 0, // tp_as_mapping 0, // tp_hash + 0, // tp_call + 0, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + Py_TPFLAGS_DEFAULT, // tp_flags + "AcquireItem Object", // tp_doc + 0, // tp_traverse + 0, // tp_clear + 0, // tp_richcompare + 0, // tp_weaklistoffset + 0, // tp_iter + 0, // tp_iternext + 0, // tp_methods + 0, // tp_members + AcquireItemGetSet, // tp_getset }; diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index e71d8ee6..3beec747 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -524,7 +524,9 @@ extern "C" void initapt_pkg() if (PyType_Ready(&PkgManagerType) == -1) INIT_ERROR; if (PyType_Ready(&PkgSrcRecordsType) == -1) INIT_ERROR; if (PyType_Ready(&PkgRecordsType) == -1) INIT_ERROR; - + if (PyType_Ready(&AcquireItemType) == -1) INIT_ERROR; + if (PyType_Ready(&PackageType) == -1) INIT_ERROR; + if (PyType_Ready(&DescriptionType) == -1) INIT_ERROR; // Initialize the module #if PY_MAJOR_VERSION >= 3 diff --git a/python/apt_pkgmodule.h b/python/apt_pkgmodule.h index d2631864..424c4788 100644 --- a/python/apt_pkgmodule.h +++ b/python/apt_pkgmodule.h @@ -56,6 +56,7 @@ PyObject *StrCheckDomainList(PyObject *Self,PyObject *Args); extern PyTypeObject PkgCacheType; extern PyTypeObject PkgCacheFileType; extern PyTypeObject PkgListType; +extern PyTypeObject DescriptionType; extern PyTypeObject PackageType; extern PyTypeObject PackageFileType; extern PyTypeObject DependencyType; @@ -77,6 +78,7 @@ extern PyTypeObject PkgCdromType; PyObject *GetCdrom(PyObject *Self,PyObject *Args); // acquire +extern PyTypeObject AcquireItemType; extern PyTypeObject PkgAcquireType; extern char *doc_GetPkgAcqFile; PyObject *GetAcquire(PyObject *Self,PyObject *Args); diff --git a/python/cache.cc b/python/cache.cc index 957681ba..52c5982e 100644 --- a/python/cache.cc +++ b/python/cache.cc @@ -368,65 +368,73 @@ PyTypeObject PkgListType = 0, // tp_hash }; - /*}}}*/ -// Package Class /*{{{*/ -// --------------------------------------------------------------------- -static PyObject *PackageAttr(PyObject *Self,char *Name) +#define MkGet(PyFunc,Ret) static PyObject *PyFunc(PyObject *Self,void*) \ +{ \ + pkgCache::PkgIterator &Pkg = GetCpp(Self); \ + PyObject *Owner = GetOwner(Self); \ + return Ret; \ +} + +MkGet(PackageGetName,PyString_FromString(Pkg.Name())); +MkGet(PackageGetSection,Safe_FromString(Pkg.Section())); +MkGet(PackageGetRevDependsList,CppOwnedPyObject_NEW(Owner, + &RDepListType, Pkg.RevDependsList())); +MkGet(PackageGetProvidesList,CreateProvides(Owner,Pkg.ProvidesList())); +MkGet(PackageGetSelectedState,Py_BuildValue("i",Pkg->SelectedState)); +MkGet(PackageGetInstState,Py_BuildValue("i",Pkg->InstState)); +MkGet(PackageGetCurrentState,Py_BuildValue("i",Pkg->CurrentState)); +MkGet(PackageGetID,Py_BuildValue("i",Pkg->ID)); +# +MkGet(PackageGetAuto,Py_BuildValue("i",(Pkg->Flags & pkgCache::Flag::Auto) != 0)); +MkGet(PackageGetEssential,Py_BuildValue("i",(Pkg->Flags & pkgCache::Flag::Essential) != 0)); +MkGet(PackageGetImportant,Py_BuildValue("i",(Pkg->Flags & pkgCache::Flag::Important) != 0)); +#undef MkGet + +static PyObject *PackageGetVersionList(PyObject *Self,void*) { pkgCache::PkgIterator &Pkg = GetCpp(Self); PyObject *Owner = GetOwner(Self); - if (strcmp("Name",Name) == 0) - return PyString_FromString(Pkg.Name()); - else if (strcmp("VersionList",Name) == 0) + PyObject *List = PyList_New(0); + for (pkgCache::VerIterator I = Pkg.VersionList(); I.end() == false; I++) { - PyObject *List = PyList_New(0); - for (pkgCache::VerIterator I = Pkg.VersionList(); I.end() == false; I++) - { - PyObject *Obj; - Obj = CppOwnedPyObject_NEW(Owner,&VersionType,I); - PyList_Append(List,Obj); - Py_DECREF(Obj); - } - return List; + PyObject *Obj; + Obj = CppOwnedPyObject_NEW(Owner,&VersionType,I); + PyList_Append(List,Obj); + Py_DECREF(Obj); } - else if (strcmp("CurrentVer",Name) == 0) + return List; +} +static PyObject *PackageGetCurrentVer(PyObject *Self,void*) +{ + pkgCache::PkgIterator &Pkg = GetCpp(Self); + PyObject *Owner = GetOwner(Self); + if (Pkg->CurrentVer == 0) { - if (Pkg->CurrentVer == 0) - { - Py_INCREF(Py_None); - return Py_None; - } - - return CppOwnedPyObject_NEW(Owner,&VersionType, - Pkg.CurrentVer()); + Py_INCREF(Py_None); + return Py_None; } - else if (strcmp("Section",Name) == 0) - return Safe_FromString(Pkg.Section()); - else if (strcmp("RevDependsList",Name) == 0) - return CppOwnedPyObject_NEW(Owner,&RDepListType, - Pkg.RevDependsList()); - else if (strcmp("ProvidesList",Name) == 0) - return CreateProvides(Owner,Pkg.ProvidesList()); - else if (strcmp("SelectedState",Name) == 0) - return Py_BuildValue("i",Pkg->SelectedState); - else if (strcmp("InstState",Name) == 0) - return Py_BuildValue("i",Pkg->InstState); - else if (strcmp("CurrentState",Name) == 0) - return Py_BuildValue("i",Pkg->CurrentState); - else if (strcmp("ID",Name) == 0) - return Py_BuildValue("i",Pkg->ID); - else if (strcmp("Auto",Name) == 0) - return Py_BuildValue("i",(Pkg->Flags & pkgCache::Flag::Auto) != 0); - else if (strcmp("Essential",Name) == 0) - return Py_BuildValue("i",(Pkg->Flags & pkgCache::Flag::Essential) != 0); - else if (strcmp("Important",Name) == 0) - return Py_BuildValue("i",(Pkg->Flags & pkgCache::Flag::Important) != 0); - - PyErr_SetString(PyExc_AttributeError,Name); - return 0; + return CppOwnedPyObject_NEW(Owner,&VersionType, + Pkg.CurrentVer()); } +static PyGetSetDef PackageGetSet[] = { + {"Name",PackageGetName}, + {"Section",PackageGetSection}, + {"RevDependsList",PackageGetRevDependsList}, + {"ProvidesList",PackageGetProvidesList}, + {"SelectedState",PackageGetSelectedState}, + {"InstState",PackageGetInstState}, + {"CurrentState",PackageGetCurrentState}, + {"ID",PackageGetID}, + {"Auto",PackageGetID}, + {"Essential",PackageGetEssential}, + {"Important",PackageGetImportant}, + {"VersionList",PackageGetVersionList}, + {"CurrentVer",PackageGetCurrentVer}, + {} +}; + static PyObject *PackageRepr(PyObject *Self) { pkgCache::PkgIterator &Pkg = GetCpp(Self); @@ -450,7 +458,7 @@ PyTypeObject PackageType = // Methods CppOwnedDealloc, // tp_dealloc 0, // tp_print - PackageAttr, // tp_getattr + 0, // tp_getattr 0, // tp_setattr 0, // tp_compare PackageRepr, // tp_repr @@ -458,40 +466,62 @@ PyTypeObject PackageType = 0, // tp_as_sequence 0, // tp_as_mapping 0, // tp_hash + 0, // tp_call + 0, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + Py_TPFLAGS_DEFAULT, // tp_flags + "Package Object", // tp_doc + 0, // tp_traverse + 0, // tp_clear + 0, // tp_richcompare + 0, // tp_weaklistoffset + 0, // tp_iter + 0, // tp_iternext + 0, // tp_methods + 0, // tp_members + PackageGetSet, // tp_getset }; - /*}}}*/ -// Description Class /*{{{*/ -// --------------------------------------------------------------------- -static PyObject *DescriptionAttr(PyObject *Self,char *Name) + +#define Description_MkGet(PyFunc,Ret) static PyObject \ + *PyFunc(PyObject *Self,void*) { \ + pkgCache::DescIterator &Desc = GetCpp(Self); \ + return Ret; } + +Description_MkGet(DescriptionGetLanguageCode, + PyString_FromString(Desc.LanguageCode())); +Description_MkGet(DescriptionGetMd5,Safe_FromString(Desc.md5())); +#undef Description_MkGet + +static PyObject *DescriptionGetFileList(PyObject *Self,void*) { pkgCache::DescIterator &Desc = GetCpp(Self); PyObject *Owner = GetOwner(Self); - if (strcmp("LanguageCode",Name) == 0) - return PyString_FromString(Desc.LanguageCode()); - else if (strcmp("md5",Name) == 0) - return Safe_FromString(Desc.md5()); - else if (strcmp("FileList",Name) == 0) + /* The second value in the tuple is the index of the VF item. If the + user wants to request a lookup then that number will be used. + Maybe later it can become an object. */ + PyObject *List = PyList_New(0); + for (pkgCache::DescFileIterator I = Desc.FileList(); I.end() == false; I++) { - /* The second value in the tuple is the index of the VF item. If the - user wants to request a lookup then that number will be used. - Maybe later it can become an object. */ - PyObject *List = PyList_New(0); - for (pkgCache::DescFileIterator I = Desc.FileList(); I.end() == false; I++) - { - PyObject *DescFile; - PyObject *Obj; - DescFile = CppOwnedPyObject_NEW(Owner,&PackageFileType,I.File()); - Obj = Py_BuildValue("Nl",DescFile,I.Index()); - PyList_Append(List,Obj); - Py_DECREF(Obj); - } - return List; + PyObject *DescFile; + PyObject *Obj; + DescFile = CppOwnedPyObject_NEW(Owner,&PackageFileType,I.File()); + Obj = Py_BuildValue("Nl",DescFile,I.Index()); + PyList_Append(List,Obj); + Py_DECREF(Obj); } - PyErr_SetString(PyExc_AttributeError,Name); - return 0; + return List; } +static PyGetSetDef DescriptionGetSet[] = { + {"LanguageCode",DescriptionGetLanguageCode}, + {"md5",DescriptionGetMd5}, + {"FileList",DescriptionGetFileList}, + {} +}; + static PyObject *DescriptionRepr(PyObject *Self) { pkgCache::DescIterator &Desc = GetCpp(Self); @@ -515,7 +545,7 @@ PyTypeObject DescriptionType = // Methods CppOwnedDealloc, // tp_dealloc 0, // tp_print - DescriptionAttr, // tp_getattr + 0, // tp_getattr 0, // tp_setattr 0, // tp_compare DescriptionRepr, // tp_repr @@ -523,6 +553,22 @@ PyTypeObject DescriptionType = 0, // tp_as_sequence 0, // tp_as_mapping 0, // tp_hash + 0, // tp_call + 0, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + Py_TPFLAGS_DEFAULT, // tp_flags + "AcquireItem Object", // tp_doc + 0, // tp_traverse + 0, // tp_clear + 0, // tp_richcompare + 0, // tp_weaklistoffset + 0, // tp_iter + 0, // tp_iternext + 0, // tp_methods + 0, // tp_members + DescriptionGetSet, // tp_getset }; /*}}}*/ // Version Class /*{{{*/ -- cgit v1.2.3 From 337c885e7dd531858c35b256d974989bac6463df Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Thu, 16 Apr 2009 20:06:14 +0200 Subject: * apt/*.py: Initial rename work for Bug#481061 A new module, apt.deprecation, is introduced containing functions and classes which assist in the deprecation. The apt_pkg extension gets a new attribute, _COMPAT_0_7 which can be set by defining COMPAT_0_7 at compile time (-DCOMPAT_0_7). The names are changed, and compatibility functions are enabled if bool(apt_pkg._COMPAT_0_7) == True, i.e. if the package has been built with backward compatibility fixes. This commit changes the apt and aptsources packages, the apt_pkg and apt_inst extensions will be the next renames. --- apt/__init__.py | 15 ++++-- apt/cache.py | 108 +++++++++++++++++++++++++-------------- apt/cdrom.py | 6 ++- apt/debfile.py | 32 ++++++------ apt/deprecation.py | 76 ++++++++++++++++++++++++++++ apt/package.py | 126 +++++++++++++++++++++++++++++++--------------- apt/progress/gtk2.py | 6 +-- aptsources/sourceslist.py | 6 ++- debian/changelog | 6 +++ debian/control | 2 +- debian/rules | 3 ++ po/python-apt.pot | 10 ++-- python/apt_pkgmodule.cc | 6 +++ 13 files changed, 290 insertions(+), 112 deletions(-) create mode 100644 apt/deprecation.py (limited to 'python') diff --git a/apt/__init__.py b/apt/__init__.py index ae2abbf2..734b3240 100644 --- a/apt/__init__.py +++ b/apt/__init__.py @@ -17,17 +17,21 @@ # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 # USA # import the core of apt_pkg +"""High-Level Interface for working with apt.""" import apt_pkg -import sys -import os # import some fancy classes from apt.package import Package from apt.cache import Cache -from apt.progress import ( - OpProgress, FetchProgress, InstallProgress, CdromProgress) from apt.cdrom import Cdrom -from apt_pkg import SizeToStr, TimeToStr, VersionCompare + +if apt_pkg._COMPAT_0_7: + from apt.progress import (OpProgress, FetchProgress, InstallProgress, + CdromProgress) + + +if apt_pkg._COMPAT_0_7: + from apt_pkg import SizeToStr, TimeToStr, VersionCompare # init the package system apt_pkg.init() @@ -36,3 +40,4 @@ apt_pkg.init() #import warnings #warnings.warn("apt API not stable yet", FutureWarning) #del warnings +__all__ = ['Cache', 'Cdrom', 'Package'] diff --git a/apt/cache.py b/apt/cache.py index d13010af..928322d2 100644 --- a/apt/cache.py +++ b/apt/cache.py @@ -24,6 +24,7 @@ import weakref import apt_pkg from apt import Package +from apt.deprecation import AttributeDeprecatedBy, function_deprecated_by import apt.progress @@ -63,7 +64,7 @@ class Cache(object): rootdir + "/var/lib/dpkg/status") self.open(progress) - def _runCallbacks(self, name): + def _run_callbacks(self, name): """ internal helper to run a callback """ if name in self._callbacks: for callback in self._callbacks[name]: @@ -75,7 +76,7 @@ class Cache(object): """ if progress is None: progress = apt.progress.OpProgress() - self._runCallbacks("cache_pre_open") + self._run_callbacks("cache_pre_open") self._cache = apt_pkg.GetCache(progress) self._depcache = apt_pkg.GetDepCache(self._cache) self._records = apt_pkg.GetPkgRecords(self._cache) @@ -98,7 +99,7 @@ class Cache(object): i += 1 progress.done() - self._runCallbacks("cache_post_open") + self._run_callbacks("cache_post_open") def __getitem__(self, key): """ look like a dictionary (get key) """ @@ -128,12 +129,12 @@ class Cache(object): def keys(self): return list(self._set) - def getChanges(self): + def get_changes(self): """ Get the marked changes """ changes = [] for p in self: - if p.markedUpgrade or p.markedInstall or p.markedDelete or \ - p.markedDowngrade or p.markedReinstall: + if p.marked_upgrade or p.marked_install or p.marked_delete or \ + p.marked_downgrade or p.marked_reinstall: changes.append(p) return changes @@ -141,12 +142,12 @@ class Cache(object): """ Upgrade the all package, DistUpgrade will also install new dependencies """ - self.cachePreChange() + self.cache_pre_change() self._depcache.Upgrade(distUpgrade) - self.cachePostChange() + self.cache_post_change() @property - def requiredDownload(self): + def required_download(self): """Get the size of the packages that are required to download.""" pm = apt_pkg.GetPackageManager(self._depcache) fetcher = apt_pkg.GetAcquire() @@ -154,12 +155,12 @@ class Cache(object): return fetcher.FetchNeeded @property - def additionalRequiredSpace(self): + def required_space(self): """Get the size of the additional required space on the fs.""" return self._depcache.UsrSize @property - def reqReinstallPkgs(self): + def req_reinstall_pkgs(self): """Return the packages not downloadable packages in reqreinst state.""" reqreinst = set() for pkg in self: @@ -169,7 +170,7 @@ class Cache(object): reqreinst.add(pkg.name) return reqreinst - def _runFetcher(self, fetcher): + def _run_fetcher(self, fetcher): # do the actual fetching res = fetcher.Run() @@ -194,7 +195,7 @@ class Cache(object): raise FetchFailedException(errMsg) return res - def _fetchArchives(self, fetcher, pm): + def _fetch_archives(self, fetcher, pm): """ fetch the needed archives """ # get lock @@ -209,16 +210,16 @@ class Cache(object): return False # now run the fetcher, throw exception if something fails to be # fetched - return self._runFetcher(fetcher) + return self._run_fetcher(fetcher) finally: os.close(lock) - def isVirtualPackage(self, pkgname): + def is_virtual_package(self, pkgname): """Return whether the package is a virtual package.""" pkg = self._cache[pkgname] return bool(pkg.ProvidesList and not pkg.VersionList) - def getProvidingPackages(self, virtual): + def get_providing_packages(self, virtual): """ Return a list of packages which provide the virtual package of the specified name @@ -254,10 +255,16 @@ class Cache(object): finally: os.close(lock) - def installArchives(self, pm, installProgress): - installProgress.startUpdate() + def install_archives(self, pm, installProgress): + try: + installProgress.start_update() + except AttributeError: + installProgress.startUpdate() res = installProgress.run(pm) - installProgress.finishUpdate() + try: + installProgress.finish_update() + except AttributeError: + installProgress.finishUpdate() return res def commit(self, fetchProgress=None, installProgress=None): @@ -278,10 +285,10 @@ class Cache(object): fetcher = apt_pkg.GetAcquire(fetchProgress) while True: # fetch archives first - res = self._fetchArchives(fetcher, pm) + res = self._fetch_archives(fetcher, pm) # then install - res = self.installArchives(pm, installProgress) + res = self.install_archives(pm, installProgress) if res == pm.ResultCompleted: break if res == pm.ResultFailed: @@ -296,14 +303,14 @@ class Cache(object): # cache changes - def cachePostChange(self): + def cache_post_change(self): " called internally if the cache has changed, emit a signal then " - self._runCallbacks("cache_post_change") + self._run_callbacks("cache_post_change") - def cachePreChange(self): + def cache_pre_change(self): """ called internally if the cache is about to change, emit a signal then """ - self._runCallbacks("cache_pre_change") + self._run_callbacks("cache_pre_change") def connect(self, name, callback): """ connect to a signal, currently only used for @@ -312,6 +319,20 @@ class Cache(object): self._callbacks[name] = [] self._callbacks[name].append(callback) + if apt_pkg._COMPAT_0_7: + _runCallbacks = function_deprecated_by(_run_callbacks) + getChanges = function_deprecated_by(get_changes) + requiredDownload = AttributeDeprecatedBy('required_download') + additionalRequiredSpace = AttributeDeprecatedBy('required_space') + reqReinstallPkgs = AttributeDeprecatedBy('req_reinstall_pkgs') + _runFetcher = function_deprecated_by(_run_fetcher) + _fetchArchives = function_deprecated_by(_fetch_archives) + isVirtualPackage = function_deprecated_by(is_virtual_package) + getProvidingPackages = function_deprecated_by(get_providing_packages) + installArchives = function_deprecated_by(install_archives) + cachePostChange = function_deprecated_by(cache_post_change) + cachePreChange = function_deprecated_by(cache_pre_change) + # ----------------------------- experimental interface @@ -330,7 +351,7 @@ class MarkedChangesFilter(Filter): """ Filter that returns all marked changes """ def apply(self, pkg): - if pkg.markedInstall or pkg.markedDelete or pkg.markedUpgrade: + if pkg.marked_install or pkg.marked_delete or pkg.marked_upgrade: return True else: return False @@ -347,8 +368,8 @@ class FilteredCache(object): self.cache = Cache(progress) else: self.cache = cache - self.cache.connect("cache_post_change", self.filterCachePostChange) - self.cache.connect("cache_post_open", self.filterCachePostChange) + self.cache.connect("cache_post_change", self.filter_cache_post_change) + self.cache.connect("cache_post_open", self.filter_cache_post_change) self._filtered = {} self._filters = [] @@ -371,7 +392,7 @@ class FilteredCache(object): def __contains__(self, key): return (key in self._filtered) - def _reapplyFilter(self): + def _reapply_filter(self): " internal helper to refilter " self._filtered = {} for pkg in self.cache: @@ -380,18 +401,19 @@ class FilteredCache(object): self._filtered[pkg.name] = 1 break - def setFilter(self, filter): + def set_filter(self, filter): """Set the current active filter.""" self._filters = [] self._filters.append(filter) #self._reapplyFilter() # force a cache-change event that will result in a refiltering - self.cache.cachePostChange() + self.cache.cache_post_change() - def filterCachePostChange(self): + def filter_cache_post_change(self): """Called internally if the cache changes, emit a signal then.""" #print "filterCachePostChange()" - self._reapplyFilter() + self._reapply_filter() + # def connect(self, name, callback): # self.cache.connect(name, callback) @@ -401,6 +423,12 @@ class FilteredCache(object): #print "getattr: %s " % key return getattr(self.cache, key) + if apt_pkg._COMPAT_0_7: + _reapplyFilter = function_deprecated_by(_reapply_filter) + setFilter = function_deprecated_by(set_filter) + filterCachePostChange = function_deprecated_by(\ + filter_cache_post_change) + def cache_pre_changed(): print "cache pre changed" @@ -410,8 +438,8 @@ def cache_post_changed(): print "cache post changed" -# internal test code -if __name__ == "__main__": +def _test(): + """Internal test code.""" print "Cache self test" apt_pkg.init() c = Cache(apt.progress.OpTextProgress()) @@ -426,7 +454,7 @@ if __name__ == "__main__": x= c[pkg].name c.upgrade() - changes = c.getChanges() + changes = c.get_changes() print len(changes) for p in changes: #print p.name @@ -440,7 +468,7 @@ if __name__ == "__main__": apt_pkg.Config.Set("Dir::Cache::Archives", "/tmp/pytest") pm = apt_pkg.GetPackageManager(c._depcache) fetcher = apt_pkg.GetAcquire(apt.progress.TextFetchProgress()) - c._fetchArchives(fetcher, pm) + c._fetch_archives(fetcher, pm) #sys.exit(1) print "Testing filtered cache (argument is old cache)" @@ -448,7 +476,7 @@ if __name__ == "__main__": f.cache.connect("cache_pre_change", cache_pre_changed) f.cache.connect("cache_post_change", cache_post_changed) f.cache.upgrade() - f.setFilter(MarkedChangesFilter()) + f.set_filter(MarkedChangesFilter()) print len(f) for pkg in f.keys(): #print c[pkg].name @@ -461,10 +489,12 @@ if __name__ == "__main__": f.cache.connect("cache_pre_change", cache_pre_changed) f.cache.connect("cache_post_change", cache_post_changed) f.cache.upgrade() - f.setFilter(MarkedChangesFilter()) + f.set_filter(MarkedChangesFilter()) print len(f) for pkg in f.keys(): #print c[pkg].name x = f[pkg].name print len(f) +if __name__ == '__main__': + _test() diff --git a/apt/cdrom.py b/apt/cdrom.py index b52762ad..907ac622 100644 --- a/apt/cdrom.py +++ b/apt/cdrom.py @@ -24,6 +24,7 @@ import glob import apt_pkg from apt.progress import CdromProgress +from apt.deprecation import AttributeDeprecatedBy class Cdrom(object): @@ -69,7 +70,7 @@ class Cdrom(object): return ident @property - def inSourcesList(self): + def in_sources_list(self): """Check if the cdrom is already in the current sources.list.""" cd_id = self.ident() if cd_id is None: @@ -84,3 +85,6 @@ class Cdrom(object): if not line.lstrip().startswith("#") and cd_id in line: return True return False + + if apt_pkg._COMPAT_0_7: + inSourcesList = AttributeDeprecatedBy('in_sources_list') diff --git a/apt/debfile.py b/apt/debfile.py index 8d4f534c..c60fc92d 100644 --- a/apt/debfile.py +++ b/apt/debfile.py @@ -97,11 +97,11 @@ class DebPackage(object): # check for virtual pkgs if not depname in self._cache: - if self._cache.isVirtualPackage(depname): + if self._cache.is_virtual_package(depname): self._dbg(3, "_isOrGroupSatisfied(): %s is virtual dep" % depname) - for pkg in self._cache.getProvidingPackages(depname): - if pkg.isInstalled: + for pkg in self._cache.get_providing_packages(depname): + if pkg.is_installed: return True continue @@ -117,9 +117,9 @@ class DebPackage(object): # if we don't have it in the cache, it may be virtual if not depname in self._cache: - if not self._cache.isVirtualPackage(depname): + if not self._cache.is_virtual_package(depname): continue - providers = self._cache.getProvidingPackages(depname) + providers = self._cache.get_providing_packages(depname) # if a package just has a single virtual provider, we # just pick that (just like apt) if len(providers) != 1: @@ -158,9 +158,9 @@ class DebPackage(object): (pkgname, ver, oper)) pkg = self._cache[pkgname] - if pkg.isInstalled: + if pkg.is_installed: pkgver = pkg.installed.version - elif pkg.markedInstall: + elif pkg.marked_install: pkgver = pkg.candidate.version else: return False @@ -191,8 +191,8 @@ class DebPackage(object): if not depname in self._cache: # FIXME: we have to check for virtual replaces here as # well (to pass tests/gdebi-test8.deb) - if self._cache.isVirtualPackage(depname): - for pkg in self._cache.getProvidingPackages(depname): + if self._cache.is_virtual_package(depname): + for pkg in self._cache.get_providing_packages(depname): self._dbg(3, "conflicts virtual check: %s" % pkg.name) # P/C/R on virtal pkg, e.g. ftpd if self.pkgname == pkg.name: @@ -253,9 +253,9 @@ class DebPackage(object): """ self._dbg(3, "replacesPkg() %s %s %s" % (pkgname, oper, ver)) pkg = self._cache[pkgname] - if pkg.isInstalled: + if pkg.is_installed: pkgver = pkg.installed.version - elif pkg.markedInstall: + elif pkg.marked_install: pkgver = pkg.candidate.version else: pkgver = None @@ -371,7 +371,7 @@ class DebPackage(object): # now try it out in the cache for pkg in self._need_pkgs: try: - self._cache[pkg].markInstall(fromUser=False) + self._cache[pkg].mark_install(fromUser=False) except SystemError, e: self._failure_string = _("Cannot install '%s'" % pkg) self._cache.clear() @@ -396,7 +396,7 @@ class DebPackage(object): remove = [] unauthenticated = [] for pkg in self._cache: - if pkg.markedInstall or pkg.markedUpgrade: + if pkg.marked_install or pkg.marked_upgrade: install.append(pkg.name) # check authentication, one authenticated origin is enough # libapt will skip non-authenticated origins then @@ -405,7 +405,7 @@ class DebPackage(object): authenticated |= origin.trusted if not authenticated: unauthenticated.append(pkg.name) - if pkg.markedDelete: + if pkg.marked_delete: remove.append(pkg.name) return (install, remove, unauthenticated) @@ -492,7 +492,7 @@ class DscSrcPackage(DebPackage): for pkgname in self._installed_conflicts: if self._cache[pkgname]._pkg.Essential: raise Exception(_("An essential package would be removed")) - self._cache[pkgname].markDelete() + self._cache[pkgname].mark_delete() # FIXME: a additional run of the checkConflicts() # after _satisfyDepends() should probably be done return self._satisfy_depends(self.depends) @@ -507,7 +507,7 @@ def _test(): vp = "www-browser" #print "%s virtual: %s" % (vp, cache.isVirtualPackage(vp)) - providers = cache.getProvidingPackages(vp) + providers = cache.get_providing_packages(vp) print "Providers for %s :" % vp for pkg in providers: print " %s" % pkg.name diff --git a/apt/deprecation.py b/apt/deprecation.py new file mode 100644 index 00000000..a14d49e6 --- /dev/null +++ b/apt/deprecation.py @@ -0,0 +1,76 @@ +# deprecation.py - Module providing classes and functions for deprecation. +# +# Copyright (c) 2009 Julian Andres Klode +# Copyright (c) 2009 Ben Finney +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as +# published by the Free Software Foundation; either version 2 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 +# USA +"""Classes and functions for deprecating features. + +This is used for internal purposes only and not part of the official API. Do +not use it for anything outside the apt package. +""" +import re +import operator +import warnings + +__all__ = [] + + +class AttributeDeprecatedBy(object): + """Property acting as a proxy for a new attribute. + + When accessed, the property issues a DeprecationWarning and (on get) calls + attrgetter() for the attribute 'attribute' on the current object or (on + set) uses setattr to set the value of the wrapped attribute. + """ + + def __init__(self, attribute): + """Initialize the property.""" + self.attribute = attribute + self.__doc__ = 'Deprecated, please use \'%s\' instead' % attribute + self.getter = operator.attrgetter(attribute) + + def __get__(self, obj, type=None): + """Issue a DeprecationWarning and return the requested value.""" + if obj is None: + return getattr(type, self.attribute, self) + warnings.warn(self.__doc__, DeprecationWarning, stacklevel=2) + return self.getter(obj or type) + + def __set__(self, obj, value): + """Issue a DeprecationWarning and set the requested value.""" + warnings.warn(self.__doc__, DeprecationWarning, stacklevel=2) + setattr(obj, self.attribute, value) + + +def function_deprecated_by(func, convert_names=True): + """Return a function that warns it is deprecated by another function. + + Returns a new function that warns it is deprecated by function 'func', + then acts as a pass-through wrapper for 'func'. + + This function also converts all keyword argument names from mixedCase to + lowercase_with_underscores, but only if 'convert_names' is True (default). + """ + warning = 'Deprecated, please use \'%s\' instead' % func.func_name + + def deprecated_function(*args, **kwds): + warnings.warn(warning, DeprecationWarning, stacklevel=2) + if convert_names: + for key in kwds.keys(): + kwds[re.sub('([A-Z])', '_\\1', key).lower()] = kwds.pop(key) + return func(*args, **kwds) + return deprecated_function diff --git a/apt/package.py b/apt/package.py index db5696ae..70997383 100644 --- a/apt/package.py +++ b/apt/package.py @@ -31,6 +31,7 @@ import warnings import apt_pkg import apt.progress +from apt.deprecation import function_deprecated_by, AttributeDeprecatedBy __all__ = ('BaseDependency', 'Dependency', 'Origin', 'Package', 'Record', 'Version') @@ -56,21 +57,24 @@ class BaseDependency(object): """A single dependency. Attributes defined here: - name - The name of the dependency - relation - The relation (>>,>=,==,<<,<=,) - version - The version depended on - preDepend - Boolean value whether this is a pre-dependency. + name - The name of the dependency + relation - The relation (>>,>=,==,<<,<=,) + version - The version depended on + pre_depend - Boolean value whether this is a pre-dependency. """ def __init__(self, name, rel, ver, pre): self.name = name self.relation = rel self.version = ver - self.preDepend = pre + self.pre_depend = pre def __repr__(self): return ('' - % (self.name, self.relation, self.version, self.preDepend)) + % (self.name, self.relation, self.version, self.pre_depend)) + + if apt_pkg._COMPAT_0_7: + preDepend = AttributeDeprecatedBy('pre_depend') class Dependency(object): @@ -103,7 +107,7 @@ class DeprecatedProperty(property): warnings.warn("Accessed deprecated property %s.%s, please see the " "Version class for alternatives." % ((obj.__class__.__name__ or type.__name__), - self.fget.func_name), DeprecationWarning, 2) + self.fget.__name__), DeprecationWarning, 2) return property.__get__(self, obj, type) @@ -528,9 +532,9 @@ class Package(object): def __set_candidate(self, version): """Set the candidate version of the package.""" - self._pcache.cachePreChange() + self._pcache.cache_pre_change() self._pcache._depcache.SetCandidateVer(self._pkg, version._cand) - self._pcache.cachePostChange() + self._pcache.cache_post_change() candidate = property(candidate, __set_candidate) @@ -703,55 +707,56 @@ class Package(object): # depcache states @property - def markedInstall(self): + def marked_install(self): """Return ``True`` if the package is marked for install.""" return self._pcache._depcache.MarkedInstall(self._pkg) @property - def markedUpgrade(self): + def marked_upgrade(self): """Return ``True`` if the package is marked for upgrade.""" return self._pcache._depcache.MarkedUpgrade(self._pkg) @property - def markedDelete(self): + def marked_delete(self): """Return ``True`` if the package is marked for delete.""" return self._pcache._depcache.MarkedDelete(self._pkg) @property - def markedKeep(self): + def marked_keep(self): """Return ``True`` if the package is marked for keep.""" return self._pcache._depcache.MarkedKeep(self._pkg) @property - def markedDowngrade(self): + def marked_downgrade(self): """ Package is marked for downgrade """ return self._pcache._depcache.MarkedDowngrade(self._pkg) @property - def markedReinstall(self): + def marked_reinstall(self): """Return ``True`` if the package is marked for reinstall.""" return self._pcache._depcache.MarkedReinstall(self._pkg) @property - def isInstalled(self): + def is_installed(self): """Return ``True`` if the package is installed.""" return (self._pkg.CurrentVer is not None) @property - def isUpgradable(self): + def is_upgradable(self): """Return ``True`` if the package is upgradable.""" - return (self.isInstalled and + return (self.is_installed and self._pcache._depcache.IsUpgradable(self._pkg)) @property - def isAutoRemovable(self): + def is_auto_removable(self): """Return ``True`` if the package is no longer required. If the package has been installed automatically as a dependency of another package, and if no packages depend on it anymore, the package is no longer required. """ - return self.isInstalled and self._pcache._depcache.IsGarbage(self._pkg) + return self.is_installed and \ + self._pcache._depcache.IsGarbage(self._pkg) # sizes @@ -789,7 +794,7 @@ class Package(object): return getattr(self.installed, 'installed_size', 0) @property - def installedFiles(self): + def installed_files(self): """Return a list of files installed by the package. Return a list of unicode names of the files which have @@ -805,7 +810,7 @@ class Package(object): except EnvironmentError: return [] - def getChangelog(self, uri=None, cancel_lock=None): + def get_changelog(self, uri=None, cancel_lock=None): """ Download the changelog of the package and return it as unicode string. @@ -928,7 +933,7 @@ class Package(object): if match: # strip epoch from installed version # and from changelog too - installed = self.installedVersion + installed = getattr(self.installed, 'version', None) if installed and ":" in installed: installed = installed.split(":", 1)[1] changelog_ver = match.group(1) @@ -976,13 +981,13 @@ class Package(object): # depcache actions - def markKeep(self): + def mark_keep(self): """Mark a package for keep.""" - self._pcache.cachePreChange() + self._pcache.cache_pre_change() self._pcache._depcache.MarkKeep(self._pkg) - self._pcache.cachePostChange() + self._pcache.cache_post_change() - def markDelete(self, autoFix=True, purge=False): + def mark_delete(self, autoFix=True, purge=False): """Mark a package for install. If *autoFix* is ``True``, the resolver will be run, trying to fix @@ -991,7 +996,7 @@ class Package(object): If *purge* is ``True``, remove the configuration files of the package as well. The default is to keep the configuration. """ - self._pcache.cachePreChange() + self._pcache.cache_pre_change() self._pcache._depcache.MarkDelete(self._pkg, purge) # try to fix broken stuffsta if autoFix and self._pcache._depcache.BrokenCount > 0: @@ -1001,9 +1006,9 @@ class Package(object): Fix.Remove(self._pkg) Fix.InstallProtect() Fix.Resolve() - self._pcache.cachePostChange() + self._pcache.cache_post_change() - def markInstall(self, autoFix=True, autoInst=True, fromUser=True): + def mark_install(self, autoFix=True, autoInst=True, fromUser=True): """Mark a package for install. If *autoFix* is ``True``, the resolver will be run, trying to fix @@ -1017,7 +1022,7 @@ class Package(object): want to be able to automatically remove the package at a later stage when no other package depends on it. """ - self._pcache.cachePreChange() + self._pcache.cache_pre_change() self._pcache._depcache.MarkInstall(self._pkg, autoInst, fromUser) # try to fix broken stuff if autoFix and self._pcache._depcache.BrokenCount > 0: @@ -1025,12 +1030,12 @@ class Package(object): fixer.Clear(self._pkg) fixer.Protect(self._pkg) fixer.Resolve(True) - self._pcache.cachePostChange() + self._pcache.cache_post_change() - def markUpgrade(self): + def mark_upgrade(self): """Mark a package for upgrade.""" - if self.isUpgradable: - self.markInstall() + if self.is_upgradable: + self.mark_install() else: # FIXME: we may want to throw a exception here sys.stderr.write(("MarkUpgrade() called on a non-upgrable pkg: " @@ -1048,11 +1053,50 @@ class Package(object): self._pcache._depcache.Commit(fprogress, iprogress) + if not apt_pkg._COMPAT_0_7: + del installedVersion + del candidateVersion + del candidateDependencies + del installedDependencies + del architecture + del candidateDownloadable + del installedDownloadable + del sourcePackageName + del homepage + del priority + del installedPriority + del summary + del description + del rawDescription + del candidateRecord + del installedRecord + del packageSize + del installedPackageSize + del candidateInstalledSize + del installedSize + del candidateOrigin + else: + markedInstalled = AttributeDeprecatedBy('marked_installed') + markedUpgrade = AttributeDeprecatedBy('marked_upgrade') + markedDelete = AttributeDeprecatedBy('marked_delete') + markedKeep = AttributeDeprecatedBy('marked_keep') + markedDowngrade = AttributeDeprecatedBy('marked_downgrade') + markedReinstall = AttributeDeprecatedBy('marked_reinstall') + isInstalled = AttributeDeprecatedBy('is_installed') + isUpgradable = AttributeDeprecatedBy('is_upgradable') + isAutoRemovable = AttributeDeprecatedBy('is_auto_removable') + installedFiles = AttributeDeprecatedBy('installed_files') + getChangelog = function_deprecated_by(get_changelog) + markDelete = function_deprecated_by(mark_delete) + markInstall = function_deprecated_by(mark_install) + markKeep = function_deprecated_by(mark_keep) + markUpgrade = function_deprecated_by(mark_upgrade) + + def _test(): """Self-test.""" print "Self-test for the Package modul" import random - import apt apt_pkg.init() progress = apt.progress.OpTextProgress() cache = apt.Cache(progress) @@ -1075,19 +1119,19 @@ def _test(): print "Dependencies: %s" % pkg.installed.dependencies for dep in pkg.candidate.dependencies: print ",".join("%s (%s) (%s) (%s)" % (o.name, o.version, o.relation, - o.preDepend) for o in dep.or_dependencies) + o.pre_depend) for o in dep.or_dependencies) print "arch: %s" % pkg.candidate.architecture print "homepage: %s" % pkg.candidate.homepage print "rec: ", pkg.candidate.record - print cache["2vcard"].getChangelog() + print cache["2vcard"].get_changelog() for i in True, False: print "Running install on random upgradable pkgs with AutoFix: %s " % i for pkg in cache: - if pkg.isUpgradable: + if pkg.is_upgradable: if random.randint(0, 1) == 1: - pkg.markInstall(i) + pkg.mark_install(i) print "Broken: %s " % cache._depcache.BrokenCount print "InstCount: %s " % cache._depcache.InstCount @@ -1099,7 +1143,7 @@ def _test(): for name in cache.keys(): if random.randint(0, 1) == 1: try: - cache[name].markDelete(i) + cache[name].mark_delete(i) except SystemError: print "Error trying to remove: %s " % name print "Broken: %s " % cache._depcache.BrokenCount diff --git a/apt/progress/gtk2.py b/apt/progress/gtk2.py index f872e34f..36d459bc 100644 --- a/apt/progress/gtk2.py +++ b/apt/progress/gtk2.py @@ -422,10 +422,10 @@ def _test(): win.show() cache = apt.cache.Cache(apt_progress.open) pkg = cache["xterm"] - if pkg.isInstalled: - pkg.markDelete() + if pkg.is_installed: + pkg.mark_delete() else: - pkg.markInstall() + pkg.mark_install() apt_progress.show_terminal(True) try: cache.commit(apt_progress.fetch, apt_progress.install) diff --git a/aptsources/sourceslist.py b/aptsources/sourceslist.py index 1dfd870f..fdc0f029 100644 --- a/aptsources/sourceslist.py +++ b/aptsources/sourceslist.py @@ -33,6 +33,7 @@ import time import apt_pkg from aptsources.distinfo import DistInfo +from apt.deprecation import function_deprecated_by # some global helpers @@ -309,7 +310,7 @@ class SourcesList(object): """ remove the specified entry from the sources.list """ self.list.remove(source_entry) - def restoreBackup(self, backup_ext): + def restore_backup(self, backup_ext): " restore sources.list files based on the backup extension " file = apt_pkg.Config.FindFile("Dir::Etc::sourcelist") if os.path.exists(file+backup_ext) and \ @@ -321,6 +322,9 @@ class SourcesList(object): if os.path.exists(file+backup_ext): shutil.copy(file+backup_ext, file) + if apt_pkg._COMPAT_0_7: + restoreBackup = function_deprecated_by(restore_backup) + def backup(self, backup_ext=None): """ make a backup of the current source files, if no backup extension is given, the current date/time is used (and returned) """ diff --git a/debian/changelog b/debian/changelog index b2f2b965..e344c145 100644 --- a/debian/changelog +++ b/debian/changelog @@ -1,3 +1,9 @@ +python-apt (0.7.91) UNRELEASED; urgency=low + + * Rename all methods,functions,attributes to conform to PEP 8 (Closes: #481061) + + -- Julian Andres Klode Thu, 16 Apr 2009 18:54:29 +0200 + python-apt (0.7.90) experimental; urgency=low * Introduce support for Python 3 (Closes: #523645) diff --git a/debian/control b/debian/control index 08ee329f..374a177c 100644 --- a/debian/control +++ b/debian/control @@ -4,7 +4,7 @@ Priority: optional Maintainer: APT Development Team Uploaders: Michael Vogt , Julian Andres Klode Standards-Version: 3.8.1 -XS-Python-Version: all +XS-Python-Version: >= 2.5 Build-Depends: apt-utils, cdbs, debhelper (>= 5.0.37.1), diff --git a/debian/rules b/debian/rules index 9d0219e2..5fc6e13b 100755 --- a/debian/rules +++ b/debian/rules @@ -16,6 +16,9 @@ PKG=python-apt DEBVER=$(shell dpkg-parsechangelog |sed -n -e '/^Version:/s/^Version: //p') DEB_COMPRESS_EXCLUDE:=.html .js _static/* _sources/* _sources/*/* .inv DEB_BUILD_PROG:=debuild --preserve-envvar PATH --preserve-envvar CCACHE_DIR -us -uc $(DEB_BUILD_PROG_OPTS) + +# Define COMPAT_0_7 to get all the deprecated interfaces. +export CFLAGS+=-DCOMPAT_0_7 export DEBVER diff --git a/po/python-apt.pot b/po/python-apt.pot index d12ae967..3fcd395a 100644 --- a/po/python-apt.pot +++ b/po/python-apt.pot @@ -8,7 +8,7 @@ msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2009-04-15 16:10+0200\n" +"POT-Creation-Date: 2009-04-16 19:54+0200\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" @@ -354,16 +354,16 @@ msgstr "" msgid "Complete" msgstr "" -#: ../apt/package.py:282 +#: ../apt/package.py:286 #, python-format msgid "Invalid unicode in description for '%s' (%s). Please report." msgstr "" -#: ../apt/package.py:830 ../apt/package.py:934 +#: ../apt/package.py:846 ../apt/package.py:950 msgid "The list of changes is not available" msgstr "" -#: ../apt/package.py:938 +#: ../apt/package.py:954 #, python-format msgid "" "The list of changes is not available yet.\n" @@ -372,7 +372,7 @@ msgid "" "until the changes become available or try again later." msgstr "" -#: ../apt/package.py:944 +#: ../apt/package.py:960 msgid "" "Failed to download the list of changes. \n" "Please check your Internet connection." diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index 3beec747..a056b0bc 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -589,6 +589,12 @@ extern "C" void initapt_pkg() AddInt(Dict,"InstStateReInstReq",pkgCache::State::ReInstReq); AddInt(Dict,"InstStateHold",pkgCache::State::Hold); AddInt(Dict,"InstStateHoldReInstReq",pkgCache::State::HoldReInstReq); + + #ifdef COMPAT_0_7 + AddInt(Dict,"_COMPAT_0_7",1); + #else + AddInt(Dict,"_COMPAT_0_7",0); + #endif #if PY_MAJOR_VERSION >= 3 return Module; #endif -- cgit v1.2.3 From c01271813f5ac3b9036971ed70bdf052ababd8a8 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Thu, 16 Apr 2009 21:47:15 +0200 Subject: * python/cache.cc: Correct the 'Auto' descriptor of the Package class. --- python/cache.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'python') diff --git a/python/cache.cc b/python/cache.cc index 52c5982e..92e064b2 100644 --- a/python/cache.cc +++ b/python/cache.cc @@ -427,7 +427,7 @@ static PyGetSetDef PackageGetSet[] = { {"InstState",PackageGetInstState}, {"CurrentState",PackageGetCurrentState}, {"ID",PackageGetID}, - {"Auto",PackageGetID}, + {"Auto",PackageGetAuto}, {"Essential",PackageGetEssential}, {"Important",PackageGetImportant}, {"VersionList",PackageGetVersionList}, -- cgit v1.2.3 From e72b1f224007c0f7d6059ee59b0ead6ab2ff628d Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Fri, 17 Apr 2009 18:16:58 +0200 Subject: * python/generic.h: Force 0.7 compatibility to be off in Python 3 builds --- python/generic.h | 2 ++ 1 file changed, 2 insertions(+) (limited to 'python') diff --git a/python/generic.h b/python/generic.h index 6e66d24c..ae2871e3 100644 --- a/python/generic.h +++ b/python/generic.h @@ -54,6 +54,8 @@ typedef int Py_ssize_t; #define PyString_AsString(op) PyBytes_AsString(PyUnicode_AsUTF8String(op)) #define PyInt_Check PyLong_Check #define PyInt_AsLong PyLong_AsLong +// Force 0.7 compatibility to be off in Python 3 builds +#undef COMPAT_0_7 #else #define PyBytes_Check PyString_Check #define PyBytes_AsString PyString_AsString -- cgit v1.2.3 From 6472bb377c1effbf2b9a17188e5e057acdf9d195 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Fri, 17 Apr 2009 19:42:38 +0200 Subject: * python/apt_pkgmodule.cc: Do not access the modules __dict__. Instead of accessing the modules __dict__ directly, we should use the functions provided by Python to add objects to the module. --- python/apt_pkgmodule.cc | 104 ++++++++++++++++++++---------------------------- 1 file changed, 44 insertions(+), 60 deletions(-) (limited to 'python') diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index a056b0bc..0fcf1f29 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -456,19 +456,6 @@ static PyMethodDef methods[] = {} }; -static void AddStr(PyObject *Dict,const char *Itm,const char *Str) -{ - PyObject *Obj = PyString_FromString(Str); - PyDict_SetItemString(Dict,(char *)Itm,Obj); - Py_DECREF(Obj); -} - -static void AddInt(PyObject *Dict,const char *Itm,unsigned long I) -{ - PyObject *Obj = Py_BuildValue("i",I); - PyDict_SetItemString(Dict,(char *)Itm,Obj); - Py_DECREF(Obj); -} #if PY_MAJOR_VERSION >= 3 struct module_state { @@ -534,66 +521,63 @@ extern "C" void initapt_pkg() #else PyObject *Module = Py_InitModule("apt_pkg",methods); #endif - PyObject *Dict = PyModule_GetDict(Module); // Global variable linked to the global configuration class CppPyObject *Config = CppPyObject_NEW(&ConfigurationPtrType); Config->Object = _config; - PyDict_SetItemString(Dict,"Config",Config); - Py_DECREF(Config); + PyModule_AddObject(Module,"Config",Config); // Tag file constants - PyObject *Obj; - PyDict_SetItemString(Dict,"RewritePackageOrder", - Obj = CharCharToList(TFRewritePackageOrder)); - Py_DECREF(Obj); - PyDict_SetItemString(Dict,"RewriteSourceOrder", - Obj = CharCharToList(TFRewriteSourceOrder)); - Py_DECREF(Obj); + PyModule_AddObject(Module,"RewritePackageOrder", + CharCharToList(TFRewritePackageOrder)); + + PyModule_AddObject(Module,"RewriteSourceOrder", + CharCharToList(TFRewriteSourceOrder)); // Version.. - AddStr(Dict,"Version",pkgVersion); - AddStr(Dict,"LibVersion",pkgLibVersion); - AddStr(Dict,"Date",__DATE__); - AddStr(Dict,"Time",__TIME__); + PyModule_AddStringConstant(Module,"Version",pkgVersion); + PyModule_AddStringConstant(Module,"LibVersion",pkgLibVersion); + PyModule_AddStringConstant(Module,"Date",__DATE__); + PyModule_AddStringConstant(Module,"Time",__TIME__); // My constants - AddInt(Dict,"DepDepends",pkgCache::Dep::Depends); - AddInt(Dict,"DepPreDepends",pkgCache::Dep::PreDepends); - AddInt(Dict,"DepSuggests",pkgCache::Dep::Suggests); - AddInt(Dict,"DepRecommends",pkgCache::Dep::Recommends); - AddInt(Dict,"DepConflicts",pkgCache::Dep::Conflicts); - AddInt(Dict,"DepReplaces",pkgCache::Dep::Replaces); - AddInt(Dict,"DepObsoletes",pkgCache::Dep::Obsoletes); - - AddInt(Dict,"PriImportant",pkgCache::State::Important); - AddInt(Dict,"PriRequired",pkgCache::State::Required); - AddInt(Dict,"PriStandard",pkgCache::State::Standard); - AddInt(Dict,"PriOptional",pkgCache::State::Optional); - AddInt(Dict,"PriExtra",pkgCache::State::Extra); - - AddInt(Dict,"CurStateNotInstalled",pkgCache::State::NotInstalled); - AddInt(Dict,"CurStateUnPacked",pkgCache::State::UnPacked); - AddInt(Dict,"CurStateHalfConfigured",pkgCache::State::HalfConfigured); - AddInt(Dict,"CurStateHalfInstalled",pkgCache::State::HalfInstalled); - AddInt(Dict,"CurStateConfigFiles",pkgCache::State::ConfigFiles); - AddInt(Dict,"CurStateInstalled",pkgCache::State::Installed); - - AddInt(Dict,"SelStateUnknown",pkgCache::State::Unknown); - AddInt(Dict,"SelStateInstall",pkgCache::State::Install); - AddInt(Dict,"SelStateHold",pkgCache::State::Hold); - AddInt(Dict,"SelStateDeInstall",pkgCache::State::DeInstall); - AddInt(Dict,"SelStatePurge",pkgCache::State::Purge); - - AddInt(Dict,"InstStateOk",pkgCache::State::Ok); - AddInt(Dict,"InstStateReInstReq",pkgCache::State::ReInstReq); - AddInt(Dict,"InstStateHold",pkgCache::State::Hold); - AddInt(Dict,"InstStateHoldReInstReq",pkgCache::State::HoldReInstReq); + + PyModule_AddIntConstant(Module,"DepDepends",pkgCache::Dep::Depends); + PyModule_AddIntConstant(Module,"DepPreDepends",pkgCache::Dep::PreDepends); + PyModule_AddIntConstant(Module,"DepSuggests",pkgCache::Dep::Suggests); + PyModule_AddIntConstant(Module,"DepRecommends",pkgCache::Dep::Recommends); + PyModule_AddIntConstant(Module,"DepConflicts",pkgCache::Dep::Conflicts); + PyModule_AddIntConstant(Module,"DepReplaces",pkgCache::Dep::Replaces); + PyModule_AddIntConstant(Module,"DepObsoletes",pkgCache::Dep::Obsoletes); + + PyModule_AddIntConstant(Module,"PriImportant",pkgCache::State::Important); + PyModule_AddIntConstant(Module,"PriRequired",pkgCache::State::Required); + PyModule_AddIntConstant(Module,"PriStandard",pkgCache::State::Standard); + PyModule_AddIntConstant(Module,"PriOptional",pkgCache::State::Optional); + PyModule_AddIntConstant(Module,"PriExtra",pkgCache::State::Extra); + + PyModule_AddIntConstant(Module,"CurStateNotInstalled",pkgCache::State::NotInstalled); + PyModule_AddIntConstant(Module,"CurStateUnPacked",pkgCache::State::UnPacked); + PyModule_AddIntConstant(Module,"CurStateHalfConfigured",pkgCache::State::HalfConfigured); + PyModule_AddIntConstant(Module,"CurStateHalfInstalled",pkgCache::State::HalfInstalled); + PyModule_AddIntConstant(Module,"CurStateConfigFiles",pkgCache::State::ConfigFiles); + PyModule_AddIntConstant(Module,"CurStateInstalled",pkgCache::State::Installed); + + PyModule_AddIntConstant(Module,"SelStateUnknown",pkgCache::State::Unknown); + PyModule_AddIntConstant(Module,"SelStateInstall",pkgCache::State::Install); + PyModule_AddIntConstant(Module,"SelStateHold",pkgCache::State::Hold); + PyModule_AddIntConstant(Module,"SelStateDeInstall",pkgCache::State::DeInstall); + PyModule_AddIntConstant(Module,"SelStatePurge",pkgCache::State::Purge); + + PyModule_AddIntConstant(Module,"InstStateOk",pkgCache::State::Ok); + PyModule_AddIntConstant(Module,"InstStateReInstReq",pkgCache::State::ReInstReq); + PyModule_AddIntConstant(Module,"InstStateHold",pkgCache::State::Hold); + PyModule_AddIntConstant(Module,"InstStateHoldReInstReq",pkgCache::State::HoldReInstReq); #ifdef COMPAT_0_7 - AddInt(Dict,"_COMPAT_0_7",1); + PyModule_AddIntConstant(Module,"_COMPAT_0_7",1); #else - AddInt(Dict,"_COMPAT_0_7",0); + PyModule_AddIntConstant(Module,"_COMPAT_0_7",0); #endif #if PY_MAJOR_VERSION >= 3 return Module; -- cgit v1.2.3 From 45cdd4f2c6b04bfdfd37ef0e1a6358b29680afb8 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Sun, 19 Apr 2009 15:17:32 +0200 Subject: * python/*.cc: Export all types and add a __new__() method to them. Some names may be changed before the release, but this is a good draft. --- python/acquire.cc | 119 ++++++++++++++++++++++++++++++++-------- python/apt_pkgmodule.cc | 49 +++++++++++++++++ python/apt_pkgmodule.h | 1 + python/cache.cc | 125 ++++++++++++++++++++++++------------------ python/cdrom.cc | 38 +++++++++---- python/configuration.cc | 23 ++++++-- python/depcache.cc | 140 +++++++++++++++++++++++++++++++++--------------- python/indexfile.cc | 2 +- python/metaindex.cc | 2 +- python/pkgmanager.cc | 52 +++++++++++------- python/pkgrecords.cc | 31 ++++++++--- python/pkgsrcrecords.cc | 18 ++++++- python/sourcelist.cc | 18 ++++++- python/tag.cc | 75 ++++++++++++++++++++------ 14 files changed, 519 insertions(+), 174 deletions(-) (limited to 'python') diff --git a/python/acquire.cc b/python/acquire.cc index abd3884d..1cdf0cb9 100644 --- a/python/acquire.cc +++ b/python/acquire.cc @@ -194,13 +194,41 @@ static PyGetSetDef PkgAcquireGetSet[] = { {} }; +static PyObject *PkgAcquireNew(PyTypeObject *type,PyObject *Args,PyObject *kwds) { + pkgAcquire *fetcher; + + PyObject *pyFetchProgressInst = NULL; + static char *kwlist[] = {"progress", 0}; + if (PyArg_ParseTupleAndKeywords(Args,kwds,"|O",kwlist,&pyFetchProgressInst) == 0) + return 0; + + if (pyFetchProgressInst != NULL) { + // FIXME: memleak? + PyFetchProgress *progress = new PyFetchProgress(); + progress->setCallbackInst(pyFetchProgressInst); + fetcher = new pkgAcquire(progress); + } else { + fetcher = new pkgAcquire(); + } + + CppPyObject *FetcherObj = + CppPyObject_NEW(type, fetcher); + + return FetcherObj; +} + +static const char *doc_PkgAcquire = "Acquire(progress) -> Acquire() object.\n\n" + "Create a new acquire object. The parameter *progress* can be used to\n" + "specify a apt.progress.FetchProgress() object, which will display the\n" + "progress of the fetching."; + PyTypeObject PkgAcquireType = { PyObject_HEAD_INIT(&PyType_Type) #if PY_MAJOR_VERSION < 3 0, // ob_size #endif - "Acquire", // tp_name + "apt_pkg.Acquire", // tp_name sizeof(CppPyObject), // tp_basicsize 0, // tp_itemsize // Methods @@ -220,7 +248,7 @@ PyTypeObject PkgAcquireType = 0, // tp_setattro 0, // tp_as_buffer Py_TPFLAGS_DEFAULT, // tp_flags - "pkgAcquire Object", // tp_doc + doc_PkgAcquire, // tp_doc 0, // tp_traverse 0, // tp_clear 0, // tp_richcompare @@ -230,38 +258,66 @@ PyTypeObject PkgAcquireType = PkgAcquireMethods, // tp_methods 0, // tp_members PkgAcquireGetSet, // tp_getset + 0, // tp_base + 0, // tp_dict + 0, // tp_descr_get + 0, // tp_descr_set + 0, // tp_dictoffset + 0, // tp_init + 0, // tp_alloc + PkgAcquireNew, // tp_new }; + PyObject *GetAcquire(PyObject *Self,PyObject *Args) { - pkgAcquire *fetcher; + return PkgAcquireNew(&PkgAcquireType,Args,0); +} - PyObject *pyFetchProgressInst = NULL; - if (PyArg_ParseTuple(Args,"|O",&pyFetchProgressInst) == 0) - return 0; +static PyObject *PkgAcquireFileNew(PyTypeObject *type, PyObject *Args, PyObject * kwds) +{ + PyObject *pyfetcher; + char *uri, *md5, *descr, *shortDescr, *destDir, *destFile; + int size = 0; + uri = md5 = descr = shortDescr = destDir = destFile = ""; - if (pyFetchProgressInst != NULL) { - // FIXME: memleak? - PyFetchProgress *progress = new PyFetchProgress(); - progress->setCallbackInst(pyFetchProgressInst); - fetcher = new pkgAcquire(progress); - } else { - fetcher = new pkgAcquire(); - } + char * kwlist[] = {"owner","uri", "md5", "size", "descr", "shortdescr", + "destdir", "destfile", NULL}; - CppPyObject *FetcherObj = - CppPyObject_NEW(&PkgAcquireType, fetcher); + if (PyArg_ParseTupleAndKeywords(Args, kwds, "O!s|sissss", kwlist, + &PkgAcquireType, &pyfetcher, &uri, &md5, + &size, &descr, &shortDescr, &destDir, &destFile) == 0) + return 0; - return FetcherObj; + pkgAcquire *fetcher = GetCpp(pyfetcher); + pkgAcqFile *af = new pkgAcqFile(fetcher, // owner + uri, // uri + md5, // md5 + size, // size + descr, // descr + shortDescr, + destDir, + destFile); // short-desc + CppPyObject *AcqFileObj = CppPyObject_NEW(type); + AcqFileObj->Object = af; + + return AcqFileObj; } + +static const char *doc_PkgAcquireFile = + "AcquireFile(owner, uri[, md5, size, descr, short_descr, dest_dir," + "dest_file]) -> New AcquireFile() object\n\n" + "The parameter *owner* refers to an apt_pkg.Acquire() object. You can use\n" + "*destdir* OR *destfile* to specify the destination directory/file."; + PyTypeObject PkgAcquireFileType = { PyObject_HEAD_INIT(&PyType_Type) #if PY_MAJOR_VERSION < 3 0, // ob_size #endif - "pkgAcquireFile", // tp_name + "apt_pkg.AcquireFile", // tp_name sizeof(CppPyObject),// tp_basicsize 0, // tp_itemsize // Methods @@ -275,6 +331,30 @@ PyTypeObject PkgAcquireFileType = 0, // tp_as_sequence 0, // tp_as_mapping 0, // tp_hash + 0, // tp_call + 0, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + Py_TPFLAGS_DEFAULT, // tp_flags + doc_PkgAcquireFile, // tp_doc + 0, // tp_traverse + 0, // tp_clear + 0, // tp_richcompare + 0, // tp_weaklistoffset + 0, // tp_iter + 0, // tp_iternext + 0, // tp_methods + 0, // tp_members + 0, // tp_getset + 0, // tp_base + 0, // tp_dict + 0, // tp_descr_get + 0, // tp_descr_set + 0, // tp_dictoffset + 0, // tp_init + 0, // tp_alloc + PkgAcquireFileNew, // tp_new }; char *doc_GetPkgAcqFile = @@ -308,6 +388,3 @@ PyObject *GetPkgAcqFile(PyObject *Self, PyObject *Args, PyObject * kwds) return AcqFileObj; } - - - /*}}}*/ diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index 0fcf1f29..a54b3922 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -385,14 +385,18 @@ static PyObject *PkgSystemUnLock(PyObject *Self,PyObject *Args) static PyMethodDef methods[] = { // Constructors + #ifdef COMPAT_0_7 {"newConfiguration",newConfiguration,METH_VARARGS,doc_newConfiguration}, + #endif {"init",Init,METH_VARARGS,doc_Init}, {"InitConfig",InitConfig,METH_VARARGS,doc_InitConfig}, {"InitSystem",InitSystem,METH_VARARGS,doc_InitSystem}, // Tag File + #ifdef COMPAT_0_7 {"ParseSection",ParseSection,METH_VARARGS,doc_ParseSection}, {"ParseTagFile",ParseTagFile,METH_VARARGS,doc_ParseTagFile}, + #endif {"RewriteSection",RewriteSection,METH_VARARGS,doc_RewriteSection}, // Locking @@ -433,6 +437,7 @@ static PyMethodDef methods[] = {"StrToTime",StrStrToTime,METH_VARARGS,"StrToTime(String) -> Int"}, // Cache + #ifdef COMPAT_0_7 {"GetCache",TmpGetCache,METH_VARARGS,"GetCache() -> PkgCache"}, {"GetDepCache",GetDepCache,METH_VARARGS,"GetDepCache(Cache) -> DepCache"}, {"GetPkgRecords",GetPkgRecords,METH_VARARGS,"GetPkgRecords(Cache) -> PkgRecords"}, @@ -452,11 +457,16 @@ static PyMethodDef methods[] = // PkgManager {"GetPackageManager",GetPkgManager,METH_VARARGS,"GetPackageManager(DepCache) -> PackageManager"}, + #endif {} }; +#define ADDTYPE(mod,name,type) { Py_INCREF(type); \ + PyModule_AddObject(mod,name,(PyObject *)type); } + + #if PY_MAJOR_VERSION >= 3 struct module_state { PyObject *error; @@ -527,6 +537,45 @@ extern "C" void initapt_pkg() Config->Object = _config; PyModule_AddObject(Module,"Config",Config); + // Add our classes. + /* ============================ tag.cc ============================ */ + ADDTYPE(Module,"TagSection",&TagSecType); + ADDTYPE(Module,"TagFile",&TagFileType); + /* ============================ acquire.cc ============================ */ + ADDTYPE(Module,"Acquire",&PkgAcquireType); + ADDTYPE(Module,"AcquireFile",&PkgAcquireFileType); + ADDTYPE(Module,"AcquireItem",&AcquireItemType); // NO __new__() + /* ============================ cache.cc ============================ */ + ADDTYPE(Module,"Cache",&PkgCacheType); + ADDTYPE(Module,"Dependency",&DependencyType); // NO __new__() + ADDTYPE(Module,"Description",&DescriptionType); // NO __new__() + ADDTYPE(Module,"PackageFile",&PackageFileType); // NO __new__() + //ADDTYPE(Module,"PackageList",&PkgListType); // NO __new__(), internal + //ADDTYPE(Module,"DependencyList",&RDepListType); // NO __new__(), internal + ADDTYPE(Module,"Package",&PackageType); // NO __new__() + ADDTYPE(Module,"Version",&VersionType); // NO __new__() + /* ============================ cdrom.cc ============================ */ + ADDTYPE(Module,"Cdrom",&PkgCdromType); + /* ========================= configuration.cc ========================= */ + ADDTYPE(Module,"Configuration",&ConfigurationType); + //ADDTYPE(Module,"ConfigurationSub",&ConfigurationSubType); // NO __new__() + //ADDTYPE(Module,"ConfigurationPtr",&ConfigurationPtrType); // NO __new__() + /* ========================= depcache.cc ========================= */ + ADDTYPE(Module,"ActionGroup",&PkgActionGroupType); + ADDTYPE(Module,"DepCache",&PkgDepCacheType); + ADDTYPE(Module,"ProblemResolver",&PkgProblemResolverType); + /* ========================= indexfile.cc ========================= */ + ADDTYPE(Module,"PackageIndexFile",&PackageIndexFileType); // NO __new__() + /* ========================= metaindex.cc ========================= */ + ADDTYPE(Module,"MetaIndex",&MetaIndexType); // NO __new__() + /* ========================= pkgmanager.cc ========================= */ + ADDTYPE(Module,"PackageManager",&PkgManagerType); + /* ========================= pkgrecords.cc ========================= */ + ADDTYPE(Module,"PackageRecords",&PkgRecordsType); + /* ========================= pkgsrcrecords.cc ========================= */ + ADDTYPE(Module,"SourceRecords",&PkgSrcRecordsType); + /* ========================= sourcelist.cc ========================= */ + ADDTYPE(Module,"SourceList",&PkgSourceListType); // Tag file constants PyModule_AddObject(Module,"RewritePackageOrder", CharCharToList(TFRewritePackageOrder)); diff --git a/python/apt_pkgmodule.h b/python/apt_pkgmodule.h index 424c4788..f7ef63c2 100644 --- a/python/apt_pkgmodule.h +++ b/python/apt_pkgmodule.h @@ -80,6 +80,7 @@ PyObject *GetCdrom(PyObject *Self,PyObject *Args); // acquire extern PyTypeObject AcquireItemType; extern PyTypeObject PkgAcquireType; +extern PyTypeObject PkgAcquireFileType; extern char *doc_GetPkgAcqFile; PyObject *GetAcquire(PyObject *Self,PyObject *Args); PyObject *GetPkgAcqFile(PyObject *Self, PyObject *Args, PyObject *kwds); diff --git a/python/cache.cc b/python/cache.cc index 92e064b2..0862cd77 100644 --- a/python/cache.cc +++ b/python/cache.cc @@ -235,6 +235,61 @@ void PkgCacheFileDealloc(PyObject *Self) CppOwnedDealloc(Self); } +static PyObject *PkgCacheNew(PyTypeObject *type,PyObject *Args,PyObject *kwds) +{ + PyObject *pyCallbackInst = 0; + static char *kwlist[] = {"progress", 0}; + if (PyArg_ParseTupleAndKeywords (Args, kwds, "|O", kwlist, &pyCallbackInst) == 0) + return 0; + + if (_system == 0) { + PyErr_SetString(PyExc_ValueError,"_system not initialized"); + return 0; + } + + pkgCacheFile *Cache = new pkgCacheFile(); + + if(pyCallbackInst != 0) { + // sanity check for the progress object, see #497049 + if (PyObject_HasAttrString(pyCallbackInst, "done") != true) { + PyErr_SetString(PyExc_ValueError, + "OpProgress object must implement done()"); + return 0; + } + if (PyObject_HasAttrString(pyCallbackInst, "update") != true) { + PyErr_SetString(PyExc_ValueError, + "OpProgress object must implement update()"); + return 0; + } + PyOpProgress progress; + progress.setCallbackInst(pyCallbackInst); + if (Cache->Open(progress,false) == false) + return HandleErrors(); + } + else { + OpTextProgress Prog; + if (Cache->Open(Prog,false) == false) + return HandleErrors(); + } + + CppOwnedPyObject *CacheFileObj = + CppOwnedPyObject_NEW(0,&PkgCacheFileType, Cache); + + CppOwnedPyObject *CacheObj = + CppOwnedPyObject_NEW(CacheFileObj,type, + (pkgCache *)(*Cache)); + + //Py_DECREF(CacheFileObj); + return CacheObj; +} + +static const char *doc_PkgCache = "Cache([progress]) -> Cache() object.\n\n" + "The cache provides access to the packages and other stuff.\n\n" + "The optional parameter *progress* can be used to specify an \n" + "apt.progress.OpProgress() object (or similar) which displays\n" + "the opening progress.\n\n" + "If not specified, the progress is displayed in simple text form."; + static PyMappingMethods CacheMap = {0,CacheMapOp,0}; PyTypeObject PkgCacheType = { @@ -242,7 +297,7 @@ PyTypeObject PkgCacheType = #if PY_MAJOR_VERSION < 3 0, // ob_size #endif - "pkgCache", // tp_name + "apt_pkg.Cache", // tp_name sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize // Methods @@ -262,7 +317,7 @@ PyTypeObject PkgCacheType = 0, // tp_setattro 0, // tp_as_buffer Py_TPFLAGS_DEFAULT , // tp_flags - "Cache Object", // tp_doc + doc_PkgCache, // tp_doc 0, // tp_traverse 0, // tp_clear 0, // tp_richcompare @@ -272,6 +327,14 @@ PyTypeObject PkgCacheType = PkgCacheMethods, // tp_methods 0, // tp_members PkgCacheGetSet, // tp_getset + 0, // tp_base + 0, // tp_dict + 0, // tp_descr_get + 0, // tp_descr_set + 0, // tp_dictoffset + 0, // tp_init + 0, // tp_alloc + PkgCacheNew, // tp_new }; /*}}}*/ // PkgCacheFile Class /*{{{*/ @@ -352,7 +415,7 @@ PyTypeObject PkgListType = #if PY_MAJOR_VERSION < 3 0, // ob_size #endif - "pkgCache::PkgIterator", // tp_name + "apt_pkg.PackageList", // tp_name sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize // Methods @@ -452,7 +515,7 @@ PyTypeObject PackageType = #if PY_MAJOR_VERSION < 3 0, // ob_size #endif - "pkgCache::Package", // tp_name + "apt_pkg.Package", // tp_name sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize // Methods @@ -539,7 +602,7 @@ PyTypeObject DescriptionType = #if PY_MAJOR_VERSION < 3 0, // ob_size #endif - "pkgCache::DescIterator", // tp_name + "apt_pkg.Description", // tp_name sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize // Methods @@ -743,7 +806,7 @@ PyTypeObject VersionType = #if PY_MAJOR_VERSION < 3 0, // ob_size #endif - "pkgCache::VerIterator", // tp_name + "apt_pkg.Version", // tp_name sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize // Methods @@ -820,7 +883,7 @@ PyTypeObject PackageFileType = #if PY_MAJOR_VERSION < 3 0, // ob_size #endif - "pkgCache::PkgFileIterator", // tp_name + "apt_pkg.PackageFile", // tp_name sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize // Methods @@ -968,7 +1031,7 @@ PyTypeObject DependencyType = #if PY_MAJOR_VERSION < 3 0, // ob_size #endif - "pkgCache::DepIterator", // tp_name + "apt_pkg.Dependency", // tp_name sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize // Methods @@ -1056,7 +1119,7 @@ PyTypeObject RDepListType = #if PY_MAJOR_VERSION < 3 0, // ob_size #endif - "pkgCache::DepIterator", // tp_name + "apt_pkg.DependencyList", // tp_name sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize // Methods @@ -1078,47 +1141,5 @@ PyTypeObject RDepListType = PyObject *TmpGetCache(PyObject *Self,PyObject *Args) { - PyObject *pyCallbackInst = 0; - if (PyArg_ParseTuple(Args, "|O", &pyCallbackInst) == 0) - return 0; - - if (_system == 0) { - PyErr_SetString(PyExc_ValueError,"_system not initialized"); - return 0; - } - - pkgCacheFile *Cache = new pkgCacheFile(); - - if(pyCallbackInst != 0) { - // sanity check for the progress object, see #497049 - if (PyObject_HasAttrString(pyCallbackInst, "done") != true) { - PyErr_SetString(PyExc_ValueError, - "OpProgress object must implement done()"); - return 0; - } - if (PyObject_HasAttrString(pyCallbackInst, "update") != true) { - PyErr_SetString(PyExc_ValueError, - "OpProgress object must implement update()"); - return 0; - } - PyOpProgress progress; - progress.setCallbackInst(pyCallbackInst); - if (Cache->Open(progress,false) == false) - return HandleErrors(); - } - else { - OpTextProgress Prog; - if (Cache->Open(Prog,false) == false) - return HandleErrors(); - } - - CppOwnedPyObject *CacheFileObj = - CppOwnedPyObject_NEW(0,&PkgCacheFileType, Cache); - - CppOwnedPyObject *CacheObj = - CppOwnedPyObject_NEW(CacheFileObj,&PkgCacheType, - (pkgCache *)(*Cache)); - - //Py_DECREF(CacheFileObj); - return CacheObj; + return PkgCacheNew(&PkgCacheType,Args,0); } diff --git a/python/cdrom.cc b/python/cdrom.cc index b3a38438..bf94a390 100644 --- a/python/cdrom.cc +++ b/python/cdrom.cc @@ -58,19 +58,34 @@ static PyObject *PkgCdromIdent(PyObject *Self,PyObject *Args) static PyMethodDef PkgCdromMethods[] = { - {"Add",PkgCdromAdd,METH_VARARGS,"Add a cdrom"}, - {"Ident",PkgCdromIdent,METH_VARARGS,"Ident a cdrom"}, + {"Add",PkgCdromAdd,METH_VARARGS,"Add(progress) -> Add a cdrom"}, + {"Ident",PkgCdromIdent,METH_VARARGS,"Ident(progress) -> Ident a cdrom"}, {} }; +static PyObject *PkgCdromNew(PyTypeObject *type,PyObject *Args,PyObject *kwds) +{ + pkgCdrom *cdrom = new pkgCdrom(); + + static char *kwlist[] = {}; + if (PyArg_ParseTupleAndKeywords(Args,kwds,"",kwlist) == 0) + return 0; + + CppOwnedPyObject *CdromObj = + CppOwnedPyObject_NEW(0,type, *cdrom); + + return CdromObj; +} + + PyTypeObject PkgCdromType = { PyObject_HEAD_INIT(&PyType_Type) #if PY_MAJOR_VERSION < 3 0, // ob_size #endif - "Cdrom", // tp_name + "apt_pkg.Cdrom", // tp_name sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize // Methods @@ -98,16 +113,21 @@ PyTypeObject PkgCdromType = 0, // tp_iter 0, // tp_iternext PkgCdromMethods, // tp_methods + 0, // tp_members + 0, // tp_getset + 0, // tp_base + 0, // tp_dict + 0, // tp_descr_get + 0, // tp_descr_set + 0, // tp_dictoffset + 0, // tp_init + 0, // tp_alloc + PkgCdromNew, // tp_new }; PyObject *GetCdrom(PyObject *Self,PyObject *Args) { - pkgCdrom *cdrom = new pkgCdrom(); - - CppOwnedPyObject *CdromObj = - CppOwnedPyObject_NEW(0,&PkgCdromType, *cdrom); - - return CdromObj; + return PkgCdromNew(&PkgCdromType,Args,0); } diff --git a/python/configuration.cc b/python/configuration.cc index eaac48ec..abbed6d9 100644 --- a/python/configuration.cc +++ b/python/configuration.cc @@ -475,6 +475,13 @@ static PyMethodDef CnfMethods[] = {} }; +static PyObject *CnfNew(PyTypeObject *type, PyObject *args, PyObject *kwds) { + static char *kwlist[] = {}; + if (PyArg_ParseTupleAndKeywords(args,kwds,"",kwlist) == 0) + return 0; + return CppPyObject_NEW(type); +} + // Type for a Normal Configuration object static PySequenceMethods ConfigurationSeq = {0,0,0,0,0,0,0,CnfContains,0,0}; static PyMappingMethods ConfigurationMap = {0,CnfMap,CnfMapSet}; @@ -484,7 +491,7 @@ PyTypeObject ConfigurationType = #if PY_MAJOR_VERSION < 3 0, // ob_size #endif - "Configuration", // tp_name + "apt_pkg.Configuration", // tp_name sizeof(CppPyObject), // tp_basicsize 0, // tp_itemsize // Methods @@ -512,6 +519,16 @@ PyTypeObject ConfigurationType = 0, // tp_iter 0, // tp_iternext CnfMethods, // tp_methods + 0, // tp_members + 0, // tp_getset + 0, // tp_base + 0, // tp_dict + 0, // tp_descr_get + 0, // tp_descr_set + 0, // tp_dictoffset + 0, // tp_init + 0, // tp_alloc + CnfNew, // tp_new }; PyTypeObject ConfigurationPtrType = @@ -520,7 +537,7 @@ PyTypeObject ConfigurationPtrType = #if PY_MAJOR_VERSION < 3 0, // ob_size #endif - "ConfigurationPtr", // tp_name + "apt_pkg.ConfigurationPtr", // tp_name sizeof(CppPyObject), // tp_basicsize 0, // tp_itemsize // Methods @@ -556,7 +573,7 @@ PyTypeObject ConfigurationSubType = #if PY_MAJOR_VERSION < 3 0, // ob_size #endif - "ConfigurationSub", // tp_name + "apt_pkg.ConfigurationSub", // tp_name sizeof(SubConfiguration), // tp_basicsize 0, // tp_itemsize // Methods diff --git a/python/depcache.cc b/python/depcache.cc index 1c9eeff7..0cadee64 100644 --- a/python/depcache.cc +++ b/python/depcache.cc @@ -591,13 +591,39 @@ static PyGetSetDef PkgDepCacheGetSet[] = { {} }; +static PyObject *PkgDepCacheNew(PyTypeObject *type,PyObject *Args,PyObject *kwds) +{ + PyObject *Owner; + static char *kwlist[] = {"cache", 0}; + if (PyArg_ParseTupleAndKeywords(Args,kwds,"O!",kwlist,&PkgCacheType, + &Owner) == 0) + return 0; + + + // the owner of the Python cache object is a cachefile object, get it + PyObject *CacheFilePy = GetOwner(Owner); + // get the pkgCacheFile from the cachefile + pkgCacheFile *CacheF = GetCpp(CacheFilePy); + // and now the depcache + pkgDepCache *depcache = (pkgDepCache *)(*CacheF); + + CppOwnedPyObject *DepCachePyObj; + DepCachePyObj = CppOwnedPyObject_NEW(Owner,type,depcache); + HandleErrors(DepCachePyObj); + + return DepCachePyObj; +} + +static const char *doc_PkgDepCache = "DepCache(cache) -> DepCache() object\n\n" + "A DepCache() holds extra information on the state of the packages.\n\n" + "The parameter *cache* refers to an apt_pkg.Cache() object."; PyTypeObject PkgDepCacheType = { PyObject_HEAD_INIT(&PyType_Type) #if PY_MAJOR_VERSION < 3 0, // ob_size #endif - "pkgDepCache", // tp_name + "apt_pkg.DepCache", // tp_name sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize // Methods @@ -617,7 +643,7 @@ PyTypeObject PkgDepCacheType = 0, // tp_setattro 0, // tp_as_buffer Py_TPFLAGS_DEFAULT, // tp_flags - "pkgDepCache Object", // tp_doc + doc_PkgDepCache, // tp_doc 0, // tp_traverse 0, // tp_clear 0, // tp_richcompare @@ -627,30 +653,20 @@ PyTypeObject PkgDepCacheType = PkgDepCacheMethods, // tp_methods 0, // tp_members PkgDepCacheGetSet, // tp_getset + 0, // tp_base + 0, // tp_dict + 0, // tp_descr_get + 0, // tp_descr_set + 0, // tp_dictoffset + 0, // tp_init + 0, // tp_alloc + PkgDepCacheNew, // tp_new }; PyObject *GetDepCache(PyObject *Self,PyObject *Args) { - PyObject *Owner; - if (PyArg_ParseTuple(Args,"O!",&PkgCacheType,&Owner) == 0) - return 0; - - - // the owner of the Python cache object is a cachefile object, get it - PyObject *CacheFilePy = GetOwner(Owner); - // get the pkgCacheFile from the cachefile - pkgCacheFile *CacheF = GetCpp(CacheFilePy); - // and now the depcache - pkgDepCache *depcache = (pkgDepCache *)(*CacheF); - - CppOwnedPyObject *DepCachePyObj; - DepCachePyObj = CppOwnedPyObject_NEW(Owner, - &PkgDepCacheType, - depcache); - HandleErrors(DepCachePyObj); - - return DepCachePyObj; + return PkgDepCacheNew(&PkgDepCacheType,Args,0); } @@ -661,26 +677,28 @@ PyObject *GetDepCache(PyObject *Self,PyObject *Args) // pkgProblemResolver Class /*{{{*/ // --------------------------------------------------------------------- - - -PyObject *GetPkgProblemResolver(PyObject *Self,PyObject *Args) +static PyObject *PkgProblemResolverNew(PyTypeObject *type,PyObject *Args,PyObject *kwds) { PyObject *Owner; - if (PyArg_ParseTuple(Args,"O!",&PkgDepCacheType,&Owner) == 0) + static char *kwlist[] = {"depcache",0}; + if (PyArg_ParseTupleAndKeywords(Args,kwds,"O!",kwlist,&PkgDepCacheType, + &Owner) == 0) return 0; pkgDepCache *depcache = GetCpp(Owner); pkgProblemResolver *fixer = new pkgProblemResolver(depcache); CppOwnedPyObject *PkgProblemResolverPyObj; PkgProblemResolverPyObj = CppOwnedPyObject_NEW(Owner, - &PkgProblemResolverType, + type, fixer); HandleErrors(PkgProblemResolverPyObj); return PkgProblemResolverPyObj; - } +PyObject *GetPkgProblemResolver(PyObject *Self,PyObject *Args) { + return PkgProblemResolverNew(&PkgProblemResolverType,Args,0); +} static PyObject *PkgProblemResolverResolve(PyObject *Self,PyObject *Args) { @@ -778,7 +796,7 @@ PyTypeObject PkgProblemResolverType = #if PY_MAJOR_VERSION < 3 0, // ob_size #endif - "pkgProblemResolver", // tp_name + "apt_pkg.ProblemResolver", // tp_name sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize // Methods @@ -806,6 +824,16 @@ PyTypeObject PkgProblemResolverType = 0, // tp_iter 0, // tp_iternext PkgProblemResolverMethods, // tp_methods + 0, // tp_members + 0, // tp_getset + 0, // tp_base + 0, // tp_dict + 0, // tp_descr_get + 0, // tp_descr_set + 0, // tp_dictoffset + 0, // tp_init + 0, // tp_alloc + PkgProblemResolverNew, // tp_new }; /*}}}*/ @@ -830,13 +858,40 @@ static PyMethodDef PkgActionGroupMethods[] = {} }; +static PyObject *PkgActionGroupNew(PyTypeObject *type,PyObject *Args,PyObject *kwds) +{ + PyObject *Owner; + static char *kwlist[] = {"depcache", 0}; + if (PyArg_ParseTupleAndKeywords(Args,kwds,"O!",kwlist,&PkgDepCacheType, + &Owner) == 0) + return 0; + + pkgDepCache *depcache = GetCpp(Owner); + pkgDepCache::ActionGroup *group = new pkgDepCache::ActionGroup(*depcache); + CppOwnedPyObject *PkgActionGroupPyObj; + PkgActionGroupPyObj = CppOwnedPyObject_NEW(Owner, + type, + group); + HandleErrors(PkgActionGroupPyObj); + + return PkgActionGroupPyObj; + +} + +static const char *doc_PkgActionGroup = "ActionGroup(depcache)\n\n" + "Create a new ActionGroup() object. ActionGroups disable certain cleanup\n" + "actions, so modifying many packages is much faster.\n\n" + "Creating an ActionGroup() makes it active, use release() to disable it\n" + "again.\n\n" + "The parameter *depcache* refers to an apt_pkg.DepCache() object."; + PyTypeObject PkgActionGroupType = { PyObject_HEAD_INIT(&PyType_Type) #if PY_MAJOR_VERSION < 3 0, // ob_size #endif - "pkgActionGroup", // tp_name + "apt_pkg.ActionGroup", // tp_name sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize // Methods @@ -856,7 +911,7 @@ PyTypeObject PkgActionGroupType = 0, // tp_setattro 0, // tp_as_buffer Py_TPFLAGS_DEFAULT, // tp_flags - "ActionGroup Object", // tp_doc + doc_PkgActionGroup, // tp_doc 0, // tp_traverse 0, // tp_clear 0, // tp_richcompare @@ -864,24 +919,21 @@ PyTypeObject PkgActionGroupType = 0, // tp_iter 0, // tp_iternext PkgActionGroupMethods, // tp_methods + 0, // tp_members + 0, // tp_getset + 0, // tp_base + 0, // tp_dict + 0, // tp_descr_get + 0, // tp_descr_set + 0, // tp_dictoffset + 0, // tp_init + 0, // tp_alloc + PkgActionGroupNew, // tp_new }; PyObject *GetPkgActionGroup(PyObject *Self,PyObject *Args) { - PyObject *Owner; - if (PyArg_ParseTuple(Args,"O!",&PkgDepCacheType,&Owner) == 0) - return 0; - - pkgDepCache *depcache = GetCpp(Owner); - pkgDepCache::ActionGroup *group = new pkgDepCache::ActionGroup(*depcache); - CppOwnedPyObject *PkgActionGroupPyObj; - PkgActionGroupPyObj = CppOwnedPyObject_NEW(Owner, - &PkgActionGroupType, - group); - HandleErrors(PkgActionGroupPyObj); - - return PkgActionGroupPyObj; - + return PkgActionGroupNew(&PkgActionGroupType,Args,0); } diff --git a/python/indexfile.cc b/python/indexfile.cc index bb40cdd0..600dc853 100644 --- a/python/indexfile.cc +++ b/python/indexfile.cc @@ -84,7 +84,7 @@ PyTypeObject PackageIndexFileType = #if PY_MAJOR_VERSION < 3 0, // ob_size #endif - "pkgIndexFile", // tp_name + "apt_pkg.PackageIndexFile", // tp_name sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize // Methods diff --git a/python/metaindex.cc b/python/metaindex.cc index cbaeafbd..557aacd8 100644 --- a/python/metaindex.cc +++ b/python/metaindex.cc @@ -62,7 +62,7 @@ PyTypeObject MetaIndexType = #if PY_MAJOR_VERSION < 3 0, // ob_size #endif - "metaIndex", // tp_name + "apt_pkg.MetaIndex", // tp_name sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize // Methods diff --git a/python/pkgmanager.cc b/python/pkgmanager.cc index 8f56cddc..781acc8b 100644 --- a/python/pkgmanager.cc +++ b/python/pkgmanager.cc @@ -15,8 +15,32 @@ #include #include #include +#include +#include + #include +static PyObject *PkgManagerNew(PyTypeObject *type,PyObject *Args,PyObject *kwds) +{ + PyObject *Owner; + char *kwlist[] = {"depcache",0}; + if (PyArg_ParseTupleAndKeywords(Args,kwds,"O!",kwlist,&PkgDepCacheType, + &Owner) == 0) + return 0; + + pkgPackageManager *pm = _system->CreatePM(GetCpp(Owner)); + + CppPyObject *PkgManagerObj = + CppPyObject_NEW(type,pm); + + return PkgManagerObj; +} + +PyObject *GetPkgManager(PyObject *Self,PyObject *Args) +{ + return PkgManagerNew(&PkgManagerType,Args,0); +} + static PyObject *PkgManagerGetArchives(PyObject *Self,PyObject *Args) { @@ -98,7 +122,7 @@ PyTypeObject PkgManagerType = #if PY_MAJOR_VERSION < 3 0, // ob_size #endif - "PackageManager", // tp_name + "apt_pkg.PackageManager", // tp_name sizeof(CppPyObject), // tp_basicsize 0, // tp_itemsize // Methods @@ -128,26 +152,16 @@ PyTypeObject PkgManagerType = PkgManagerMethods, // tp_methods 0, // tp_members PkgManagerGetSet, // tp_getset + 0, // tp_base + 0, // tp_dict + 0, // tp_descr_get + 0, // tp_descr_set + 0, // tp_dictoffset + 0, // tp_init + 0, // tp_alloc + PkgManagerNew, // tp_new }; -#include -#include - -PyObject *GetPkgManager(PyObject *Self,PyObject *Args) -{ - PyObject *Owner; - if (PyArg_ParseTuple(Args,"O!",&PkgDepCacheType,&Owner) == 0) - return 0; - - pkgPackageManager *pm = _system->CreatePM(GetCpp(Owner)); - - CppPyObject *PkgManagerObj = - CppPyObject_NEW(&PkgManagerType,pm); - - return PkgManagerObj; -} - - /*}}}*/ diff --git a/python/pkgrecords.cc b/python/pkgrecords.cc index 978de6b7..1cccfce2 100644 --- a/python/pkgrecords.cc +++ b/python/pkgrecords.cc @@ -132,13 +132,25 @@ static PyGetSetDef PkgRecordsGetSet[] = { {} }; +static PyObject *PkgRecordsNew(PyTypeObject *type,PyObject *Args,PyObject *kwds) +{ + PyObject *Owner; + char *kwlist[] = {"cache",0}; + if (PyArg_ParseTupleAndKeywords(Args,kwds,"O!",kwlist,&PkgCacheType, + &Owner) == 0) + return 0; + + return HandleErrors(CppOwnedPyObject_NEW(Owner,type, + GetCpp(Owner))); +} + PyTypeObject PkgRecordsType = { PyObject_HEAD_INIT(&PyType_Type) #if PY_MAJOR_VERSION < 3 0, // ob_size #endif - "pkgRecords", // tp_name + "apt_pkg.PackageRecords", // tp_name sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize // Methods @@ -168,17 +180,22 @@ PyTypeObject PkgRecordsType = PkgRecordsMethods, // tp_methods 0, // tp_members PkgRecordsGetSet, // tp_getset + 0, // tp_base + 0, // tp_dict + 0, // tp_descr_get + 0, // tp_descr_set + 0, // tp_dictoffset + 0, // tp_init + 0, // tp_alloc + PkgRecordsNew, // tp_new }; /*}}}*/ + + PyObject *GetPkgRecords(PyObject *Self,PyObject *Args) { - PyObject *Owner; - if (PyArg_ParseTuple(Args,"O!",&PkgCacheType,&Owner) == 0) - return 0; - - return HandleErrors(CppOwnedPyObject_NEW(Owner,&PkgRecordsType, - GetCpp(Owner))); + return PkgRecordsNew(&PkgRecordsType,Args,0); } diff --git a/python/pkgsrcrecords.cc b/python/pkgsrcrecords.cc index 97667d7a..8b4dce3e 100644 --- a/python/pkgsrcrecords.cc +++ b/python/pkgsrcrecords.cc @@ -180,13 +180,21 @@ static PyGetSetDef PkgSrcRecordsGetSet[] = { {} }; +static PyObject *PkgSrcRecordsNew(PyTypeObject *type,PyObject *args,PyObject *kwds) { + char *kwlist[] = {0}; + if (PyArg_ParseTupleAndKeywords(args,kwds,"",kwlist) == 0) + return 0; + + return HandleErrors(CppPyObject_NEW(type)); +} + PyTypeObject PkgSrcRecordsType = { PyObject_HEAD_INIT(&PyType_Type) #if PY_MAJOR_VERSION < 3 0, // ob_size #endif - "pkgSrcRecords", // tp_name + "apt_pkg.SourceRecords", // tp_name sizeof(CppPyObject), // tp_basicsize 0, // tp_itemsize // Methods @@ -216,6 +224,14 @@ PyTypeObject PkgSrcRecordsType = PkgSrcRecordsMethods, // tp_methods 0, // tp_members PkgSrcRecordsGetSet, // tp_getset + 0, // tp_base + 0, // tp_dict + 0, // tp_descr_get + 0, // tp_descr_set + 0, // tp_dictoffset + 0, // tp_init + 0, // tp_alloc + PkgSrcRecordsNew, // tp_new }; /*}}}*/ diff --git a/python/sourcelist.cc b/python/sourcelist.cc index 48b3b7c8..15311e94 100644 --- a/python/sourcelist.cc +++ b/python/sourcelist.cc @@ -97,13 +97,21 @@ static PyGetSetDef PkgSourceListGetSet[] = { {} }; +static PyObject *PkgSourceListNew(PyTypeObject *type,PyObject *args,PyObject *kwds) +{ + char *kwlist[] = {0}; + if (PyArg_ParseTupleAndKeywords(args,kwds,"",kwlist) == 0) + return 0; + return CppPyObject_NEW(type,new pkgSourceList()); +} + PyTypeObject PkgSourceListType = { PyObject_HEAD_INIT(&PyType_Type) #if PY_MAJOR_VERSION < 3 0, // ob_size #endif - "pkgSourceList", // tp_name + "apt_pkg.SourceList", // tp_name sizeof(CppPyObject), // tp_basicsize 0, // tp_itemsize // Methods @@ -133,6 +141,14 @@ PyTypeObject PkgSourceListType = PkgSourceListMethods, // tp_methods 0, // tp_members PkgSourceListGetSet, // tp_getset + 0, // tp_base + 0, // tp_dict + 0, // tp_descr_get + 0, // tp_descr_set + 0, // tp_dictoffset + 0, // tp_init + 0, // tp_alloc + PkgSourceListNew, // tp_new }; PyObject *GetPkgSourceList(PyObject *Self,PyObject *Args) diff --git a/python/tag.cc b/python/tag.cc index 18d08580..007a6122 100644 --- a/python/tag.cc +++ b/python/tag.cc @@ -239,15 +239,14 @@ static PyObject *TagFileJump(PyObject *Self,PyObject *Args) /*}}}*/ // ParseSection - Parse a single section from a tag file /*{{{*/ // --------------------------------------------------------------------- -char *doc_ParseSection ="ParseSection(Text) -> SectionObject"; -PyObject *ParseSection(PyObject *self,PyObject *Args) -{ +static PyObject *TagSecNew(PyTypeObject *type,PyObject *Args,PyObject *kwds) { char *Data; - if (PyArg_ParseTuple(Args,"s",&Data) == 0) + static char *kwlist[] = {"text", 0}; + if (PyArg_ParseTupleAndKeywords(Args,kwds,"s",kwlist,&Data) == 0) return 0; // Create the object.. - TagSecData *New = PyObject_NEW(TagSecData,&TagSecType); + TagSecData *New = PyObject_NEW(TagSecData,type); new (&New->Object) pkgTagSection(); New->Data = new char[strlen(Data)+2]; snprintf(New->Data,strlen(Data)+2,"%s\n",Data); @@ -264,21 +263,28 @@ PyObject *ParseSection(PyObject *self,PyObject *Args) return New; } + +char *doc_ParseSection ="ParseSection(Text) -> TagSection() object. Deprecated."; +PyObject *ParseSection(PyObject *self,PyObject *Args) +{ + return TagSecNew(&TagSecType,Args,0); +} /*}}}*/ // ParseTagFile - Parse a tagd file /*{{{*/ // --------------------------------------------------------------------- /* This constructs the parser state. */ -char *doc_ParseTagFile = "ParseTagFile(File) -> TagFile"; -PyObject *ParseTagFile(PyObject *self,PyObject *Args) + +static PyObject *TagFileNew(PyTypeObject *type,PyObject *Args,PyObject *kwds) { PyObject *File; - if (PyArg_ParseTuple(Args,"O",&File) == 0) + static char *kwlist[] = {"file", 0}; + if (PyArg_ParseTupleAndKeywords(Args,kwds,"O",kwlist,&File) == 0) return 0; int fileno = PyObject_AsFileDescriptor(File); if (fileno == -1) return 0; - TagFileData *New = PyObject_NEW(TagFileData,&TagFileType); + TagFileData *New = PyObject_NEW(TagFileData,type); new (&New->Fd) FileFd(fileno,false); New->File = File; Py_INCREF(New->File); @@ -290,6 +296,10 @@ PyObject *ParseTagFile(PyObject *self,PyObject *Args) New->Section->Data = 0; return HandleErrors(New); +} +char *doc_ParseTagFile = "ParseTagFile(File) -> TagFile() object. Deprecated."; +PyObject *ParseTagFile(PyObject *self,PyObject *Args) { + return TagFileNew(&TagFileType,Args,0); } /*}}}*/ // RewriteSection - Rewrite a section.. /*{{{*/ @@ -381,13 +391,20 @@ static PyMethodDef TagSecMethods[] = PySequenceMethods TagSecSeqMeth = {0,0,0,0,0,0,0,TagSecContains,0,0}; PyMappingMethods TagSecMapMeth = {TagSecLength,TagSecMap,0}; + + +static const char *doc_TagSec = "TagSection(text) -> Create a new object.\n\n" + "TagSection() objects provide methods to access rfc822-style formatted\n" + "header sections, like those in debian/control or Packages files.\n\n" + "TagSection() behave like read-only dictionaries and also provide access\n" + "to the functions provided by the C++ class (e.g. Find)"; PyTypeObject TagSecType = { PyObject_HEAD_INIT(&PyType_Type) #if PY_MAJOR_VERSION < 3 0, // ob_size #endif - "TagSection", // tp_name + "apt_pkg.TagSection", // tp_name sizeof(TagSecData), // tp_basicsize 0, // tp_itemsize // Methods @@ -407,14 +424,24 @@ PyTypeObject TagSecType = 0, // tp_setattro 0, // tp_as_buffer Py_TPFLAGS_DEFAULT, // tp_flags - "TagSection Object", // tp_doc + doc_TagSec, // tp_doc 0, // tp_traverse 0, // tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset 0, // tp_iter 0, // tp_iternext - TagSecMethods // tp_methods + TagSecMethods, // tp_methods + 0, // tp_members + 0, // tp_getset + 0, // tp_base + 0, // tp_dict + 0, // tp_descr_get + 0, // tp_descr_set + 0, // tp_dictoffset + 0, // tp_init + 0, // tp_alloc + TagSecNew, // tp_new }; // Method table for the Tag File object @@ -440,6 +467,15 @@ static PyGetSetDef TagFileGetSet[] = { {} }; +static const char *doc_TagFile = "TagFile(file) -> TagFile() object. \n\n" + "TagFile() objects provide access to debian control files, which consists\n" + "of multiple RFC822-like formatted sections.\n\n" + "A file may consists of multiple sections, and you can use Step() to move\n" + "forward. The current TagSection() is available via the attribute section" + ".\n\n" + "The parameter *file* refers to an object providing a fileno() method or\n" + "a file descriptor (an integer)"; + // Type for a Tag File PyTypeObject TagFileType = { @@ -447,7 +483,7 @@ PyTypeObject TagFileType = #if PY_MAJOR_VERSION < 3 0, // ob_size #endif - "TagFile", // tp_name + "apt_pkg.TagFile", // tp_name sizeof(TagFileData), // tp_basicsize 0, // tp_itemsize // Methods @@ -467,7 +503,7 @@ PyTypeObject TagFileType = 0, // tp_setattro 0, // tp_as_buffer Py_TPFLAGS_DEFAULT, // tp_flags - "TagFile Object", // tp_doc + doc_TagFile, // tp_doc 0, // tp_traverse 0, // tp_clear 0, // tp_richcompare @@ -476,5 +512,14 @@ PyTypeObject TagFileType = 0, // tp_iternext TagFileMethods, // tp_methods 0, // tp_members - TagFileGetSet // tp_getset + TagFileGetSet, // tp_getset + 0, // tp_base + 0, // tp_dict + 0, // tp_descr_get + 0, // tp_descr_set + 0, // tp_dictoffset + 0, // tp_init + 0, // tp_alloc + TagFileNew, // tp_new + }; -- cgit v1.2.3 From a7026989dd1ea3b70cbfc80cf92077efb2f52ba3 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Sun, 19 Apr 2009 15:57:07 +0200 Subject: ActionGroups can be used as a context manager for the 'with' statement. --- debian/changelog | 1 + python/depcache.cc | 32 +++++++++++++++++++++++++++----- 2 files changed, 28 insertions(+), 5 deletions(-) (limited to 'python') diff --git a/debian/changelog b/debian/changelog index e8e14306..30d54a29 100644 --- a/debian/changelog +++ b/debian/changelog @@ -2,6 +2,7 @@ python-apt (0.7.91) UNRELEASED; urgency=low * Rename all methods,functions,attributes to conform to PEP 8 (Closes: #481061) * Where possible, derive apt.package.Record from collections.Mapping. + * ActionGroups can be used as a context manager for the 'with' statement. -- Julian Andres Klode Fri, 17 Apr 2009 17:48:27 +0200 diff --git a/python/depcache.cc b/python/depcache.cc index 0cadee64..70d5af4e 100644 --- a/python/depcache.cc +++ b/python/depcache.cc @@ -852,9 +852,24 @@ static PyObject *PkgActionGroupRelease(PyObject *Self,PyObject *Args) return HandleErrors(Py_None); } +static PyObject *PkgActionGroupEnter(PyObject *Self,PyObject *Args) { + if (PyArg_ParseTuple(Args,"") == 0) + return 0; + return Self; +} +static PyObject *PkgActionGroupExit(PyObject *Self,PyObject *Args) { + pkgDepCache::ActionGroup *ag = GetCpp(Self); + ag->release(); + Py_RETURN_FALSE; +} + static PyMethodDef PkgActionGroupMethods[] = { {"release", PkgActionGroupRelease, METH_VARARGS, "release()"}, + {"__exit__", PkgActionGroupExit, METH_VARARGS, "__exit__(...) -> " + "Release the action group, for 'with' statement."}, + {"__enter__", PkgActionGroupEnter, METH_VARARGS, "__enter__() -> " + "Enter, for the 'with' statement. Does nothing."}, {} }; @@ -879,11 +894,18 @@ static PyObject *PkgActionGroupNew(PyTypeObject *type,PyObject *Args,PyObject *k } static const char *doc_PkgActionGroup = "ActionGroup(depcache)\n\n" - "Create a new ActionGroup() object. ActionGroups disable certain cleanup\n" - "actions, so modifying many packages is much faster.\n\n" - "Creating an ActionGroup() makes it active, use release() to disable it\n" - "again.\n\n" - "The parameter *depcache* refers to an apt_pkg.DepCache() object."; + "Create a new ActionGroup() object. The parameter *depcache* refers to an\n" + "apt_pkg.DepCache() object.\n\n" + "ActionGroups disable certain cleanup actions, so modifying many packages\n" + "is much faster.\n\n" + "ActionGroup() can also be used with the 'with' statement, but be aware\n" + "that the ActionGroup() is active as soon as it is created, and not just\n" + "when entering the context. This means you can write::\n\n" + " with apt_pkg.ActionGroup(depcache):\n" + " depcache.markInstall(pkg)\n\n" + "Once the block of the with statement is left, the action group is \n" + "automatically released from the cache."; + PyTypeObject PkgActionGroupType = { -- cgit v1.2.3 From 55eaca76738417f719c1e3b66da94c7307308d74 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Fri, 24 Apr 2009 19:01:38 +0200 Subject: * python/*.cc: Fix build failures with python2.4-dbg. --- python/acquire.cc | 4 ++-- python/apt_pkgmodule.cc | 4 ++-- python/cache.cc | 2 +- python/depcache.cc | 4 ++-- python/tag.cc | 4 ++-- 5 files changed, 9 insertions(+), 9 deletions(-) (limited to 'python') diff --git a/python/acquire.cc b/python/acquire.cc index 1cdf0cb9..ccd3a479 100644 --- a/python/acquire.cc +++ b/python/acquire.cc @@ -217,7 +217,7 @@ static PyObject *PkgAcquireNew(PyTypeObject *type,PyObject *Args,PyObject *kwds) return FetcherObj; } -static const char *doc_PkgAcquire = "Acquire(progress) -> Acquire() object.\n\n" +static char *doc_PkgAcquire = "Acquire(progress) -> Acquire() object.\n\n" "Create a new acquire object. The parameter *progress* can be used to\n" "specify a apt.progress.FetchProgress() object, which will display the\n" "progress of the fetching."; @@ -305,7 +305,7 @@ static PyObject *PkgAcquireFileNew(PyTypeObject *type, PyObject *Args, PyObject } -static const char *doc_PkgAcquireFile = +static char *doc_PkgAcquireFile = "AcquireFile(owner, uri[, md5, size, descr, short_descr, dest_dir," "dest_file]) -> New AcquireFile() object\n\n" "The parameter *owner* refers to an apt_pkg.Acquire() object. You can use\n" diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index a54b3922..bdea5fae 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -584,8 +584,8 @@ extern "C" void initapt_pkg() CharCharToList(TFRewriteSourceOrder)); // Version.. - PyModule_AddStringConstant(Module,"Version",pkgVersion); - PyModule_AddStringConstant(Module,"LibVersion",pkgLibVersion); + PyModule_AddStringConstant(Module,"Version",(char *)pkgVersion); + PyModule_AddStringConstant(Module,"LibVersion",(char *)pkgLibVersion); PyModule_AddStringConstant(Module,"Date",__DATE__); PyModule_AddStringConstant(Module,"Time",__TIME__); diff --git a/python/cache.cc b/python/cache.cc index 0862cd77..f545a605 100644 --- a/python/cache.cc +++ b/python/cache.cc @@ -283,7 +283,7 @@ static PyObject *PkgCacheNew(PyTypeObject *type,PyObject *Args,PyObject *kwds) return CacheObj; } -static const char *doc_PkgCache = "Cache([progress]) -> Cache() object.\n\n" +static char *doc_PkgCache = "Cache([progress]) -> Cache() object.\n\n" "The cache provides access to the packages and other stuff.\n\n" "The optional parameter *progress* can be used to specify an \n" "apt.progress.OpProgress() object (or similar) which displays\n" diff --git a/python/depcache.cc b/python/depcache.cc index 70d5af4e..ef2240ce 100644 --- a/python/depcache.cc +++ b/python/depcache.cc @@ -614,7 +614,7 @@ static PyObject *PkgDepCacheNew(PyTypeObject *type,PyObject *Args,PyObject *kwds return DepCachePyObj; } -static const char *doc_PkgDepCache = "DepCache(cache) -> DepCache() object\n\n" +static char *doc_PkgDepCache = "DepCache(cache) -> DepCache() object\n\n" "A DepCache() holds extra information on the state of the packages.\n\n" "The parameter *cache* refers to an apt_pkg.Cache() object."; PyTypeObject PkgDepCacheType = @@ -893,7 +893,7 @@ static PyObject *PkgActionGroupNew(PyTypeObject *type,PyObject *Args,PyObject *k } -static const char *doc_PkgActionGroup = "ActionGroup(depcache)\n\n" +static char *doc_PkgActionGroup = "ActionGroup(depcache)\n\n" "Create a new ActionGroup() object. The parameter *depcache* refers to an\n" "apt_pkg.DepCache() object.\n\n" "ActionGroups disable certain cleanup actions, so modifying many packages\n" diff --git a/python/tag.cc b/python/tag.cc index 007a6122..bc23e98b 100644 --- a/python/tag.cc +++ b/python/tag.cc @@ -393,7 +393,7 @@ PySequenceMethods TagSecSeqMeth = {0,0,0,0,0,0,0,TagSecContains,0,0}; PyMappingMethods TagSecMapMeth = {TagSecLength,TagSecMap,0}; -static const char *doc_TagSec = "TagSection(text) -> Create a new object.\n\n" +static char *doc_TagSec = "TagSection(text) -> Create a new object.\n\n" "TagSection() objects provide methods to access rfc822-style formatted\n" "header sections, like those in debian/control or Packages files.\n\n" "TagSection() behave like read-only dictionaries and also provide access\n" @@ -467,7 +467,7 @@ static PyGetSetDef TagFileGetSet[] = { {} }; -static const char *doc_TagFile = "TagFile(file) -> TagFile() object. \n\n" +static char *doc_TagFile = "TagFile(file) -> TagFile() object. \n\n" "TagFile() objects provide access to debian control files, which consists\n" "of multiple RFC822-like formatted sections.\n\n" "A file may consists of multiple sections, and you can use Step() to move\n" -- cgit v1.2.3 From 7051066cf258caa2a3fd45271faa3d46b8a6d98a Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Wed, 3 Jun 2009 17:27:33 +0200 Subject: python/: Convert most names to PEP8 naming conventions (except Version,PackageFile,MetaIndex). On our way to close Bug#481061, this converts almost all names to PEP 8 naming conventions. Missing are now apt_pkg.Version, apt_pkg.PackageFile, apt_pkg.MetaIndex and apt.progress.*. In case of the missing apt_pkg classes, they are not converted yet because they do not use getset descriptors yet. apt.progress.* has not been converted yet because the extension interacts with it, and we first need to modify the extension to recognize the new names, as well as the old names (old applications shouldn't break). --- python/acquire.cc | 29 +++++++++++++++ python/apt_instmodule.cc | 21 +++++++---- python/apt_pkgmodule.cc | 94 ++++++++++++++++++++++++++++++++++++++++++++++-- python/cache.cc | 49 ++++++++++++++++++++++++- python/cdrom.cc | 4 +++ python/configuration.cc | 21 +++++++++-- python/depcache.cc | 57 ++++++++++++++++++++++++----- python/indexfile.cc | 11 ++++++ python/pkgmanager.cc | 10 ++++++ python/pkgrecords.cc | 17 +++++++++ python/pkgsrcrecords.cc | 15 ++++++++ python/sourcelist.cc | 8 +++++ python/tag.cc | 15 ++++++++ 13 files changed, 329 insertions(+), 22 deletions(-) (limited to 'python') diff --git a/python/acquire.cc b/python/acquire.cc index ccd3a479..6cb2130c 100644 --- a/python/acquire.cc +++ b/python/acquire.cc @@ -38,6 +38,21 @@ MkGet(AcquireItemGetStatAuthError,Py_BuildValue("i", pkgAcquire::Item::StatAuthE #undef MkGet static PyGetSetDef AcquireItemGetSet[] = { + {"complete",AcquireItemGetComplete}, + {"descuri",AcquireItemGetDescURI}, + {"destfile",AcquireItemGetDestFile}, + {"errortext",AcquireItemGetErrorText}, + {"filesize",AcquireItemGetFileSize}, + {"is",AcquireItemGetID}, + {"is_trusted",AcquireItemGetIsTrusted}, + {"local",AcquireItemGetLocal}, + {"status",AcquireItemGetStatus}, + {"stat_idle",AcquireItemGetStatIdle}, + {"stat_fetching",AcquireItemGetStatFetching}, + {"stat_done",AcquireItemGetStatDone}, + {"stat_error",AcquireItemGetStatError}, + {"stat_auth_error",AcquireItemGetStatAuthError}, +#ifdef COMPAT_0_7 {"Complete",AcquireItemGetComplete}, {"DescURI",AcquireItemGetDescURI}, {"DestFile",AcquireItemGetDestFile}, @@ -52,6 +67,7 @@ static PyGetSetDef AcquireItemGetSet[] = { {"StatDone",AcquireItemGetStatDone}, {"StatError",AcquireItemGetStatError}, {"StatAuthError",AcquireItemGetStatAuthError}, +#endif {} }; @@ -140,8 +156,12 @@ static PyObject *PkgAcquireShutdown(PyObject *Self,PyObject *Args) static PyMethodDef PkgAcquireMethods[] = { + {"run",PkgAcquireRun,METH_VARARGS,"Run the fetcher"}, + {"shutdown",PkgAcquireShutdown, METH_VARARGS,"Shutdown the fetcher"}, + #ifdef COMPAT_0_7 {"Run",PkgAcquireRun,METH_VARARGS,"Run the fetcher"}, {"Shutdown",PkgAcquireShutdown, METH_VARARGS,"Shutdown the fetcher"}, + #endif {} }; @@ -184,6 +204,14 @@ static PyObject *PkgAcquireGetResultCancelled(PyObject *Self,void*) { } static PyGetSetDef PkgAcquireGetSet[] = { + {"fetch_needed",PkgAcquireGetFetchNeeded}, + {"items",PkgAcquireGetItems}, + {"partial_present",PkgAcquireGetPartialPresent}, + {"result_cancelled",PkgAcquireGetResultCancelled}, + {"result_continue",PkgAcquireGetResultContinue}, + {"result_failed",PkgAcquireGetResultFailed}, + {"total_needed",PkgAcquireGetTotalNeeded}, + #ifdef COMPAT_0_7 {"FetchNeeded",PkgAcquireGetFetchNeeded}, {"Items",PkgAcquireGetItems}, {"PartialPresent",PkgAcquireGetPartialPresent}, @@ -191,6 +219,7 @@ static PyGetSetDef PkgAcquireGetSet[] = { {"ResultContinue",PkgAcquireGetResultContinue}, {"ResultFailed",PkgAcquireGetResultFailed}, {"TotalNeeded",PkgAcquireGetTotalNeeded}, + #endif {} }; diff --git a/python/apt_instmodule.cc b/python/apt_instmodule.cc index 09e3937e..84479fcb 100644 --- a/python/apt_instmodule.cc +++ b/python/apt_instmodule.cc @@ -29,7 +29,7 @@ expose the full range of the apt-inst .deb processing will join it some day. */ static char *doc_debExtractControl = -"debExtractControl(File[,Member]) -> String\n" +"deb_extract_control(file[,member]) -> String\n" "Returns the indicated file from the control tar. The default is 'control'\n"; static PyObject *debExtractControl(PyObject *Self,PyObject *Args) { @@ -72,7 +72,7 @@ static PyObject *debExtractControl(PyObject *Self,PyObject *Args) // debExtractArchive - Exctract the archive /*{{{*/ // --------------------------------------------------------------------- static char *doc_debExtractArchive = -"debExtractArchve(File,rootdir) -> Bool\n" +"deb_extract_archive(File,rootdir) -> Bool\n" "Extracts the Archive into the given root dir"; static PyObject *debExtractArchive(PyObject *Self,PyObject *Args) { @@ -118,7 +118,7 @@ static PyObject *debExtractArchive(PyObject *Self,PyObject *Args) // arFindMember - Find member in AR archive /*{{{*/ // --------------------------------------------------------------------- static char *doc_arCheckMember = -"arCheckMember(File, membername) -> Bool\n"; +"ar_check_member(file, membername) -> Bool\n"; static PyObject *arCheckMember(PyObject *Self,PyObject *Args) { char *Member = NULL; @@ -149,16 +149,23 @@ static PyObject *arCheckMember(PyObject *Self,PyObject *Args) static PyMethodDef methods[] = { // access to ar files - {"arCheckMember", arCheckMember, METH_VARARGS, doc_arCheckMember}, + {"ar_check_member", arCheckMember, METH_VARARGS, doc_arCheckMember}, // access to deb files - {"debExtractControl",debExtractControl,METH_VARARGS,doc_debExtractControl}, - {"debExtractArchive",debExtractArchive,METH_VARARGS,doc_debExtractArchive}, + {"deb_extract_control",debExtractControl,METH_VARARGS,doc_debExtractControl}, + {"deb_extract_archive",debExtractArchive,METH_VARARGS,doc_debExtractArchive}, // access to tar streams + {"tar_extract",tarExtract,METH_VARARGS,doc_tarExtract}, + {"deb_extract",debExtract,METH_VARARGS,doc_debExtract}, + +#ifdef COMPAT_0_7 + {"arCheckMember", arCheckMember, METH_VARARGS, doc_arCheckMember}, + {"debExtractControl",debExtractControl,METH_VARARGS,doc_debExtractControl}, + {"debExtractArchive",debExtractArchive,METH_VARARGS,doc_debExtractArchive}, {"tarExtract",tarExtract,METH_VARARGS,doc_tarExtract}, {"debExtract",debExtract,METH_VARARGS,doc_debExtract}, - +#endif {} }; diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index bdea5fae..ddd6d38b 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -389,35 +389,60 @@ static PyMethodDef methods[] = {"newConfiguration",newConfiguration,METH_VARARGS,doc_newConfiguration}, #endif {"init",Init,METH_VARARGS,doc_Init}, + {"init_config",InitConfig,METH_VARARGS,doc_InitConfig}, + {"init_system",InitSystem,METH_VARARGS,doc_InitSystem}, + #ifdef COMPAT_0_7 {"InitConfig",InitConfig,METH_VARARGS,doc_InitConfig}, {"InitSystem",InitSystem,METH_VARARGS,doc_InitSystem}, + #endif // Tag File #ifdef COMPAT_0_7 {"ParseSection",ParseSection,METH_VARARGS,doc_ParseSection}, {"ParseTagFile",ParseTagFile,METH_VARARGS,doc_ParseTagFile}, - #endif {"RewriteSection",RewriteSection,METH_VARARGS,doc_RewriteSection}, + #endif + {"rewrite_section",RewriteSection,METH_VARARGS,doc_RewriteSection}, // Locking + {"get_lock",GetLock,METH_VARARGS,doc_GetLock}, + {"pkgsystem_lock",PkgSystemLock,METH_VARARGS,doc_PkgSystemLock}, + {"pkgsystem_unlock",PkgSystemUnLock,METH_VARARGS,doc_PkgSystemUnLock}, + #ifdef COMPAT_0_7 {"GetLock",GetLock,METH_VARARGS,doc_GetLock}, {"PkgSystemLock",PkgSystemLock,METH_VARARGS,doc_PkgSystemLock}, {"PkgSystemUnLock",PkgSystemUnLock,METH_VARARGS,doc_PkgSystemUnLock}, + #endif // Command line + {"read_configfile",LoadConfig,METH_VARARGS,doc_LoadConfig}, + {"read_configdir",LoadConfigDir,METH_VARARGS,doc_LoadConfigDir}, + {"read_configfile_isc",LoadConfigISC,METH_VARARGS,doc_LoadConfig}, + {"parse_commandline",ParseCommandLine,METH_VARARGS,doc_ParseCommandLine}, + #ifdef COMPAT_0_7 {"ReadConfigFile",LoadConfig,METH_VARARGS,doc_LoadConfig}, {"ReadConfigDir",LoadConfigDir,METH_VARARGS,doc_LoadConfigDir}, {"ReadConfigFileISC",LoadConfigISC,METH_VARARGS,doc_LoadConfig}, {"ParseCommandLine",ParseCommandLine,METH_VARARGS,doc_ParseCommandLine}, + #endif // Versioning + {"version_compare",VersionCompare,METH_VARARGS,doc_VersionCompare}, + {"check_dep",CheckDep,METH_VARARGS,doc_CheckDep}, + {"upstream_version",UpstreamVersion,METH_VARARGS,doc_UpstreamVersion}, + #ifdef COMPAT_0_7 {"VersionCompare",VersionCompare,METH_VARARGS,doc_VersionCompare}, {"CheckDep",CheckDep,METH_VARARGS,doc_CheckDep}, {"UpstreamVersion",UpstreamVersion,METH_VARARGS,doc_UpstreamVersion}, + #endif // Depends + {"parse_depends",ParseDepends,METH_VARARGS,doc_ParseDepends}, + {"parse_srcdepends",ParseSrcDepends,METH_VARARGS,doc_ParseDepends}, + #ifdef COMPAT_0_7 {"ParseDepends",ParseDepends,METH_VARARGS,doc_ParseDepends}, {"ParseSrcDepends",ParseSrcDepends,METH_VARARGS,doc_ParseDepends}, + #endif // Stuff {"md5sum",md5sum,METH_VARARGS,doc_md5sum}, @@ -425,6 +450,17 @@ static PyMethodDef methods[] = {"sha256sum",sha256sum,METH_VARARGS,doc_sha256sum}, // Strings + {"check_domainlist",StrCheckDomainList,METH_VARARGS,"CheckDomainList(String,String) -> Bool"}, + {"quote_string",StrQuoteString,METH_VARARGS,"QuoteString(String,String) -> String"}, + {"dequote_string",StrDeQuote,METH_VARARGS,"DeQuoteString(String) -> String"}, + {"size_to_str",StrSizeToStr,METH_VARARGS,"SizeToStr(int) -> String"}, + {"time_to_str",StrTimeToStr,METH_VARARGS,"TimeToStr(int) -> String"}, + {"uri_to_filename",StrURItoFileName,METH_VARARGS,"URItoFileName(String) -> String"}, + {"base64_encode",StrBase64Encode,METH_VARARGS,"Base64Encode(String) -> String"}, + {"string_to_bool",StrStringToBool,METH_VARARGS,"StringToBool(String) -> int"}, + {"time_rfc1123",StrTimeRFC1123,METH_VARARGS,"TimeRFC1123(int) -> String"}, + {"str_to_time",StrStrToTime,METH_VARARGS,"StrToTime(String) -> Int"}, + #ifdef COMPAT_0_7 {"CheckDomainList",StrCheckDomainList,METH_VARARGS,"CheckDomainList(String,String) -> Bool"}, {"QuoteString",StrQuoteString,METH_VARARGS,"QuoteString(String,String) -> String"}, {"DeQuoteString",StrDeQuote,METH_VARARGS,"DeQuoteString(String) -> String"}, @@ -435,6 +471,7 @@ static PyMethodDef methods[] = {"StringToBool",StrStringToBool,METH_VARARGS,"StringToBool(String) -> int"}, {"TimeRFC1123",StrTimeRFC1123,METH_VARARGS,"TimeRFC1123(int) -> String"}, {"StrToTime",StrStrToTime,METH_VARARGS,"StrToTime(String) -> Int"}, + #endif // Cache #ifdef COMPAT_0_7 @@ -535,7 +572,10 @@ extern "C" void initapt_pkg() // Global variable linked to the global configuration class CppPyObject *Config = CppPyObject_NEW(&ConfigurationPtrType); Config->Object = _config; + PyModule_AddObject(Module,"config",Config); + #ifdef COMPAT_0_7 PyModule_AddObject(Module,"Config",Config); + #endif // Add our classes. /* ============================ tag.cc ============================ */ @@ -577,20 +617,40 @@ extern "C" void initapt_pkg() /* ========================= sourcelist.cc ========================= */ ADDTYPE(Module,"SourceList",&PkgSourceListType); // Tag file constants + PyModule_AddObject(Module,"REWRITE_PACKAGE_ORDER", + CharCharToList(TFRewritePackageOrder)); + + PyModule_AddObject(Module,"REWRITE_SOURCE_ORDER", + CharCharToList(TFRewriteSourceOrder)); +#ifdef COMPAT_0_7 PyModule_AddObject(Module,"RewritePackageOrder", CharCharToList(TFRewritePackageOrder)); PyModule_AddObject(Module,"RewriteSourceOrder", CharCharToList(TFRewriteSourceOrder)); +#endif // Version.. + PyModule_AddStringConstant(Module,"VERSION",(char *)pkgVersion); + PyModule_AddStringConstant(Module,"LIB_VERSION",(char *)pkgLibVersion); + PyModule_AddStringConstant(Module,"DATE",__DATE__); + PyModule_AddStringConstant(Module,"TIME",__TIME__); +#ifdef COMPAT_0_7 PyModule_AddStringConstant(Module,"Version",(char *)pkgVersion); PyModule_AddStringConstant(Module,"LibVersion",(char *)pkgLibVersion); PyModule_AddStringConstant(Module,"Date",__DATE__); PyModule_AddStringConstant(Module,"Time",__TIME__); +#endif // My constants - + PyModule_AddIntConstant(Module,"DEP_DEPENDS",pkgCache::Dep::Depends); + PyModule_AddIntConstant(Module,"DEP_PREDEPENDS",pkgCache::Dep::PreDepends); + PyModule_AddIntConstant(Module,"DEP_SUGGESTS",pkgCache::Dep::Suggests); + PyModule_AddIntConstant(Module,"DEP_RECOMMENDS",pkgCache::Dep::Recommends); + PyModule_AddIntConstant(Module,"DEP_CONFLICTS",pkgCache::Dep::Conflicts); + PyModule_AddIntConstant(Module,"DEP_REPLACES",pkgCache::Dep::Replaces); + PyModule_AddIntConstant(Module,"DEP_OBSOLTES",pkgCache::Dep::Obsoletes); +#ifdef COMPAT_0_7 PyModule_AddIntConstant(Module,"DepDepends",pkgCache::Dep::Depends); PyModule_AddIntConstant(Module,"DepPreDepends",pkgCache::Dep::PreDepends); PyModule_AddIntConstant(Module,"DepSuggests",pkgCache::Dep::Suggests); @@ -598,13 +658,40 @@ extern "C" void initapt_pkg() PyModule_AddIntConstant(Module,"DepConflicts",pkgCache::Dep::Conflicts); PyModule_AddIntConstant(Module,"DepReplaces",pkgCache::Dep::Replaces); PyModule_AddIntConstant(Module,"DepObsoletes",pkgCache::Dep::Obsoletes); +#endif + PyModule_AddIntConstant(Module,"PRI_IMPORTANT",pkgCache::State::Important); + PyModule_AddIntConstant(Module,"PRI_REQUIRED",pkgCache::State::Required); + PyModule_AddIntConstant(Module,"PRI_STANDARD",pkgCache::State::Standard); + PyModule_AddIntConstant(Module,"PRI_OPTIONAL",pkgCache::State::Optional); + PyModule_AddIntConstant(Module,"PRI_EXTRA",pkgCache::State::Extra); +#ifdef COMPAT_0_7 PyModule_AddIntConstant(Module,"PriImportant",pkgCache::State::Important); PyModule_AddIntConstant(Module,"PriRequired",pkgCache::State::Required); PyModule_AddIntConstant(Module,"PriStandard",pkgCache::State::Standard); PyModule_AddIntConstant(Module,"PriOptional",pkgCache::State::Optional); PyModule_AddIntConstant(Module,"PriExtra",pkgCache::State::Extra); - +#endif + // CurState + PyModule_AddIntConstant(Module,"STATE_NOTINSTALLED",pkgCache::State::NotInstalled); + PyModule_AddIntConstant(Module,"STATE_UNPACKED",pkgCache::State::UnPacked); + PyModule_AddIntConstant(Module,"STATE_HALFCONFIGURED",pkgCache::State::HalfConfigured); + PyModule_AddIntConstant(Module,"STATE_HALFINSTALLED",pkgCache::State::HalfInstalled); + PyModule_AddIntConstant(Module,"STATE_CONFIGFILES",pkgCache::State::ConfigFiles); + PyModule_AddIntConstant(Module,"STATE_INSTALLED",pkgCache::State::Installed); + // SelState + PyModule_AddIntConstant(Module,"STATE_UNKNOWN",pkgCache::State::Unknown); + PyModule_AddIntConstant(Module,"STATE_INSTALL",pkgCache::State::Install); + PyModule_AddIntConstant(Module,"STATE_HOLD",pkgCache::State::Hold); + PyModule_AddIntConstant(Module,"STATE_DEINSTALL",pkgCache::State::DeInstall); + PyModule_AddIntConstant(Module,"STATE_PURGE",pkgCache::State::Purge); + // InstState + PyModule_AddIntConstant(Module,"STATE_OK",pkgCache::State::Ok); + PyModule_AddIntConstant(Module,"STATE_REINSTREQ",pkgCache::State::ReInstReq); + PyModule_AddIntConstant(Module,"STATE_HOLD",pkgCache::State::Hold); + PyModule_AddIntConstant(Module,"STATE_HOLD_REINSTREQ",pkgCache::State::HoldReInstReq); + +#ifdef COMPAT_0_7 PyModule_AddIntConstant(Module,"CurStateNotInstalled",pkgCache::State::NotInstalled); PyModule_AddIntConstant(Module,"CurStateUnPacked",pkgCache::State::UnPacked); PyModule_AddIntConstant(Module,"CurStateHalfConfigured",pkgCache::State::HalfConfigured); @@ -622,6 +709,7 @@ extern "C" void initapt_pkg() PyModule_AddIntConstant(Module,"InstStateReInstReq",pkgCache::State::ReInstReq); PyModule_AddIntConstant(Module,"InstStateHold",pkgCache::State::Hold); PyModule_AddIntConstant(Module,"InstStateHoldReInstReq",pkgCache::State::HoldReInstReq); +#endif #ifdef COMPAT_0_7 PyModule_AddIntConstant(Module,"_COMPAT_0_7",1); diff --git a/python/cache.cc b/python/cache.cc index f545a605..644646a1 100644 --- a/python/cache.cc +++ b/python/cache.cc @@ -136,9 +136,14 @@ static PyObject *PkgCacheOpen(PyObject *Self,PyObject *Args) static PyMethodDef PkgCacheMethods[] = { + {"update",PkgCacheUpdate,METH_VARARGS,"Update the cache"}, + {"open", PkgCacheOpen, METH_VARARGS,"Open the cache"}, + {"close", PkgCacheClose, METH_VARARGS,"Close the cache"}, +#ifdef COMPAT_0_7 {"Update",PkgCacheUpdate,METH_VARARGS,"Update the cache"}, {"Open", PkgCacheOpen, METH_VARARGS,"Open the cache"}, {"Close", PkgCacheClose, METH_VARARGS,"Close the cache"}, +#endif {} }; @@ -190,6 +195,15 @@ static PyObject *PkgCacheGetFileList(PyObject *Self, void*) { } static PyGetSetDef PkgCacheGetSet[] = { + {"depends_count",PkgCacheGetDependsCount}, + {"filelist",PkgCacheGetFileList}, + {"package_count",PkgCacheGetPackageCount}, + {"packagefile_count",PkgCacheGetPackageFileCount}, + {"packages",PkgCacheGetPackages}, + {"provides_count",PkgCacheGetProvidesCount}, + {"verfile_count",PkgCacheGetVerFileCount}, + {"version_count",PkgCacheGetVersionCount}, +#ifdef COMPAT_0_7 {"DependsCount",PkgCacheGetDependsCount}, {"FileList",PkgCacheGetFileList}, {"PackageCount",PkgCacheGetPackageCount}, @@ -198,6 +212,7 @@ static PyGetSetDef PkgCacheGetSet[] = { {"ProvidesCount",PkgCacheGetProvidesCount}, {"VerFileCount",PkgCacheGetVerFileCount}, {"VersionCount",PkgCacheGetVersionCount}, +#endif {} }; @@ -482,6 +497,20 @@ static PyObject *PackageGetCurrentVer(PyObject *Self,void*) } static PyGetSetDef PackageGetSet[] = { + {"name",PackageGetName}, + {"section",PackageGetSection}, + {"revdependslist",PackageGetRevDependsList}, + {"provideslist",PackageGetProvidesList}, + {"selected_state",PackageGetSelectedState}, + {"inst_state",PackageGetInstState}, + {"current_state",PackageGetCurrentState}, + {"id",PackageGetID}, + {"auto",PackageGetAuto}, + {"essential",PackageGetEssential}, + {"important",PackageGetImportant}, + {"versionlist",PackageGetVersionList}, + {"currentver",PackageGetCurrentVer}, + #ifdef COMPAT_0_7 {"Name",PackageGetName}, {"Section",PackageGetSection}, {"RevDependsList",PackageGetRevDependsList}, @@ -495,6 +524,7 @@ static PyGetSetDef PackageGetSet[] = { {"Important",PackageGetImportant}, {"VersionList",PackageGetVersionList}, {"CurrentVer",PackageGetCurrentVer}, + #endif {} }; @@ -579,9 +609,13 @@ static PyObject *DescriptionGetFileList(PyObject *Self,void*) } static PyGetSetDef DescriptionGetSet[] = { - {"LanguageCode",DescriptionGetLanguageCode}, + {"languagecode",DescriptionGetLanguageCode}, {"md5",DescriptionGetMd5}, + {"filelist",DescriptionGetFileList}, + #ifdef COMPAT_0_7 + {"LanguageCode",DescriptionGetLanguageCode}, {"FileList",DescriptionGetFileList}, + #endif {} }; @@ -955,8 +989,12 @@ static PyObject *DepAllTargets(PyObject *Self,PyObject *Args) static PyMethodDef DependencyMethods[] = { + {"smart_target_pkg",DepSmartTargetPkg,METH_VARARGS,"Returns the natural Target or None"}, + {"all_targets",DepAllTargets,METH_VARARGS,"Returns all possible Versions that match this dependency"}, +#ifdef COMPAT_0_7 {"SmartTargetPkg",DepSmartTargetPkg,METH_VARARGS,"Returns the natural Target or None"}, {"AllTargets",DepAllTargets,METH_VARARGS,"Returns all possible Versions that match this dependency"}, +#endif {} }; @@ -1014,6 +1052,14 @@ static PyObject *DependencyGetID(PyObject *Self,void*) } static PyGetSetDef DependencyGetSet[] = { + {"comptype",DependencyGetCompType}, + {"deptype",DependencyGetDepType}, + {"id",DependencyGetID}, + {"parentpkg",DependencyGetParentPkg}, + {"parentver",DependencyGetParentVer}, + {"targetpkg",DependencyGetTargetPkg}, + {"targetver",DependencyGetTargetVer}, +#ifdef COMPAT_0_7 {"CompType",DependencyGetCompType}, {"DepType",DependencyGetDepType}, {"ID",DependencyGetID}, @@ -1021,6 +1067,7 @@ static PyGetSetDef DependencyGetSet[] = { {"ParentVer",DependencyGetParentVer}, {"TargetPkg",DependencyGetTargetPkg}, {"TargetVer",DependencyGetTargetVer}, +#endif {} }; diff --git a/python/cdrom.cc b/python/cdrom.cc index bf94a390..044bbf30 100644 --- a/python/cdrom.cc +++ b/python/cdrom.cc @@ -58,8 +58,12 @@ static PyObject *PkgCdromIdent(PyObject *Self,PyObject *Args) static PyMethodDef PkgCdromMethods[] = { + {"add",PkgCdromAdd,METH_VARARGS,"add(progress) -> Add a cdrom"}, + {"ident",PkgCdromIdent,METH_VARARGS,"ident(progress) -> Ident a cdrom"}, +#ifdef COMPAT_0_7 {"Add",PkgCdromAdd,METH_VARARGS,"Add(progress) -> Add a cdrom"}, {"Ident",PkgCdromIdent,METH_VARARGS,"Ident(progress) -> Ident a cdrom"}, +#endif {} }; diff --git a/python/configuration.cc b/python/configuration.cc index abbed6d9..107cf90f 100644 --- a/python/configuration.cc +++ b/python/configuration.cc @@ -453,13 +453,26 @@ PyObject *ParseCommandLine(PyObject *Self,PyObject *Args) static PyMethodDef CnfMethods[] = { // Query + {"find",CnfFind,METH_VARARGS,doc_Find}, + {"find_file",CnfFindFile,METH_VARARGS,doc_FindFile}, + {"find_dir",CnfFindDir,METH_VARARGS,doc_FindDir}, + {"find_i",CnfFindI,METH_VARARGS,doc_FindI}, + {"find_b",CnfFindB,METH_VARARGS,doc_FindB}, + + // Others + {"set",CnfSet,METH_VARARGS,doc_Set}, + {"exists",CnfExists,METH_VARARGS,doc_Exists}, + {"subtree",CnfSubTree,METH_VARARGS,doc_SubTree}, + {"list",CnfList,METH_VARARGS,doc_List}, + {"valuelist",CnfValueList,METH_VARARGS,doc_ValueList}, + {"mytag",CnfMyTag,METH_VARARGS,doc_MyTag}, + {"clear",CnfClear,METH_VARARGS,doc_Clear}, +#ifdef COMPAT_0_7 {"Find",CnfFind,METH_VARARGS,doc_Find}, {"FindFile",CnfFindFile,METH_VARARGS,doc_FindFile}, {"FindDir",CnfFindDir,METH_VARARGS,doc_FindDir}, {"FindI",CnfFindI,METH_VARARGS,doc_FindI}, {"FindB",CnfFindB,METH_VARARGS,doc_FindB}, - - // Others {"Set",CnfSet,METH_VARARGS,doc_Set}, {"Exists",CnfExists,METH_VARARGS,doc_Exists}, {"SubTree",CnfSubTree,METH_VARARGS,doc_SubTree}, @@ -467,10 +480,12 @@ static PyMethodDef CnfMethods[] = {"ValueList",CnfValueList,METH_VARARGS,doc_ValueList}, {"MyTag",CnfMyTag,METH_VARARGS,doc_MyTag}, {"Clear",CnfClear,METH_VARARGS,doc_Clear}, - +#endif // Python Special {"keys",CnfKeys,METH_VARARGS,doc_Keys}, + #if PY_MAJOR_VERSION < 3 {"has_key",CnfExists,METH_VARARGS,doc_Exists}, + #endif {"get",CnfFind,METH_VARARGS,doc_Find}, {} }; diff --git a/python/depcache.cc b/python/depcache.cc index ef2240ce..f3b16211 100644 --- a/python/depcache.cc +++ b/python/depcache.cc @@ -528,21 +528,47 @@ static PyObject *PkgDepCacheMarkedReinstall(PyObject *Self,PyObject *Args) static PyMethodDef PkgDepCacheMethods[] = { + {"init",PkgDepCacheInit,METH_VARARGS,"Init the depcache (done on construct automatically)"}, + {"get_candidate",PkgDepCacheGetCandidateVer,METH_VARARGS,"Get candidate version"}, + {"set_candidate",PkgDepCacheSetCandidateVer,METH_VARARGS,"Set candidate version"}, + + // global cache operations + {"upgrade",PkgDepCacheUpgrade,METH_VARARGS,"Perform Upgrade (optional boolean argument if dist-upgrade should be performed)"}, + {"fix_broken",PkgDepCacheFixBroken,METH_VARARGS,"Fix broken packages"}, + {"read_pinfile",PkgDepCacheReadPinFile,METH_VARARGS,"Read the pin policy"}, + {"minimize_upgrade",PkgDepCacheMinimizeUpgrade, METH_VARARGS,"Go over the entire set of packages and try to keep each package marked for upgrade. If a conflict is generated then the package is restored."}, + // Manipulators + {"mark_keep",PkgDepCacheMarkKeep,METH_VARARGS,"Mark package for keep"}, + {"mark_delete",PkgDepCacheMarkDelete,METH_VARARGS,"Mark package for delete (optional boolean argument if it should be purged)"}, + {"mark_install",PkgDepCacheMarkInstall,METH_VARARGS,"Mark package for Install"}, + {"set_reinstall",PkgDepCacheSetReInstall,METH_VARARGS,"Set if the package should be reinstalled"}, + // state information + {"is_upgradable",PkgDepCacheIsUpgradable,METH_VARARGS,"Is pkg upgradable"}, + {"is_now_broken",PkgDepCacheIsNowBroken,METH_VARARGS,"Is pkg is now broken"}, + {"is_inst_broken",PkgDepCacheIsInstBroken,METH_VARARGS,"Is pkg broken on the current install"}, + {"is_garbage",PkgDepCacheIsGarbage,METH_VARARGS,"Is pkg garbage (mark-n-sweep)"}, + {"is_auto_installed",PkgDepCacheIsAutoInstalled,METH_VARARGS,"Is pkg marked as auto installed"}, + {"marked_install",PkgDepCacheMarkedInstall,METH_VARARGS,"Is pkg marked for install"}, + {"marked_upgrade",PkgDepCacheMarkedUpgrade,METH_VARARGS,"Is pkg marked for upgrade"}, + {"marked_delete",PkgDepCacheMarkedDelete,METH_VARARGS,"Is pkg marked for delete"}, + {"marked_keep",PkgDepCacheMarkedKeep,METH_VARARGS,"Is pkg marked for keep"}, + {"marked_reinstall",PkgDepCacheMarkedReinstall,METH_VARARGS,"Is pkg marked for reinstall"}, + {"marked_downgrade",PkgDepCacheMarkedDowngrade,METH_VARARGS,"Is pkg marked for downgrade"}, + + // Action + {"commit", PkgDepCacheCommit, METH_VARARGS, "Commit pending changes"}, +#ifdef COMPAT_0_7 {"Init",PkgDepCacheInit,METH_VARARGS,"Init the depcache (done on construct automatically)"}, {"GetCandidateVer",PkgDepCacheGetCandidateVer,METH_VARARGS,"Get candidate version"}, {"SetCandidateVer",PkgDepCacheSetCandidateVer,METH_VARARGS,"Set candidate version"}, - - // global cache operations {"Upgrade",PkgDepCacheUpgrade,METH_VARARGS,"Perform Upgrade (optional boolean argument if dist-upgrade should be performed)"}, {"FixBroken",PkgDepCacheFixBroken,METH_VARARGS,"Fix broken packages"}, {"ReadPinFile",PkgDepCacheReadPinFile,METH_VARARGS,"Read the pin policy"}, {"MinimizeUpgrade",PkgDepCacheMinimizeUpgrade, METH_VARARGS,"Go over the entire set of packages and try to keep each package marked for upgrade. If a conflict is generated then the package is restored."}, - // Manipulators {"MarkKeep",PkgDepCacheMarkKeep,METH_VARARGS,"Mark package for keep"}, {"MarkDelete",PkgDepCacheMarkDelete,METH_VARARGS,"Mark package for delete (optional boolean argument if it should be purged)"}, {"MarkInstall",PkgDepCacheMarkInstall,METH_VARARGS,"Mark package for Install"}, {"SetReInstall",PkgDepCacheSetReInstall,METH_VARARGS,"Set if the package should be reinstalled"}, - // state information {"IsUpgradable",PkgDepCacheIsUpgradable,METH_VARARGS,"Is pkg upgradable"}, {"IsNowBroken",PkgDepCacheIsNowBroken,METH_VARARGS,"Is pkg is now broken"}, {"IsInstBroken",PkgDepCacheIsInstBroken,METH_VARARGS,"Is pkg broken on the current install"}, @@ -554,9 +580,8 @@ static PyMethodDef PkgDepCacheMethods[] = {"MarkedKeep",PkgDepCacheMarkedKeep,METH_VARARGS,"Is pkg marked for keep"}, {"MarkedReinstall",PkgDepCacheMarkedReinstall,METH_VARARGS,"Is pkg marked for reinstall"}, {"MarkedDowngrade",PkgDepCacheMarkedDowngrade,METH_VARARGS,"Is pkg marked for downgrade"}, - - // Action {"Commit", PkgDepCacheCommit, METH_VARARGS, "Commit pending changes"}, +#endif {} }; @@ -582,12 +607,20 @@ static PyObject *PkgDepCacheGetDebSize(PyObject *Self,void*) { #undef depcache static PyGetSetDef PkgDepCacheGetSet[] = { + {"brokencount",PkgDepCacheGetBrokenCount}, + {"debsize",PkgDepCacheGetDebSize}, + {"delcount",PkgDepCacheGetDelCount}, + {"instcount",PkgDepCacheGetInstCount}, + {"keepcount",PkgDepCacheGetKeepCount}, + {"usrsize",PkgDepCacheGetUsrSize}, + #ifdef COMPAT_0_7 {"BrokenCount",PkgDepCacheGetBrokenCount}, {"DebSize",PkgDepCacheGetDebSize}, {"DelCount",PkgDepCacheGetDelCount}, {"InstCount",PkgDepCacheGetInstCount}, {"KeepCount",PkgDepCacheGetKeepCount}, {"UsrSize",PkgDepCacheGetUsrSize}, + #endif {} }; @@ -779,14 +812,22 @@ static PyObject *PkgProblemResolverInstallProtect(PyObject *Self,PyObject *Args) static PyMethodDef PkgProblemResolverMethods[] = { // config + {"protect", PkgProblemResolverProtect, METH_VARARGS, "protect(PkgIterator)"}, + {"remove", PkgProblemResolverRemove, METH_VARARGS, "remove(PkgIterator)"}, + {"clear", PkgProblemResolverClear, METH_VARARGS, "clear(PkgIterator)"}, + {"install_protect", PkgProblemResolverInstallProtect, METH_VARARGS, "install_protect()"}, + + // Actions + {"resolve", PkgProblemResolverResolve, METH_VARARGS, "Try to intelligently resolve problems by installing and removing packages"}, + {"resolve_by_keep", PkgProblemResolverResolveByKeep, METH_VARARGS, "Try to resolv problems only by using keep"}, + #ifdef COMPAT_0_7 {"Protect", PkgProblemResolverProtect, METH_VARARGS, "Protect(PkgIterator)"}, {"Remove", PkgProblemResolverRemove, METH_VARARGS, "Remove(PkgIterator)"}, {"Clear", PkgProblemResolverClear, METH_VARARGS, "Clear(PkgIterator)"}, {"InstallProtect", PkgProblemResolverInstallProtect, METH_VARARGS, "ProtectInstalled()"}, - - // Actions {"Resolve", PkgProblemResolverResolve, METH_VARARGS, "Try to intelligently resolve problems by installing and removing packages"}, {"ResolveByKeep", PkgProblemResolverResolveByKeep, METH_VARARGS, "Try to resolv problems only by using keep"}, + #endif {} }; diff --git a/python/indexfile.cc b/python/indexfile.cc index 600dc853..795931fb 100644 --- a/python/indexfile.cc +++ b/python/indexfile.cc @@ -28,7 +28,10 @@ static PyObject *PackageIndexFileArchiveURI(PyObject *Self,PyObject *Args) static PyMethodDef PackageIndexFileMethods[] = { + {"archive_uri",PackageIndexFileArchiveURI,METH_VARARGS,"Returns the ArchiveURI"}, + #ifdef COMPAT_0_7 {"ArchiveURI",PackageIndexFileArchiveURI,METH_VARARGS,"Returns the ArchiveURI"}, + #endif {} }; @@ -69,12 +72,20 @@ static PyObject *PackageIndexFileRepr(PyObject *Self) } static PyGetSetDef PackageIndexFileGetSet[] = { + {"describe",PackageIndexFileGetDescribe}, + {"exists",PackageIndexFileGetExists}, + {"has_packages",PackageIndexFileGetHasPackages}, + {"is_trusted",PackageIndexFileGetIsTrusted}, + {"label",PackageIndexFileGetLabel}, + {"size",PackageIndexFileGetSize}, + #ifdef COMPAT_0_7 {"Describe",PackageIndexFileGetDescribe}, {"Exists",PackageIndexFileGetExists}, {"HasPackages",PackageIndexFileGetHasPackages}, {"IsTrusted",PackageIndexFileGetIsTrusted}, {"Label",PackageIndexFileGetLabel}, {"Size",PackageIndexFileGetSize}, + #endif {} }; diff --git a/python/pkgmanager.cc b/python/pkgmanager.cc index 781acc8b..cae2b580 100644 --- a/python/pkgmanager.cc +++ b/python/pkgmanager.cc @@ -92,9 +92,14 @@ static PyObject *PkgManagerFixMissing(PyObject *Self,PyObject *Args) static PyMethodDef PkgManagerMethods[] = { + {"get_archives",PkgManagerGetArchives,METH_VARARGS,"Load the selected archives into the fetcher"}, + {"do_install",PkgManagerDoInstall,METH_VARARGS,"Do the actual install"}, + {"fix_missing",PkgManagerFixMissing,METH_VARARGS,"Fix the install if a pkg couldn't be downloaded"}, +#ifdef COMPAT_0_7 {"GetArchives",PkgManagerGetArchives,METH_VARARGS,"Load the selected archives into the fetcher"}, {"DoInstall",PkgManagerDoInstall,METH_VARARGS,"Do the actual install"}, {"FixMissing",PkgManagerFixMissing,METH_VARARGS,"Fix the install if a pkg couldn't be downloaded"}, +#endif {} }; @@ -110,9 +115,14 @@ static PyObject *PkgManagerGetResultIncomplete(PyObject *Self,void*) { } static PyGetSetDef PkgManagerGetSet[] = { + {"result_completed",PkgManagerGetResultCompleted}, + {"result_failed",PkgManagerGetResultFailed}, + {"result_incomplete",PkgManagerGetResultIncomplete}, +#ifdef COMPAT_0_7 {"ResultCompleted",PkgManagerGetResultCompleted}, {"ResultFailed",PkgManagerGetResultFailed}, {"ResultIncomplete",PkgManagerGetResultIncomplete}, +#endif {} }; diff --git a/python/pkgrecords.cc b/python/pkgrecords.cc index 1cccfce2..f9e48352 100644 --- a/python/pkgrecords.cc +++ b/python/pkgrecords.cc @@ -49,7 +49,10 @@ static PyObject *PkgRecordsLookup(PyObject *Self,PyObject *Args) static PyMethodDef PkgRecordsMethods[] = { + {"lookup",PkgRecordsLookup,METH_VARARGS,"Changes to a new package"}, + #ifdef COMPAT_0_7 {"Lookup",PkgRecordsLookup,METH_VARARGS,"Changes to a new package"}, + #endif {} }; @@ -117,6 +120,19 @@ static PyObject *PkgRecordsGetRecord(PyObject *Self,void*) { return PyString_FromStringAndSize(start,stop-start); } static PyGetSetDef PkgRecordsGetSet[] = { + {"filename",PkgRecordsGetFileName}, + {"homepage",PkgRecordsGetHomepage}, + {"longdesc",PkgRecordsGetLongDesc}, + {"md5",PkgRecordsGetMD5Hash}, + {"maintainer",PkgRecordsGetMaintainer}, + {"name",PkgRecordsGetName}, + {"record",PkgRecordsGetRecord}, + {"sha1",PkgRecordsGetSHA1Hash}, + {"sha256",PkgRecordsGetSHA256Hash}, + {"shortdesc",PkgRecordsGetShortDesc}, + {"sourcepkg",PkgRecordsGetSourcePkg}, + {"sourcever",PkgRecordsGetSourceVer}, +#ifdef COMPAT_0_7 {"FileName",PkgRecordsGetFileName}, {"Homepage",PkgRecordsGetHomepage}, {"LongDesc",PkgRecordsGetLongDesc}, @@ -129,6 +145,7 @@ static PyGetSetDef PkgRecordsGetSet[] = { {"ShortDesc",PkgRecordsGetShortDesc}, {"SourcePkg",PkgRecordsGetSourcePkg}, {"SourceVer",PkgRecordsGetSourceVer}, +#endif {} }; diff --git a/python/pkgsrcrecords.cc b/python/pkgsrcrecords.cc index 8b4dce3e..2a8b7bab 100644 --- a/python/pkgsrcrecords.cc +++ b/python/pkgsrcrecords.cc @@ -70,8 +70,12 @@ static PyObject *PkgSrcRecordsRestart(PyObject *Self,PyObject *Args) static PyMethodDef PkgSrcRecordsMethods[] = { + {"lookup",PkgSrcRecordsLookup,METH_VARARGS,doc_PkgSrcRecordsLookup}, + {"restart",PkgSrcRecordsRestart,METH_VARARGS,doc_PkgSrcRecordsRestart}, +#ifdef COMPAT_0_7 {"Lookup",PkgSrcRecordsLookup,METH_VARARGS,doc_PkgSrcRecordsLookup}, {"Restart",PkgSrcRecordsRestart,METH_VARARGS,doc_PkgSrcRecordsRestart}, +#endif {} }; @@ -168,6 +172,16 @@ static PyObject *PkgSrcRecordsGetBuildDepends(PyObject *Self,void*) { } static PyGetSetDef PkgSrcRecordsGetSet[] = { + {"binaries",PkgSrcRecordsGetBinaries}, + {"builddepends",PkgSrcRecordsGetBuildDepends}, + {"files",PkgSrcRecordsGetFiles}, + {"index",PkgSrcRecordsGetIndex}, + {"maintainer",PkgSrcRecordsGetMaintainer}, + {"package",PkgSrcRecordsGetPackage}, + {"record",PkgSrcRecordsGetRecord}, + {"section",PkgSrcRecordsGetSection}, + {"version",PkgSrcRecordsGetVersion}, +#ifdef COMPAT_0_7 {"Binaries",PkgSrcRecordsGetBinaries}, {"BuildDepends",PkgSrcRecordsGetBuildDepends}, {"Files",PkgSrcRecordsGetFiles}, @@ -177,6 +191,7 @@ static PyGetSetDef PkgSrcRecordsGetSet[] = { {"Record",PkgSrcRecordsGetRecord}, {"Section",PkgSrcRecordsGetSection}, {"Version",PkgSrcRecordsGetVersion}, +#endif {} }; diff --git a/python/sourcelist.cc b/python/sourcelist.cc index 15311e94..daf0c08c 100644 --- a/python/sourcelist.cc +++ b/python/sourcelist.cc @@ -72,9 +72,14 @@ static PyObject *PkgSourceListGetIndexes(PyObject *Self,PyObject *Args) static PyMethodDef PkgSourceListMethods[] = { + {"find_index",PkgSourceListFindIndex,METH_VARARGS,doc_PkgSourceListFindIndex}, + {"read_main_list",PkgSourceListReadMainList,METH_VARARGS,doc_PkgSourceListReadMainList}, + {"get_indexes",PkgSourceListGetIndexes,METH_VARARGS,doc_PkgSourceListGetIndexes}, +#ifdef COMPAT_0_7 {"FindIndex",PkgSourceListFindIndex,METH_VARARGS,doc_PkgSourceListFindIndex}, {"ReadMainList",PkgSourceListReadMainList,METH_VARARGS,doc_PkgSourceListReadMainList}, {"GetIndexes",PkgSourceListGetIndexes,METH_VARARGS,doc_PkgSourceListGetIndexes}, +#endif {} }; @@ -93,7 +98,10 @@ static PyObject *PkgSourceListGetList(PyObject *Self,void*) } static PyGetSetDef PkgSourceListGetSet[] = { + {"list",PkgSourceListGetList,0,"A list of MetaIndex() objects.",0}, +#ifdef COMPAT_0_7 {"List",PkgSourceListGetList,0,"A list of MetaIndex() objects.",0}, +#endif {} }; diff --git a/python/tag.cc b/python/tag.cc index bc23e98b..846123ba 100644 --- a/python/tag.cc +++ b/python/tag.cc @@ -377,13 +377,20 @@ PyObject *RewriteSection(PyObject *self,PyObject *Args) static PyMethodDef TagSecMethods[] = { // Query + {"find",TagSecFind,METH_VARARGS,doc_Find}, + {"findflag",TagSecFindFlag,METH_VARARGS,doc_FindFlag}, + {"bytes",TagSecBytes,METH_VARARGS,doc_Bytes}, +#ifdef COMPAT_0_7 {"Find",TagSecFind,METH_VARARGS,doc_Find}, {"FindFlag",TagSecFindFlag,METH_VARARGS,doc_FindFlag}, {"Bytes",TagSecBytes,METH_VARARGS,doc_Bytes}, +#endif // Python Special {"keys",TagSecKeys,METH_VARARGS,doc_Keys}, +#if PY_MAJOR_VERSION < 3 {"has_key",TagSecExists,METH_VARARGS,doc_Exists}, +#endif {"get",TagSecFind,METH_VARARGS,doc_Find}, {} }; @@ -448,9 +455,14 @@ PyTypeObject TagSecType = static PyMethodDef TagFileMethods[] = { // Query + {"step",TagFileStep,METH_VARARGS,doc_Step}, + {"offset",TagFileOffset,METH_VARARGS,doc_Offset}, + {"jump",TagFileJump,METH_VARARGS,doc_Jump}, +#ifdef COMPAT_0_7 {"Step",TagFileStep,METH_VARARGS,doc_Step}, {"Offset",TagFileOffset,METH_VARARGS,doc_Offset}, {"Jump",TagFileJump,METH_VARARGS,doc_Jump}, +#endif {} }; @@ -463,7 +475,10 @@ static PyObject *TagFileGetSection(PyObject *Self,void*) { } static PyGetSetDef TagFileGetSet[] = { + {"section",TagFileGetSection,0,"Return a TagSection.",0}, +#ifdef COMPAT_0_7 {"Section",TagFileGetSection,0,"Return a TagSection.",0}, +#endif {} }; -- cgit v1.2.3 From 0726f9830527c0d5eb4aff7d71d983e5c69fa018 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Wed, 3 Jun 2009 17:51:04 +0200 Subject: python/apt_pkgmodule.cc: Rename STATE_* constants. --- python/apt_pkgmodule.cc | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) (limited to 'python') diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index ddd6d38b..44234f8d 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -673,23 +673,23 @@ extern "C" void initapt_pkg() PyModule_AddIntConstant(Module,"PriExtra",pkgCache::State::Extra); #endif // CurState - PyModule_AddIntConstant(Module,"STATE_NOTINSTALLED",pkgCache::State::NotInstalled); - PyModule_AddIntConstant(Module,"STATE_UNPACKED",pkgCache::State::UnPacked); - PyModule_AddIntConstant(Module,"STATE_HALFCONFIGURED",pkgCache::State::HalfConfigured); - PyModule_AddIntConstant(Module,"STATE_HALFINSTALLED",pkgCache::State::HalfInstalled); - PyModule_AddIntConstant(Module,"STATE_CONFIGFILES",pkgCache::State::ConfigFiles); - PyModule_AddIntConstant(Module,"STATE_INSTALLED",pkgCache::State::Installed); + PyModule_AddIntConstant(Module,"CURSTATE_NOTINSTALLED",pkgCache::State::NotInstalled); + PyModule_AddIntConstant(Module,"CURSTATE_UNPACKED",pkgCache::State::UnPacked); + PyModule_AddIntConstant(Module,"CURSTATE_HALFCONFIGURED",pkgCache::State::HalfConfigured); + PyModule_AddIntConstant(Module,"CURSTATE_HALFINSTALLED",pkgCache::State::HalfInstalled); + PyModule_AddIntConstant(Module,"CURSTATE_CONFIGFILES",pkgCache::State::ConfigFiles); + PyModule_AddIntConstant(Module,"CURSTATE_INSTALLED",pkgCache::State::Installed); // SelState - PyModule_AddIntConstant(Module,"STATE_UNKNOWN",pkgCache::State::Unknown); - PyModule_AddIntConstant(Module,"STATE_INSTALL",pkgCache::State::Install); - PyModule_AddIntConstant(Module,"STATE_HOLD",pkgCache::State::Hold); - PyModule_AddIntConstant(Module,"STATE_DEINSTALL",pkgCache::State::DeInstall); - PyModule_AddIntConstant(Module,"STATE_PURGE",pkgCache::State::Purge); + PyModule_AddIntConstant(Module,"SELSTATE_UNKNOWN",pkgCache::State::Unknown); + PyModule_AddIntConstant(Module,"SELSTATE_INSTALL",pkgCache::State::Install); + PyModule_AddIntConstant(Module,"SELSTATE_HOLD",pkgCache::State::Hold); + PyModule_AddIntConstant(Module,"SELSTATE_DEINSTALL",pkgCache::State::DeInstall); + PyModule_AddIntConstant(Module,"SELSTATE_PURGE",pkgCache::State::Purge); // InstState - PyModule_AddIntConstant(Module,"STATE_OK",pkgCache::State::Ok); - PyModule_AddIntConstant(Module,"STATE_REINSTREQ",pkgCache::State::ReInstReq); - PyModule_AddIntConstant(Module,"STATE_HOLD",pkgCache::State::Hold); - PyModule_AddIntConstant(Module,"STATE_HOLD_REINSTREQ",pkgCache::State::HoldReInstReq); + PyModule_AddIntConstant(Module,"INSTSTATE_OK",pkgCache::State::Ok); + PyModule_AddIntConstant(Module,"INSTSTATE_REINSTREQ",pkgCache::State::ReInstReq); + PyModule_AddIntConstant(Module,"INSTSTATE_HOLD",pkgCache::State::Hold); + PyModule_AddIntConstant(Module,"INSTSTATE_HOLD_REINSTREQ",pkgCache::State::HoldReInstReq); #ifdef COMPAT_0_7 PyModule_AddIntConstant(Module,"CurStateNotInstalled",pkgCache::State::NotInstalled); -- cgit v1.2.3 From 34f5670f3af2b04a4a575695584e46e4bf4106e9 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Thu, 4 Jun 2009 17:01:51 +0200 Subject: python/cache.cc, python/metaindex.cc: Convert remaining stuff to getset descriptors. --- python/cache.cc | 396 ++++++++++++++++++++++++++++++++++++---------------- python/metaindex.cc | 130 ++++++++++------- 2 files changed, 356 insertions(+), 170 deletions(-) (limited to 'python') diff --git a/python/cache.cc b/python/cache.cc index 644646a1..c7694026 100644 --- a/python/cache.cc +++ b/python/cache.cc @@ -745,63 +745,86 @@ static PyObject *MakeDepends(PyObject *Owner,pkgCache::VerIterator &Ver, return Dict; } -static PyObject *VersionAttr(PyObject *Self,char *Name) -{ +static inline pkgCache::VerIterator Version_GetVer(PyObject *Self) { + return GetCpp(Self); +} + +// Version attributes. +static PyObject *VersionGetVerStr(PyObject *Self, void*) { + return PyString_FromString(Version_GetVer(Self).VerStr()); +} +static PyObject *VersionGetSection(PyObject *Self, void*) { + return Safe_FromString(Version_GetVer(Self).Section()); +} +static PyObject *VersionGetArch(PyObject *Self, void*) { + return Safe_FromString(Version_GetVer(Self).Arch()); +} +static PyObject *VersionGetFileList(PyObject *Self, void*) { pkgCache::VerIterator &Ver = GetCpp(Self); PyObject *Owner = GetOwner(Self); - - if (strcmp("VerStr",Name) == 0) - return PyString_FromString(Ver.VerStr()); - else if (strcmp("Section",Name) == 0) - return Safe_FromString(Ver.Section()); - else if (strcmp("Arch",Name) == 0) - return Safe_FromString(Ver.Arch()); - else if (strcmp("FileList",Name) == 0) + PyObject *List = PyList_New(0); + for (pkgCache::VerFileIterator I = Ver.FileList(); I.end() == false; I++) { - /* The second value in the tuple is the index of the VF item. If the - user wants to request a lookup then that number will be used. - Maybe later it can become an object. */ - PyObject *List = PyList_New(0); - for (pkgCache::VerFileIterator I = Ver.FileList(); I.end() == false; I++) - { - PyObject *PkgFile; - PyObject *Obj; - PkgFile = CppOwnedPyObject_NEW(Owner,&PackageFileType,I.File()); - Obj = Py_BuildValue("Nl",PkgFile,I.Index()); - PyList_Append(List,Obj); - Py_DECREF(Obj); - } - return List; - } - else if (strcmp("DependsListStr",Name) == 0) - return MakeDepends(Owner,Ver,false); - else if (strcmp("DependsList",Name) == 0) - return MakeDepends(Owner,Ver,true); - else if (strcmp("ParentPkg",Name) == 0) - return CppOwnedPyObject_NEW(Owner,&PackageType, - Ver.ParentPkg()); - else if (strcmp("ProvidesList",Name) == 0) - return CreateProvides(Owner,Ver.ProvidesList()); - else if (strcmp("Size",Name) == 0) - return Py_BuildValue("i",Ver->Size); - else if (strcmp("InstalledSize",Name) == 0) - return Py_BuildValue("i",Ver->InstalledSize); - else if (strcmp("Hash",Name) == 0) - return Py_BuildValue("i",Ver->Hash); - else if (strcmp("ID",Name) == 0) - return Py_BuildValue("i",Ver->ID); - else if (strcmp("Priority",Name) == 0) - return Py_BuildValue("i",Ver->Priority); - else if (strcmp("PriorityStr",Name) == 0) - return Safe_FromString(Ver.PriorityType()); - else if (strcmp("Downloadable", Name) == 0) - return Py_BuildValue("b", Ver.Downloadable()); - else if (strcmp("TranslatedDescription", Name) == 0) { - return CppOwnedPyObject_NEW(Owner, - &DescriptionType, - Ver.TranslatedDescription()); + PyObject *PkgFile; + PyObject *Obj; + PkgFile = CppOwnedPyObject_NEW(Owner,&PackageFileType,I.File()); + Obj = Py_BuildValue("Nl",PkgFile,I.Index()); + PyList_Append(List,Obj); + Py_DECREF(Obj); } + return List; +} + +static PyObject *VersionGetDependsListStr(PyObject *Self, void*) { + pkgCache::VerIterator &Ver = GetCpp(Self); + PyObject *Owner = GetOwner(Self); + return MakeDepends(Owner,Ver,false); +} +static PyObject *VersionGetDependsList(PyObject *Self, void*) { + pkgCache::VerIterator &Ver = GetCpp(Self); + PyObject *Owner = GetOwner(Self); + return MakeDepends(Owner,Ver,true); +} +static PyObject *VersionGetParentPkg(PyObject *Self, void*) { + PyObject *Owner = GetOwner(Self); + return CppOwnedPyObject_NEW(Owner,&PackageType, + Version_GetVer(Self).ParentPkg()); +} +static PyObject *VersionGetProvidesList(PyObject *Self, void*) { + PyObject *Owner = GetOwner(Self); + return CreateProvides(Owner,Version_GetVer(Self).ProvidesList()); +} +static PyObject *VersionGetSize(PyObject *Self, void*) { + return Py_BuildValue("i", Version_GetVer(Self)->Size); +} +static PyObject *VersionGetInstalledSize(PyObject *Self, void*) { + return Py_BuildValue("i", Version_GetVer(Self)->InstalledSize); +} +static PyObject *VersionGetHash(PyObject *Self, void*) { + return Py_BuildValue("i", Version_GetVer(Self)->Hash); +} +static PyObject *VersionGetID(PyObject *Self, void*) { + return Py_BuildValue("i", Version_GetVer(Self)->ID); +} +static PyObject *VersionGetPriority(PyObject *Self, void*) { + return Py_BuildValue("i",Version_GetVer(Self)->Priority); +} +static PyObject *VersionGetPriorityStr(PyObject *Self, void*) { + return Safe_FromString(Version_GetVer(Self).PriorityType()); +} +static PyObject *VersionGetDownloadable(PyObject *Self, void*) { + return Py_BuildValue("b",Version_GetVer(Self).Downloadable()); +} +static PyObject *VersionGetTranslatedDescription(PyObject *Self, void*) { + pkgCache::VerIterator &Ver = GetCpp(Self); + PyObject *Owner = GetOwner(Self); + return CppOwnedPyObject_NEW(Owner, + &DescriptionType, + Ver.TranslatedDescription()); +} + #if 0 // FIXME: enable once pkgSourceList is stored somewhere +static PyObject *VersionGetIsTrusted(PyObject *Self, void*) { else if (strcmp("IsTrusted", Name) == 0) { pkgSourceList Sources; @@ -814,18 +837,16 @@ static PyObject *VersionAttr(PyObject *Self,char *Name) } return Py_BuildValue("b", true); } +} #endif - PyErr_SetString(PyExc_AttributeError,Name); - return 0; -} static PyObject *VersionRepr(PyObject *Self) { pkgCache::VerIterator &Ver = GetCpp(Self); char S[300]; - snprintf(S,sizeof(S),"", Ver.ParentPkg().Name(),Ver.VerStr(),Ver.Section(),Ver.Arch(), @@ -834,6 +855,44 @@ static PyObject *VersionRepr(PyObject *Self) return PyString_FromString(S); } +static PyGetSetDef VersionGetSet[] = { + {"arch",VersionGetArch}, + {"depends_list",VersionGetDependsList}, + {"depends_list_str",VersionGetDependsListStr}, + {"downloadable",VersionGetDownloadable}, + {"file_list",VersionGetFileList}, + {"hash",VersionGetHash}, + {"id",VersionGetID}, + {"installed_size",VersionGetInstalledSize}, + {"parent_pkg",VersionGetParentPkg}, + {"priority",VersionGetPriority}, + {"priority_str",VersionGetPriorityStr}, + {"provides_list",VersionGetProvidesList}, + {"section",VersionGetSection}, + {"size",VersionGetSize}, + {"translated_description",VersionGetTranslatedDescription}, + {"ver_str",VersionGetVerStr}, +#ifdef COMPAT_0_7 + {"Arch",VersionGetArch}, + {"DependsList",VersionGetDependsList}, + {"DependsListStr",VersionGetDependsListStr}, + {"Downloadable",VersionGetDownloadable}, + {"FileList",VersionGetFileList}, + {"Hash",VersionGetHash}, + {"ID",VersionGetID}, + {"InstalledSize",VersionGetInstalledSize}, + {"ParentPkg",VersionGetParentPkg}, + {"Priority",VersionGetPriority}, + {"PriorityStr",VersionGetPriorityStr}, + {"ProvidesList",VersionGetProvidesList}, + {"Section",VersionGetSection}, + {"Size",VersionGetSize}, + {"TranslationDescription",VersionGetTranslatedDescription}, + {"VerStr",VersionGetVerStr}, +#endif + {} +}; + PyTypeObject VersionType = { PyObject_HEAD_INIT(&PyType_Type) @@ -846,7 +905,7 @@ PyTypeObject VersionType = // Methods CppOwnedDealloc, // tp_dealloc 0, // tp_print - VersionAttr, // tp_getattr + 0, // tp_getattr 0, // tp_setattr 0, // tp_compare VersionRepr, // tp_repr @@ -854,86 +913,187 @@ PyTypeObject VersionType = 0, // tp_as_sequence 0, // tp_as_mapping 0, // tp_hash + 0, // tp_call + 0, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + Py_TPFLAGS_DEFAULT, // tp_flags + "Version Object", // tp_doc + 0, // tp_traverse + 0, // tp_clear + 0, // tp_richcompare + 0, // tp_weaklistoffset + 0, // tp_iter + 0, // tp_iternext + 0, // tp_methods + 0, // tp_members + VersionGetSet, // tp_getset }; /*}}}*/ // PackageFile Class /*{{{*/ // --------------------------------------------------------------------- -static PyObject *PackageFileAttr(PyObject *Self,char *Name) +static PyObject *PackageFile_GetFileName(PyObject *Self,void*) { - pkgCache::PkgFileIterator &File = GetCpp(Self); -// PyObject *Owner = GetOwner(Self); - - if (strcmp("FileName",Name) == 0) - return Safe_FromString(File.FileName()); - else if (strcmp("Archive",Name) == 0) - return Safe_FromString(File.Archive()); - else if (strcmp("Component",Name) == 0) - return Safe_FromString(File.Component()); - else if (strcmp("Version",Name) == 0) - return Safe_FromString(File.Version()); - else if (strcmp("Origin",Name) == 0) - return Safe_FromString(File.Origin()); - else if (strcmp("Label",Name) == 0) - return Safe_FromString(File.Label()); - else if (strcmp("Architecture",Name) == 0) - return Safe_FromString(File.Architecture()); - else if (strcmp("Site",Name) == 0) - return Safe_FromString(File.Site()); - else if (strcmp("IndexType",Name) == 0) - return Safe_FromString(File.IndexType()); - else if (strcmp("Size",Name) == 0) - return Py_BuildValue("i",File->Size); - else if (strcmp("NotSource",Name) == 0) - return Py_BuildValue("i",(File->Flags & pkgCache::Flag::NotSource) != 0); - else if (strcmp("NotAutomatic",Name) == 0) - return Py_BuildValue("i",(File->Flags & pkgCache::Flag::NotAutomatic) != 0); - else if (strcmp("ID",Name) == 0) - return Py_BuildValue("i",File->ID); - - PyErr_SetString(PyExc_AttributeError,Name); - return 0; + pkgCache::PkgFileIterator &File = GetCpp(Self); + return Safe_FromString(File.FileName()); } -static PyObject *PackageFileRepr(PyObject *Self) +static PyObject *PackageFile_GetArchive(PyObject *Self,void*) { - pkgCache::PkgFileIterator &File = GetCpp(Self); + pkgCache::PkgFileIterator &File = GetCpp(Self); + return Safe_FromString(File.Archive()); +} - char S[300]; - snprintf(S,sizeof(S),"", - File.FileName(),File.Archive(),File.Component(),File.Version(), - File.Origin(),File.Label(),File.Architecture(),File.Site(), - File.IndexType(),File->Size,File->Flags,File->ID); - return PyString_FromString(S); +static PyObject *PackageFile_GetComponent(PyObject *Self,void*) +{ + pkgCache::PkgFileIterator &File = GetCpp(Self); + return Safe_FromString(File.Component()); +} + +static PyObject *PackageFile_GetVersion(PyObject *Self,void*) +{ + pkgCache::PkgFileIterator &File = GetCpp(Self); + return Safe_FromString(File.Version()); +} + +static PyObject *PackageFile_GetOrigin(PyObject *Self,void*) +{ + pkgCache::PkgFileIterator &File = GetCpp(Self); + return Safe_FromString(File.Origin()); +} + +static PyObject *PackageFile_GetLabel(PyObject *Self,void*) +{ + pkgCache::PkgFileIterator &File = GetCpp(Self); + return Safe_FromString(File.Label()); +} + +static PyObject *PackageFile_GetArchitecture(PyObject *Self,void*) +{ + pkgCache::PkgFileIterator &File = GetCpp(Self); + return Safe_FromString(File.Architecture()); +} + +static PyObject *PackageFile_GetSite(PyObject *Self,void*) +{ + pkgCache::PkgFileIterator &File = GetCpp(Self); + return Safe_FromString(File.Site()); +} + +static PyObject *PackageFile_GetIndexType(PyObject *Self,void*) +{ + pkgCache::PkgFileIterator &File = GetCpp(Self); + return Safe_FromString(File.IndexType()); +} +static PyObject *PackageFile_GetSize(PyObject *Self,void*) +{ + pkgCache::PkgFileIterator &File = GetCpp(Self); + return Py_BuildValue("i",File->Size); +} + +static PyObject *PackageFile_GetNotSource(PyObject *Self,void*) +{ + pkgCache::PkgFileIterator &File = GetCpp(Self); + return Py_BuildValue("i",(File->Flags & pkgCache::Flag::NotSource) != 0); +} +static PyObject *PackageFile_GetNotAutomatic(PyObject *Self,void*) +{ + pkgCache::PkgFileIterator &File = GetCpp(Self); + return Py_BuildValue("i",(File->Flags & pkgCache::Flag::NotSource) != 0); } -PyTypeObject PackageFileType = +static PyObject *PackageFile_GetID(PyObject *Self,void*) { + pkgCache::PkgFileIterator &File = GetCpp(Self); + return Py_BuildValue("i",File->ID); +} + +static PyObject *PackageFileRepr(PyObject *Self) +{ + pkgCache::PkgFileIterator &File = GetCpp(Self); + + char S[300]; + snprintf(S,sizeof(S),"", + File.FileName(),File.Archive(),File.Component(),File.Version(), + File.Origin(),File.Label(),File.Architecture(),File.Site(), + File.IndexType(),File->Size,File->Flags,File->ID); + return PyString_FromString(S); +} + +static PyGetSetDef PackageFileGetSet[] = { + {(char*)"architecture",PackageFile_GetArchitecture}, + {(char*)"archive",PackageFile_GetArchive}, + {(char*)"component",PackageFile_GetComponent}, + {(char*)"file_name",PackageFile_GetFileName}, + {(char*)"id",PackageFile_GetID}, + {(char*)"index_type",PackageFile_GetIndexType}, + {(char*)"label",PackageFile_GetLabel}, + {(char*)"not_automatic",PackageFile_GetNotAutomatic}, + {(char*)"not_source",PackageFile_GetNotSource}, + {(char*)"origin",PackageFile_GetOrigin}, + {(char*)"site",PackageFile_GetSite}, + {(char*)"size",PackageFile_GetSize}, + {(char*)"version",PackageFile_GetVersion}, + #ifdef COMPAT_0_7 + {(char*)"Architecture",PackageFile_GetArchitecture}, + {(char*)"Archive",PackageFile_GetArchive}, + {(char*)"Component",PackageFile_GetComponent}, + {(char*)"FileName",PackageFile_GetFileName}, + {(char*)"ID",PackageFile_GetID}, + {(char*)"IndexType",PackageFile_GetIndexType}, + {(char*)"Label",PackageFile_GetLabel}, + {(char*)"NotAutomatic",PackageFile_GetNotAutomatic}, + {(char*)"NotSource",PackageFile_GetNotSource}, + {(char*)"Origin",PackageFile_GetOrigin}, + {(char*)"Site",PackageFile_GetSite}, + {(char*)"Size",PackageFile_GetSize}, + {(char*)"Version",PackageFile_GetVersion}, + #endif + {} +}; + +PyTypeObject PackageFileType = { PyObject_HEAD_INIT(&PyType_Type) #if PY_MAJOR_VERSION < 3 - 0, // ob_size + 0, // ob_size #endif - "apt_pkg.PackageFile", // tp_name - sizeof(CppOwnedPyObject), // tp_basicsize - 0, // tp_itemsize - // Methods - CppOwnedDealloc, // tp_dealloc - 0, // tp_print - PackageFileAttr, // tp_getattr - 0, // tp_setattr - 0, // tp_compare - PackageFileRepr, // tp_repr - 0, // tp_as_number - 0, // tp_as_sequence - 0, // tp_as_mapping - 0, // tp_hash + "apt_pkg.PackageFile", // tp_name + sizeof(CppOwnedPyObject), // tp_basicsize + 0, // tp_itemsize + CppOwnedDealloc, // tp_dealloc + 0, // tp_print + 0, // tp_getattr + 0, // tp_setattr + 0, // tp_compare + PackageFileRepr, // tp_repr + 0, // tp_as_number + 0, // tp_as_sequence + 0, // tp_as_mapping + 0, // tp_hash + 0, // tp_call + 0, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + Py_TPFLAGS_DEFAULT, // tp_flags + "apt_pkg.PackageFile Object", // tp_doc + 0, // tp_traverse + 0, // tp_clear + 0, // tp_richcompare + 0, // tp_weaklistoffset + 0, // tp_iter + 0, // tp_iternext + 0, // tp_methods + 0, // tp_members + PackageFileGetSet, // tp_getset }; - // depends class static PyObject *DependencyRepr(PyObject *Self) { diff --git a/python/metaindex.cc b/python/metaindex.cc index 557aacd8..b451f0b5 100644 --- a/python/metaindex.cc +++ b/python/metaindex.cc @@ -1,13 +1,13 @@ // -*- mode: cpp; mode: fold -*- -// Description /*{{{*/ +// Description /*{{{*/ // $Id: metaindex.cc,v 1.2 2003/12/26 17:04:22 mdz Exp $ /* ###################################################################### metaindex - Wrapper for the metaIndex functions ##################################################################### */ - /*}}}*/ -// Include Files /*{{{*/ + /*}}}*/ +// Include Files /*{{{*/ #include "generic.h" #include "apt_pkgmodule.h" @@ -15,69 +15,95 @@ #include +static PyObject *MetaIndexGetURI(PyObject *Self,void*) { + metaIndex *meta = GetCpp(Self); + return Safe_FromString(meta->GetURI().c_str()); +} -static PyObject *MetaIndexAttr(PyObject *Self,char *Name) -{ - metaIndex *meta = GetCpp(Self); - if (strcmp("URI",Name) == 0) - return Safe_FromString(meta->GetURI().c_str()); - else if (strcmp("Dist",Name) == 0) - return Safe_FromString(meta->GetDist().c_str()); - else if (strcmp("IsTrusted",Name) == 0) - return Py_BuildValue("i",(meta->IsTrusted())); - else if (strcmp("IndexFiles",Name) == 0) - { - PyObject *List = PyList_New(0); - vector *indexFiles = meta->GetIndexFiles(); - for (vector::const_iterator I = indexFiles->begin(); - I != indexFiles->end(); I++) - { - PyObject *Obj; - Obj = CppPyObject_NEW(&PackageIndexFileType,*I); - PyList_Append(List,Obj); - } - return List; - } +static PyObject *MetaIndexGetDist(PyObject *Self,void*) { + metaIndex *meta = GetCpp(Self); + return Safe_FromString(meta->GetDist().c_str()); +} - PyErr_SetString(PyExc_AttributeError,Name); - return 0; +static PyObject *MetaIndexGetIsTrusted(PyObject *Self,void*) { + metaIndex *meta = GetCpp(Self); + return Py_BuildValue("i",(meta->IsTrusted())); } +static PyObject *MetaIndexGetIndexFiles(PyObject *Self,void*) { + metaIndex *meta = GetCpp(Self); + PyObject *List = PyList_New(0); + vector *indexFiles = meta->GetIndexFiles(); + for (vector::const_iterator I = indexFiles->begin(); + I != indexFiles->end(); I++) + { + PyObject *Obj; + Obj = CppPyObject_NEW(&PackageIndexFileType,*I); + PyList_Append(List,Obj); + } + return List; +} + +static PyGetSetDef MetaIndexGetSet[] = { + {"dist",MetaIndexGetDist}, + {"index_files",MetaIndexGetIndexFiles}, + {"is_trusted",MetaIndexGetIsTrusted}, + {"uri",MetaIndexGetURI}, + #ifdef COMPAT_0_7 + {"Dist",MetaIndexGetDist}, + {"IndexFiles",MetaIndexGetIndexFiles}, + {"IsTrusted",MetaIndexGetIsTrusted}, + {"URI",MetaIndexGetURI}, + #endif + {} +}; + static PyObject *MetaIndexRepr(PyObject *Self) { - metaIndex *meta = GetCpp(Self); - - char S[1024]; - snprintf(S,sizeof(S),"", - meta->GetType(), meta->GetURI().c_str(), meta->GetDist().c_str(), - meta->IsTrusted()); + metaIndex *meta = GetCpp(Self); - return PyString_FromString(S); + char S[1024]; + snprintf(S,sizeof(S),"", + meta->GetType(), meta->GetURI().c_str(), meta->GetDist().c_str(), + meta->IsTrusted()); + return PyString_FromString(S); } PyTypeObject MetaIndexType = { PyObject_HEAD_INIT(&PyType_Type) #if PY_MAJOR_VERSION < 3 - 0, // ob_size + 0, // ob_size #endif - "apt_pkg.MetaIndex", // tp_name + "apt_pkg.MetaIndex", // tp_name sizeof(CppOwnedPyObject), // tp_basicsize - 0, // tp_itemsize + 0, // tp_itemsize // Methods - CppOwnedDealloc, // tp_dealloc - 0, // tp_print - MetaIndexAttr, // tp_getattr - 0, // tp_setattr - 0, // tp_compare - MetaIndexRepr, // tp_repr - 0, // tp_as_number - 0, // tp_as_sequence - 0, // tp_as_mapping - 0, // tp_hash + CppOwnedDealloc, // tp_dealloc + 0, // tp_print + 0, // tp_getattr + 0, // tp_setattr + 0, // tp_compare + MetaIndexRepr, // tp_repr + 0, // tp_as_number + 0, // tp_as_sequence + 0, // tp_as_mapping + 0, // tp_hash + 0, // tp_call + 0, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + Py_TPFLAGS_DEFAULT, // tp_flags + "apt_pkg.MetaIndex Object", // tp_doc + 0, // tp_traverse + 0, // tp_clear + 0, // tp_richcompare + 0, // tp_weaklistoffset + 0, // tp_iter + 0, // tp_iternext + 0, // tp_methods + 0, // tp_members + MetaIndexGetSet, // tp_getset }; - - - - -- cgit v1.2.3 From 884c8a4ebdfcedf8143dcb2ce8ef92779c353e06 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Thu, 4 Jun 2009 17:18:29 +0200 Subject: python/: Unify naming conventions for all new names. Unify all names to follow these rules: 1. Replace the first [A-Z] with the lowercase version [a-z] 2. Replace multiple [A-Z] with [A-Z][a-z] (one upper, remaining ones lowercase) 3. Replace all remaining [A-Z] with _[a-z] This brings us from 'FileName' to 'file_name' and from 'DescURI' to 'desc_uri'. We will at a later stage add some exceptions to this rule, like 'filename' instead of 'file_name', to improve readability. --- python/acquire.cc | 8 ++++---- python/apt_pkgmodule.cc | 36 ++++++++++++++++++------------------ python/cache.cc | 30 +++++++++++++++--------------- python/configuration.cc | 6 +++--- python/depcache.cc | 20 ++++++++++---------- python/pkgrecords.cc | 16 ++++++++-------- python/pkgsrcrecords.cc | 2 +- python/tag.cc | 2 +- 8 files changed, 60 insertions(+), 60 deletions(-) (limited to 'python') diff --git a/python/acquire.cc b/python/acquire.cc index 6cb2130c..1b1c5dd8 100644 --- a/python/acquire.cc +++ b/python/acquire.cc @@ -39,10 +39,10 @@ MkGet(AcquireItemGetStatAuthError,Py_BuildValue("i", pkgAcquire::Item::StatAuthE static PyGetSetDef AcquireItemGetSet[] = { {"complete",AcquireItemGetComplete}, - {"descuri",AcquireItemGetDescURI}, - {"destfile",AcquireItemGetDestFile}, - {"errortext",AcquireItemGetErrorText}, - {"filesize",AcquireItemGetFileSize}, + {"desc_uri",AcquireItemGetDescURI}, + {"dest_file",AcquireItemGetDestFile}, + {"error_text",AcquireItemGetErrorText}, + {"file_size",AcquireItemGetFileSize}, {"is",AcquireItemGetID}, {"is_trusted",AcquireItemGetIsTrusted}, {"local",AcquireItemGetLocal}, diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index 44234f8d..8259d7c3 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -407,7 +407,7 @@ static PyMethodDef methods[] = // Locking {"get_lock",GetLock,METH_VARARGS,doc_GetLock}, {"pkgsystem_lock",PkgSystemLock,METH_VARARGS,doc_PkgSystemLock}, - {"pkgsystem_unlock",PkgSystemUnLock,METH_VARARGS,doc_PkgSystemUnLock}, + {"pkgsystem_un_lock",PkgSystemUnLock,METH_VARARGS,doc_PkgSystemUnLock}, #ifdef COMPAT_0_7 {"GetLock",GetLock,METH_VARARGS,doc_GetLock}, {"PkgSystemLock",PkgSystemLock,METH_VARARGS,doc_PkgSystemLock}, @@ -415,10 +415,10 @@ static PyMethodDef methods[] = #endif // Command line - {"read_configfile",LoadConfig,METH_VARARGS,doc_LoadConfig}, - {"read_configdir",LoadConfigDir,METH_VARARGS,doc_LoadConfigDir}, - {"read_configfile_isc",LoadConfigISC,METH_VARARGS,doc_LoadConfig}, - {"parse_commandline",ParseCommandLine,METH_VARARGS,doc_ParseCommandLine}, + {"read_config_file",LoadConfig,METH_VARARGS,doc_LoadConfig}, + {"read_config_dir",LoadConfigDir,METH_VARARGS,doc_LoadConfigDir}, + {"read_config_file_isc",LoadConfigISC,METH_VARARGS,doc_LoadConfig}, + {"parse_command_line",ParseCommandLine,METH_VARARGS,doc_ParseCommandLine}, #ifdef COMPAT_0_7 {"ReadConfigFile",LoadConfig,METH_VARARGS,doc_LoadConfig}, {"ReadConfigDir",LoadConfigDir,METH_VARARGS,doc_LoadConfigDir}, @@ -438,7 +438,7 @@ static PyMethodDef methods[] = // Depends {"parse_depends",ParseDepends,METH_VARARGS,doc_ParseDepends}, - {"parse_srcdepends",ParseSrcDepends,METH_VARARGS,doc_ParseDepends}, + {"parse_src_depends",ParseSrcDepends,METH_VARARGS,doc_ParseDepends}, #ifdef COMPAT_0_7 {"ParseDepends",ParseDepends,METH_VARARGS,doc_ParseDepends}, {"ParseSrcDepends",ParseSrcDepends,METH_VARARGS,doc_ParseDepends}, @@ -450,12 +450,12 @@ static PyMethodDef methods[] = {"sha256sum",sha256sum,METH_VARARGS,doc_sha256sum}, // Strings - {"check_domainlist",StrCheckDomainList,METH_VARARGS,"CheckDomainList(String,String) -> Bool"}, + {"check_domain_list",StrCheckDomainList,METH_VARARGS,"CheckDomainList(String,String) -> Bool"}, {"quote_string",StrQuoteString,METH_VARARGS,"QuoteString(String,String) -> String"}, - {"dequote_string",StrDeQuote,METH_VARARGS,"DeQuoteString(String) -> String"}, + {"de_quote_string",StrDeQuote,METH_VARARGS,"DeQuoteString(String) -> String"}, {"size_to_str",StrSizeToStr,METH_VARARGS,"SizeToStr(int) -> String"}, {"time_to_str",StrTimeToStr,METH_VARARGS,"TimeToStr(int) -> String"}, - {"uri_to_filename",StrURItoFileName,METH_VARARGS,"URItoFileName(String) -> String"}, + {"uri_to_file_name",StrURItoFileName,METH_VARARGS,"URItoFileName(String) -> String"}, {"base64_encode",StrBase64Encode,METH_VARARGS,"Base64Encode(String) -> String"}, {"string_to_bool",StrStringToBool,METH_VARARGS,"StringToBool(String) -> int"}, {"time_rfc1123",StrTimeRFC1123,METH_VARARGS,"TimeRFC1123(int) -> String"}, @@ -644,7 +644,7 @@ extern "C" void initapt_pkg() // My constants PyModule_AddIntConstant(Module,"DEP_DEPENDS",pkgCache::Dep::Depends); - PyModule_AddIntConstant(Module,"DEP_PREDEPENDS",pkgCache::Dep::PreDepends); + PyModule_AddIntConstant(Module,"DEP_PRE_DEPENDS",pkgCache::Dep::PreDepends); PyModule_AddIntConstant(Module,"DEP_SUGGESTS",pkgCache::Dep::Suggests); PyModule_AddIntConstant(Module,"DEP_RECOMMENDS",pkgCache::Dep::Recommends); PyModule_AddIntConstant(Module,"DEP_CONFLICTS",pkgCache::Dep::Conflicts); @@ -673,23 +673,23 @@ extern "C" void initapt_pkg() PyModule_AddIntConstant(Module,"PriExtra",pkgCache::State::Extra); #endif // CurState - PyModule_AddIntConstant(Module,"CURSTATE_NOTINSTALLED",pkgCache::State::NotInstalled); - PyModule_AddIntConstant(Module,"CURSTATE_UNPACKED",pkgCache::State::UnPacked); - PyModule_AddIntConstant(Module,"CURSTATE_HALFCONFIGURED",pkgCache::State::HalfConfigured); - PyModule_AddIntConstant(Module,"CURSTATE_HALFINSTALLED",pkgCache::State::HalfInstalled); - PyModule_AddIntConstant(Module,"CURSTATE_CONFIGFILES",pkgCache::State::ConfigFiles); + PyModule_AddIntConstant(Module,"CURSTATE_NOT_INSTALLED",pkgCache::State::NotInstalled); + PyModule_AddIntConstant(Module,"CURSTATE_UN_PACKED",pkgCache::State::UnPacked); + PyModule_AddIntConstant(Module,"CURSTATE_HALF_CONFIGURED",pkgCache::State::HalfConfigured); + PyModule_AddIntConstant(Module,"CURSTATE_HALF_INSTALLED",pkgCache::State::HalfInstalled); + PyModule_AddIntConstant(Module,"CURSTATE_CONFIG_FILES",pkgCache::State::ConfigFiles); PyModule_AddIntConstant(Module,"CURSTATE_INSTALLED",pkgCache::State::Installed); // SelState PyModule_AddIntConstant(Module,"SELSTATE_UNKNOWN",pkgCache::State::Unknown); PyModule_AddIntConstant(Module,"SELSTATE_INSTALL",pkgCache::State::Install); PyModule_AddIntConstant(Module,"SELSTATE_HOLD",pkgCache::State::Hold); - PyModule_AddIntConstant(Module,"SELSTATE_DEINSTALL",pkgCache::State::DeInstall); + PyModule_AddIntConstant(Module,"SELSTATE_DE_INSTALL",pkgCache::State::DeInstall); PyModule_AddIntConstant(Module,"SELSTATE_PURGE",pkgCache::State::Purge); // InstState PyModule_AddIntConstant(Module,"INSTSTATE_OK",pkgCache::State::Ok); - PyModule_AddIntConstant(Module,"INSTSTATE_REINSTREQ",pkgCache::State::ReInstReq); + PyModule_AddIntConstant(Module,"INSTSTATE_RE_INST_REQ",pkgCache::State::ReInstReq); PyModule_AddIntConstant(Module,"INSTSTATE_HOLD",pkgCache::State::Hold); - PyModule_AddIntConstant(Module,"INSTSTATE_HOLD_REINSTREQ",pkgCache::State::HoldReInstReq); + PyModule_AddIntConstant(Module,"INSTSTATE_HOLD_RE_INST_REQ",pkgCache::State::HoldReInstReq); #ifdef COMPAT_0_7 PyModule_AddIntConstant(Module,"CurStateNotInstalled",pkgCache::State::NotInstalled); diff --git a/python/cache.cc b/python/cache.cc index c7694026..27b77773 100644 --- a/python/cache.cc +++ b/python/cache.cc @@ -196,12 +196,12 @@ static PyObject *PkgCacheGetFileList(PyObject *Self, void*) { static PyGetSetDef PkgCacheGetSet[] = { {"depends_count",PkgCacheGetDependsCount}, - {"filelist",PkgCacheGetFileList}, + {"file_list",PkgCacheGetFileList}, {"package_count",PkgCacheGetPackageCount}, - {"packagefile_count",PkgCacheGetPackageFileCount}, + {"package_file_count",PkgCacheGetPackageFileCount}, {"packages",PkgCacheGetPackages}, {"provides_count",PkgCacheGetProvidesCount}, - {"verfile_count",PkgCacheGetVerFileCount}, + {"ver_file_count",PkgCacheGetVerFileCount}, {"version_count",PkgCacheGetVersionCount}, #ifdef COMPAT_0_7 {"DependsCount",PkgCacheGetDependsCount}, @@ -499,8 +499,8 @@ static PyObject *PackageGetCurrentVer(PyObject *Self,void*) static PyGetSetDef PackageGetSet[] = { {"name",PackageGetName}, {"section",PackageGetSection}, - {"revdependslist",PackageGetRevDependsList}, - {"provideslist",PackageGetProvidesList}, + {"rev_depends_list",PackageGetRevDependsList}, + {"provides_list",PackageGetProvidesList}, {"selected_state",PackageGetSelectedState}, {"inst_state",PackageGetInstState}, {"current_state",PackageGetCurrentState}, @@ -508,8 +508,8 @@ static PyGetSetDef PackageGetSet[] = { {"auto",PackageGetAuto}, {"essential",PackageGetEssential}, {"important",PackageGetImportant}, - {"versionlist",PackageGetVersionList}, - {"currentver",PackageGetCurrentVer}, + {"version_list",PackageGetVersionList}, + {"current_ver",PackageGetCurrentVer}, #ifdef COMPAT_0_7 {"Name",PackageGetName}, {"Section",PackageGetSection}, @@ -609,9 +609,9 @@ static PyObject *DescriptionGetFileList(PyObject *Self,void*) } static PyGetSetDef DescriptionGetSet[] = { - {"languagecode",DescriptionGetLanguageCode}, + {"language_code",DescriptionGetLanguageCode}, {"md5",DescriptionGetMd5}, - {"filelist",DescriptionGetFileList}, + {"file_list",DescriptionGetFileList}, #ifdef COMPAT_0_7 {"LanguageCode",DescriptionGetLanguageCode}, {"FileList",DescriptionGetFileList}, @@ -1212,13 +1212,13 @@ static PyObject *DependencyGetID(PyObject *Self,void*) } static PyGetSetDef DependencyGetSet[] = { - {"comptype",DependencyGetCompType}, - {"deptype",DependencyGetDepType}, + {"comp_type",DependencyGetCompType}, + {"dep_type",DependencyGetDepType}, {"id",DependencyGetID}, - {"parentpkg",DependencyGetParentPkg}, - {"parentver",DependencyGetParentVer}, - {"targetpkg",DependencyGetTargetPkg}, - {"targetver",DependencyGetTargetVer}, + {"parent_pkg",DependencyGetParentPkg}, + {"parent_ver",DependencyGetParentVer}, + {"target_pkg",DependencyGetTargetPkg}, + {"target_ver",DependencyGetTargetVer}, #ifdef COMPAT_0_7 {"CompType",DependencyGetCompType}, {"DepType",DependencyGetDepType}, diff --git a/python/configuration.cc b/python/configuration.cc index 107cf90f..7b08d90e 100644 --- a/python/configuration.cc +++ b/python/configuration.cc @@ -462,10 +462,10 @@ static PyMethodDef CnfMethods[] = // Others {"set",CnfSet,METH_VARARGS,doc_Set}, {"exists",CnfExists,METH_VARARGS,doc_Exists}, - {"subtree",CnfSubTree,METH_VARARGS,doc_SubTree}, + {"sub_tree",CnfSubTree,METH_VARARGS,doc_SubTree}, {"list",CnfList,METH_VARARGS,doc_List}, - {"valuelist",CnfValueList,METH_VARARGS,doc_ValueList}, - {"mytag",CnfMyTag,METH_VARARGS,doc_MyTag}, + {"value_list",CnfValueList,METH_VARARGS,doc_ValueList}, + {"my_tag",CnfMyTag,METH_VARARGS,doc_MyTag}, {"clear",CnfClear,METH_VARARGS,doc_Clear}, #ifdef COMPAT_0_7 {"Find",CnfFind,METH_VARARGS,doc_Find}, diff --git a/python/depcache.cc b/python/depcache.cc index f3b16211..650dcb23 100644 --- a/python/depcache.cc +++ b/python/depcache.cc @@ -529,19 +529,19 @@ static PyObject *PkgDepCacheMarkedReinstall(PyObject *Self,PyObject *Args) static PyMethodDef PkgDepCacheMethods[] = { {"init",PkgDepCacheInit,METH_VARARGS,"Init the depcache (done on construct automatically)"}, - {"get_candidate",PkgDepCacheGetCandidateVer,METH_VARARGS,"Get candidate version"}, - {"set_candidate",PkgDepCacheSetCandidateVer,METH_VARARGS,"Set candidate version"}, + {"get_candidate_ver",PkgDepCacheGetCandidateVer,METH_VARARGS,"Get candidate version"}, + {"set_candidate_ver",PkgDepCacheSetCandidateVer,METH_VARARGS,"Set candidate version"}, // global cache operations {"upgrade",PkgDepCacheUpgrade,METH_VARARGS,"Perform Upgrade (optional boolean argument if dist-upgrade should be performed)"}, {"fix_broken",PkgDepCacheFixBroken,METH_VARARGS,"Fix broken packages"}, - {"read_pinfile",PkgDepCacheReadPinFile,METH_VARARGS,"Read the pin policy"}, + {"read_pin_file",PkgDepCacheReadPinFile,METH_VARARGS,"Read the pin policy"}, {"minimize_upgrade",PkgDepCacheMinimizeUpgrade, METH_VARARGS,"Go over the entire set of packages and try to keep each package marked for upgrade. If a conflict is generated then the package is restored."}, // Manipulators {"mark_keep",PkgDepCacheMarkKeep,METH_VARARGS,"Mark package for keep"}, {"mark_delete",PkgDepCacheMarkDelete,METH_VARARGS,"Mark package for delete (optional boolean argument if it should be purged)"}, {"mark_install",PkgDepCacheMarkInstall,METH_VARARGS,"Mark package for Install"}, - {"set_reinstall",PkgDepCacheSetReInstall,METH_VARARGS,"Set if the package should be reinstalled"}, + {"set_re_install",PkgDepCacheSetReInstall,METH_VARARGS,"Set if the package should be reinstalled"}, // state information {"is_upgradable",PkgDepCacheIsUpgradable,METH_VARARGS,"Is pkg upgradable"}, {"is_now_broken",PkgDepCacheIsNowBroken,METH_VARARGS,"Is pkg is now broken"}, @@ -607,12 +607,12 @@ static PyObject *PkgDepCacheGetDebSize(PyObject *Self,void*) { #undef depcache static PyGetSetDef PkgDepCacheGetSet[] = { - {"brokencount",PkgDepCacheGetBrokenCount}, - {"debsize",PkgDepCacheGetDebSize}, - {"delcount",PkgDepCacheGetDelCount}, - {"instcount",PkgDepCacheGetInstCount}, - {"keepcount",PkgDepCacheGetKeepCount}, - {"usrsize",PkgDepCacheGetUsrSize}, + {"broken_count",PkgDepCacheGetBrokenCount}, + {"deb_size",PkgDepCacheGetDebSize}, + {"del_count",PkgDepCacheGetDelCount}, + {"inst_count",PkgDepCacheGetInstCount}, + {"keep_count",PkgDepCacheGetKeepCount}, + {"usr_size",PkgDepCacheGetUsrSize}, #ifdef COMPAT_0_7 {"BrokenCount",PkgDepCacheGetBrokenCount}, {"DebSize",PkgDepCacheGetDebSize}, diff --git a/python/pkgrecords.cc b/python/pkgrecords.cc index f9e48352..48440387 100644 --- a/python/pkgrecords.cc +++ b/python/pkgrecords.cc @@ -120,18 +120,18 @@ static PyObject *PkgRecordsGetRecord(PyObject *Self,void*) { return PyString_FromStringAndSize(start,stop-start); } static PyGetSetDef PkgRecordsGetSet[] = { - {"filename",PkgRecordsGetFileName}, + {"file_name",PkgRecordsGetFileName}, {"homepage",PkgRecordsGetHomepage}, - {"longdesc",PkgRecordsGetLongDesc}, - {"md5",PkgRecordsGetMD5Hash}, + {"long_desc",PkgRecordsGetLongDesc}, + {"md5_hash",PkgRecordsGetMD5Hash}, {"maintainer",PkgRecordsGetMaintainer}, {"name",PkgRecordsGetName}, {"record",PkgRecordsGetRecord}, - {"sha1",PkgRecordsGetSHA1Hash}, - {"sha256",PkgRecordsGetSHA256Hash}, - {"shortdesc",PkgRecordsGetShortDesc}, - {"sourcepkg",PkgRecordsGetSourcePkg}, - {"sourcever",PkgRecordsGetSourceVer}, + {"sha1_hash",PkgRecordsGetSHA1Hash}, + {"sha256_hash",PkgRecordsGetSHA256Hash}, + {"short_desc",PkgRecordsGetShortDesc}, + {"source_pkg",PkgRecordsGetSourcePkg}, + {"source_ver",PkgRecordsGetSourceVer}, #ifdef COMPAT_0_7 {"FileName",PkgRecordsGetFileName}, {"Homepage",PkgRecordsGetHomepage}, diff --git a/python/pkgsrcrecords.cc b/python/pkgsrcrecords.cc index 2a8b7bab..dea7ff37 100644 --- a/python/pkgsrcrecords.cc +++ b/python/pkgsrcrecords.cc @@ -173,7 +173,7 @@ static PyObject *PkgSrcRecordsGetBuildDepends(PyObject *Self,void*) { static PyGetSetDef PkgSrcRecordsGetSet[] = { {"binaries",PkgSrcRecordsGetBinaries}, - {"builddepends",PkgSrcRecordsGetBuildDepends}, + {"build_depends",PkgSrcRecordsGetBuildDepends}, {"files",PkgSrcRecordsGetFiles}, {"index",PkgSrcRecordsGetIndex}, {"maintainer",PkgSrcRecordsGetMaintainer}, diff --git a/python/tag.cc b/python/tag.cc index 846123ba..c30adb0a 100644 --- a/python/tag.cc +++ b/python/tag.cc @@ -378,7 +378,7 @@ static PyMethodDef TagSecMethods[] = { // Query {"find",TagSecFind,METH_VARARGS,doc_Find}, - {"findflag",TagSecFindFlag,METH_VARARGS,doc_FindFlag}, + {"find_flag",TagSecFindFlag,METH_VARARGS,doc_FindFlag}, {"bytes",TagSecBytes,METH_VARARGS,doc_Bytes}, #ifdef COMPAT_0_7 {"Find",TagSecFind,METH_VARARGS,doc_Find}, -- cgit v1.2.3 From 12302575b6b6f67e62466349db8580426484cea1 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Thu, 4 Jun 2009 18:02:50 +0200 Subject: python/cache.cc: Remove some (char*) to make migrate-0.8.py work again. --- python/cache.cc | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) (limited to 'python') diff --git a/python/cache.cc b/python/cache.cc index 27b77773..21a6a872 100644 --- a/python/cache.cc +++ b/python/cache.cc @@ -1041,19 +1041,19 @@ static PyGetSetDef PackageFileGetSet[] = { {(char*)"size",PackageFile_GetSize}, {(char*)"version",PackageFile_GetVersion}, #ifdef COMPAT_0_7 - {(char*)"Architecture",PackageFile_GetArchitecture}, - {(char*)"Archive",PackageFile_GetArchive}, - {(char*)"Component",PackageFile_GetComponent}, - {(char*)"FileName",PackageFile_GetFileName}, - {(char*)"ID",PackageFile_GetID}, - {(char*)"IndexType",PackageFile_GetIndexType}, - {(char*)"Label",PackageFile_GetLabel}, - {(char*)"NotAutomatic",PackageFile_GetNotAutomatic}, - {(char*)"NotSource",PackageFile_GetNotSource}, - {(char*)"Origin",PackageFile_GetOrigin}, - {(char*)"Site",PackageFile_GetSite}, - {(char*)"Size",PackageFile_GetSize}, - {(char*)"Version",PackageFile_GetVersion}, + {"Architecture",PackageFile_GetArchitecture}, + {"Archive",PackageFile_GetArchive}, + {"Component",PackageFile_GetComponent}, + {"FileName",PackageFile_GetFileName}, + {"ID",PackageFile_GetID}, + {"IndexType",PackageFile_GetIndexType}, + {"Label",PackageFile_GetLabel}, + {"NotAutomatic",PackageFile_GetNotAutomatic}, + {"NotSource",PackageFile_GetNotSource}, + {"Origin",PackageFile_GetOrigin}, + {"Site",PackageFile_GetSite}, + {"Size",PackageFile_GetSize}, + {"Version",PackageFile_GetVersion}, #endif {} }; -- cgit v1.2.3 From 75567ebb307ea8cdc9a7c36d8d5a9beb3aca1aa6 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Thu, 4 Jun 2009 18:47:00 +0200 Subject: python/apt_pkgmodule.cc: Make sure all types are ready. --- python/apt_pkgmodule.cc | 19 +------------------ 1 file changed, 1 insertion(+), 18 deletions(-) (limited to 'python') diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index 8259d7c3..bfabc652 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -501,6 +501,7 @@ static PyMethodDef methods[] = #define ADDTYPE(mod,name,type) { Py_INCREF(type); \ + if (PyType_Ready(type) == -1) INIT_ERROR; \ PyModule_AddObject(mod,name,(PyObject *)type); } @@ -541,26 +542,8 @@ extern "C" void initapt_pkg() #endif { // Finalize our types to add slots, etc. - if (PyType_Ready(&TagSecType) == -1) INIT_ERROR; - if (PyType_Ready(&TagFileType) == -1) INIT_ERROR; - if (PyType_Ready(&ConfigurationType) == -1) INIT_ERROR; if (PyType_Ready(&ConfigurationPtrType) == -1) INIT_ERROR; if (PyType_Ready(&ConfigurationSubType) == -1) INIT_ERROR; - if (PyType_Ready(&PkgCdromType) == -1) INIT_ERROR; - if (PyType_Ready(&PkgProblemResolverType) == -1) INIT_ERROR; - if (PyType_Ready(&PkgActionGroupType) == -1) INIT_ERROR; - if (PyType_Ready(&PkgSourceListType) == -1) INIT_ERROR; - if (PyType_Ready(&PkgCacheType) == -1) INIT_ERROR; - if (PyType_Ready(&DependencyType) == -1) INIT_ERROR; - if (PyType_Ready(&PkgDepCacheType) == -1) INIT_ERROR; - if (PyType_Ready(&PkgAcquireType) == -1) INIT_ERROR; - if (PyType_Ready(&PackageIndexFileType) == -1) INIT_ERROR; - if (PyType_Ready(&PkgManagerType) == -1) INIT_ERROR; - if (PyType_Ready(&PkgSrcRecordsType) == -1) INIT_ERROR; - if (PyType_Ready(&PkgRecordsType) == -1) INIT_ERROR; - if (PyType_Ready(&AcquireItemType) == -1) INIT_ERROR; - if (PyType_Ready(&PackageType) == -1) INIT_ERROR; - if (PyType_Ready(&DescriptionType) == -1) INIT_ERROR; // Initialize the module #if PY_MAJOR_VERSION >= 3 -- cgit v1.2.3 From 14dfadc054e9bdafd2507dbca70dbec925471ae0 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Fri, 5 Jun 2009 15:00:15 +0200 Subject: Introduce the rename rules formally, and add some exceptions. --- apt/cache.py | 4 +- apt/package.py | 10 ++--- doc/source/apt_pkg.rst | 36 ++++++++-------- doc/source/examples/cache-pkgfile.py | 2 +- doc/source/whatsnew/0.8.0.rst | 82 +++++++++++++++++++++++++++++++++++- python/acquire.cc | 10 ++--- python/apt_pkgmodule.cc | 16 +++---- python/cache.cc | 2 +- python/configuration.cc | 2 +- python/depcache.cc | 4 +- python/pkgrecords.cc | 2 +- 11 files changed, 124 insertions(+), 46 deletions(-) (limited to 'python') diff --git a/apt/cache.py b/apt/cache.py index 56b32d45..8590510c 100644 --- a/apt/cache.py +++ b/apt/cache.py @@ -170,8 +170,8 @@ class Cache(object): reqreinst = set() for pkg in self: if (not pkg.candidate.downloadable and - (pkg._pkg.inst_state == apt_pkg.INSTSTATE_RE_INST_REQ or - pkg._pkg.inst_state == apt_pkg.INSTSTATE_HOLD_RE_INST_REQ)): + (pkg._pkg.inst_state == apt_pkg.INSTSTATE_REINSTREQ or + pkg._pkg.inst_state == apt_pkg.INSTSTATE_HOLD_REINSTREQ)): reqreinst.add(pkg.name) return reqreinst diff --git a/apt/package.py b/apt/package.py index a24486e1..48d14595 100644 --- a/apt/package.py +++ b/apt/package.py @@ -379,7 +379,7 @@ class Version(object): .. versionadded:: 0.7.10 """ - return self._records.file_name + return self._records.filename @property def md5(self): @@ -413,7 +413,7 @@ class Version(object): for (packagefile, index) in self._cand.file_list: indexfile = self.package._pcache._list.find_index(packagefile) if indexfile: - yield indexfile.archive_uri(self._records.file_name) + yield indexfile.archive_uri(self._records.filename) @property def uris(self): @@ -443,19 +443,19 @@ class Version(object): .. versionadded:: 0.7.10 """ - base = os.path.basename(self._records.file_name) + base = os.path.basename(self._records.filename) destfile = os.path.join(destdir, base) if _file_is_same(destfile, self.size, self._records.md5_hash): print 'Ignoring already existing file:', destfile return acq = apt_pkg.Acquire(progress or apt.progress.TextFetchProgress()) apt_pkg.AcquireFile(acq, self.uri, self._records.md5_hash, self.size, - base, dest_file=destfile) + base, destfile=destfile) acq.run() for item in acq.items: if item.status != item.stat_done: raise FetchError("The item %r could not be fetched: %s" % - (item.dest_file, item.error_text)) + (item.destfile, item.error_text)) return os.path.abspath(destfile) def fetch_source(self, destdir="", progress=None, unpack=True): diff --git a/doc/source/apt_pkg.rst b/doc/source/apt_pkg.rst index 39b48c35..c814615c 100644 --- a/doc/source/apt_pkg.rst +++ b/doc/source/apt_pkg.rst @@ -167,7 +167,7 @@ Working with the cache If *from_user* is ``True``, the package will be marked as manually installed. This is the default. - .. method:: set_re_install(pkg) + .. method:: set_reinstall(pkg) Set if the :class:`Package` *pkg* should be reinstalled. @@ -398,7 +398,7 @@ Resolving Dependencies The component (eg. main) - .. attribute:: file_name + .. attribute:: filename The name of the file. @@ -430,7 +430,7 @@ Resolving Dependencies for pkgfile in cache.file_list: if pkgfile.not_source: - print 'The file %s has no source.' % pkgfile.file_name + print 'The file %s has no source.' % pkgfile.filename .. attribute:: origin @@ -809,7 +809,7 @@ Records # Now you can access the record print records.SourcePkg # == python-apt - .. attribute:: file_name + .. attribute:: filename Return the field 'Filename' of the record. This is the path to the package, relative to the base path of the archive. @@ -1103,7 +1103,7 @@ installation. Constant for comparing :attr:`AcquireItem.status` -.. class:: AcquireFile(owner, uri[, md5, size, descr, short_descr, dest_dir, dest_file]) +.. class:: AcquireFile(owner, uri[, md5, size, descr, short_descr, destdir, destfile]) Create a new :class:`AcquireFile()` object and register it with *acquire*, so it will be fetched. AcquireFile objects provide no methods or attributes @@ -1126,9 +1126,9 @@ installation. used to describe the item in the progress class. *short_descr* is the short form of it. - You can use *dest_dir* to manipulate the directory where the file will - be saved in. Instead of *dest_dir*, you can also specify the full path to - the file using the parameter *dest_file*. You can not combine both. + You can use *destdir* to manipulate the directory where the file will + be saved in. Instead of *destdir*, you can also specify the full path to + the file using the parameter *destfile*. You can not combine both. @@ -1379,7 +1379,7 @@ Configuration Check whether the key *key* exists in the configuration. - .. method:: sub_tree(key) + .. method:: subtree(key) Return a sub tree starting at *key*. The resulting object can be used like this one. @@ -1429,7 +1429,7 @@ Configuration Behaves like a :class:`Configuration()` objects, but provides access to a subsection of another Configuration-like object. This type of object is - returned by the :meth:`Configuration.sub_tree()` method. + returned by the :meth:`Configuration.subtree()` method. .. data:: config @@ -1459,7 +1459,7 @@ Modifying the settings therein to the :class:`Configuration()` object specified by the parameter *configuration* -.. function:: parse_command_line(configuration, options, argv) +.. function:: parse_commandline(configuration, options, argv) This function is like getopt except it manipulates a configuration space. output is a list of non-option arguments (filenames, etc). *options* is a @@ -1541,11 +1541,11 @@ String functions apt_pkg.check_domain_list("alioth.debian.org","debian.net,debian.org") -.. function:: de_quote_string(string) +.. function:: dequote_string(string) Dequote the string specified by the parameter *string*, e.g.:: - >>> apt_pkg.DeQuoteString("%61%70%74%20is%20cool") + >>> apt_pkg.dequote_string("%61%70%74%20is%20cool") 'apt is cool' .. function:: quote_string(string, repl) @@ -1627,14 +1627,14 @@ String functions Return the string *version*, eliminating everything following the last '-'. Thus, this should be equivalent to ``version.rsplit('-', 1)[0]``. -.. function:: uri_to_file_name(uri) +.. function:: uri_to_filename(uri) Take a string *uri* as parameter and return a filename which can be used to store the file, based on the URI. Example:: - >>> apt_pkg.uri_to_file_name('http://debian.org/index.html') + >>> apt_pkg.uri_to_filename('http://debian.org/index.html') 'debian.org_index.html' @@ -1667,7 +1667,7 @@ Package States .. data:: CURSTATE_HALF_INSTALLED .. data:: CURSTATE_INSTALLED .. data:: CURSTATE_NOT_INSTALLED -.. data:: CURSTATE_UN_PACKED +.. data:: CURSTATE_UNPACKED @@ -1687,9 +1687,9 @@ Dependency types Installed states ^^^^^^^^^^^^^^^^ .. data:: INSTSTATE_HOLD -.. data:: INSTSTATE_HOLD_RE_INST_REQ +.. data:: INSTSTATE_HOLD_REINSTREQ .. data:: INSTSTATE_OK -.. data:: INSTSTATE_RE_INST_REQ +.. data:: INSTSTATE_REINSTREQ .. _Priorities: diff --git a/doc/source/examples/cache-pkgfile.py b/doc/source/examples/cache-pkgfile.py index 1300a55c..f4cc2e66 100644 --- a/doc/source/examples/cache-pkgfile.py +++ b/doc/source/examples/cache-pkgfile.py @@ -7,7 +7,7 @@ def main(): apt_pkg.init() cache = apt_pkg.Cache() for pkgfile in cache.file_list: - print 'Package-File:', pkgfile.file_name + print 'Package-File:', pkgfile.filename print 'Index-Type:', pkgfile.index_type # 'Debian Package Index' if pkgfile.not_source: print 'Source: None' diff --git a/doc/source/whatsnew/0.8.0.rst b/doc/source/whatsnew/0.8.0.rst index d1ac3ac5..d507e82a 100644 --- a/doc/source/whatsnew/0.8.0.rst +++ b/doc/source/whatsnew/0.8.0.rst @@ -15,19 +15,97 @@ Python-apt is the first Debian package to support the third major release of Python. The port is straight forward and integrates as nicely in Python 3 as the Python 2 builds integrate in Python 2. +Please be aware that python-apt builds for Python 3 are built without the +compatibility options enabled for Python 2 builds. They also do not provide +methods like :meth:`has_key` on mapping objects, because it has been removed +in Python 3. + Real classes in :mod:`apt_pkg` ------------------------------ +The 0.8 release introduces real classes in the :mod:`apt_pkg` extension. This +is an important step forward and makes writing code much easier, because you +can see the classes without having to create an object first. It also makes +it easier to talk about those classes, because they have a real name now. + +The 0.7 series shipped many functions for creating new objects, because the +classes were not exported. In 0.8, the classes themselves replace those +functions, as you can see in the following table. + +.. table:: + + ===================================== ================================= + Function Replacing class + ===================================== ================================= + :func:`apt_pkg.GetAcquire` :class:`apt_pkg.Acquire` + :func:`apt_pkg.GetCache()` :class:`apt_pkg.Cache` + :func:`apt_pkg.GetCdrom()` :class:`apt_pkg.Cdrom` + :func:`apt_pkg.GetDepCache()` :class:`apt_pkg.DepCache` + :func:`apt_pkg.GetPackageManager` :class:`apt_pkg.PackageManager` + :func:`apt_pkg.GetPkgAcqFile` :class:`apt_pkg.AcquireFile` + :func:`apt_pkg.GetPkgActionGroup` :class:`apt_pkg.ActionGroup` + :func:`apt_pkg.GetPkgProblemResolver` :class:`apt_pkg.ProblemResolver` + :func:`apt_pkg.GetPkgRecords` :class:`apt_pkg.PackageRecords` + :func:`apt_pkg.GetPkgSourceList` :class:`apt_pkg.SourceList` + :func:`apt_pkg.GetPkgSrcRecords` :class:`apt_pkg.SourceRecords` + :func:`apt_pkg.ParseSection` :class:`apt_pkg.TagSection` + :func:`apt_pkg.ParseTagFile` :class:`apt_pkg.TagFile` + ===================================== ================================= Complete rename of functions, methods and attributes ----------------------------------------------------- +In May 2008, Ben Finney reported bug 481061 against the python-apt package, +asking for PEP8 conformant names. With the release of python-apt 0.8, this +is finally happening. Supporting new language features like the :keyword:`with` statement ------------------------------------------------------------------- +This is not a real big change, but it's good to have it: +:class:`apt_pkg.ActionGroup` can now be used as a context manager for the +:keyword:`with` statement. This makes it more obvious that you are using an +action group, and is just cooler:: + + with apt_pkg.ActionGroup(depcache): + for package in my_selected_packages: + depcache.mark_install(package) + +This also works for :class:`apt.Cache`:: + + with cache.action_group(): # cache is an Instance of apt.Cache + for package in my_selected_packages: + package.mark_install() # Instance of apt.Package + Other changes ------------- This release of python-apt also features several other, smaller changes: - * Reduced memory usage by creating Package() objects in apt.Cache() only - when needed. + * Reduced memory usage by making :class:`apt.Cache` create + :class:`apt.Package()` object dynamically, instead of creating all of + them during the cache initialization. * Support to set the candidate version in :class:`apt.package.Package` + +Porting your applications to python-apt 0.8 +------------------------------------------- +Porting your application to python-apt 0.8 may be trivial. You should download +the source tarball of python-apt and run the tool utils/migrate-0.8 using +Python 2.6 over your code:: + + python2.6 utils/migrate-0.8.py -c myapp.py mypackage/ + +This will search your code for places where possibly deprecated names are +used. Using the argument ``-c``, you can turn colorized output on. + +Now that you know which parts of your code have to be changed, you have to know +how to do this. For classes, please look at the table. For all attributes, +methods, functions, and their parameters the following rules apply: + + 1. Replace leading [A-Z] with [a-z] (e.g DescURI => descURI) + 2. Replace multiple [A-Z] with [A-Z][a-z] (e.g. descURI => descUri) + 3. Replace every [A-Z] with the corresponding [a-z] (descUri => desc_uri) + +As an exception, refixes such as 'de' (e.g. 'dequote') or 'un' (e.g. 'unlock') +are normally not seperated by underscores from the next word. There are also +some other exceptions which are listed here, and apply to any name containing +this word: **filename**, **filesize**, **destdir**, **destfile**, **dequote**, +**unlock**, **reinstall**, **pinfile**, **REINSTREQ**, **UNPACKED**, +**parse_commandline**. diff --git a/python/acquire.cc b/python/acquire.cc index 1b1c5dd8..5f38f7bd 100644 --- a/python/acquire.cc +++ b/python/acquire.cc @@ -40,9 +40,9 @@ MkGet(AcquireItemGetStatAuthError,Py_BuildValue("i", pkgAcquire::Item::StatAuthE static PyGetSetDef AcquireItemGetSet[] = { {"complete",AcquireItemGetComplete}, {"desc_uri",AcquireItemGetDescURI}, - {"dest_file",AcquireItemGetDestFile}, + {"destfile",AcquireItemGetDestFile}, {"error_text",AcquireItemGetErrorText}, - {"file_size",AcquireItemGetFileSize}, + {"filesize",AcquireItemGetFileSize}, {"is",AcquireItemGetID}, {"is_trusted",AcquireItemGetIsTrusted}, {"local",AcquireItemGetLocal}, @@ -310,7 +310,7 @@ static PyObject *PkgAcquireFileNew(PyTypeObject *type, PyObject *Args, PyObject int size = 0; uri = md5 = descr = shortDescr = destDir = destFile = ""; - char * kwlist[] = {"owner","uri", "md5", "size", "descr", "shortdescr", + char * kwlist[] = {"owner","uri", "md5", "size", "descr", "short_descr", "destdir", "destfile", NULL}; if (PyArg_ParseTupleAndKeywords(Args, kwds, "O!s|sissss", kwlist, @@ -335,8 +335,8 @@ static PyObject *PkgAcquireFileNew(PyTypeObject *type, PyObject *Args, PyObject static char *doc_PkgAcquireFile = - "AcquireFile(owner, uri[, md5, size, descr, short_descr, dest_dir," - "dest_file]) -> New AcquireFile() object\n\n" + "AcquireFile(owner, uri[, md5, size, descr, short_descr, destdir," + "destfile]) -> New AcquireFile() object\n\n" "The parameter *owner* refers to an apt_pkg.Acquire() object. You can use\n" "*destdir* OR *destfile* to specify the destination directory/file."; diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index bfabc652..403e0ebf 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -407,7 +407,7 @@ static PyMethodDef methods[] = // Locking {"get_lock",GetLock,METH_VARARGS,doc_GetLock}, {"pkgsystem_lock",PkgSystemLock,METH_VARARGS,doc_PkgSystemLock}, - {"pkgsystem_un_lock",PkgSystemUnLock,METH_VARARGS,doc_PkgSystemUnLock}, + {"pkgsystem_unlock",PkgSystemUnLock,METH_VARARGS,doc_PkgSystemUnLock}, #ifdef COMPAT_0_7 {"GetLock",GetLock,METH_VARARGS,doc_GetLock}, {"PkgSystemLock",PkgSystemLock,METH_VARARGS,doc_PkgSystemLock}, @@ -418,7 +418,7 @@ static PyMethodDef methods[] = {"read_config_file",LoadConfig,METH_VARARGS,doc_LoadConfig}, {"read_config_dir",LoadConfigDir,METH_VARARGS,doc_LoadConfigDir}, {"read_config_file_isc",LoadConfigISC,METH_VARARGS,doc_LoadConfig}, - {"parse_command_line",ParseCommandLine,METH_VARARGS,doc_ParseCommandLine}, + {"parse_commandline",ParseCommandLine,METH_VARARGS,doc_ParseCommandLine}, #ifdef COMPAT_0_7 {"ReadConfigFile",LoadConfig,METH_VARARGS,doc_LoadConfig}, {"ReadConfigDir",LoadConfigDir,METH_VARARGS,doc_LoadConfigDir}, @@ -452,10 +452,10 @@ static PyMethodDef methods[] = // Strings {"check_domain_list",StrCheckDomainList,METH_VARARGS,"CheckDomainList(String,String) -> Bool"}, {"quote_string",StrQuoteString,METH_VARARGS,"QuoteString(String,String) -> String"}, - {"de_quote_string",StrDeQuote,METH_VARARGS,"DeQuoteString(String) -> String"}, + {"dequote_string",StrDeQuote,METH_VARARGS,"DeQuoteString(String) -> String"}, {"size_to_str",StrSizeToStr,METH_VARARGS,"SizeToStr(int) -> String"}, {"time_to_str",StrTimeToStr,METH_VARARGS,"TimeToStr(int) -> String"}, - {"uri_to_file_name",StrURItoFileName,METH_VARARGS,"URItoFileName(String) -> String"}, + {"uri_to_filename",StrURItoFileName,METH_VARARGS,"URItoFileName(String) -> String"}, {"base64_encode",StrBase64Encode,METH_VARARGS,"Base64Encode(String) -> String"}, {"string_to_bool",StrStringToBool,METH_VARARGS,"StringToBool(String) -> int"}, {"time_rfc1123",StrTimeRFC1123,METH_VARARGS,"TimeRFC1123(int) -> String"}, @@ -657,7 +657,7 @@ extern "C" void initapt_pkg() #endif // CurState PyModule_AddIntConstant(Module,"CURSTATE_NOT_INSTALLED",pkgCache::State::NotInstalled); - PyModule_AddIntConstant(Module,"CURSTATE_UN_PACKED",pkgCache::State::UnPacked); + PyModule_AddIntConstant(Module,"CURSTATE_UNPACKED",pkgCache::State::UnPacked); PyModule_AddIntConstant(Module,"CURSTATE_HALF_CONFIGURED",pkgCache::State::HalfConfigured); PyModule_AddIntConstant(Module,"CURSTATE_HALF_INSTALLED",pkgCache::State::HalfInstalled); PyModule_AddIntConstant(Module,"CURSTATE_CONFIG_FILES",pkgCache::State::ConfigFiles); @@ -666,13 +666,13 @@ extern "C" void initapt_pkg() PyModule_AddIntConstant(Module,"SELSTATE_UNKNOWN",pkgCache::State::Unknown); PyModule_AddIntConstant(Module,"SELSTATE_INSTALL",pkgCache::State::Install); PyModule_AddIntConstant(Module,"SELSTATE_HOLD",pkgCache::State::Hold); - PyModule_AddIntConstant(Module,"SELSTATE_DE_INSTALL",pkgCache::State::DeInstall); + PyModule_AddIntConstant(Module,"SELSTATE_DEINSTALL",pkgCache::State::DeInstall); PyModule_AddIntConstant(Module,"SELSTATE_PURGE",pkgCache::State::Purge); // InstState PyModule_AddIntConstant(Module,"INSTSTATE_OK",pkgCache::State::Ok); - PyModule_AddIntConstant(Module,"INSTSTATE_RE_INST_REQ",pkgCache::State::ReInstReq); + PyModule_AddIntConstant(Module,"INSTSTATE_REINSTREQ",pkgCache::State::ReInstReq); PyModule_AddIntConstant(Module,"INSTSTATE_HOLD",pkgCache::State::Hold); - PyModule_AddIntConstant(Module,"INSTSTATE_HOLD_RE_INST_REQ",pkgCache::State::HoldReInstReq); + PyModule_AddIntConstant(Module,"INSTSTATE_HOLD_REINSTREQ",pkgCache::State::HoldReInstReq); #ifdef COMPAT_0_7 PyModule_AddIntConstant(Module,"CurStateNotInstalled",pkgCache::State::NotInstalled); diff --git a/python/cache.cc b/python/cache.cc index 21a6a872..d09e22f3 100644 --- a/python/cache.cc +++ b/python/cache.cc @@ -1030,7 +1030,7 @@ static PyGetSetDef PackageFileGetSet[] = { {(char*)"architecture",PackageFile_GetArchitecture}, {(char*)"archive",PackageFile_GetArchive}, {(char*)"component",PackageFile_GetComponent}, - {(char*)"file_name",PackageFile_GetFileName}, + {(char*)"filename",PackageFile_GetFileName}, {(char*)"id",PackageFile_GetID}, {(char*)"index_type",PackageFile_GetIndexType}, {(char*)"label",PackageFile_GetLabel}, diff --git a/python/configuration.cc b/python/configuration.cc index 7b08d90e..81dd78ac 100644 --- a/python/configuration.cc +++ b/python/configuration.cc @@ -462,7 +462,7 @@ static PyMethodDef CnfMethods[] = // Others {"set",CnfSet,METH_VARARGS,doc_Set}, {"exists",CnfExists,METH_VARARGS,doc_Exists}, - {"sub_tree",CnfSubTree,METH_VARARGS,doc_SubTree}, + {"subtree",CnfSubTree,METH_VARARGS,doc_SubTree}, {"list",CnfList,METH_VARARGS,doc_List}, {"value_list",CnfValueList,METH_VARARGS,doc_ValueList}, {"my_tag",CnfMyTag,METH_VARARGS,doc_MyTag}, diff --git a/python/depcache.cc b/python/depcache.cc index 650dcb23..f69802f8 100644 --- a/python/depcache.cc +++ b/python/depcache.cc @@ -535,13 +535,13 @@ static PyMethodDef PkgDepCacheMethods[] = // global cache operations {"upgrade",PkgDepCacheUpgrade,METH_VARARGS,"Perform Upgrade (optional boolean argument if dist-upgrade should be performed)"}, {"fix_broken",PkgDepCacheFixBroken,METH_VARARGS,"Fix broken packages"}, - {"read_pin_file",PkgDepCacheReadPinFile,METH_VARARGS,"Read the pin policy"}, + {"read_pinfile",PkgDepCacheReadPinFile,METH_VARARGS,"Read the pin policy"}, {"minimize_upgrade",PkgDepCacheMinimizeUpgrade, METH_VARARGS,"Go over the entire set of packages and try to keep each package marked for upgrade. If a conflict is generated then the package is restored."}, // Manipulators {"mark_keep",PkgDepCacheMarkKeep,METH_VARARGS,"Mark package for keep"}, {"mark_delete",PkgDepCacheMarkDelete,METH_VARARGS,"Mark package for delete (optional boolean argument if it should be purged)"}, {"mark_install",PkgDepCacheMarkInstall,METH_VARARGS,"Mark package for Install"}, - {"set_re_install",PkgDepCacheSetReInstall,METH_VARARGS,"Set if the package should be reinstalled"}, + {"set_reinstall",PkgDepCacheSetReInstall,METH_VARARGS,"Set if the package should be reinstalled"}, // state information {"is_upgradable",PkgDepCacheIsUpgradable,METH_VARARGS,"Is pkg upgradable"}, {"is_now_broken",PkgDepCacheIsNowBroken,METH_VARARGS,"Is pkg is now broken"}, diff --git a/python/pkgrecords.cc b/python/pkgrecords.cc index 48440387..212e4ab0 100644 --- a/python/pkgrecords.cc +++ b/python/pkgrecords.cc @@ -120,7 +120,7 @@ static PyObject *PkgRecordsGetRecord(PyObject *Self,void*) { return PyString_FromStringAndSize(start,stop-start); } static PyGetSetDef PkgRecordsGetSet[] = { - {"file_name",PkgRecordsGetFileName}, + {"filename",PkgRecordsGetFileName}, {"homepage",PkgRecordsGetHomepage}, {"long_desc",PkgRecordsGetLongDesc}, {"md5_hash",PkgRecordsGetMD5Hash}, -- cgit v1.2.3 From f4fc81750d2dd7df9eda9599d2841ea70ff610ad Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Fri, 5 Jun 2009 16:16:31 +0200 Subject: python/apt_pkgmodule.cc: Fix refcount problem. --- python/apt_pkgmodule.cc | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'python') diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index 403e0ebf..a34d4720 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -500,8 +500,9 @@ static PyMethodDef methods[] = }; -#define ADDTYPE(mod,name,type) { Py_INCREF(type); \ +#define ADDTYPE(mod,name,type) { \ if (PyType_Ready(type) == -1) INIT_ERROR; \ + Py_INCREF(type); \ PyModule_AddObject(mod,name,(PyObject *)type); } @@ -557,6 +558,7 @@ extern "C" void initapt_pkg() Config->Object = _config; PyModule_AddObject(Module,"config",Config); #ifdef COMPAT_0_7 + Py_INCREF(Config); PyModule_AddObject(Module,"Config",Config); #endif -- cgit v1.2.3 From acf0e2af557be18a31570f8e21ccf67233b20004 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Fri, 5 Jun 2009 16:36:52 +0200 Subject: python/: Put all deprecated Get*() functions into #ifdef COMPAT_0_7. --- python/acquire.cc | 5 ++++- python/apt_pkgmodule.cc | 2 ++ python/cache.cc | 3 ++- python/cdrom.cc | 2 ++ python/depcache.cc | 8 ++++++-- python/pkgmanager.cc | 2 ++ python/pkgrecords.cc | 4 ++-- python/pkgsrcrecords.cc | 3 ++- python/sourcelist.cc | 5 +++-- python/tag.cc | 4 ++++ 10 files changed, 29 insertions(+), 9 deletions(-) (limited to 'python') diff --git a/python/acquire.cc b/python/acquire.cc index 5f38f7bd..e6a23548 100644 --- a/python/acquire.cc +++ b/python/acquire.cc @@ -297,11 +297,12 @@ PyTypeObject PkgAcquireType = PkgAcquireNew, // tp_new }; - +#ifdef COMPAT_0_7 PyObject *GetAcquire(PyObject *Self,PyObject *Args) { return PkgAcquireNew(&PkgAcquireType,Args,0); } +#endif static PyObject *PkgAcquireFileNew(PyTypeObject *type, PyObject *Args, PyObject * kwds) { @@ -386,6 +387,7 @@ PyTypeObject PkgAcquireFileType = PkgAcquireFileNew, // tp_new }; +#ifdef COMPAT_0_7 char *doc_GetPkgAcqFile = "GetPkgAcqFile(pkgAquire, uri[, md5, size, descr, shortDescr, destDir, destFile]) -> PkgAcqFile\n"; PyObject *GetPkgAcqFile(PyObject *Self, PyObject *Args, PyObject * kwds) @@ -417,3 +419,4 @@ PyObject *GetPkgAcqFile(PyObject *Self, PyObject *Args, PyObject * kwds) return AcqFileObj; } +#endif diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index a34d4720..4ad4e56c 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -30,11 +30,13 @@ // newConfiguration - Build a new configuration class /*{{{*/ // --------------------------------------------------------------------- +#ifdef COMPAT_0_7 static char *doc_newConfiguration = "Construct a configuration instance"; static PyObject *newConfiguration(PyObject *self,PyObject *args) { return CppPyObject_NEW(&ConfigurationType); } +#endif /*}}}*/ // Version Wrappers /*{{{*/ diff --git a/python/cache.cc b/python/cache.cc index d09e22f3..38b715de 100644 --- a/python/cache.cc +++ b/python/cache.cc @@ -1345,8 +1345,9 @@ PyTypeObject RDepListType = /*}}}*/ - +#ifdef COMPAT_0_7 PyObject *TmpGetCache(PyObject *Self,PyObject *Args) { return PkgCacheNew(&PkgCacheType,Args,0); } +#endif diff --git a/python/cdrom.cc b/python/cdrom.cc index 044bbf30..3e63a89c 100644 --- a/python/cdrom.cc +++ b/python/cdrom.cc @@ -129,10 +129,12 @@ PyTypeObject PkgCdromType = PkgCdromNew, // tp_new }; +#ifdef COMPAT_0_7 PyObject *GetCdrom(PyObject *Self,PyObject *Args) { return PkgCdromNew(&PkgCdromType,Args,0); } +#endif diff --git a/python/depcache.cc b/python/depcache.cc index f69802f8..a69e0723 100644 --- a/python/depcache.cc +++ b/python/depcache.cc @@ -696,12 +696,12 @@ PyTypeObject PkgDepCacheType = PkgDepCacheNew, // tp_new }; - +#ifdef COMPAT_0_7 PyObject *GetDepCache(PyObject *Self,PyObject *Args) { return PkgDepCacheNew(&PkgDepCacheType,Args,0); } - +#endif @@ -729,9 +729,11 @@ static PyObject *PkgProblemResolverNew(PyTypeObject *type,PyObject *Args,PyObjec return PkgProblemResolverPyObj; } +#ifdef COMPAT_0_7 PyObject *GetPkgProblemResolver(PyObject *Self,PyObject *Args) { return PkgProblemResolverNew(&PkgProblemResolverType,Args,0); } +#endif static PyObject *PkgProblemResolverResolve(PyObject *Self,PyObject *Args) { @@ -994,10 +996,12 @@ PyTypeObject PkgActionGroupType = PkgActionGroupNew, // tp_new }; +#ifdef COMPAT_0_7 PyObject *GetPkgActionGroup(PyObject *Self,PyObject *Args) { return PkgActionGroupNew(&PkgActionGroupType,Args,0); } +#endif /*}}}*/ diff --git a/python/pkgmanager.cc b/python/pkgmanager.cc index cae2b580..7752ce5b 100644 --- a/python/pkgmanager.cc +++ b/python/pkgmanager.cc @@ -36,10 +36,12 @@ static PyObject *PkgManagerNew(PyTypeObject *type,PyObject *Args,PyObject *kwds) return PkgManagerObj; } +#ifdef COMPAT_0_7 PyObject *GetPkgManager(PyObject *Self,PyObject *Args) { return PkgManagerNew(&PkgManagerType,Args,0); } +#endif static PyObject *PkgManagerGetArchives(PyObject *Self,PyObject *Args) diff --git a/python/pkgrecords.cc b/python/pkgrecords.cc index 212e4ab0..6022097a 100644 --- a/python/pkgrecords.cc +++ b/python/pkgrecords.cc @@ -210,9 +210,9 @@ PyTypeObject PkgRecordsType = /*}}}*/ - +#ifdef COMPAT_0_7 PyObject *GetPkgRecords(PyObject *Self,PyObject *Args) { return PkgRecordsNew(&PkgRecordsType,Args,0); } - +#endif diff --git a/python/pkgsrcrecords.cc b/python/pkgsrcrecords.cc index dea7ff37..50445432 100644 --- a/python/pkgsrcrecords.cc +++ b/python/pkgsrcrecords.cc @@ -251,6 +251,7 @@ PyTypeObject PkgSrcRecordsType = /*}}}*/ +#ifdef COMPAT_0_7 PyObject *GetPkgSrcRecords(PyObject *Self,PyObject *Args) { #if 0 @@ -266,4 +267,4 @@ PyObject *GetPkgSrcRecords(PyObject *Self,PyObject *Args) return HandleErrors(CppPyObject_NEW(&PkgSrcRecordsType)); } - +#endif diff --git a/python/sourcelist.cc b/python/sourcelist.cc index daf0c08c..1c05d83e 100644 --- a/python/sourcelist.cc +++ b/python/sourcelist.cc @@ -159,8 +159,9 @@ PyTypeObject PkgSourceListType = PkgSourceListNew, // tp_new }; +#ifdef COMPAT_0_7 PyObject *GetPkgSourceList(PyObject *Self,PyObject *Args) { - return CppPyObject_NEW(&PkgSourceListType,new pkgSourceList()); + return PkgSourceListNew(&PkgSourceListType,Args,0); } - +#endif diff --git a/python/tag.cc b/python/tag.cc index c30adb0a..5a31488c 100644 --- a/python/tag.cc +++ b/python/tag.cc @@ -264,11 +264,13 @@ static PyObject *TagSecNew(PyTypeObject *type,PyObject *Args,PyObject *kwds) { return New; } +#ifdef COMPAT_0_7 char *doc_ParseSection ="ParseSection(Text) -> TagSection() object. Deprecated."; PyObject *ParseSection(PyObject *self,PyObject *Args) { return TagSecNew(&TagSecType,Args,0); } +#endif /*}}}*/ // ParseTagFile - Parse a tagd file /*{{{*/ // --------------------------------------------------------------------- @@ -297,10 +299,12 @@ static PyObject *TagFileNew(PyTypeObject *type,PyObject *Args,PyObject *kwds) return HandleErrors(New); } +#ifdef COMPAT_0_7 char *doc_ParseTagFile = "ParseTagFile(File) -> TagFile() object. Deprecated."; PyObject *ParseTagFile(PyObject *self,PyObject *Args) { return TagFileNew(&TagFileType,Args,0); } +#endif /*}}}*/ // RewriteSection - Rewrite a section.. /*{{{*/ // --------------------------------------------------------------------- -- cgit v1.2.3 From b67d9c0abebee2a3e7f09ddccb357f633ee3ec00 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Fri, 5 Jun 2009 16:40:39 +0200 Subject: python/acquire.cc(AcquireItemType): Use "apt_pkg.AcquireItem" as tp_name --- python/acquire.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'python') diff --git a/python/acquire.cc b/python/acquire.cc index e6a23548..05bffc65 100644 --- a/python/acquire.cc +++ b/python/acquire.cc @@ -95,7 +95,7 @@ PyTypeObject AcquireItemType = #if PY_MAJOR_VERSION < 3 0, // ob_size #endif - "pkgAcquire::ItemIterator", // tp_name + "apt_pkg.AcquireItem", // tp_name sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize // Methods -- cgit v1.2.3 From 994a13b252f97f6ae77872b5d5118ac1366b2a24 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Fri, 5 Jun 2009 19:13:20 +0200 Subject: python/progress.cc, apt/progress/*.py: Use PEP 8 naming conventions for progress This changes the progress classes to use PEP 8 names. Due to the concept of the deprecation system, this causes methods of subclasses not to be called at all. If a class implements a command with underscores, it is called. If the class also implements the version in mixedCase, this is ignored. This means that all subclasses will not work correctly, because only the method from the parent class is called. --- apt/deprecation.py | 2 +- apt/progress/__init__.py | 133 +++++++++++++++++++++++++++++++---------------- apt/progress/gtk2.py | 52 +++++++++++------- python/progress.cc | 81 +++++++++++++++++++++++------ 4 files changed, 184 insertions(+), 84 deletions(-) (limited to 'python') diff --git a/apt/deprecation.py b/apt/deprecation.py index 6827a8b9..0f39ad63 100644 --- a/apt/deprecation.py +++ b/apt/deprecation.py @@ -67,7 +67,7 @@ def function_deprecated_by(func, convert_names=True): This function also converts all keyword argument names from mixedCase to lowercase_with_underscores, but only if 'convert_names' is True (default). """ - warning = 'Deprecated, please use \'%s\' instead' % func.__name__ + warning = 'Deprecated, please use \'%s()\' instead' % func.__name__ def deprecated_function(*args, **kwds): """Wrapper around a deprecated function.""" diff --git a/apt/progress/__init__.py b/apt/progress/__init__.py index d2a9d497..6e4c6eec 100644 --- a/apt/progress/__init__.py +++ b/apt/progress/__init__.py @@ -33,6 +33,7 @@ import select import sys import apt_pkg +from apt.deprecation import AttributeDeprecatedBy, function_deprecated_by __all__ = ('CdromProgress', 'DpkgInstallProgress', 'DumbInstallProgress', @@ -48,7 +49,7 @@ class OpProgress(object): def __init__(self): self.op = None - self.subOp = None + self.sub_op = None def update(self, percent): """Called periodically to update the user interface.""" @@ -56,6 +57,9 @@ class OpProgress(object): def done(self): """Called once an operation has been completed.""" + if apt_pkg._COMPAT_0_7: + subOp = AttributeDeprecatedBy('sub_op') + class OpTextProgress(OpProgress): """A simple text based cache open reporting class.""" @@ -65,7 +69,7 @@ class OpTextProgress(OpProgress): def update(self, percent): """Called periodically to update the user interface.""" - sys.stdout.write("\r%s: %.2i " % (self.subOp, percent)) + sys.stdout.write("\r%s: %.2i " % (self.sub_op, percent)) sys.stdout.flush() def done(self): @@ -80,26 +84,26 @@ class FetchProgress(object): """ # download status constants - dlDone = 0 - dlQueued = 1 - dlFailed = 2 - dlHit = 3 - dlIgnored = 4 - dlStatusStr = {dlDone: "Done", - dlQueued: "Queued", - dlFailed: "Failed", - dlHit: "Hit", - dlIgnored: "Ignored"} + dl_done = 0 + dl_queued = 1 + dl_failed = 2 + dl_hit = 3 + dl_ignored = 4 + dl_status_str = {dl_done: "Done", + dl_queued: "Queued", + dl_failed: "Failed", + dl_hit: "Hit", + dl_ignored: "Ignored"} def __init__(self): self.eta = 0.0 self.percent = 0.0 # Make checking easier - self.currentBytes = 0 - self.currentItems = 0 - self.totalBytes = 0 - self.totalItems = 0 - self.currentCPS = 0 + self.current_bytes = 0 + self.current_items = 0 + self.total_bytes = 0 + self.total_items = 0 + self.current_cps = 0 def start(self): """Called when the fetching starts.""" @@ -107,7 +111,7 @@ class FetchProgress(object): def stop(self): """Called when all files have been fetched.""" - def updateStatus(self, uri, descr, shortDescr, status): + def update_status(self, uri, descr, short_descr, status): """Called when the status of an item changes. This happens eg. when the downloads fails or is completed. @@ -118,16 +122,31 @@ class FetchProgress(object): Return True to continue or False to cancel. """ - self.percent = (((self.currentBytes + self.currentItems) * 100.0) / - float(self.totalBytes + self.totalItems)) - if self.currentCPS > 0: - self.eta = ((self.totalBytes - self.currentBytes) / - float(self.currentCPS)) + self.percent = (((self.current_bytes + self.current_items) * 100.0) / + float(self.total_bytes + self.total_items)) + if self.current_cps > 0: + self.eta = ((self.total_bytes - self.current_bytes) / + float(self.current_cps)) return True - def mediaChange(self, medium, drive): + def media_change(self, medium, drive): """react to media change events.""" + if apt_pkg._COMPAT_0_7: + dlDone = AttributeDeprecatedBy('dl_done') + dlQueued = AttributeDeprecatedBy('dl_queued') + dlFailed = AttributeDeprecatedBy('dl_failed') + dlHit = AttributeDeprecatedBy('dl_hit') + dlIgnored = AttributeDeprecatedBy('dl_ignored') + dlStatusStr = AttributeDeprecatedBy('dl_status_str') + currentBytes = AttributeDeprecatedBy('current_bytes') + currentItems = AttributeDeprecatedBy('current_items') + totalBytes = AttributeDeprecatedBy('total_bytes') + totalItems = AttributeDeprecatedBy('total_items') + currentCPS = AttributeDeprecatedBy('current_cps') + updateStatus = function_deprecated_by(update_status) + mediaChange = function_deprecated_by(media_change) + class TextFetchProgress(FetchProgress): """ Ready to use progress object for terminal windows """ @@ -136,13 +155,13 @@ class TextFetchProgress(FetchProgress): FetchProgress.__init__(self) self.items = {} - def updateStatus(self, uri, descr, shortDescr, status): + def update_status(self, uri, descr, short_descr, status): """Called when the status of an item changes. This happens eg. when the downloads fails or is completed. """ - if status != self.dlQueued: - print "\r%s %s" % (self.dlStatusStr[status], descr) + if status != self.dl_queued: + print "\r%s %s" % (self.dl_status_str[status], descr) self.items[uri] = status def pulse(self): @@ -151,10 +170,10 @@ class TextFetchProgress(FetchProgress): Return True to continue or False to cancel. """ FetchProgress.pulse(self) - if self.currentCPS > 0: + if self.current_cps > 0: s = "[%2.f%%] %sB/s %s" % (self.percent, - apt_pkg.size_to_str(int(self.currentCPS)), - apt_pkg.time_to_str(int(self.eta))) + apt_pkg.size_to_str(int(self.current_cps)), + apt_pkg.time_to_str(int(self.eta))) else: s = "%2.f%% [Working]" % (self.percent) print "\r%s" % (s), @@ -165,13 +184,17 @@ class TextFetchProgress(FetchProgress): """Called when all files have been fetched.""" print "\rDone downloading " - def mediaChange(self, medium, drive): + def media_change(self, medium, drive): """react to media change events.""" print ("Media change: please insert the disc labeled " "'%s' in the drive '%s' and press enter") % (medium, drive) return raw_input() not in ('c', 'C') + if apt_pkg._COMPAT_0_7: + updateStatus = function_deprecated_by(update_status) + mediaChange = function_deprecated_by(media_change) + class DumbInstallProgress(object): """Report the install progress. @@ -179,19 +202,24 @@ class DumbInstallProgress(object): Subclass this class to implement install progress reporting. """ - def startUpdate(self): + def start_update(self): """Start update.""" def run(self, pm): """Start installation.""" return pm.do_install() - def finishUpdate(self): + def finish_update(self): """Called when update has finished.""" - def updateInterface(self): + def update_interface(self): """Called periodically to update the user interface""" + if apt_pkg._COMPAT_0_7: + startUpdate = function_deprecated_by(start_update) + finishUpdate = function_deprecated_by(finish_update) + updateInterface = function_deprecated_by(update_interface) + class InstallProgress(DumbInstallProgress): """An InstallProgress that is pretty useful. @@ -202,7 +230,7 @@ class InstallProgress(DumbInstallProgress): def __init__(self): DumbInstallProgress.__init__(self) - self.selectTimeout = 0.1 + self.select_timeout = 0.1 (read, write) = os.pipe() self.writefd = write self.statusfd = os.fdopen(read, "r") @@ -217,10 +245,10 @@ class InstallProgress(DumbInstallProgress): def conffile(self, current, new): """Called when a conffile question from dpkg is detected.""" - def statusChange(self, pkg, percent, status): + def status_change(self, pkg, percent, status): """Called when the status changed.""" - def updateInterface(self): + def update_interface(self): """Called periodically to update the interface.""" if self.statusfd is None: return @@ -253,7 +281,7 @@ class InstallProgress(DumbInstallProgress): self.conffile(match.group(1), match.group(2)) elif status == "pmstatus": if float(percent) != self.percent or status_str != self.status: - self.statusChange(pkg, float(percent), + self.status_change(pkg, float(percent), status_str.strip()) self.percent = float(percent) self.status = status_str.strip() @@ -263,11 +291,11 @@ class InstallProgress(DumbInstallProgress): """Fork.""" return os.fork() - def waitChild(self): + def wait_child(self): """Wait for child progress to exit.""" while True: - select.select([self.statusfd], [], [], self.selectTimeout) - self.updateInterface() + select.select([self.statusfd], [], [], self.select_timeout) + self.update_interface() (pid, res) = os.waitpid(self.child_pid, os.WNOHANG) if pid == self.child_pid: break @@ -281,9 +309,15 @@ class InstallProgress(DumbInstallProgress): res = pm.do_install(self.writefd) os._exit(res) self.child_pid = pid - res = self.waitChild() + res = self.wait_child() return os.WEXITSTATUS(res) + if apt_pkg._COMPAT_0_7: + selectTimeout = AttributeDeprecatedBy('select_timeout') + statusChange = function_deprecated_by(status_change) + waitChild = function_deprecated_by(wait_child) + updateInterface = function_deprecated_by(update_interface) + class CdromProgress(object): """Report the cdrom add progress. @@ -297,12 +331,16 @@ class CdromProgress(object): def update(self, text, step): """Called periodically to update the user interface.""" - def askCdromName(self): + def ask_cdrom_name(self): """Called to ask for the name of the cdrom.""" - def changeCdrom(self): + def change_cdrom(self): """Called to ask for the cdrom to be changed.""" + if apt_pkg._COMPAT_0_7: + askCdromName = function_deprecated_by(ask_cdrom_name) + changeCdrom = function_deprecated_by(change_cdrom) + class DpkgInstallProgress(InstallProgress): """Progress handler for a local Debian package installation.""" @@ -318,10 +356,10 @@ class DpkgInstallProgress(InstallProgress): (self.writefd, self.debfile)) os._exit(os.WEXITSTATUS(res)) self.child_pid = pid - res = self.waitChild() + res = self.wait_child() return res - def updateInterface(self): + def update_interface(self): """Process status messages from dpkg.""" if self.statusfd is None: return @@ -354,3 +392,6 @@ class DpkgInstallProgress(InstallProgress): else: self.status = status self.read = "" + + if apt_pkg._COMPAT_0_7: + updateInterface = function_deprecated_by(update_interface) diff --git a/apt/progress/gtk2.py b/apt/progress/gtk2.py index 06ece2d5..c0c05426 100644 --- a/apt/progress/gtk2.py +++ b/apt/progress/gtk2.py @@ -39,6 +39,7 @@ import vte import apt import apt_pkg +from apt.deprecation import function_deprecated_by def mksig(params=(), run=gobject.SIGNAL_RUN_FIRST, rettype=gobject.TYPE_NONE): @@ -113,13 +114,13 @@ class GInstallProgress(gobject.GObject, apt.progress.InstallProgress): self.time_last_update = time.time() self.term = term reaper = vte.reaper_get() - reaper.connect("child-exited", self.childExited) + reaper.connect("child-exited", self.child_exited) self.env = ["VTE_PTY_KEEP_FD=%s" % self.writefd, "DEBIAN_FRONTEND=gnome", "APT_LISTCHANGES_FRONTEND=gtk"] self._context = glib.main_context_default() - def childExited(self, term, pid, status): + def child_exited(self, term, pid, status): """Called when a child process exits""" self.apt_status = os.WEXITSTATUS(status) self.finished = True @@ -138,21 +139,21 @@ class GInstallProgress(gobject.GObject, apt.progress.InstallProgress): """ self.emit("status-conffile") - def startUpdate(self): + def start_update(self): """Called when the update starts. Emits: status-started() """ self.emit("status-started") - def finishUpdate(self): + def finish_update(self): """Called when the update finished. Emits: status-finished() """ self.emit("status-finished") - def statusChange(self, pkg, percent, status): + def status_change(self, pkg, percent, status): """Called when the status changed. Emits: status-changed(status, percent) @@ -160,12 +161,12 @@ class GInstallProgress(gobject.GObject, apt.progress.InstallProgress): self.time_last_update = time.time() self.emit("status-changed", status, percent) - def updateInterface(self): + def update_interface(self): """Called periodically to update the interface. Emits: status-timeout() [When a timeout happens] """ - apt.progress.InstallProgress.updateInterface(self) + apt.progress.InstallProgress.update_interface(self) while self._context.pending(): self._context.iteration() if self.time_last_update + self.INSTALL_TIMEOUT < time.time(): @@ -175,12 +176,20 @@ class GInstallProgress(gobject.GObject, apt.progress.InstallProgress): """Fork the process.""" return self.term.forkpty(envv=self.env) - def waitChild(self): + def wait_child(self): """Wait for the child process to exit.""" while not self.finished: - self.updateInterface() + self.update_interface() return self.apt_status + if apt_pkg._COMPAT_0_7: + updateInterface = function_deprecated_by(update_interface) + startUpdate = function_deprecated_by(start_update) + finishUpdate = function_deprecated_by(finish_update) + statusChange = function_deprecated_by(status_change) + waitChild = function_deprecated_by(wait_child) + childExited = function_deprecated_by(child_exited) + class GDpkgInstallProgress(apt.progress.DpkgInstallProgress, GInstallProgress): """An InstallProgress for local installations. @@ -199,14 +208,17 @@ class GDpkgInstallProgress(apt.progress.DpkgInstallProgress, GInstallProgress): """Install the given package.""" apt.progress.DpkgInstallProgress.run(self, debfile) - def updateInterface(self): + def update_interface(self): """Called periodically to update the interface. Emits: status-timeout() [When a timeout happens]""" - apt.progress.DpkgInstallProgress.updateInterface(self) + apt.progress.DpkgInstallProgress.update_interface(self) if self.time_last_update + self.INSTALL_TIMEOUT < time.time(): self.emit("status-timeout") + if apt_pkg._COMPAT_0_7: + updateInterface = function_deprecated_by(update_interface) + class GFetchProgress(gobject.GObject, apt.progress.FetchProgress): """A Fetch Progress with GObject signals. @@ -239,19 +251,19 @@ class GFetchProgress(gobject.GObject, apt.progress.FetchProgress): def pulse(self): apt.progress.FetchProgress.pulse(self) - currentItem = self.currentItems + 1 - if currentItem > self.totalItems: - currentItem = self.totalItems - if self.currentCPS > 0: + current_item = self.current_items + 1 + if current_item > self.total_items: + current_item = self.total_items + if self.current_cps > 0: text = (_("Downloading file %(current)li of %(total)li with " "%(speed)s/s") % \ - {"current": currentItem, - "total": self.totalItems, - "speed": apt_pkg.size_to_str(self.currentCPS)}) + {"current": current_item, + "total": self.total_items, + "speed": apt_pkg.size_to_str(self.current_cps)}) else: text = (_("Downloading file %(current)li of %(total)li") % \ - {"current": currentItem, - "total": self.totalItems}) + {"current": current_item, + "total": self.total_items}) self.emit("status-changed", text, self.percent) while self._context.pending(): self._context.iteration() diff --git a/python/progress.cc b/python/progress.cc index bec40ce9..8214a789 100644 --- a/python/progress.cc +++ b/python/progress.cc @@ -12,7 +12,6 @@ #include #include "progress.h" - // generic bool PyCallbackObj::RunSimpleCallback(const char* method_name, PyObject *arglist, @@ -58,10 +57,16 @@ void PyOpProgress::Update() PyObject_SetAttrString(callbackInst, "op", o); Py_XDECREF(o); o = Py_BuildValue("s", SubOp.c_str()); - PyObject_SetAttrString(callbackInst, "subOp", o); + if(PyObject_HasAttrString(callbackInst, "sub_op")) + PyObject_SetAttrString(callbackInst, "sub_op", o); + else + PyObject_SetAttrString(callbackInst, "subOp", o); Py_XDECREF(o); o = Py_BuildValue("b", MajorChange); - PyObject_SetAttrString(callbackInst, "majorChange", o); + if(PyObject_HasAttrString(callbackInst, "major_change")) + PyObject_SetAttrString(callbackInst, "major_change", o); + else + PyObject_SetAttrString(callbackInst, "majorChange", o); Py_XDECREF(o); // Build up the argument list... @@ -89,7 +94,10 @@ bool PyFetchProgress::MediaChange(string Media, string Drive) //std::cout << "MediaChange" << std::endl; PyObject *arglist = Py_BuildValue("(ss)", Media.c_str(), Drive.c_str()); PyObject *result; - RunSimpleCallback("mediaChange", arglist, &result); + if(PyObject_HasAttrString(callbackInst, "media_change")) + RunSimpleCallback("media_change", arglist, &result); + else + RunSimpleCallback("mediaChange", arglist, &result); bool res = true; if(!PyArg_Parse(result, "b", &res)) @@ -105,7 +113,10 @@ void PyFetchProgress::UpdateStatus(pkgAcquire::ItemDesc &Itm, int status) { //std::cout << "UpdateStatus: " << Itm.URI << " " << status << std::endl; PyObject *arglist = Py_BuildValue("(sssi)", Itm.URI.c_str(), Itm.Description.c_str(), Itm.ShortDesc.c_str(), status); - RunSimpleCallback("updateStatus", arglist); + if(PyObject_HasAttrString(callbackInst, "update_status")) + RunSimpleCallback("update_status", arglist); + else + RunSimpleCallback("updateStatus", arglist); } void PyFetchProgress::IMSHit(pkgAcquire::ItemDesc &Itm) @@ -163,19 +174,34 @@ bool PyFetchProgress::Pulse(pkgAcquire * Owner) // set stats PyObject *o; o = Py_BuildValue("f", CurrentCPS); - PyObject_SetAttrString(callbackInst, "currentCPS", o); + if(PyObject_HasAttrString(callbackInst, "current_cps")) + PyObject_SetAttrString(callbackInst, "current_cps", o); + else + PyObject_SetAttrString(callbackInst, "currentCPS", o); Py_XDECREF(o); o = Py_BuildValue("f", CurrentBytes); - PyObject_SetAttrString(callbackInst, "currentBytes", o); + if(PyObject_HasAttrString(callbackInst, "current_bytes")) + PyObject_SetAttrString(callbackInst, "current_bytes", o); + else + PyObject_SetAttrString(callbackInst, "currentBytes", o); Py_XDECREF(o); o = Py_BuildValue("i", CurrentItems); - PyObject_SetAttrString(callbackInst, "currentItems", o); + if(PyObject_HasAttrString(callbackInst, "current_items")) + PyObject_SetAttrString(callbackInst, "current_items", o); + else + PyObject_SetAttrString(callbackInst, "currentItems", o); Py_XDECREF(o); o = Py_BuildValue("i", TotalItems); - PyObject_SetAttrString(callbackInst, "totalItems", o); + if(PyObject_HasAttrString(callbackInst, "total_items")) + PyObject_SetAttrString(callbackInst, "total_items", o); + else + PyObject_SetAttrString(callbackInst, "totalItems", o); Py_XDECREF(o); o = Py_BuildValue("f", TotalBytes); - PyObject_SetAttrString(callbackInst, "totalBytes", o); + if(PyObject_HasAttrString(callbackInst, "total_bytes")) + PyObject_SetAttrString(callbackInst, "total_bytes", o); + else + PyObject_SetAttrString(callbackInst, "totalBytes", o); Py_XDECREF(o); PyObject *arglist = Py_BuildValue("()"); @@ -201,17 +227,26 @@ bool PyFetchProgress::Pulse(pkgAcquire * Owner) void PyInstallProgress::StartUpdate() { - RunSimpleCallback("startUpdate"); + if(PyObject_HasAttrString(callbackInst, "start_update")) + RunSimpleCallback("start_update"); + else + RunSimpleCallback("startUpdate"); } void PyInstallProgress::UpdateInterface() { - RunSimpleCallback("updateInterface"); + if(PyObject_HasAttrString(callbackInst, "update_interface")) + RunSimpleCallback("update_interface"); + else + RunSimpleCallback("updateInterface"); } void PyInstallProgress::FinishUpdate() { - RunSimpleCallback("finishUpdate"); + if(PyObject_HasAttrString(callbackInst, "finish_update")) + RunSimpleCallback("finish_update"); + else + RunSimpleCallback("finishUpdate"); } pkgPackageManager::OrderResult PyInstallProgress::Run(pkgPackageManager *pm) @@ -272,8 +307,13 @@ pkgPackageManager::OrderResult PyInstallProgress::Run(pkgPackageManager *pm) StartUpdate(); - if(PyObject_HasAttrString(callbackInst, "waitChild")) { - PyObject *method = PyObject_GetAttrString(callbackInst, "waitChild"); + if(PyObject_HasAttrString(callbackInst, "waitChild") || + PyObject_HasAttrString(callbackInst, "wait_child")) { + PyObject *method; + if (PyObject_HasAttrString(callbackInst, "wait_child")) + method = PyObject_GetAttrString(callbackInst, "wait_child"); + else + method = PyObject_GetAttrString(callbackInst, "waitChild"); //std::cerr << "custom waitChild found" << std::endl; PyObject *arglist = Py_BuildValue("(i)",child_id); PyObject *result = PyEval_CallObject(method, arglist); @@ -323,7 +363,10 @@ bool PyCdromProgress::ChangeCdrom() { PyObject *arglist = Py_BuildValue("()"); PyObject *result; - RunSimpleCallback("changeCdrom", arglist, &result); + if(PyObject_HasAttrString(callbackInst, "change_cdrom")) + RunSimpleCallback("change_cdrom", arglist, &result); + else + RunSimpleCallback("changeCdrom", arglist, &result); bool res = true; if(!PyArg_Parse(result, "b", &res)) @@ -337,7 +380,11 @@ bool PyCdromProgress::AskCdromName(string &Name) { PyObject *arglist = Py_BuildValue("()"); PyObject *result; - RunSimpleCallback("askCdromName", arglist, &result); + + if(PyObject_HasAttrString(callbackInst, "ask_cdrom_name")) + RunSimpleCallback("ask_cdrom_name", arglist, &result); + else + RunSimpleCallback("askCdromName", arglist, &result); const char *new_name; bool res; -- cgit v1.2.3 From 1040f7f6ec9cf689d6530827348a63daad52b3ef Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Mon, 8 Jun 2009 17:17:48 +0200 Subject: python/generic.h,tag.cc,configuration.cc: Use tp_alloc/tp_free instead of PyObject_NEW/DEL This allows us to finally implement subclassing. Previously deletion of an instance of a subclass caused segmentation faults, this is not the case anymore. --- python/configuration.cc | 3 ++- python/generic.h | 12 ++++++------ python/tag.cc | 8 ++++---- 3 files changed, 12 insertions(+), 11 deletions(-) (limited to 'python') diff --git a/python/configuration.cc b/python/configuration.cc index 81dd78ac..3c6ea88c 100644 --- a/python/configuration.cc +++ b/python/configuration.cc @@ -161,7 +161,8 @@ static PyObject *CnfSubTree(PyObject *Self,PyObject *Args) } // Create a new sub configuration. - SubConfiguration *New = PyObject_NEW(SubConfiguration,&ConfigurationSubType); + SubConfiguration *New = (SubConfiguration*)(&ConfigurationSubType) + ->tp_alloc(&ConfigurationSubType,0); new (&New->Object) Configuration(Itm); New->Owner = Self; Py_INCREF(Self); diff --git a/python/generic.h b/python/generic.h index ae2871e3..df4d8755 100644 --- a/python/generic.h +++ b/python/generic.h @@ -99,7 +99,7 @@ inline PyObject *GetOwner(PyObject *Obj) template inline CppPyObject *CppPyObject_NEW(PyTypeObject *Type) { - CppPyObject *New = PyObject_NEW(CppPyObject,Type); + CppPyObject *New = (CppPyObject*)Type->tp_alloc(Type, 0); new (&New->Object) T; return New; } @@ -107,7 +107,7 @@ inline CppPyObject *CppPyObject_NEW(PyTypeObject *Type) template inline CppPyObject *CppPyObject_NEW(PyTypeObject *Type,A const &Arg) { - CppPyObject *New = PyObject_NEW(CppPyObject,Type); + CppPyObject *New = (CppPyObject*)Type->tp_alloc(Type, 0); new (&New->Object) T(Arg); return New; } @@ -116,7 +116,7 @@ template inline CppOwnedPyObject *CppOwnedPyObject_NEW(PyObject *Owner, PyTypeObject *Type) { - CppOwnedPyObject *New = PyObject_NEW(CppOwnedPyObject,Type); + CppOwnedPyObject *New = (CppOwnedPyObject*)Type->tp_alloc(Type, 0); new (&New->Object) T; New->Owner = Owner; Py_INCREF(Owner); @@ -127,7 +127,7 @@ template inline CppOwnedPyObject *CppOwnedPyObject_NEW(PyObject *Owner, PyTypeObject *Type,A const &Arg) { - CppOwnedPyObject *New = PyObject_NEW(CppOwnedPyObject,Type); + CppOwnedPyObject *New = (CppOwnedPyObject*)Type->tp_alloc(Type, 0); new (&New->Object) T(Arg); New->Owner = Owner; if (Owner != 0) @@ -140,7 +140,7 @@ template void CppDealloc(PyObject *Obj) { GetCpp(Obj).~T(); - PyObject_DEL(Obj); + Obj->ob_type->tp_free(Obj); } template @@ -150,7 +150,7 @@ void CppOwnedDealloc(PyObject *iObj) Obj->Object.~T(); if (Obj->Owner != 0) Py_DECREF(Obj->Owner); - PyObject_DEL(Obj); + iObj->ob_type->tp_free(iObj); } inline PyObject *CppPyString(std::string Str) diff --git a/python/tag.cc b/python/tag.cc index 5a31488c..31491c90 100644 --- a/python/tag.cc +++ b/python/tag.cc @@ -68,7 +68,7 @@ void TagFileFree(PyObject *Obj) Self->Object.~pkgTagFile(); Self->Fd.~FileFd(); Py_DECREF(Self->File); - PyObject_DEL(Obj); + Obj->ob_type->tp_free(Obj); } /*}}}*/ @@ -246,7 +246,7 @@ static PyObject *TagSecNew(PyTypeObject *type,PyObject *Args,PyObject *kwds) { return 0; // Create the object.. - TagSecData *New = PyObject_NEW(TagSecData,type); + TagSecData *New = (TagSecData*)type->tp_alloc(type, 0); new (&New->Object) pkgTagSection(); New->Data = new char[strlen(Data)+2]; snprintf(New->Data,strlen(Data)+2,"%s\n",Data); @@ -286,14 +286,14 @@ static PyObject *TagFileNew(PyTypeObject *type,PyObject *Args,PyObject *kwds) if (fileno == -1) return 0; - TagFileData *New = PyObject_NEW(TagFileData,type); + TagFileData *New = (TagFileData*)type->tp_alloc(type, 0); new (&New->Fd) FileFd(fileno,false); New->File = File; Py_INCREF(New->File); new (&New->Object) pkgTagFile(&New->Fd); // Create the section - New->Section = PyObject_NEW(TagSecData,&TagSecType); + New->Section = (TagSecData*)(&TagSecType)->tp_alloc(&TagSecType, 0); new (&New->Section->Object) pkgTagSection(); New->Section->Data = 0; -- cgit v1.2.3 From 33293ab8c53a9b1427012c297f288972e11ea3bb Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Mon, 8 Jun 2009 17:47:46 +0200 Subject: Add apt_pkg.HashString and apt_pkg.IndexRecords (Closes: #456141) --- debian/changelog | 6 +++ python/apt_pkgmodule.cc | 2 + python/apt_pkgmodule.h | 7 +++ python/hashstring.cc | 140 ++++++++++++++++++++++++++++++++++++++++++++++++ python/indexrecords.cc | 121 +++++++++++++++++++++++++++++++++++++++++ python/makefile | 2 +- 6 files changed, 277 insertions(+), 1 deletion(-) create mode 100644 python/hashstring.cc create mode 100644 python/indexrecords.cc (limited to 'python') diff --git a/debian/changelog b/debian/changelog index ca215554..1a80d081 100644 --- a/debian/changelog +++ b/debian/changelog @@ -1,3 +1,9 @@ +python-apt (0.7.92) experimental; urgency=low + + * Add apt_pkg.HashString and apt_pkg.IndexRecords (Closes: #456141) + + -- Julian Andres Klode Mon, 08 Jun 2009 17:23:37 +0200 + python-apt (0.7.91) experimental; urgency=low [ Julian Andres Klode ] diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index 4ad4e56c..085d12f4 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -603,6 +603,8 @@ extern "C" void initapt_pkg() ADDTYPE(Module,"SourceRecords",&PkgSrcRecordsType); /* ========================= sourcelist.cc ========================= */ ADDTYPE(Module,"SourceList",&PkgSourceListType); + ADDTYPE(Module,"IndexRecords",&PyIndexRecords_Type); + ADDTYPE(Module,"HashString",&PyHashString_Type); // Tag file constants PyModule_AddObject(Module,"REWRITE_PACKAGE_ORDER", CharCharToList(TFRewritePackageOrder)); diff --git a/python/apt_pkgmodule.h b/python/apt_pkgmodule.h index f7ef63c2..043e29cc 100644 --- a/python/apt_pkgmodule.h +++ b/python/apt_pkgmodule.h @@ -11,6 +11,7 @@ #define APT_PKGMODULE_H #include +#include // Configuration Stuff #define Configuration_Check(op) ((op)->ob_type == &ConfigurationType || \ @@ -106,5 +107,11 @@ extern PyTypeObject PackageIndexFileType; // metaIndex extern PyTypeObject MetaIndexType; +// HashString +PyObject *PyHashString_FromCpp(HashString *obj); +extern PyTypeObject PyHashString_Type; + +// IndexRecord +extern PyTypeObject PyIndexRecords_Type; #endif diff --git a/python/hashstring.cc b/python/hashstring.cc new file mode 100644 index 00000000..02a80210 --- /dev/null +++ b/python/hashstring.cc @@ -0,0 +1,140 @@ +/* hashstring.cc - Wrapper around HashString + * + * Copyright 2009 Julian Andres Klode + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + */ +#include +#include "generic.h" +#include "apt_pkgmodule.h" +#include + +static PyObject *HashString_NEW(PyTypeObject *type,PyObject *Args, + PyObject *kwds) +{ + const char *Hash; + const char *Type; + char *kwlist[] = {"type", "hash", NULL}; + if (PyArg_ParseTupleAndKeywords(Args, kwds, "s|s", kwlist, &Type, + &Hash) == 0) + return 0; + CppPyObject *PyObj = CppPyObject_NEW(type); + if (Hash) + PyObj->Object = new HashString(Type,Hash); + else // Type is the combined form now (i.e. type:hash) + PyObj->Object = new HashString(Type); + return PyObj; +} + +PyObject *PyHashString_FromCpp(HashString *obj) +{ + return CppPyObject_NEW(&PyHashString_Type, obj); +} + +static PyObject *HashString_Repr(PyObject *self) +{ + HashString *hash = GetCpp(self); + char repr[100]; + sprintf(repr, "<%s: \"%s\">", self->ob_type->tp_name, hash->toStr().c_str()); + return PyString_FromString(repr); +} + +static PyObject *HashString_ToStr(PyObject *self) +{ + HashString *hash = GetCpp(self); + return CppPyString(hash->toStr()); +} + +static PyObject *HashString_HashType(PyObject *self) +{ + HashString *hash = GetCpp(self); + return CppPyString(hash->HashType()); +} + +static const char *HashString_VerifyFile_doc = + "verify_file(filename: str) --> bool\n\n" + "Verify that the file indicated by filename matches the hash."; + +static PyObject *HashString_VerifyFile(PyObject *self,PyObject *args) +{ + HashString *hash = GetCpp(self); + char *filename; + if (PyArg_ParseTuple(args, "s", &filename) == 0) + return 0; + return PyBool_FromLong(hash->VerifyFile(filename)); +} + +static PyMethodDef HashString_Methods[] = { + {"to_str",(PyCFunction)HashString_ToStr,METH_NOARGS, + "to_str() --> str\n\nReturn a string, consisting of type:hash"}, + {"verify_file",HashString_VerifyFile,METH_VARARGS, + HashString_VerifyFile_doc}, + {"hash_type",(PyCFunction)HashString_HashType,METH_NOARGS, + "hash_type() --> str\n\nReturn the type of hash (MD5Sum,SHA1,SHA256)"}, + {} +}; + +static const char *HashString_doc = + "HashString(type, hash) OR HashString('type:hash')\n\n" + "Create a new HashString object. The first form allows you to specify\n" + "a type and a hash, and the second form a single string where type and\n" + "hash are seperated by a colon, e.g.::\n\n" + " HashString('MD5Sum', '6cc1b6e6655e3555ac47e5b5fe26d04e')\n\n" + "Valid options for 'type' are: MD5Sum, SHA1, SHA256."; +PyTypeObject PyHashString_Type = { + PyObject_HEAD_INIT(&PyType_Type) +#if PY_MAJOR_VERSION < 3 + 0, // ob_size +#endif + "apt_pkg.HashString", // tp_name + sizeof(CppPyObject), // tp_basicsize + 0, // tp_itemsize + // Methods + CppDealloc, // tp_dealloc + 0, // tp_print + 0, // tp_getattr + 0, // tp_setattr + 0, // tp_compare + HashString_Repr, // tp_repr + 0, // tp_as_number + 0, // tp_as_sequence + 0, // tp_as_mapping + 0, // tp_hash + 0, // tp_call + HashString_ToStr, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + Py_TPFLAGS_DEFAULT, // tp_flags + HashString_doc, // tp_doc + 0, // tp_traverse + 0, // tp_clear + 0, // tp_richcompare + 0, // tp_weaklistoffset + 0, // tp_iter + 0, // tp_iternext + HashString_Methods, // tp_methods + 0, // tp_members + 0, // tp_getset + 0, // tp_base + 0, // tp_dict + 0, // tp_descr_get + 0, // tp_descr_set + 0, // tp_dictoffset + 0, // tp_init + 0, // tp_alloc + HashString_NEW, // tp_new +}; diff --git a/python/indexrecords.cc b/python/indexrecords.cc new file mode 100644 index 00000000..e6099a69 --- /dev/null +++ b/python/indexrecords.cc @@ -0,0 +1,121 @@ +/* + * indexrecords.cc - Wrapper around indexRecords + * + * Copyright 2009 Julian Andres Klode + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + */ +#include +#include "apt_pkgmodule.h" +#include "generic.h" +#include + +static PyObject *IndexRecords_NEW(PyTypeObject *type,PyObject *Args, + PyObject *kwds) +{ + char * kwlist[] = {NULL}; + if (PyArg_ParseTupleAndKeywords(Args, kwds, "", kwlist) == 0) + return 0; + indexRecords *records = new indexRecords(); + CppPyObject *New = CppPyObject_NEW(type, + records); + return New; +} + +static PyObject *IndexRecords_Load(PyObject *self,PyObject *args) +{ + const char *filename; + if (PyArg_ParseTuple(args, "s", &filename) == 0) + return 0; + indexRecords *records = GetCpp(self); + return HandleErrors(Py_BuildValue("i", records->Load(filename))); +} + +static const char *IndexRecords_Lookup_doc = "lookup(metakey)\n\n" + "Lookup the filename given by metakey, return a tuple (size,hash).\n" + "The hash part is a HashString() object."; +static PyObject *IndexRecords_Lookup(PyObject *self,PyObject *args) +{ + const char *keyname; + if (PyArg_ParseTuple(args, "s", &keyname) == 0) + return 0; + indexRecords *records = GetCpp(self); + const indexRecords::checkSum *result = records->Lookup(keyname); + return Py_BuildValue("(iO)",result->Size, + PyHashString_FromCpp((HashString*)&result->Hash)); +} + +static PyObject *IndexRecords_GetDist(PyObject *self) +{ + indexRecords *records = GetCpp(self); + return HandleErrors(PyString_FromString(records->GetDist().c_str())); +} + +static PyMethodDef IndexRecords_Methods[] = { + {"load",IndexRecords_Load,METH_VARARGS, + "load(filename: str)\n\nLoad the file given by filename."}, + {"get_dist",(PyCFunction)IndexRecords_GetDist,METH_NOARGS, + "get_dist() -> str\n\nReturn a distribution set in the release file."}, + {"lookup",IndexRecords_Lookup,METH_VARARGS,IndexRecords_Lookup_doc}, + {} +}; + +static char *IndexRecords_doc = "IndexRecords()\n\n" + "Representation of a release file."; +PyTypeObject PyIndexRecords_Type = { + PyObject_HEAD_INIT(&PyType_Type) +#if PY_MAJOR_VERSION < 3 + 0, // ob_size +#endif + "apt_pkg.IndexRecords", // tp_name + sizeof(CppPyObject), // tp_basicsize + 0, // tp_itemsize + // Methods + CppDealloc, // tp_dealloc + 0, // tp_print + 0, // tp_getattr + 0, // tp_setattr + 0, // tp_compare + 0, // tp_repr + 0, // tp_as_number + 0, // tp_as_sequence + 0, // tp_as_mapping + 0, // tp_hash + 0, // tp_call + 0, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + Py_TPFLAGS_DEFAULT, // tp_flags + IndexRecords_doc, // tp_doc + 0, // tp_traverse + 0, // tp_clear + 0, // tp_richcompare + 0, // tp_weaklistoffset + 0, // tp_iter + 0, // tp_iternext + IndexRecords_Methods, // tp_methods + 0, // tp_members + 0, // tp_getset + 0, // tp_base + 0, // tp_dict + 0, // tp_descr_get + 0, // tp_descr_set + 0, // tp_dictoffset + 0, // tp_init + 0, // tp_alloc + IndexRecords_NEW, // tp_new +}; diff --git a/python/makefile b/python/makefile index 3e6458f4..f4d559ce 100644 --- a/python/makefile +++ b/python/makefile @@ -12,7 +12,7 @@ LIB_MAKES = apt-pkg/makefile APT_PKG_SRC = apt_pkgmodule.cc configuration.cc generic.cc tag.cc string.cc \ cache.cc pkgrecords.cc pkgsrcrecords.cc sourcelist.cc \ depcache.cc progress.cc cdrom.cc acquire.cc pkgmanager.cc \ - indexfile.cc metaindex.cc + indexfile.cc metaindex.cc hashstring.cc indexrecords.cc SOURCE := $(APT_PKG_SRC) include $(PYTHON_H) progress.h -- cgit v1.2.3 From 6bad14680b22f2bffbe9a3a10a954acaf13a7ad5 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Mon, 8 Jun 2009 17:55:23 +0200 Subject: python/indexrecords.cc: Swap tuple elements in lookup, and raise KeyError when none is found. --- python/indexrecords.cc | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) (limited to 'python') diff --git a/python/indexrecords.cc b/python/indexrecords.cc index e6099a69..917c3bbf 100644 --- a/python/indexrecords.cc +++ b/python/indexrecords.cc @@ -45,7 +45,7 @@ static PyObject *IndexRecords_Load(PyObject *self,PyObject *args) } static const char *IndexRecords_Lookup_doc = "lookup(metakey)\n\n" - "Lookup the filename given by metakey, return a tuple (size,hash).\n" + "Lookup the filename given by metakey, return a tuple (hash, size).\n" "The hash part is a HashString() object."; static PyObject *IndexRecords_Lookup(PyObject *self,PyObject *args) { @@ -54,8 +54,13 @@ static PyObject *IndexRecords_Lookup(PyObject *self,PyObject *args) return 0; indexRecords *records = GetCpp(self); const indexRecords::checkSum *result = records->Lookup(keyname); - return Py_BuildValue("(iO)",result->Size, - PyHashString_FromCpp((HashString*)&result->Hash)); + if (result == 0) { + PyErr_SetString(PyExc_KeyError,keyname); + return 0; + } + return Py_BuildValue("(Oi)", + PyHashString_FromCpp((HashString*)&result->Hash), + result->Size); } static PyObject *IndexRecords_GetDist(PyObject *self) -- cgit v1.2.3 From 13b0eb25325d44c05ac36f6d1069fd735992bbc1 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Mon, 8 Jun 2009 18:11:10 +0200 Subject: python/progress.cc: #include "generic.h" to fix build failure with python2.4 --- python/progress.cc | 1 + 1 file changed, 1 insertion(+) (limited to 'python') diff --git a/python/progress.cc b/python/progress.cc index 39124df1..2671f6fc 100644 --- a/python/progress.cc +++ b/python/progress.cc @@ -14,6 +14,7 @@ #include #include #include "progress.h" +#include "generic.h" // generic bool PyCallbackObj::RunSimpleCallback(const char* method_name, -- cgit v1.2.3 From 09d94116e3aae865d2b04020725f90814bd7cb3c Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Mon, 8 Jun 2009 18:22:32 +0200 Subject: Fix build failures with python2.4-dbg (const) --- python/hashstring.cc | 4 ++-- python/indexrecords.cc | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) (limited to 'python') diff --git a/python/hashstring.cc b/python/hashstring.cc index 02a80210..71ae5bf4 100644 --- a/python/hashstring.cc +++ b/python/hashstring.cc @@ -64,7 +64,7 @@ static PyObject *HashString_HashType(PyObject *self) return CppPyString(hash->HashType()); } -static const char *HashString_VerifyFile_doc = +static char *HashString_VerifyFile_doc = "verify_file(filename: str) --> bool\n\n" "Verify that the file indicated by filename matches the hash."; @@ -87,7 +87,7 @@ static PyMethodDef HashString_Methods[] = { {} }; -static const char *HashString_doc = +static char *HashString_doc = "HashString(type, hash) OR HashString('type:hash')\n\n" "Create a new HashString object. The first form allows you to specify\n" "a type and a hash, and the second form a single string where type and\n" diff --git a/python/indexrecords.cc b/python/indexrecords.cc index 917c3bbf..35e41c59 100644 --- a/python/indexrecords.cc +++ b/python/indexrecords.cc @@ -44,7 +44,7 @@ static PyObject *IndexRecords_Load(PyObject *self,PyObject *args) return HandleErrors(Py_BuildValue("i", records->Load(filename))); } -static const char *IndexRecords_Lookup_doc = "lookup(metakey)\n\n" +static char *IndexRecords_Lookup_doc = "lookup(metakey)\n\n" "Lookup the filename given by metakey, return a tuple (hash, size).\n" "The hash part is a HashString() object."; static PyObject *IndexRecords_Lookup(PyObject *self,PyObject *args) -- cgit v1.2.3 From fc874b8b9507401a232d42fa7936148f76b0a1e2 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Tue, 9 Jun 2009 17:29:57 +0200 Subject: python/cache.cc: Fix segfaults using the new allocation methods. We switched to using tp_alloc() to create new objects. Some types had no tp_flags set and were not initialized using PyType_Ready, causing tp_alloc (PyType_GenericAlloc) to crash. --- python/apt_pkgmodule.cc | 5 +++-- python/cache.cc | 20 +++++++++++++++++++- 2 files changed, 22 insertions(+), 3 deletions(-) (limited to 'python') diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index 085d12f4..95b72de4 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -547,6 +547,7 @@ extern "C" void initapt_pkg() // Finalize our types to add slots, etc. if (PyType_Ready(&ConfigurationPtrType) == -1) INIT_ERROR; if (PyType_Ready(&ConfigurationSubType) == -1) INIT_ERROR; + if (PyType_Ready(&PkgCacheFileType) == -1) INIT_ERROR; // Initialize the module #if PY_MAJOR_VERSION >= 3 @@ -577,8 +578,8 @@ extern "C" void initapt_pkg() ADDTYPE(Module,"Dependency",&DependencyType); // NO __new__() ADDTYPE(Module,"Description",&DescriptionType); // NO __new__() ADDTYPE(Module,"PackageFile",&PackageFileType); // NO __new__() - //ADDTYPE(Module,"PackageList",&PkgListType); // NO __new__(), internal - //ADDTYPE(Module,"DependencyList",&RDepListType); // NO __new__(), internal + ADDTYPE(Module,"PackageList",&PkgListType); // NO __new__(), internal + ADDTYPE(Module,"DependencyList",&RDepListType); // NO __new__(), internal ADDTYPE(Module,"Package",&PackageType); // NO __new__() ADDTYPE(Module,"Version",&VersionType); // NO __new__() /* ============================ cdrom.cc ============================ */ diff --git a/python/cache.cc b/python/cache.cc index 38b715de..c988145f 100644 --- a/python/cache.cc +++ b/python/cache.cc @@ -374,6 +374,12 @@ PyTypeObject PkgCacheFileType = 0, // tp_as_sequence 0, // tp_as_mapping 0, // tp_hash + 0, // tp_call + 0, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + Py_TPFLAGS_DEFAULT, // tp_flags }; /*}}}*/ // Package List Class /*{{{*/ @@ -444,6 +450,12 @@ PyTypeObject PkgListType = &PkgListSeq, // tp_as_sequence 0, // tp_as_mapping 0, // tp_hash + 0, // tp_call + 0, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + Py_TPFLAGS_DEFAULT , // tp_flags }; #define MkGet(PyFunc,Ret) static PyObject *PyFunc(PyObject *Self,void*) \ @@ -656,7 +668,7 @@ PyTypeObject DescriptionType = 0, // tp_setattro 0, // tp_as_buffer Py_TPFLAGS_DEFAULT, // tp_flags - "AcquireItem Object", // tp_doc + "apt_pkg.Description Object", // tp_doc 0, // tp_traverse 0, // tp_clear 0, // tp_richcompare @@ -1340,6 +1352,12 @@ PyTypeObject RDepListType = &RDepListSeq, // tp_as_sequence 0, // tp_as_mapping 0, // tp_hash + 0, // tp_call + 0, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + Py_TPFLAGS_DEFAULT, // tp_flags }; /*}}}*/ -- cgit v1.2.3 From f652213b76f72382bab21e730bf0ccc4419a1267 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Tue, 9 Jun 2009 18:10:19 +0200 Subject: Allow types providing __new__() to be subclassed. --- debian/changelog | 3 ++- python/acquire.cc | 6 ++++-- python/cache.cc | 3 ++- python/cdrom.cc | 3 ++- python/configuration.cc | 3 ++- python/depcache.cc | 9 ++++++--- python/hashstring.cc | 3 ++- python/indexrecords.cc | 3 ++- python/pkgmanager.cc | 3 ++- python/pkgrecords.cc | 3 ++- python/pkgsrcrecords.cc | 3 ++- python/sourcelist.cc | 3 ++- python/tag.cc | 6 ++++-- 13 files changed, 34 insertions(+), 17 deletions(-) (limited to 'python') diff --git a/debian/changelog b/debian/changelog index 1a80d081..818bf630 100644 --- a/debian/changelog +++ b/debian/changelog @@ -1,8 +1,9 @@ python-apt (0.7.92) experimental; urgency=low * Add apt_pkg.HashString and apt_pkg.IndexRecords (Closes: #456141) + * Allow types providing __new__() to be subclassed. - -- Julian Andres Klode Mon, 08 Jun 2009 17:23:37 +0200 + -- Julian Andres Klode Tue, 09 Jun 2009 18:09:53 +0200 python-apt (0.7.91) experimental; urgency=low diff --git a/python/acquire.cc b/python/acquire.cc index 05bffc65..702d48ce 100644 --- a/python/acquire.cc +++ b/python/acquire.cc @@ -276,7 +276,8 @@ PyTypeObject PkgAcquireType = 0, // tp_getattro 0, // tp_setattro 0, // tp_as_buffer - Py_TPFLAGS_DEFAULT, // tp_flags + (Py_TPFLAGS_DEFAULT | // tp_flags + Py_TPFLAGS_BASETYPE), doc_PkgAcquire, // tp_doc 0, // tp_traverse 0, // tp_clear @@ -366,7 +367,8 @@ PyTypeObject PkgAcquireFileType = 0, // tp_getattro 0, // tp_setattro 0, // tp_as_buffer - Py_TPFLAGS_DEFAULT, // tp_flags + (Py_TPFLAGS_DEFAULT | // tp_flags + Py_TPFLAGS_BASETYPE), doc_PkgAcquireFile, // tp_doc 0, // tp_traverse 0, // tp_clear diff --git a/python/cache.cc b/python/cache.cc index c988145f..14484104 100644 --- a/python/cache.cc +++ b/python/cache.cc @@ -331,7 +331,8 @@ PyTypeObject PkgCacheType = 0, // tp_getattro 0, // tp_setattro 0, // tp_as_buffer - Py_TPFLAGS_DEFAULT , // tp_flags + (Py_TPFLAGS_DEFAULT | // tp_flags + Py_TPFLAGS_BASETYPE), doc_PkgCache, // tp_doc 0, // tp_traverse 0, // tp_clear diff --git a/python/cdrom.cc b/python/cdrom.cc index 3e63a89c..e98947d1 100644 --- a/python/cdrom.cc +++ b/python/cdrom.cc @@ -108,7 +108,8 @@ PyTypeObject PkgCdromType = 0, // tp_getattro 0, // tp_setattro 0, // tp_as_buffer - Py_TPFLAGS_DEFAULT, // tp_flags + (Py_TPFLAGS_DEFAULT | // tp_flags + Py_TPFLAGS_BASETYPE), "Cdrom Object", // tp_doc 0, // tp_traverse 0, // tp_clear diff --git a/python/configuration.cc b/python/configuration.cc index 3c6ea88c..365a35fd 100644 --- a/python/configuration.cc +++ b/python/configuration.cc @@ -526,7 +526,8 @@ PyTypeObject ConfigurationType = 0, // tp_getattro 0, // tp_setattro 0, // tp_as_buffer - Py_TPFLAGS_DEFAULT, // tp_flags + (Py_TPFLAGS_DEFAULT | // tp_flags + Py_TPFLAGS_BASETYPE), "Configuration Object", // tp_doc 0, // tp_traverse 0, // tp_clear diff --git a/python/depcache.cc b/python/depcache.cc index a69e0723..f1c34fef 100644 --- a/python/depcache.cc +++ b/python/depcache.cc @@ -675,7 +675,8 @@ PyTypeObject PkgDepCacheType = 0, // tp_getattro 0, // tp_setattro 0, // tp_as_buffer - Py_TPFLAGS_DEFAULT, // tp_flags + (Py_TPFLAGS_DEFAULT | // tp_flags + Py_TPFLAGS_BASETYPE), doc_PkgDepCache, // tp_doc 0, // tp_traverse 0, // tp_clear @@ -858,7 +859,8 @@ PyTypeObject PkgProblemResolverType = 0, // tp_getattro 0, // tp_setattro 0, // tp_as_buffer - Py_TPFLAGS_DEFAULT, // tp_flags + (Py_TPFLAGS_DEFAULT | // tp_flags + Py_TPFLAGS_BASETYPE), "ProblemResolver Object", // tp_doc 0, // tp_traverse 0, // tp_clear @@ -975,7 +977,8 @@ PyTypeObject PkgActionGroupType = 0, // tp_getattro 0, // tp_setattro 0, // tp_as_buffer - Py_TPFLAGS_DEFAULT, // tp_flags + (Py_TPFLAGS_DEFAULT | // tp_flags + Py_TPFLAGS_BASETYPE), doc_PkgActionGroup, // tp_doc 0, // tp_traverse 0, // tp_clear diff --git a/python/hashstring.cc b/python/hashstring.cc index 71ae5bf4..58bcca9e 100644 --- a/python/hashstring.cc +++ b/python/hashstring.cc @@ -118,7 +118,8 @@ PyTypeObject PyHashString_Type = { 0, // tp_getattro 0, // tp_setattro 0, // tp_as_buffer - Py_TPFLAGS_DEFAULT, // tp_flags + (Py_TPFLAGS_DEFAULT | // tp_flags + Py_TPFLAGS_BASETYPE), HashString_doc, // tp_doc 0, // tp_traverse 0, // tp_clear diff --git a/python/indexrecords.cc b/python/indexrecords.cc index 35e41c59..61ff07fc 100644 --- a/python/indexrecords.cc +++ b/python/indexrecords.cc @@ -104,7 +104,8 @@ PyTypeObject PyIndexRecords_Type = { 0, // tp_getattro 0, // tp_setattro 0, // tp_as_buffer - Py_TPFLAGS_DEFAULT, // tp_flags + (Py_TPFLAGS_DEFAULT | // tp_flags + Py_TPFLAGS_BASETYPE), IndexRecords_doc, // tp_doc 0, // tp_traverse 0, // tp_clear diff --git a/python/pkgmanager.cc b/python/pkgmanager.cc index 7752ce5b..f47e77ad 100644 --- a/python/pkgmanager.cc +++ b/python/pkgmanager.cc @@ -153,7 +153,8 @@ PyTypeObject PkgManagerType = 0, // tp_getattro 0, // tp_setattro 0, // tp_as_buffer - Py_TPFLAGS_DEFAULT, // tp_flags + (Py_TPFLAGS_DEFAULT | // tp_flags + Py_TPFLAGS_BASETYPE), "PackageManager Object", // tp_doc 0, // tp_traverse 0, // tp_clear diff --git a/python/pkgrecords.cc b/python/pkgrecords.cc index 6022097a..8beefffd 100644 --- a/python/pkgrecords.cc +++ b/python/pkgrecords.cc @@ -186,7 +186,8 @@ PyTypeObject PkgRecordsType = 0, // tp_getattro 0, // tp_setattro 0, // tp_as_buffer - Py_TPFLAGS_DEFAULT, // tp_flags + (Py_TPFLAGS_DEFAULT | // tp_flags + Py_TPFLAGS_BASETYPE), "Records Object", // tp_doc 0, // tp_traverse 0, // tp_clear diff --git a/python/pkgsrcrecords.cc b/python/pkgsrcrecords.cc index 50445432..e6b78a83 100644 --- a/python/pkgsrcrecords.cc +++ b/python/pkgsrcrecords.cc @@ -228,7 +228,8 @@ PyTypeObject PkgSrcRecordsType = 0, // tp_getattro 0, // tp_setattro 0, // tp_as_buffer - Py_TPFLAGS_DEFAULT, // tp_flags + (Py_TPFLAGS_DEFAULT | // tp_flags + Py_TPFLAGS_BASETYPE), "SourceRecords Object", // tp_doc 0, // tp_traverse 0, // tp_clear diff --git a/python/sourcelist.cc b/python/sourcelist.cc index 1c05d83e..5e5838d8 100644 --- a/python/sourcelist.cc +++ b/python/sourcelist.cc @@ -138,7 +138,8 @@ PyTypeObject PkgSourceListType = 0, // tp_getattro 0, // tp_setattro 0, // tp_as_buffer - Py_TPFLAGS_DEFAULT, // tp_flags + (Py_TPFLAGS_DEFAULT | // tp_flags + Py_TPFLAGS_BASETYPE), "pkgSourceList Object", // tp_doc 0, // tp_traverse 0, // tp_clear diff --git a/python/tag.cc b/python/tag.cc index 31491c90..7e7eb21c 100644 --- a/python/tag.cc +++ b/python/tag.cc @@ -434,7 +434,8 @@ PyTypeObject TagSecType = 0, // tp_getattro 0, // tp_setattro 0, // tp_as_buffer - Py_TPFLAGS_DEFAULT, // tp_flags + (Py_TPFLAGS_DEFAULT | // tp_flags + Py_TPFLAGS_BASETYPE), doc_TagSec, // tp_doc 0, // tp_traverse 0, // tp_clear @@ -521,7 +522,8 @@ PyTypeObject TagFileType = 0, // tp_getattro 0, // tp_setattro 0, // tp_as_buffer - Py_TPFLAGS_DEFAULT, // tp_flags + (Py_TPFLAGS_DEFAULT | // tp_flags + Py_TPFLAGS_BASETYPE), doc_TagFile, // tp_doc 0, // tp_traverse 0, // tp_clear -- cgit v1.2.3 From a307f6c405d55895690e16d55de36549f5b05d8b Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Tue, 9 Jun 2009 20:44:58 +0200 Subject: Add apt_pkg.Policy class (Closes: #382725) --- debian/changelog | 3 +- python/apt_pkgmodule.cc | 1 + python/apt_pkgmodule.h | 3 + python/makefile | 2 +- python/policy.cc | 189 ++++++++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 196 insertions(+), 2 deletions(-) create mode 100644 python/policy.cc (limited to 'python') diff --git a/debian/changelog b/debian/changelog index 818bf630..3e85c5be 100644 --- a/debian/changelog +++ b/debian/changelog @@ -1,9 +1,10 @@ python-apt (0.7.92) experimental; urgency=low * Add apt_pkg.HashString and apt_pkg.IndexRecords (Closes: #456141) + * Add apt_pkg.Policy class (Closes: #382725) * Allow types providing __new__() to be subclassed. - -- Julian Andres Klode Tue, 09 Jun 2009 18:09:53 +0200 + -- Julian Andres Klode Tue, 09 Jun 2009 20:39:39 +0200 python-apt (0.7.91) experimental; urgency=low diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index 95b72de4..3d76894d 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -606,6 +606,7 @@ extern "C" void initapt_pkg() ADDTYPE(Module,"SourceList",&PkgSourceListType); ADDTYPE(Module,"IndexRecords",&PyIndexRecords_Type); ADDTYPE(Module,"HashString",&PyHashString_Type); + ADDTYPE(Module,"Policy",&PyPolicy_Type); // Tag file constants PyModule_AddObject(Module,"REWRITE_PACKAGE_ORDER", CharCharToList(TFRewritePackageOrder)); diff --git a/python/apt_pkgmodule.h b/python/apt_pkgmodule.h index 043e29cc..21355072 100644 --- a/python/apt_pkgmodule.h +++ b/python/apt_pkgmodule.h @@ -114,4 +114,7 @@ extern PyTypeObject PyHashString_Type; // IndexRecord extern PyTypeObject PyIndexRecords_Type; +// Policy +extern PyTypeObject PyPolicy_Type; + #endif diff --git a/python/makefile b/python/makefile index f4d559ce..6799d749 100644 --- a/python/makefile +++ b/python/makefile @@ -12,7 +12,7 @@ LIB_MAKES = apt-pkg/makefile APT_PKG_SRC = apt_pkgmodule.cc configuration.cc generic.cc tag.cc string.cc \ cache.cc pkgrecords.cc pkgsrcrecords.cc sourcelist.cc \ depcache.cc progress.cc cdrom.cc acquire.cc pkgmanager.cc \ - indexfile.cc metaindex.cc hashstring.cc indexrecords.cc + indexfile.cc metaindex.cc hashstring.cc indexrecords.cc policy.cc SOURCE := $(APT_PKG_SRC) include $(PYTHON_H) progress.h diff --git a/python/policy.cc b/python/policy.cc new file mode 100644 index 00000000..89604e9a --- /dev/null +++ b/python/policy.cc @@ -0,0 +1,189 @@ +/* + * policy.cc - Wrapper around pkgPolicy + * + * Copyright 2009 Julian Andres Klode + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + */ +#include +#include "apt_pkgmodule.h" +#include "generic.h" +#include + +static PyObject *Policy_NEW(PyTypeObject *type,PyObject *Args, + PyObject *kwds) { + PyObject *cache; + char *kwlist[] = {"cache", NULL}; + if (PyArg_ParseTupleAndKeywords(Args, kwds, "O", kwlist, &cache) == 0) + return 0; + if (!PyObject_TypeCheck(cache, &PkgCacheType)) { + PyErr_SetString(PyExc_TypeError,"`cache` must be a apt_pkg.Cache()."); + return 0; + } + pkgPolicy *policy = new pkgPolicy(GetCpp(cache)); + return CppOwnedPyObject_NEW(cache,&PyPolicy_Type,policy); +} + +static char *Policy_GetPriority_doc = "get_priority(package: apt_pkg.Package)" + " -> int\n\n" + "Return the priority of the package."; + +PyObject *Policy_GetPriority(PyObject *self, PyObject *arg) { + pkgPolicy *policy = GetCpp(self); + if (PyObject_TypeCheck(arg, &PackageType)) { + pkgCache::PkgIterator pkg = GetCpp(arg); + return Py_BuildValue("i", policy->GetPriority(pkg)); + } else { + PyErr_SetString(PyExc_TypeError,"Argument must be of Package()."); + return 0; + } +} + +static char *Policy_GetCandidateVer_doc = "get_match(package: apt_pkg.Package)" + " -> apt_pkg.Version\n\n" + "Get the best package for the job."; + +PyObject *Policy_GetCandidateVer(PyObject *self, PyObject *arg) { + if (PyObject_TypeCheck(arg, &PackageType)) { + pkgPolicy *policy = GetCpp(self); + pkgCache::PkgIterator pkg = GetCpp(arg); + pkgCache::VerIterator ver = policy->GetCandidateVer(pkg); + return CppOwnedPyObject_NEW(arg,&VersionType, + ver); + } else { + PyErr_SetString(PyExc_TypeError,"Argument must be of Package()."); + return 0; + } +} + +static char *Policy_GetMatch_doc = "get_match(package: apt_pkg.Package) -> " + "apt_pkg.Version\n\n" + "Return a matching version for the given package."; + +static PyObject *Policy_GetMatch(PyObject *self, PyObject *arg) { + if (PyObject_TypeCheck(arg, &PackageType) == 0) { + PyErr_SetString(PyExc_TypeError,"Argument must be of Package()."); + return 0; + } + pkgPolicy *policy = GetCpp(self); + pkgCache::PkgIterator pkg = GetCpp(arg); + pkgCache::VerIterator ver = policy->GetMatch(pkg); + return CppOwnedPyObject_NEW(arg,&VersionType,ver); +} + +static char *Policy_ReadPinFile_doc = "read_pinfile(filename: str) -> bool\n\n" + "Read the pin file given by filename (e.g. '/etc/apt/preferences') and\n" + "add it to the policy."; + +static PyObject *Policy_ReadPinFile(PyObject *self, PyObject *arg) { + if (!PyString_Check(arg)) + return 0; + pkgPolicy *policy = GetCpp(self); + + return PyBool_FromLong(ReadPinFile(*policy, PyString_AsString(arg))); +} + +static char *Policy_CreatePin_doc = "create_pin(type: str, pkg: str, " + "data: str, priority: int)\n\n" + "Create a pin for the policy. The parameter 'type' refers to one of the\n" + "following strings: 'Version', 'Release', 'Origin'. The argument 'pkg'\n" + "is the name of the package, the parameter 'data' refers to the value\n" + "e.g. unstable for type='Release' and the other possible options. \n" + "The parameter 'priority' gives the priority of the pin."; + +static PyObject *Policy_CreatePin(PyObject *self, PyObject *args) { + pkgVersionMatch::MatchType match_type; + const char *type, *pkg, *data; + signed short priority; + if (PyArg_ParseTuple(args, "sssh", &type, &pkg, &data, &priority) == 0) + return 0; + pkgPolicy *policy = GetCpp(self); + if (type == "Version" || type == "version") + match_type = pkgVersionMatch::Version; + if (type == "Release" || type == "release") + match_type = pkgVersionMatch::Release; + if (type == "Origin" || type == "origin") + match_type = pkgVersionMatch::Origin; + else + match_type = pkgVersionMatch::None; + policy->CreatePin(match_type,pkg,data,priority); + HandleErrors(); + Py_RETURN_NONE; +} + +static PyMethodDef Policy_Methods[] = { + {"get_priority",(PyCFunction)Policy_GetPriority,METH_O, + Policy_GetPriority_doc}, + {"get_candidate_ver",(PyCFunction)Policy_GetCandidateVer,METH_O, + Policy_GetCandidateVer_doc}, + {"read_pinfile",(PyCFunction)Policy_ReadPinFile,METH_O, + Policy_ReadPinFile_doc}, + {"create_pin",Policy_CreatePin,METH_VARARGS,Policy_CreatePin_doc}, + {"get_match",(PyCFunction)Policy_GetMatch,METH_O, Policy_GetMatch_doc}, + {} +}; + +static char *Policy_doc = "Policy(cache)\n\n" + "Representation of the policy of the Cache object given by cache. This\n" + "provides a superset of policy-related functionality compared to the\n" + "DepCache class. The DepCache can be used for most purposes, but there\n" + "may be some cases where a special policy class is needed."; + +PyTypeObject PyPolicy_Type = { + PyObject_HEAD_INIT(&PyType_Type) +#if PY_MAJOR_VERSION < 3 + 0, // ob_size +#endif + "apt_pkg.Policy", // tp_name + sizeof(CppOwnedPyObject),// tp_basicsize + 0, // tp_itemsize + // Methods + CppOwnedDealloc, // tp_dealloc + 0, // tp_print + 0, // tp_getattr + 0, // tp_setattr + 0, // tp_compare + 0, // tp_repr + 0, // tp_as_number + 0, // tp_as_sequence + 0, // tp_as_mapping + 0, // tp_hash + 0, // tp_call + 0, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + (Py_TPFLAGS_DEFAULT | // tp_flags + Py_TPFLAGS_BASETYPE), + Policy_doc, // tp_doc + 0, // tp_traverse + 0, // tp_clear + 0, // tp_richcompare + 0, // tp_weaklistoffset + 0, // tp_iter + 0, // tp_iternext + Policy_Methods, // tp_methods + 0, // tp_members + 0, // tp_getset + 0, // tp_base + 0, // tp_dict + 0, // tp_descr_get + 0, // tp_descr_set + 0, // tp_dictoffset + 0, // tp_init + 0, // tp_alloc + Policy_NEW, // tp_new +}; -- cgit v1.2.3 From aa31a066174571a64e68c35203f6b2404ef2393f Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Tue, 9 Jun 2009 21:04:36 +0200 Subject: python/apt_pkgmodule.cc: Fix the modulename. --- python/apt_pkgmodule.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'python') diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index 3d76894d..bfa59f8e 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -527,7 +527,7 @@ static int apt_inst_clear(PyObject *m) { static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, - "apt_inst", + "apt_pkg", NULL, sizeof(struct module_state), methods, -- cgit v1.2.3 From 395b33f9f8e93223f933c625bacbf1e2d23c6673 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Fri, 12 Jun 2009 18:56:23 +0200 Subject: Bugfix: Delete pointers correctly, fixing memory leaks. (LP: #370149) We previously called the destructor of the pointer. This resulted in no object using pointers being deallocated. This patch introduces CppDeallocPtr() and CppOwnedDeallocPtr() which do the same as the other CppDealloc() and CppOwnedDealloc(), but use 'delete' on the pointer instead of the deconstructor. Furthermore, this patch also changes AcquireFile to be a CppOwnedPyObject, owned by the Acquire object. Without this change, deleting the Acquire object would cause a crash when AcquireFile is deallocated. --- debian/changelog | 5 +++-- python/acquire.cc | 8 ++++---- python/cache.cc | 4 ++-- python/depcache.cc | 6 +++--- python/generic.h | 19 +++++++++++++++++++ python/hashstring.cc | 2 +- python/indexfile.cc | 2 +- python/indexrecords.cc | 2 +- python/metaindex.cc | 2 +- python/pkgmanager.cc | 2 +- python/policy.cc | 2 +- python/sourcelist.cc | 2 +- 12 files changed, 38 insertions(+), 18 deletions(-) (limited to 'python') diff --git a/debian/changelog b/debian/changelog index 3e85c5be..9f9838c3 100644 --- a/debian/changelog +++ b/debian/changelog @@ -1,10 +1,11 @@ -python-apt (0.7.92) experimental; urgency=low +python-apt (0.7.92) UNRELEASED; urgency=low * Add apt_pkg.HashString and apt_pkg.IndexRecords (Closes: #456141) * Add apt_pkg.Policy class (Closes: #382725) * Allow types providing __new__() to be subclassed. + * Bugfix: Delete pointers correctly, fixing memory leaks. (LP: #370149) - -- Julian Andres Klode Tue, 09 Jun 2009 20:39:39 +0200 + -- Julian Andres Klode Fri, 12 Jun 2009 18:42:02 +0200 python-apt (0.7.91) experimental; urgency=low diff --git a/python/acquire.cc b/python/acquire.cc index 702d48ce..6b091479 100644 --- a/python/acquire.cc +++ b/python/acquire.cc @@ -261,7 +261,7 @@ PyTypeObject PkgAcquireType = sizeof(CppPyObject), // tp_basicsize 0, // tp_itemsize // Methods - CppDealloc, // tp_dealloc + CppDeallocPtr, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr @@ -329,7 +329,7 @@ static PyObject *PkgAcquireFileNew(PyTypeObject *type, PyObject *Args, PyObject shortDescr, destDir, destFile); // short-desc - CppPyObject *AcqFileObj = CppPyObject_NEW(type); + CppOwnedPyObject *AcqFileObj = CppOwnedPyObject_NEW(pyfetcher, type); AcqFileObj->Object = af; return AcqFileObj; @@ -349,10 +349,10 @@ PyTypeObject PkgAcquireFileType = 0, // ob_size #endif "apt_pkg.AcquireFile", // tp_name - sizeof(CppPyObject),// tp_basicsize + sizeof(CppOwnedPyObject),// tp_basicsize 0, // tp_itemsize // Methods - CppDealloc, // tp_dealloc + CppOwnedDeallocPtr, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr diff --git a/python/cache.cc b/python/cache.cc index 14484104..22ed9ecc 100644 --- a/python/cache.cc +++ b/python/cache.cc @@ -247,7 +247,7 @@ void PkgCacheFileDealloc(PyObject *Self) PyObject *CacheFilePy = GetOwner(Self); pkgCacheFile *CacheF = GetCpp(CacheFilePy); CacheF->Close(); - CppOwnedDealloc(Self); + CppOwnedDeallocPtr(Self); } static PyObject *PkgCacheNew(PyTypeObject *type,PyObject *Args,PyObject *kwds) @@ -365,7 +365,7 @@ PyTypeObject PkgCacheFileType = sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize // Methods - CppOwnedDealloc, // tp_dealloc + CppOwnedDeallocPtr, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr diff --git a/python/depcache.cc b/python/depcache.cc index f1c34fef..9bbda527 100644 --- a/python/depcache.cc +++ b/python/depcache.cc @@ -660,7 +660,7 @@ PyTypeObject PkgDepCacheType = sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize // Methods - CppOwnedDealloc, // tp_dealloc + CppOwnedDeallocPtr, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr @@ -844,7 +844,7 @@ PyTypeObject PkgProblemResolverType = sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize // Methods - CppOwnedDealloc, // tp_dealloc + CppOwnedDeallocPtr,// tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr @@ -962,7 +962,7 @@ PyTypeObject PkgActionGroupType = sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize // Methods - CppOwnedDealloc, // tp_dealloc + CppOwnedDeallocPtr, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr diff --git a/python/generic.h b/python/generic.h index df4d8755..b7b958f5 100644 --- a/python/generic.h +++ b/python/generic.h @@ -153,6 +153,25 @@ void CppOwnedDealloc(PyObject *iObj) iObj->ob_type->tp_free(iObj); } +// Pointer deallocation +// Generic Dealloc type functions +template +void CppDeallocPtr(PyObject *Obj) +{ + delete GetCpp(Obj); + Obj->ob_type->tp_free(Obj); +} + +template +void CppOwnedDeallocPtr(PyObject *iObj) +{ + CppOwnedPyObject *Obj = (CppOwnedPyObject *)iObj; + delete Obj->Object; + if (Obj->Owner != 0) + Py_DECREF(Obj->Owner); + iObj->ob_type->tp_free(iObj); +} + inline PyObject *CppPyString(std::string Str) { return PyString_FromStringAndSize(Str.c_str(),Str.length()); diff --git a/python/hashstring.cc b/python/hashstring.cc index 58bcca9e..23212a4b 100644 --- a/python/hashstring.cc +++ b/python/hashstring.cc @@ -103,7 +103,7 @@ PyTypeObject PyHashString_Type = { sizeof(CppPyObject), // tp_basicsize 0, // tp_itemsize // Methods - CppDealloc, // tp_dealloc + CppDeallocPtr, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr diff --git a/python/indexfile.cc b/python/indexfile.cc index 795931fb..78a4f513 100644 --- a/python/indexfile.cc +++ b/python/indexfile.cc @@ -99,7 +99,7 @@ PyTypeObject PackageIndexFileType = sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize // Methods - CppOwnedDealloc, // tp_dealloc + CppOwnedDeallocPtr, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr diff --git a/python/indexrecords.cc b/python/indexrecords.cc index 61ff07fc..fcb2b85d 100644 --- a/python/indexrecords.cc +++ b/python/indexrecords.cc @@ -89,7 +89,7 @@ PyTypeObject PyIndexRecords_Type = { sizeof(CppPyObject), // tp_basicsize 0, // tp_itemsize // Methods - CppDealloc, // tp_dealloc + CppDeallocPtr, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr diff --git a/python/metaindex.cc b/python/metaindex.cc index b451f0b5..b5d194b4 100644 --- a/python/metaindex.cc +++ b/python/metaindex.cc @@ -80,7 +80,7 @@ PyTypeObject MetaIndexType = sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize // Methods - CppOwnedDealloc, // tp_dealloc + CppOwnedDeallocPtr, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr diff --git a/python/pkgmanager.cc b/python/pkgmanager.cc index f47e77ad..0fd2cd92 100644 --- a/python/pkgmanager.cc +++ b/python/pkgmanager.cc @@ -138,7 +138,7 @@ PyTypeObject PkgManagerType = sizeof(CppPyObject), // tp_basicsize 0, // tp_itemsize // Methods - CppDealloc, // tp_dealloc + CppDeallocPtr, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr diff --git a/python/policy.cc b/python/policy.cc index 89604e9a..992a1192 100644 --- a/python/policy.cc +++ b/python/policy.cc @@ -151,7 +151,7 @@ PyTypeObject PyPolicy_Type = { sizeof(CppOwnedPyObject),// tp_basicsize 0, // tp_itemsize // Methods - CppOwnedDealloc, // tp_dealloc + CppOwnedDeallocPtr, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr diff --git a/python/sourcelist.cc b/python/sourcelist.cc index 5e5838d8..e53fccd3 100644 --- a/python/sourcelist.cc +++ b/python/sourcelist.cc @@ -123,7 +123,7 @@ PyTypeObject PkgSourceListType = sizeof(CppPyObject), // tp_basicsize 0, // tp_itemsize // Methods - CppDealloc, // tp_dealloc + CppDeallocPtr, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr -- cgit v1.2.3 From dc6cdb234d24cbcc0cb9e5c93c01ac63898c3e40 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Sun, 14 Jun 2009 16:11:35 +0200 Subject: python/cache.cc,depcache.cc: Do not delete the depcache and cache pointers. Deleting the pointers caused a crash because those pointers will also be deleted by closing the cache file. --- python/cache.cc | 4 +++- python/depcache.cc | 3 ++- 2 files changed, 5 insertions(+), 2 deletions(-) (limited to 'python') diff --git a/python/cache.cc b/python/cache.cc index 22ed9ecc..80a7a8a5 100644 --- a/python/cache.cc +++ b/python/cache.cc @@ -247,7 +247,9 @@ void PkgCacheFileDealloc(PyObject *Self) PyObject *CacheFilePy = GetOwner(Self); pkgCacheFile *CacheF = GetCpp(CacheFilePy); CacheF->Close(); - CppOwnedDeallocPtr(Self); + // Do not delete the pointer here, because it has already been deleted by + // closing the cache file. + CppOwnedDealloc(Self); } static PyObject *PkgCacheNew(PyTypeObject *type,PyObject *Args,PyObject *kwds) diff --git a/python/depcache.cc b/python/depcache.cc index 9bbda527..288eb0b0 100644 --- a/python/depcache.cc +++ b/python/depcache.cc @@ -660,7 +660,8 @@ PyTypeObject PkgDepCacheType = sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize // Methods - CppOwnedDeallocPtr, // tp_dealloc + // Not ..Ptr, because the pkgDepCache pointer is managed by the CacheFile. + CppOwnedDealloc, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr -- cgit v1.2.3 From 7618780d7e0550897f87eecc4ab52d75b9c0ec39 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Mon, 15 Jun 2009 14:58:41 +0200 Subject: Add support for Enhances as a dependency type (Closes: #416247) --- debian/changelog | 1 + python/cache.cc | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) (limited to 'python') diff --git a/debian/changelog b/debian/changelog index 55d3a834..9809d423 100644 --- a/debian/changelog +++ b/debian/changelog @@ -8,6 +8,7 @@ python-apt (0.7.92) UNRELEASED; urgency=low * apt/package.py: Return VersionList objects in Package.versions, which are sequences and also provide features of mappings. (small API BREAK) * apt/progress/__init__.py: Check for EINTR in select (Closes: #499296) + * Add support for Enhances as a dependency type (Closes: #416247) [ Sebastian Heinlein ] * apt/progress.py: Extract the package name from the status message diff --git a/python/cache.cc b/python/cache.cc index 80a7a8a5..7e75ccab 100644 --- a/python/cache.cc +++ b/python/cache.cc @@ -711,7 +711,7 @@ static PyObject *MakeDepends(PyObject *Owner,pkgCache::VerIterator &Ver, { "", "Depends","PreDepends","Suggests", "Recommends","Conflicts","Replaces", - "Obsoletes", "Breaks" + "Obsoletes", "Breaks", "Enhances" }; PyObject *Dep = PyString_FromString(Types[Start->Type]); LastDepType = Start->Type; -- cgit v1.2.3 From 498e518b22f9976c4ebcf110c05ada4c0d9bedf6 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Sun, 21 Jun 2009 11:17:08 +0200 Subject: python/progress.cc: Fix segfault related to pulse_items. --- python/progress.cc | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) (limited to 'python') diff --git a/python/progress.cc b/python/progress.cc index 2671f6fc..bc46b0c8 100644 --- a/python/progress.cc +++ b/python/progress.cc @@ -310,11 +310,11 @@ bool PyFetchProgress::Pulse(pkgAcquire * Owner) PyObject *result; bool res = true; - - RunSimpleCallback("pulse_items", arglist, &result); - if (result != NULL && PyArg_Parse(result, "b", &res) && res == false) { - // the user returned a explicit false here, stop - return false; + if (RunSimpleCallback("pulse_items", arglist, &result)) { + if (result != NULL && PyArg_Parse(result, "b", &res) && res == false) { + // the user returned a explicit false here, stop + return false; + } } arglist = Py_BuildValue("()"); -- cgit v1.2.3 From cef5268fc12c6a4b4b8aa2b58a09494b1944e28a Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Sun, 21 Jun 2009 13:45:11 +0200 Subject: python/progress.cc: Just try to call a function and fallback. --- python/progress.cc | 28 +++++++--------------------- 1 file changed, 7 insertions(+), 21 deletions(-) (limited to 'python') diff --git a/python/progress.cc b/python/progress.cc index bc46b0c8..c5035e62 100644 --- a/python/progress.cc +++ b/python/progress.cc @@ -101,9 +101,7 @@ bool PyFetchProgress::MediaChange(string Media, string Drive) //std::cout << "MediaChange" << std::endl; PyObject *arglist = Py_BuildValue("(ss)", Media.c_str(), Drive.c_str()); PyObject *result; - if(PyObject_HasAttrString(callbackInst, "media_change")) - RunSimpleCallback("media_change", arglist, &result); - else + if(! RunSimpleCallback("media_change", arglist, &result)) RunSimpleCallback("mediaChange", arglist, &result); bool res = true; @@ -137,9 +135,7 @@ void PyFetchProgress::UpdateStatus(pkgAcquire::ItemDesc &Itm, int status) Itm.Description.c_str(), Itm.ShortDesc.c_str(), status); - if(PyObject_HasAttrString(callbackInst, "update_status")) - RunSimpleCallback("update_status", arglist); - else + if(!RunSimpleCallback("update_status", arglist)) RunSimpleCallback("updateStatus", arglist); } @@ -340,25 +336,19 @@ bool PyFetchProgress::Pulse(pkgAcquire * Owner) void PyInstallProgress::StartUpdate() { - if(PyObject_HasAttrString(callbackInst, "start_update")) - RunSimpleCallback("start_update"); - else + if (!RunSimpleCallback("start_update")) RunSimpleCallback("startUpdate"); } void PyInstallProgress::UpdateInterface() { - if(PyObject_HasAttrString(callbackInst, "update_interface")) - RunSimpleCallback("update_interface"); - else + if (!RunSimpleCallback("update_interface")) RunSimpleCallback("updateInterface"); } void PyInstallProgress::FinishUpdate() { - if(PyObject_HasAttrString(callbackInst, "finish_update")) - RunSimpleCallback("finish_update"); - else + if (!RunSimpleCallback("finish_update")) RunSimpleCallback("finishUpdate"); } @@ -476,9 +466,7 @@ bool PyCdromProgress::ChangeCdrom() { PyObject *arglist = Py_BuildValue("()"); PyObject *result; - if(PyObject_HasAttrString(callbackInst, "change_cdrom")) - RunSimpleCallback("change_cdrom", arglist, &result); - else + if(!RunSimpleCallback("change_cdrom", arglist, &result)) RunSimpleCallback("changeCdrom", arglist, &result); bool res = true; @@ -494,9 +482,7 @@ bool PyCdromProgress::AskCdromName(string &Name) PyObject *arglist = Py_BuildValue("()"); PyObject *result; - if(PyObject_HasAttrString(callbackInst, "ask_cdrom_name")) - RunSimpleCallback("ask_cdrom_name", arglist, &result); - else + if (!RunSimpleCallback("ask_cdrom_name", arglist, &result)) RunSimpleCallback("askCdromName", arglist, &result); const char *new_name; -- cgit v1.2.3 From 2d962f13c554681ded71e665a429eb359742531f Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Sun, 21 Jun 2009 13:54:20 +0200 Subject: python/cache.cc: Give more information on TypeErrors in CacheMapOp --- python/cache.cc | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'python') diff --git a/python/cache.cc b/python/cache.cc index 7e75ccab..35c8b78f 100644 --- a/python/cache.cc +++ b/python/cache.cc @@ -223,7 +223,9 @@ static PyObject *CacheMapOp(PyObject *Self,PyObject *Arg) if (PyString_Check(Arg) == 0) { - PyErr_SetNone(PyExc_TypeError); + PyObject *repr = PyObject_Repr(Arg); + PyErr_SetObject(PyExc_TypeError, repr); + Py_DECREF(repr); return 0; } -- cgit v1.2.3 From b81133a92aa673d0d9315e9837012e59a988333a Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Sun, 21 Jun 2009 14:05:49 +0200 Subject: python: Add DeprecationWarning to functions which were replaced by classes. --- python/acquire.cc | 5 +++++ python/apt_pkgmodule.cc | 2 ++ python/cache.cc | 2 ++ python/cdrom.cc | 2 ++ python/depcache.cc | 8 ++++++++ python/pkgmanager.cc | 3 +++ python/pkgrecords.cc | 3 +++ python/pkgsrcrecords.cc | 11 +++-------- python/sourcelist.cc | 3 +++ python/tag.cc | 6 ++++++ 10 files changed, 37 insertions(+), 8 deletions(-) (limited to 'python') diff --git a/python/acquire.cc b/python/acquire.cc index 6b091479..d0549fd9 100644 --- a/python/acquire.cc +++ b/python/acquire.cc @@ -301,6 +301,8 @@ PyTypeObject PkgAcquireType = #ifdef COMPAT_0_7 PyObject *GetAcquire(PyObject *Self,PyObject *Args) { + PyErr_WarnEx(PyExc_DeprecationWarning,"apt_pkg.GetAcquire() is deprecated." + " Please see apt_pkg.Acquire() for the replacement.", 1); return PkgAcquireNew(&PkgAcquireType,Args,0); } #endif @@ -394,6 +396,9 @@ char *doc_GetPkgAcqFile = "GetPkgAcqFile(pkgAquire, uri[, md5, size, descr, shortDescr, destDir, destFile]) -> PkgAcqFile\n"; PyObject *GetPkgAcqFile(PyObject *Self, PyObject *Args, PyObject * kwds) { + PyErr_WarnEx(PyExc_DeprecationWarning, "apt_pkg.GetPkgAcqFile() is " + "deprecated. Please see apt_pkg.AcquireFile() for the " + "replacement", 1); PyObject *pyfetcher; char *uri, *md5, *descr, *shortDescr, *destDir, *destFile; int size = 0; diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index bfa59f8e..3a31440c 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -34,6 +34,8 @@ static char *doc_newConfiguration = "Construct a configuration instance"; static PyObject *newConfiguration(PyObject *self,PyObject *args) { + PyErr_WarnEx(PyExc_DeprecationWarning, "apt_pkg.newConfiguration() is " + "deprecated. Use apt_pkg.Configuration() instead.", 1); return CppPyObject_NEW(&ConfigurationType); } #endif diff --git a/python/cache.cc b/python/cache.cc index 35c8b78f..a8da6696 100644 --- a/python/cache.cc +++ b/python/cache.cc @@ -1371,6 +1371,8 @@ PyTypeObject RDepListType = #ifdef COMPAT_0_7 PyObject *TmpGetCache(PyObject *Self,PyObject *Args) { + PyErr_WarnEx(PyExc_DeprecationWarning, "apt_pkg.GetCache() is deprecated. " + "Please see apt_pkg.Cache() for the replacement.", 1); return PkgCacheNew(&PkgCacheType,Args,0); } #endif diff --git a/python/cdrom.cc b/python/cdrom.cc index e98947d1..e2651670 100644 --- a/python/cdrom.cc +++ b/python/cdrom.cc @@ -133,6 +133,8 @@ PyTypeObject PkgCdromType = #ifdef COMPAT_0_7 PyObject *GetCdrom(PyObject *Self,PyObject *Args) { + PyErr_WarnEx(PyExc_DeprecationWarning, "apt_pkg.GetCdrom() is deprecated. " + "Please see apt_pkg.Cdrom() for the replacement.", 1); return PkgCdromNew(&PkgCdromType,Args,0); } #endif diff --git a/python/depcache.cc b/python/depcache.cc index 288eb0b0..7cf8e0a2 100644 --- a/python/depcache.cc +++ b/python/depcache.cc @@ -701,6 +701,8 @@ PyTypeObject PkgDepCacheType = #ifdef COMPAT_0_7 PyObject *GetDepCache(PyObject *Self,PyObject *Args) { + PyErr_WarnEx(PyExc_DeprecationWarning,"apt_pkg.GetDepCache() is deprecated" + ". Please see apt_pkg.DepCache() for the replacement.",1); return PkgDepCacheNew(&PkgDepCacheType,Args,0); } #endif @@ -733,6 +735,9 @@ static PyObject *PkgProblemResolverNew(PyTypeObject *type,PyObject *Args,PyObjec #ifdef COMPAT_0_7 PyObject *GetPkgProblemResolver(PyObject *Self,PyObject *Args) { + PyErr_WarnEx(PyExc_DeprecationWarning, "apt_pkg.GetPkgProblemResolver() is" + " deprecated. Please see apt_pkg.ProblemResolver() for the " + "replacement.", 1); return PkgProblemResolverNew(&PkgProblemResolverType,Args,0); } #endif @@ -1003,6 +1008,9 @@ PyTypeObject PkgActionGroupType = #ifdef COMPAT_0_7 PyObject *GetPkgActionGroup(PyObject *Self,PyObject *Args) { + PyErr_WarnEx(PyExc_DeprecationWarning, "apt_pkg.GetPkgActionGroup() is " + "deprecated. Please see apt_pkg.ActionGroup() for the " + "replacement.", 1); return PkgActionGroupNew(&PkgActionGroupType,Args,0); } #endif diff --git a/python/pkgmanager.cc b/python/pkgmanager.cc index 0fd2cd92..668f7cfc 100644 --- a/python/pkgmanager.cc +++ b/python/pkgmanager.cc @@ -39,6 +39,9 @@ static PyObject *PkgManagerNew(PyTypeObject *type,PyObject *Args,PyObject *kwds) #ifdef COMPAT_0_7 PyObject *GetPkgManager(PyObject *Self,PyObject *Args) { + PyErr_WarnEx(PyExc_DeprecationWarning, "apt_pkg.GetPackageManager() is " + "deprecated. Please see apt_pkg.PackageManager() for the " + "replacement.", 1); return PkgManagerNew(&PkgManagerType,Args,0); } #endif diff --git a/python/pkgrecords.cc b/python/pkgrecords.cc index 8beefffd..1e36259d 100644 --- a/python/pkgrecords.cc +++ b/python/pkgrecords.cc @@ -214,6 +214,9 @@ PyTypeObject PkgRecordsType = #ifdef COMPAT_0_7 PyObject *GetPkgRecords(PyObject *Self,PyObject *Args) { + PyErr_WarnEx(PyExc_DeprecationWarning, "apt_pkg.GetPkgRecords() is " + "deprecated. Please see apt_pkg.Records() for the " + "replacement.", 1); return PkgRecordsNew(&PkgRecordsType,Args,0); } #endif diff --git a/python/pkgsrcrecords.cc b/python/pkgsrcrecords.cc index e6b78a83..f75934f9 100644 --- a/python/pkgsrcrecords.cc +++ b/python/pkgsrcrecords.cc @@ -255,14 +255,9 @@ PyTypeObject PkgSrcRecordsType = #ifdef COMPAT_0_7 PyObject *GetPkgSrcRecords(PyObject *Self,PyObject *Args) { -#if 0 - PyObject *Owner; - if (PyArg_ParseTuple(Args,"O!",&PkgCacheType,&Owner) == 0) - return 0; - - return HandleErrors(CppOwnedPyObject_NEW(Owner, - &PkgSrcRecordsType)); -#endif + PyErr_WarnEx(PyExc_DeprecationWarning, "apt_pkg.GetPkgSrcRecords() is " + "deprecated. Please see apt_pkg.SourceRecords() for the " + "replacement.", 1); if (PyArg_ParseTuple(Args,"") == 0) return 0; diff --git a/python/sourcelist.cc b/python/sourcelist.cc index e53fccd3..2cf5eea9 100644 --- a/python/sourcelist.cc +++ b/python/sourcelist.cc @@ -163,6 +163,9 @@ PyTypeObject PkgSourceListType = #ifdef COMPAT_0_7 PyObject *GetPkgSourceList(PyObject *Self,PyObject *Args) { + PyErr_WarnEx(PyExc_DeprecationWarning, "apt_pkg.GetPkgSourceList() is " + "deprecated. Please see apt_pkg.SourceList() for the " + "replacement.", 1); return PkgSourceListNew(&PkgSourceListType,Args,0); } #endif diff --git a/python/tag.cc b/python/tag.cc index 7e7eb21c..05423e3d 100644 --- a/python/tag.cc +++ b/python/tag.cc @@ -268,6 +268,9 @@ static PyObject *TagSecNew(PyTypeObject *type,PyObject *Args,PyObject *kwds) { char *doc_ParseSection ="ParseSection(Text) -> TagSection() object. Deprecated."; PyObject *ParseSection(PyObject *self,PyObject *Args) { + PyErr_WarnEx(PyExc_DeprecationWarning, "apt_pkg.ParseSection() is " + "deprecated. Please see apt_pkg.TagSection() for the " + "replacement.", 1); return TagSecNew(&TagSecType,Args,0); } #endif @@ -302,6 +305,9 @@ static PyObject *TagFileNew(PyTypeObject *type,PyObject *Args,PyObject *kwds) #ifdef COMPAT_0_7 char *doc_ParseTagFile = "ParseTagFile(File) -> TagFile() object. Deprecated."; PyObject *ParseTagFile(PyObject *self,PyObject *Args) { + PyErr_WarnEx(PyExc_DeprecationWarning, "apt_pkg.ParseTagFile() is " + "deprecated. Please see apt_pkg.TagFile() for the " + "replacement.", 1); return TagFileNew(&TagFileType,Args,0); } #endif -- cgit v1.2.3 From 6338b8abafaef4dcdcf852cab049124cc4ecce06 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Sun, 21 Jun 2009 14:46:19 +0200 Subject: python/acquire.cc, python/indexfile.cc: Do not delete the pointers for some objects. We can not delete the AcquireFile object's pointer on deallocation because this would cause the item to be removed from the fetcher, which would be incompatible to the previous behaviour. We can not delete the IndexFile object's pointer on deallocation because it is managed by other objects like MetaIndex. --- python/acquire.cc | 4 +++- python/indexfile.cc | 4 ++-- 2 files changed, 5 insertions(+), 3 deletions(-) (limited to 'python') diff --git a/python/acquire.cc b/python/acquire.cc index d0549fd9..704ad0bd 100644 --- a/python/acquire.cc +++ b/python/acquire.cc @@ -354,7 +354,9 @@ PyTypeObject PkgAcquireFileType = sizeof(CppOwnedPyObject),// tp_basicsize 0, // tp_itemsize // Methods - CppOwnedDeallocPtr, // tp_dealloc + // Not ..Ptr, because this would cause the item to be removed from the + // fetcher, which would be incompatible to previous behaviour. + CppOwnedDealloc, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr diff --git a/python/indexfile.cc b/python/indexfile.cc index 78a4f513..ba709872 100644 --- a/python/indexfile.cc +++ b/python/indexfile.cc @@ -22,7 +22,6 @@ static PyObject *PackageIndexFileArchiveURI(PyObject *Self,PyObject *Args) if (PyArg_ParseTuple(Args, "s",&path) == 0) return 0; - return HandleErrors(Safe_FromString(File->ArchiveURI(path).c_str())); } @@ -99,7 +98,8 @@ PyTypeObject PackageIndexFileType = sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize // Methods - CppOwnedDeallocPtr, // tp_dealloc + // Not ..Ptr, because the pointer is managed somewhere else. + CppOwnedDealloc, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr -- cgit v1.2.3 From 13423bbbafc823740126e90ef0d7ca6e76fc7341 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Sun, 21 Jun 2009 19:47:31 +0200 Subject: python: Make all CppOwnedPyObjects and similar support garbage collection. If you want to subclass apt_pkg.Cache() and create an apt_pkg.DepCache() object in it (e.g. as self.depcache) this is needed because otherwise, Python would not know about the cyclic dependency and refuse to free any of them. This also changes apt_pkg.Cache to the standard deallocation schema, because the underlying CacheFile deletes its pointers automatically on deletion. Thus a second call is not needed. --- python/acquire.cc | 7 +++--- python/cache.cc | 62 ++++++++++++++++++++++++---------------------------- python/depcache.cc | 23 ++++++++++--------- python/generic.h | 44 +++++++++++++++++++++++++++++++++---- python/indexfile.cc | 6 ++--- python/pkgrecords.cc | 7 +++--- python/policy.cc | 9 ++++---- python/tag.cc | 37 +++++++++++++++++++++++-------- 8 files changed, 125 insertions(+), 70 deletions(-) (limited to 'python') diff --git a/python/acquire.cc b/python/acquire.cc index 704ad0bd..b0dd2cab 100644 --- a/python/acquire.cc +++ b/python/acquire.cc @@ -372,10 +372,11 @@ PyTypeObject PkgAcquireFileType = 0, // tp_setattro 0, // tp_as_buffer (Py_TPFLAGS_DEFAULT | // tp_flags - Py_TPFLAGS_BASETYPE), + Py_TPFLAGS_BASETYPE | + Py_TPFLAGS_HAVE_GC), doc_PkgAcquireFile, // tp_doc - 0, // tp_traverse - 0, // tp_clear + CppOwnedTraverse, // tp_traverse + CppOwnedClear, // tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset 0, // tp_iter diff --git a/python/cache.cc b/python/cache.cc index a8da6696..4624dc34 100644 --- a/python/cache.cc +++ b/python/cache.cc @@ -241,19 +241,6 @@ static PyObject *CacheMapOp(PyObject *Self,PyObject *Arg) return CppOwnedPyObject_NEW(Self,&PackageType,Pkg); } -// we need a special dealloc here to make sure that the CacheFile -// is closed before deallocation the cache (otherwise we have a bad) -// memory leak -void PkgCacheFileDealloc(PyObject *Self) -{ - PyObject *CacheFilePy = GetOwner(Self); - pkgCacheFile *CacheF = GetCpp(CacheFilePy); - CacheF->Close(); - // Do not delete the pointer here, because it has already been deleted by - // closing the cache file. - CppOwnedDealloc(Self); -} - static PyObject *PkgCacheNew(PyTypeObject *type,PyObject *Args,PyObject *kwds) { PyObject *pyCallbackInst = 0; @@ -320,7 +307,7 @@ PyTypeObject PkgCacheType = sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize // Methods - PkgCacheFileDealloc, // tp_dealloc + CppOwnedDealloc, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr @@ -336,10 +323,11 @@ PyTypeObject PkgCacheType = 0, // tp_setattro 0, // tp_as_buffer (Py_TPFLAGS_DEFAULT | // tp_flags - Py_TPFLAGS_BASETYPE), + Py_TPFLAGS_BASETYPE | + Py_TPFLAGS_HAVE_GC), doc_PkgCache, // tp_doc - 0, // tp_traverse - 0, // tp_clear + CppOwnedTraverse, // tp_traverse + CppOwnedClear, // tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset 0, // tp_iter @@ -460,7 +448,10 @@ PyTypeObject PkgListType = 0, // tp_getattro 0, // tp_setattro 0, // tp_as_buffer - Py_TPFLAGS_DEFAULT , // tp_flags + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, // tp_flags + 0, // tp_doc + CppOwnedTraverse, // tp_traverse + CppOwnedClear, // tp_clear }; #define MkGet(PyFunc,Ret) static PyObject *PyFunc(PyObject *Self,void*) \ @@ -581,10 +572,10 @@ PyTypeObject PackageType = 0, // tp_getattro 0, // tp_setattro 0, // tp_as_buffer - Py_TPFLAGS_DEFAULT, // tp_flags + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, // tp_flags "Package Object", // tp_doc - 0, // tp_traverse - 0, // tp_clear + CppOwnedTraverse, // tp_traverse + CppOwnedClear,// tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset 0, // tp_iter @@ -672,10 +663,10 @@ PyTypeObject DescriptionType = 0, // tp_getattro 0, // tp_setattro 0, // tp_as_buffer - Py_TPFLAGS_DEFAULT, // tp_flags + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, // tp_flags "apt_pkg.Description Object", // tp_doc - 0, // tp_traverse - 0, // tp_clear + CppOwnedTraverse, // tp_traverse + CppOwnedClear,// tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset 0, // tp_iter @@ -935,10 +926,10 @@ PyTypeObject VersionType = 0, // tp_getattro 0, // tp_setattro 0, // tp_as_buffer - Py_TPFLAGS_DEFAULT, // tp_flags + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, // tp_flags "Version Object", // tp_doc - 0, // tp_traverse - 0, // tp_clear + CppOwnedTraverse, // tp_traverse + CppOwnedClear,// tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset 0, // tp_iter @@ -1098,10 +1089,10 @@ PyTypeObject PackageFileType = { 0, // tp_getattro 0, // tp_setattro 0, // tp_as_buffer - Py_TPFLAGS_DEFAULT, // tp_flags + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, // tp_flags "apt_pkg.PackageFile Object", // tp_doc - 0, // tp_traverse - 0, // tp_clear + CppOwnedTraverse, // tp_traverse + CppOwnedClear, // tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset 0, // tp_iter @@ -1274,10 +1265,10 @@ PyTypeObject DependencyType = 0, // tp_getattro 0, // tp_setattro 0, // tp_as_buffer - Py_TPFLAGS_DEFAULT, // tp_flags + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, // tp_flags "Dependency Object", // tp_doc - 0, // tp_traverse - 0, // tp_clear + CppOwnedTraverse, // tp_traverse + CppOwnedClear, // tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset 0, // tp_iter @@ -1362,7 +1353,10 @@ PyTypeObject RDepListType = 0, // tp_getattro 0, // tp_setattro 0, // tp_as_buffer - Py_TPFLAGS_DEFAULT, // tp_flags + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, // tp_flags + "DependencyList Object", // tp_doc + CppOwnedTraverse, // tp_traverse + CppOwnedClear, // tp_clear }; /*}}}*/ diff --git a/python/depcache.cc b/python/depcache.cc index 7cf8e0a2..d0b233b8 100644 --- a/python/depcache.cc +++ b/python/depcache.cc @@ -677,10 +677,11 @@ PyTypeObject PkgDepCacheType = 0, // tp_setattro 0, // tp_as_buffer (Py_TPFLAGS_DEFAULT | // tp_flags - Py_TPFLAGS_BASETYPE), + Py_TPFLAGS_BASETYPE | + Py_TPFLAGS_HAVE_GC), doc_PkgDepCache, // tp_doc - 0, // tp_traverse - 0, // tp_clear + CppOwnedTraverse, // tp_traverse + CppOwnedClear, // tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset 0, // tp_iter @@ -866,10 +867,11 @@ PyTypeObject PkgProblemResolverType = 0, // tp_setattro 0, // tp_as_buffer (Py_TPFLAGS_DEFAULT | // tp_flags - Py_TPFLAGS_BASETYPE), + Py_TPFLAGS_BASETYPE | + Py_TPFLAGS_HAVE_GC), "ProblemResolver Object", // tp_doc - 0, // tp_traverse - 0, // tp_clear + CppOwnedTraverse, // tp_traverse + CppOwnedClear, // tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset 0, // tp_iter @@ -984,10 +986,11 @@ PyTypeObject PkgActionGroupType = 0, // tp_setattro 0, // tp_as_buffer (Py_TPFLAGS_DEFAULT | // tp_flags - Py_TPFLAGS_BASETYPE), + Py_TPFLAGS_BASETYPE | + Py_TPFLAGS_HAVE_GC), doc_PkgActionGroup, // tp_doc - 0, // tp_traverse - 0, // tp_clear + CppOwnedTraverse, // tp_traverse + CppOwnedClear, // tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset 0, // tp_iter @@ -1002,7 +1005,7 @@ PyTypeObject PkgActionGroupType = 0, // tp_dictoffset 0, // tp_init 0, // tp_alloc - PkgActionGroupNew, // tp_new + PkgActionGroupNew, // tp_new }; #ifdef COMPAT_0_7 diff --git a/python/generic.h b/python/generic.h index b7b958f5..a9e6b8bf 100644 --- a/python/generic.h +++ b/python/generic.h @@ -29,6 +29,7 @@ #include #include +#include #include #if PYTHON_API_VERSION < 1013 @@ -99,6 +100,9 @@ inline PyObject *GetOwner(PyObject *Obj) template inline CppPyObject *CppPyObject_NEW(PyTypeObject *Type) { + #ifdef ALLOC_DEBUG + std::cerr << "=== ALLOCATING " << Type->tp_name << " ===\n"; + #endif CppPyObject *New = (CppPyObject*)Type->tp_alloc(Type, 0); new (&New->Object) T; return New; @@ -107,6 +111,9 @@ inline CppPyObject *CppPyObject_NEW(PyTypeObject *Type) template inline CppPyObject *CppPyObject_NEW(PyTypeObject *Type,A const &Arg) { + #ifdef ALLOC_DEBUG + std::cerr << "=== ALLOCATING " << Type->tp_name << " ===\n"; + #endif CppPyObject *New = (CppPyObject*)Type->tp_alloc(Type, 0); new (&New->Object) T(Arg); return New; @@ -116,6 +123,9 @@ template inline CppOwnedPyObject *CppOwnedPyObject_NEW(PyObject *Owner, PyTypeObject *Type) { + #ifdef ALLOC_DEBUG + std::cerr << "=== ALLOCATING " << Type->tp_name << "+ ===\n"; + #endif CppOwnedPyObject *New = (CppOwnedPyObject*)Type->tp_alloc(Type, 0); new (&New->Object) T; New->Owner = Owner; @@ -127,6 +137,9 @@ template inline CppOwnedPyObject *CppOwnedPyObject_NEW(PyObject *Owner, PyTypeObject *Type,A const &Arg) { + #ifdef ALLOC_DEBUG + std::cerr << "=== ALLOCATING " << Type->tp_name << "+ ===\n"; + #endif CppOwnedPyObject *New = (CppOwnedPyObject*)Type->tp_alloc(Type, 0); new (&New->Object) T(Arg); New->Owner = Owner; @@ -135,10 +148,26 @@ inline CppOwnedPyObject *CppOwnedPyObject_NEW(PyObject *Owner, return New; } +// Traversal and Clean for owned objects +template +int CppOwnedTraverse(PyObject *self, visitproc visit, void* arg) { + Py_VISIT(((CppOwnedPyObject *)self)->Owner); + return 0; +} + +template +int CppOwnedClear(PyObject *self) { + Py_CLEAR(((CppOwnedPyObject *)self)->Owner); + return 0; +} + // Generic Dealloc type functions template void CppDealloc(PyObject *Obj) { + #ifdef ALLOC_DEBUG + std::cerr << "=== DEALLOCATING " << Obj->ob_type->tp_name << " ===\n"; + #endif GetCpp(Obj).~T(); Obj->ob_type->tp_free(Obj); } @@ -146,10 +175,12 @@ void CppDealloc(PyObject *Obj) template void CppOwnedDealloc(PyObject *iObj) { + #ifdef ALLOC_DEBUG + std::cerr << "=== DEALLOCATING " << iObj->ob_type->tp_name << "+ ===\n"; + #endif CppOwnedPyObject *Obj = (CppOwnedPyObject *)iObj; Obj->Object.~T(); - if (Obj->Owner != 0) - Py_DECREF(Obj->Owner); + CppOwnedClear(iObj); iObj->ob_type->tp_free(iObj); } @@ -158,6 +189,9 @@ void CppOwnedDealloc(PyObject *iObj) template void CppDeallocPtr(PyObject *Obj) { + #ifdef ALLOC_DEBUG + std::cerr << "=== DEALLOCATING " << Obj->ob_type->tp_name << "* ===\n"; + #endif delete GetCpp(Obj); Obj->ob_type->tp_free(Obj); } @@ -165,10 +199,12 @@ void CppDeallocPtr(PyObject *Obj) template void CppOwnedDeallocPtr(PyObject *iObj) { + #ifdef ALLOC_DEBUG + std::cerr << "=== DEALLOCATING " << iObj->ob_type->tp_name << "*+ ===\n"; + #endif CppOwnedPyObject *Obj = (CppOwnedPyObject *)iObj; delete Obj->Object; - if (Obj->Owner != 0) - Py_DECREF(Obj->Owner); + CppOwnedClear(iObj); iObj->ob_type->tp_free(iObj); } diff --git a/python/indexfile.cc b/python/indexfile.cc index ba709872..ef88c2f0 100644 --- a/python/indexfile.cc +++ b/python/indexfile.cc @@ -114,10 +114,10 @@ PyTypeObject PackageIndexFileType = 0, // tp_getattro 0, // tp_setattro 0, // tp_as_buffer - Py_TPFLAGS_DEFAULT, // tp_flags + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, // tp_flags "pkgIndexFile Object", // tp_doc - 0, // tp_traverse - 0, // tp_clear + CppOwnedTraverse, // tp_traverse + CppOwnedClear, // tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset 0, // tp_iter diff --git a/python/pkgrecords.cc b/python/pkgrecords.cc index 1e36259d..4a3c80db 100644 --- a/python/pkgrecords.cc +++ b/python/pkgrecords.cc @@ -187,10 +187,11 @@ PyTypeObject PkgRecordsType = 0, // tp_setattro 0, // tp_as_buffer (Py_TPFLAGS_DEFAULT | // tp_flags - Py_TPFLAGS_BASETYPE), + Py_TPFLAGS_BASETYPE | + Py_TPFLAGS_HAVE_GC), "Records Object", // tp_doc - 0, // tp_traverse - 0, // tp_clear + CppOwnedTraverse, // tp_traverse + CppOwnedClear, // tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset 0, // tp_iter diff --git a/python/policy.cc b/python/policy.cc index 992a1192..39bbc1a3 100644 --- a/python/policy.cc +++ b/python/policy.cc @@ -167,15 +167,16 @@ PyTypeObject PyPolicy_Type = { 0, // tp_setattro 0, // tp_as_buffer (Py_TPFLAGS_DEFAULT | // tp_flags - Py_TPFLAGS_BASETYPE), + Py_TPFLAGS_BASETYPE | + Py_TPFLAGS_HAVE_GC), Policy_doc, // tp_doc - 0, // tp_traverse - 0, // tp_clear + CppOwnedTraverse, // tp_traverse + CppOwnedClear, // tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset 0, // tp_iter 0, // tp_iternext - Policy_Methods, // tp_methods + Policy_Methods, // tp_methods 0, // tp_members 0, // tp_getset 0, // tp_base diff --git a/python/tag.cc b/python/tag.cc index 05423e3d..74857fe5 100644 --- a/python/tag.cc +++ b/python/tag.cc @@ -34,7 +34,7 @@ using namespace std; /*}}}*/ /* We need to keep a private copy of the data.. */ -struct TagSecData : public CppPyObject +struct TagSecData : public CppOwnedPyObject { char *Data; }; @@ -47,6 +47,18 @@ struct TagFileData : public PyObject FileFd Fd; }; +// Traversal and Clean for owned objects +int TagFileTraverse(PyObject *self, visitproc visit, void* arg) { + Py_VISIT(((TagFileData *)self)->Section); + return 0; +} + +int TagFileClear(PyObject *self) { + Py_CLEAR(((TagFileData *)self)->Section); + return 0; +} + + /*}}}*/ // TagSecFree - Free a Tag Section /*{{{*/ // --------------------------------------------------------------------- @@ -55,7 +67,7 @@ void TagSecFree(PyObject *Obj) { TagSecData *Self = (TagSecData *)Obj; delete [] Self->Data; - CppDealloc(Obj); + CppOwnedDealloc(Obj); } /*}}}*/ // TagFileFree - Free a Tag File /*{{{*/ @@ -63,8 +75,11 @@ void TagSecFree(PyObject *Obj) /* */ void TagFileFree(PyObject *Obj) { + #ifdef ALLOC_DEBUG + std::cerr << "=== DEALLOCATING " << Obj->ob_type->tp_name << "^ ===\n"; + #endif TagFileData *Self = (TagFileData *)Obj; - Py_DECREF((PyObject *)Self->Section); + TagFileClear(Obj); Self->Object.~pkgTagFile(); Self->Fd.~FileFd(); Py_DECREF(Self->File); @@ -298,6 +313,8 @@ static PyObject *TagFileNew(PyTypeObject *type,PyObject *Args,PyObject *kwds) // Create the section New->Section = (TagSecData*)(&TagSecType)->tp_alloc(&TagSecType, 0); new (&New->Section->Object) pkgTagSection(); + New->Section->Owner = New; + Py_INCREF(New->Section->Owner); New->Section->Data = 0; return HandleErrors(New); @@ -441,10 +458,11 @@ PyTypeObject TagSecType = 0, // tp_setattro 0, // tp_as_buffer (Py_TPFLAGS_DEFAULT | // tp_flags - Py_TPFLAGS_BASETYPE), + Py_TPFLAGS_BASETYPE | + Py_TPFLAGS_HAVE_GC), doc_TagSec, // tp_doc - 0, // tp_traverse - 0, // tp_clear + CppOwnedTraverse, // tp_traverse + CppOwnedClear, // tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset 0, // tp_iter @@ -529,10 +547,11 @@ PyTypeObject TagFileType = 0, // tp_setattro 0, // tp_as_buffer (Py_TPFLAGS_DEFAULT | // tp_flags - Py_TPFLAGS_BASETYPE), + Py_TPFLAGS_BASETYPE | + Py_TPFLAGS_HAVE_GC), doc_TagFile, // tp_doc - 0, // tp_traverse - 0, // tp_clear + TagFileTraverse, // tp_traverse + TagFileClear, // tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset 0, // tp_iter -- cgit v1.2.3 From d19176793f57ab8e5882928acd9fb79398e3ac6b Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Sun, 21 Jun 2009 20:17:54 +0200 Subject: python/apt_pkgmodule.cc: Delete apt_pkg.Version constant [API break] We can not keep the old apt_pkg.Version constant, because the name Version is already used by the Version class. --- python/apt_pkgmodule.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'python') diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index 3a31440c..9f750996 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -629,7 +629,7 @@ extern "C" void initapt_pkg() PyModule_AddStringConstant(Module,"DATE",__DATE__); PyModule_AddStringConstant(Module,"TIME",__TIME__); #ifdef COMPAT_0_7 - PyModule_AddStringConstant(Module,"Version",(char *)pkgVersion); + //PyModule_AddStringConstant(Module,"Version",(char *)pkgVersion); PyModule_AddStringConstant(Module,"LibVersion",(char *)pkgLibVersion); PyModule_AddStringConstant(Module,"Date",__DATE__); PyModule_AddStringConstant(Module,"Time",__TIME__); -- cgit v1.2.3 From 5e72b1f4f302e86a75399694d293e09a58d4bdbe Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Sun, 21 Jun 2009 21:05:24 +0200 Subject: python/generic.h: Define a compat macro PyErr_WarnEx for Python 2.4 --- python/generic.h | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'python') diff --git a/python/generic.h b/python/generic.h index a9e6b8bf..4fe1f915 100644 --- a/python/generic.h +++ b/python/generic.h @@ -63,6 +63,11 @@ typedef int Py_ssize_t; #define PyBytes_AsStringAndSize PyString_AsStringAndSize #endif +// Hacks to make Python 2.4 build. +#if PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION <= 4 +#define PyErr_WarnEx(cat,msg,stacklevel) PyErr_Warn(cat,msg) +#endif + template struct CppPyObject : public PyObject { // We are only using CppPyObject and friends as dumb structs only, ie the -- cgit v1.2.3 From b426f959e7e515d5f267558b6ae51ed9ae03fb9d Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Mon, 22 Jun 2009 14:54:31 +0200 Subject: Add apt_pkg.DepCache.mark_auto() and apt.Package.mark_auto() methods to mark a package as automatically installed. --- apt/package.py | 13 +++++++++++++ debian/changelog | 4 +++- python/depcache.cc | 18 ++++++++++++++++++ 3 files changed, 34 insertions(+), 1 deletion(-) (limited to 'python') diff --git a/apt/package.py b/apt/package.py index cb99fe6a..39a73c07 100644 --- a/apt/package.py +++ b/apt/package.py @@ -846,6 +846,10 @@ class Package(object): return self.is_installed and \ self._pcache._depcache.is_garbage(self._pkg) + @property + def is_auto_installed(self): + """Return whether the package is marked as automatically installed.""" + return self._pcache._depcache.is_auto_installed(self._pkg) # sizes @DeprecatedProperty @@ -1135,6 +1139,15 @@ class Package(object): sys.stderr.write(("MarkUpgrade() called on a non-upgrable pkg: " "'%s'\n") % self._pkg.name) + def mark_auto(self, auto=True): + """Mark a package as automatically installed. + + Call this function to mark a package as automatically installed. If the + optional parameter *auto* is set to ``False``, the package will not be + marked as automatically installed anymore. The default is ``True``. + """ + self._pcache._depcache.mark_auto(self._pkg, auto) + def commit(self, fprogress, iprogress): """Commit the changes. diff --git a/debian/changelog b/debian/changelog index 4fb6b0de..f0b3efbe 100644 --- a/debian/changelog +++ b/debian/changelog @@ -13,6 +13,8 @@ python-apt (0.7.92) UNRELEASED; urgency=low properties (Closes: #532338) * apt/cache.py: Correctly handle rootdir on second and later invocations of open() (LP: #320665). + * Add apt_pkg.DepCache.mark_auto() and apt.Package.mark_auto() methods to + mark a package as automatically installed. [ Sebastian Heinlein ] * apt/progress.py: Extract the package name from the status message @@ -28,7 +30,7 @@ python-apt (0.7.92) UNRELEASED; urgency=low * python/progress.cc: - low level code for update_status_full and pulse_items() - -- Julian Andres Klode Mon, 15 Jun 2009 14:45:06 +0200 + -- Julian Andres Klode Mon, 22 Jun 2009 14:38:19 +0200 python-apt (0.7.91) experimental; urgency=low diff --git a/python/depcache.cc b/python/depcache.cc index d0b233b8..e1514300 100644 --- a/python/depcache.cc +++ b/python/depcache.cc @@ -367,6 +367,23 @@ static PyObject *PkgDepCacheMarkInstall(PyObject *Self,PyObject *Args) return HandleErrors(Py_None); } +static PyObject *PkgDepCacheMarkAuto(PyObject *Self,PyObject *Args) +{ + pkgDepCache *depcache = GetCpp(Self); + + PyObject *PackageObj; + char value = 0; + if (PyArg_ParseTuple(Args,"O!b",&PackageType,&PackageObj, &value) == 0) + return 0; + + pkgCache::PkgIterator &Pkg = GetCpp(PackageObj); + depcache->MarkAuto(Pkg,value); + + Py_INCREF(Py_None); + return HandleErrors(Py_None); +} + + static PyObject *PkgDepCacheIsUpgradable(PyObject *Self,PyObject *Args) { pkgDepCache *depcache = GetCpp(Self); @@ -541,6 +558,7 @@ static PyMethodDef PkgDepCacheMethods[] = {"mark_keep",PkgDepCacheMarkKeep,METH_VARARGS,"Mark package for keep"}, {"mark_delete",PkgDepCacheMarkDelete,METH_VARARGS,"Mark package for delete (optional boolean argument if it should be purged)"}, {"mark_install",PkgDepCacheMarkInstall,METH_VARARGS,"Mark package for Install"}, + {"mark_auto",PkgDepCacheMarkAuto,METH_VARARGS,"mark_auto(pkg: apt_pkg.Package, auto: bool)\n\nMark package as automatically installed."}, {"set_reinstall",PkgDepCacheSetReInstall,METH_VARARGS,"Set if the package should be reinstalled"}, // state information {"is_upgradable",PkgDepCacheIsUpgradable,METH_VARARGS,"Is pkg upgradable"}, -- cgit v1.2.3 From 7c248775da6c86e70a8444630722c92a2dcd676f Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Mon, 22 Jun 2009 15:53:45 +0200 Subject: python/cache.cc: Drop apt_pkg.Cache.open() and apt_pkg.Cache.close(). Drop these functions, because they cause segfaults and memory leaks. To replace this functionality, simply create/delete a Cache object. This way, reference counting can work. --- debian/changelog | 4 +++- python/cache.cc | 7 +++++-- 2 files changed, 8 insertions(+), 3 deletions(-) (limited to 'python') diff --git a/debian/changelog b/debian/changelog index f0b3efbe..0ef7e38b 100644 --- a/debian/changelog +++ b/debian/changelog @@ -15,6 +15,8 @@ python-apt (0.7.92) UNRELEASED; urgency=low open() (LP: #320665). * Add apt_pkg.DepCache.mark_auto() and apt.Package.mark_auto() methods to mark a package as automatically installed. + * Drop apt_pkg.Cache.open() and apt_pkg.Cache.close(), they cause segfaults + and memory leaks. Simply create a new cache instead. [ Sebastian Heinlein ] * apt/progress.py: Extract the package name from the status message @@ -30,7 +32,7 @@ python-apt (0.7.92) UNRELEASED; urgency=low * python/progress.cc: - low level code for update_status_full and pulse_items() - -- Julian Andres Klode Mon, 22 Jun 2009 14:38:19 +0200 + -- Julian Andres Klode Mon, 22 Jun 2009 15:49:03 +0200 python-apt (0.7.91) experimental; urgency=low diff --git a/python/cache.cc b/python/cache.cc index 4624dc34..4ce3178c 100644 --- a/python/cache.cc +++ b/python/cache.cc @@ -95,6 +95,8 @@ static PyObject *PkgCacheUpdate(PyObject *Self,PyObject *Args) static PyObject *PkgCacheClose(PyObject *Self,PyObject *Args) { + PyErr_WarnEx(PyExc_DeprecationWarning, "Cache.Close() is deprecated, " + "because it causes segfaults. Delete the Cache instead.", 1); PyObject *CacheFilePy = GetOwner(Self); pkgCacheFile *Cache = GetCpp(CacheFilePy); Cache->Close(); @@ -105,6 +107,9 @@ static PyObject *PkgCacheClose(PyObject *Self,PyObject *Args) static PyObject *PkgCacheOpen(PyObject *Self,PyObject *Args) { + PyErr_WarnEx(PyExc_DeprecationWarning, "Cache.Open() is deprecated, " + "because it causes memory leaks. Create a new Cache instead.", + 1); PyObject *CacheFilePy = GetOwner(Self); pkgCacheFile *Cache = GetCpp(CacheFilePy); @@ -137,8 +142,6 @@ static PyObject *PkgCacheOpen(PyObject *Self,PyObject *Args) static PyMethodDef PkgCacheMethods[] = { {"update",PkgCacheUpdate,METH_VARARGS,"Update the cache"}, - {"open", PkgCacheOpen, METH_VARARGS,"Open the cache"}, - {"close", PkgCacheClose, METH_VARARGS,"Close the cache"}, #ifdef COMPAT_0_7 {"Update",PkgCacheUpdate,METH_VARARGS,"Update the cache"}, {"Open", PkgCacheOpen, METH_VARARGS,"Open the cache"}, -- cgit v1.2.3 From 6e9b361307e4c024fd882ab4a59d39dfb2b25b60 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Tue, 23 Jun 2009 11:29:21 +0200 Subject: python/acquire.cc: Make AcquireFile a subclass of AcquireItem Generalized the code a bit, so we can now access the various attributes of AcquireItem in the AcquireFile (pkgAcqFile is a subclass of pkgAcquire::Item). This will allow us to implement a raw object with a single pointer to an Item later, which we will need for the new progress interface. --- debian/changelog | 1 + python/acquire.cc | 50 ++++++++++++++++++++++++++++++++------------------ 2 files changed, 33 insertions(+), 18 deletions(-) (limited to 'python') diff --git a/debian/changelog b/debian/changelog index 843c6b3b..c4486505 100644 --- a/debian/changelog +++ b/debian/changelog @@ -19,6 +19,7 @@ python-apt (0.7.92) UNRELEASED; urgency=low and memory leaks. Simply create a new cache instead. * Merge 0.7.10.4 from unstable * debian/control: Update Standards-Version to 3.8.2 + * Make AcquireFile a subclass of AcquireItem [ Sebastian Heinlein ] * apt/progress.py: Extract the package name from the status message diff --git a/python/acquire.cc b/python/acquire.cc index b0dd2cab..e13e47d6 100644 --- a/python/acquire.cc +++ b/python/acquire.cc @@ -14,20 +14,27 @@ #define MkGet(PyFunc,Ret) static PyObject *PyFunc(PyObject *Self,void*) \ { \ - pkgAcquire::ItemIterator &I = GetCpp(Self); \ + pkgAcquire::Item *Itm; \ + if (PyObject_TypeCheck(Self, &PkgAcquireFileType)) { \ + Itm = GetCpp(Self); \ + } else { \ + pkgAcquire::ItemIterator &I = GetCpp(Self); \ + Itm = *I; \ + } \ return Ret; \ } // Define our getters -MkGet(AcquireItemGetComplete,Py_BuildValue("i",(*I)->Complete)); -MkGet(AcquireItemGetDescURI,Safe_FromString((*I)->DescURI().c_str())); -MkGet(AcquireItemGetDestFile,Safe_FromString((*I)->DestFile.c_str())); -MkGet(AcquireItemGetErrorText,Safe_FromString((*I)->ErrorText.c_str())); -MkGet(AcquireItemGetFileSize,Py_BuildValue("i",(*I)->FileSize)); -MkGet(AcquireItemGetID,Py_BuildValue("i",(*I)->ID)); -MkGet(AcquireItemGetIsTrusted,Py_BuildValue("i",(*I)->IsTrusted())); -MkGet(AcquireItemGetLocal,Py_BuildValue("i",(*I)->Local)); -MkGet(AcquireItemGetStatus,Py_BuildValue("i",(*I)->Status)); +MkGet(AcquireItemGetComplete,Py_BuildValue("i",Itm->Complete)); +MkGet(AcquireItemGetDescURI,Safe_FromString(Itm->DescURI().c_str())); +MkGet(AcquireItemGetDestFile,Safe_FromString(Itm->DestFile.c_str())); +MkGet(AcquireItemGetErrorText,Safe_FromString(Itm->ErrorText.c_str())); +MkGet(AcquireItemGetFileSize,Py_BuildValue("i",Itm->FileSize)); +MkGet(AcquireItemGetID,Py_BuildValue("i",Itm->ID)); +MkGet(AcquireItemGetIsTrusted,Py_BuildValue("i",Itm->IsTrusted())); +MkGet(AcquireItemGetLocal,Py_BuildValue("i",Itm->Local)); +MkGet(AcquireItemGetStatus,Py_BuildValue("i",Itm->Status)); + // Constants MkGet(AcquireItemGetStatIdle,Py_BuildValue("i", pkgAcquire::Item::StatIdle)); @@ -43,7 +50,7 @@ static PyGetSetDef AcquireItemGetSet[] = { {"destfile",AcquireItemGetDestFile}, {"error_text",AcquireItemGetErrorText}, {"filesize",AcquireItemGetFileSize}, - {"is",AcquireItemGetID}, + {"id",AcquireItemGetID}, {"is_trusted",AcquireItemGetIsTrusted}, {"local",AcquireItemGetLocal}, {"status",AcquireItemGetStatus}, @@ -75,16 +82,23 @@ static PyGetSetDef AcquireItemGetSet[] = { static PyObject *AcquireItemRepr(PyObject *Self) { - pkgAcquire::ItemIterator &I = GetCpp(Self); + pkgAcquire::Item *Itm; + if (PyObject_TypeCheck(Self, &PkgAcquireFileType)) { + Itm = GetCpp(Self); + } else { + pkgAcquire::ItemIterator &I = GetCpp(Self); + Itm = *I; + } char S[300]; - snprintf(S,sizeof(S),"", - (*I)->Status, (*I)->Complete, (*I)->Local, (*I)->IsTrusted(), - (*I)->FileSize, (*I)->DestFile.c_str(), (*I)->DescURI().c_str(), - (*I)->ID,(*I)->ErrorText.c_str()); + Self->ob_type->tp_name, + Itm->Status, Itm->Complete, Itm->Local, Itm->IsTrusted(), + Itm->FileSize, Itm->DestFile.c_str(), Itm->DescURI().c_str(), + Itm->ID,Itm->ErrorText.c_str()); return PyString_FromString(S); } @@ -383,8 +397,8 @@ PyTypeObject PkgAcquireFileType = 0, // tp_iternext 0, // tp_methods 0, // tp_members - 0, // tp_getset - 0, // tp_base + 0, // tp_getset + &AcquireItemType, // tp_base 0, // tp_dict 0, // tp_descr_get 0, // tp_descr_set -- cgit v1.2.3 From c41d1e0c66ab4effdf737ca4c9a9c86c08237451 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Tue, 23 Jun 2009 11:39:09 +0200 Subject: python/configuration.cc: Make ConfigurationPtr,ConfigurationSub subclasses of Configuration. This makes isinstance(apt_pkg.config, apt_pkg.Configuration) return True instead of False. --- debian/changelog | 1 + python/configuration.cc | 6 ++++++ 2 files changed, 7 insertions(+) (limited to 'python') diff --git a/debian/changelog b/debian/changelog index c4486505..3209f7ee 100644 --- a/debian/changelog +++ b/debian/changelog @@ -20,6 +20,7 @@ python-apt (0.7.92) UNRELEASED; urgency=low * Merge 0.7.10.4 from unstable * debian/control: Update Standards-Version to 3.8.2 * Make AcquireFile a subclass of AcquireItem + * Make ConfigurationPtr,ConfigurationSub subclasses of Configuration. [ Sebastian Heinlein ] * apt/progress.py: Extract the package name from the status message diff --git a/python/configuration.cc b/python/configuration.cc index 365a35fd..9ef5967b 100644 --- a/python/configuration.cc +++ b/python/configuration.cc @@ -582,6 +582,9 @@ PyTypeObject ConfigurationPtrType = 0, // tp_iter 0, // tp_iternext CnfMethods, // tp_methods + 0, // tp_members + 0, // tp_getset + &ConfigurationType, // tp_base }; PyTypeObject ConfigurationSubType = @@ -618,5 +621,8 @@ PyTypeObject ConfigurationSubType = 0, // tp_iter 0, // tp_iternext CnfMethods, // tp_methods + 0, // tp_members + 0, // tp_getset + &ConfigurationType, // tp_base }; -- cgit v1.2.3 From b0e6c5bdad8b182d4144ccf929e919bb687ac98c Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Thu, 25 Jun 2009 16:44:33 +0200 Subject: python/policy.cc: Use strcmp() for comparing strings. --- python/policy.cc | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'python') diff --git a/python/policy.cc b/python/policy.cc index 39bbc1a3..5150af91 100644 --- a/python/policy.cc +++ b/python/policy.cc @@ -111,11 +111,11 @@ static PyObject *Policy_CreatePin(PyObject *self, PyObject *args) { if (PyArg_ParseTuple(args, "sssh", &type, &pkg, &data, &priority) == 0) return 0; pkgPolicy *policy = GetCpp(self); - if (type == "Version" || type == "version") + if (strcmp(type,"Version") == 0 || strcmp(type, "version") == 0) match_type = pkgVersionMatch::Version; - if (type == "Release" || type == "release") + if (strcmp(type,"Release") == 0 || strcmp(type, "release") == 0) match_type = pkgVersionMatch::Release; - if (type == "Origin" || type == "origin") + if (strcmp(type,"Origin") == 0 || strcmp(type, "origin") == 0) match_type = pkgVersionMatch::Origin; else match_type = pkgVersionMatch::None; -- cgit v1.2.3 From 35c637e1d9a78fe88c935f3545f98f68b32403f4 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Thu, 25 Jun 2009 16:44:55 +0200 Subject: python/tag.cc: Store the return value of PyString_AsString as const char*. --- python/tag.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'python') diff --git a/python/tag.cc b/python/tag.cc index 74857fe5..4fcdf067 100644 --- a/python/tag.cc +++ b/python/tag.cc @@ -191,7 +191,7 @@ static PyObject *TagSecExists(PyObject *Self,PyObject *Args) static int TagSecContains(PyObject *Self,PyObject *Arg) { - char *Name = PyString_AsString(Arg); + const char *Name = PyString_AsString(Arg); const char *Start; const char *Stop; if (GetCpp(Self).Find(Name,Start,Stop) == false) -- cgit v1.2.3 From 4f76b8075e8a6acd8fbaad8693ba456a0dcfc836 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Thu, 25 Jun 2009 17:13:21 +0200 Subject: python/tag.cc: Return False for non-strings in 'TagSection.__contains__()'. --- python/tag.cc | 2 ++ 1 file changed, 2 insertions(+) (limited to 'python') diff --git a/python/tag.cc b/python/tag.cc index 4fcdf067..1ad0a465 100644 --- a/python/tag.cc +++ b/python/tag.cc @@ -191,6 +191,8 @@ static PyObject *TagSecExists(PyObject *Self,PyObject *Args) static int TagSecContains(PyObject *Self,PyObject *Arg) { + if (PyString_Check(Arg) == 0) + return 0; const char *Name = PyString_AsString(Arg); const char *Start; const char *Stop; -- cgit v1.2.3 From ca4408170dd5d2a6bba176409e0f0af1156357a6 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Thu, 25 Jun 2009 17:37:23 +0200 Subject: python/cache.cc: Support unicode objects and str objects in Python 2. --- python/cache.cc | 13 ++++++------- python/generic.cc | 3 ++- python/generic.h | 27 ++++++++++++++++++++++++++- 3 files changed, 34 insertions(+), 9 deletions(-) (limited to 'python') diff --git a/python/cache.cc b/python/cache.cc index 4ce3178c..2de9c76a 100644 --- a/python/cache.cc +++ b/python/cache.cc @@ -219,21 +219,20 @@ static PyGetSetDef PkgCacheGetSet[] = { {} }; + + // Map access, operator [] static PyObject *CacheMapOp(PyObject *Self,PyObject *Arg) { pkgCache *Cache = GetCpp(Self); - if (PyString_Check(Arg) == 0) - { - PyObject *repr = PyObject_Repr(Arg); - PyErr_SetObject(PyExc_TypeError, repr); - Py_DECREF(repr); + // Get the name of the package, unicode and normal strings. + const char *Name = PyObject_AsString(Arg); + if (Name == NULL) return 0; - } + // Search for the package - const char *Name = PyString_AsString(Arg); pkgCache::PkgIterator Pkg = Cache->FindPkg(Name); if (Pkg.end() == true) { diff --git a/python/generic.cc b/python/generic.cc index 7309d978..51439a1b 100644 --- a/python/generic.cc +++ b/python/generic.cc @@ -25,8 +25,9 @@ PyObject *HandleErrors(PyObject *Res) return Res; } - if (Res != 0) + if (Res != 0) { Py_DECREF(Res); + } string Err; int errcnt = 0; diff --git a/python/generic.h b/python/generic.h index 4fe1f915..2a87b39c 100644 --- a/python/generic.h +++ b/python/generic.h @@ -52,22 +52,47 @@ typedef int Py_ssize_t; #define PyString_Check PyUnicode_Check #define PyString_FromString PyUnicode_FromString #define PyString_FromStringAndSize PyUnicode_FromStringAndSize -#define PyString_AsString(op) PyBytes_AsString(PyUnicode_AsUTF8String(op)) +#define PyString_AsString PyUnicode_AsString #define PyInt_Check PyLong_Check #define PyInt_AsLong PyLong_AsLong // Force 0.7 compatibility to be off in Python 3 builds #undef COMPAT_0_7 #else +// Compatibility for Python 2.5 and previous. +#if (PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION <= 5) #define PyBytes_Check PyString_Check #define PyBytes_AsString PyString_AsString #define PyBytes_AsStringAndSize PyString_AsStringAndSize #endif +#endif // Hacks to make Python 2.4 build. #if PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION <= 4 #define PyErr_WarnEx(cat,msg,stacklevel) PyErr_Warn(cat,msg) #endif + +static inline const char *PyUnicode_AsString(PyObject *op) { + // Convert to bytes object, using the default encoding. + PyObject *bytes = PyUnicode_AsEncodedString(op,0,0); + if (!bytes) + return 0; + const char *result = PyBytes_AsString(bytes); + Py_DECREF(bytes); + return result; +} + +// Convert any type of string based object to a const char. +static inline const char *PyObject_AsString(PyObject *object) { + if (PyBytes_Check(object)) + return PyBytes_AsString(object); + else if (PyUnicode_Check(object)) + return PyUnicode_AsString(object); + else + PyErr_SetObject(PyExc_TypeError, object); + return 0; +} + template struct CppPyObject : public PyObject { // We are only using CppPyObject and friends as dumb structs only, ie the -- cgit v1.2.3 From 128c1f00b2006c9c24638c11000e1864fc15bd04 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Thu, 25 Jun 2009 18:11:13 +0200 Subject: python/generic.h: Make PyObject_AsString() only accept unicode on Python 3. --- python/generic.h | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) (limited to 'python') diff --git a/python/generic.h b/python/generic.h index 2a87b39c..182b1b53 100644 --- a/python/generic.h +++ b/python/generic.h @@ -83,15 +83,25 @@ static inline const char *PyUnicode_AsString(PyObject *op) { } // Convert any type of string based object to a const char. +#if PY_MAJOR_VERSION < 3 static inline const char *PyObject_AsString(PyObject *object) { if (PyBytes_Check(object)) return PyBytes_AsString(object); else if (PyUnicode_Check(object)) return PyUnicode_AsString(object); else - PyErr_SetObject(PyExc_TypeError, object); + PyErr_SetString(PyExc_TypeError, "Argument must be str."); return 0; } +#else +static inline const char *PyObject_AsString(PyObject *object) { + if (PyUnicode_Check(object) == 0) { + PyErr_SetString(PyExc_TypeError, "Argument must be str."); + return 0; + } + return PyUnicode_AsString(object); +} +#endif template struct CppPyObject : public PyObject { -- cgit v1.2.3 From a4e69e11e544844034c3fbdc6789d5573f802117 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Thu, 25 Jun 2009 18:31:00 +0200 Subject: python: Fix some build warnings. --- python/acquire.cc | 4 ++-- python/cache.cc | 9 ++++----- python/depcache.cc | 3 --- python/indexfile.cc | 2 +- python/pkgsrcrecords.cc | 1 - python/progress.cc | 2 -- python/tar.cc | 4 ++++ setup.py | 4 ++-- 8 files changed, 13 insertions(+), 16 deletions(-) (limited to 'python') diff --git a/python/acquire.cc b/python/acquire.cc index e13e47d6..a36012bc 100644 --- a/python/acquire.cc +++ b/python/acquire.cc @@ -93,8 +93,8 @@ static PyObject *AcquireItemRepr(PyObject *Self) char S[300]; snprintf(S,sizeof(S),"<%s object: " "Status: %i Complete: %i Local: %i IsTrusted: %i " - "FileSize: %i DestFile:'%s' " - "DescURI: '%s' ID:%i ErrorText: '%s'>", + "FileSize: %lu DestFile:'%s' " + "DescURI: '%s' ID:%lu ErrorText: '%s'>", Self->ob_type->tp_name, Itm->Status, Itm->Complete, Itm->Local, Itm->IsTrusted(), Itm->FileSize, Itm->DestFile.c_str(), Itm->DescURI().c_str(), diff --git a/python/cache.cc b/python/cache.cc index 2de9c76a..0f5e27eb 100644 --- a/python/cache.cc +++ b/python/cache.cc @@ -76,9 +76,6 @@ static PyObject *CreateProvides(PyObject *Owner,pkgCache::PrvIterator I) // --------------------------------------------------------------------- static PyObject *PkgCacheUpdate(PyObject *Self,PyObject *Args) { - PyObject *CacheFilePy = GetOwner(Self); - pkgCacheFile *Cache = GetCpp(CacheFilePy); - PyObject *pyFetchProgressInst = 0; PyObject *pySourcesList = 0; if (PyArg_ParseTuple(Args, "OO", &pyFetchProgressInst,&pySourcesList) == 0) @@ -93,6 +90,7 @@ static PyObject *PkgCacheUpdate(PyObject *Self,PyObject *Args) return HandleErrors(PyRes); } +#ifdef COMPAT_0_7 static PyObject *PkgCacheClose(PyObject *Self,PyObject *Args) { PyErr_WarnEx(PyExc_DeprecationWarning, "Cache.Close() is deprecated, " @@ -137,7 +135,7 @@ static PyObject *PkgCacheOpen(PyObject *Self,PyObject *Args) Py_INCREF(Py_None); return HandleErrors(Py_None); } - +#endif static PyMethodDef PkgCacheMethods[] = { @@ -456,10 +454,10 @@ PyTypeObject PkgListType = CppOwnedClear, // tp_clear }; +#define Owner (GetOwner(Self)) #define MkGet(PyFunc,Ret) static PyObject *PyFunc(PyObject *Self,void*) \ { \ pkgCache::PkgIterator &Pkg = GetCpp(Self); \ - PyObject *Owner = GetOwner(Self); \ return Ret; \ } @@ -477,6 +475,7 @@ MkGet(PackageGetAuto,Py_BuildValue("i",(Pkg->Flags & pkgCache::Flag::Auto) != 0) MkGet(PackageGetEssential,Py_BuildValue("i",(Pkg->Flags & pkgCache::Flag::Essential) != 0)); MkGet(PackageGetImportant,Py_BuildValue("i",(Pkg->Flags & pkgCache::Flag::Important) != 0)); #undef MkGet +#undef Owner static PyObject *PackageGetVersionList(PyObject *Self,void*) { diff --git a/python/depcache.cc b/python/depcache.cc index e1514300..9c0c9a6f 100644 --- a/python/depcache.cc +++ b/python/depcache.cc @@ -62,8 +62,6 @@ static PyObject *PkgDepCacheInit(PyObject *Self,PyObject *Args) static PyObject *PkgDepCacheCommit(PyObject *Self,PyObject *Args) { - PyObject *result; - pkgDepCache *depcache = GetCpp(Self); PyObject *pyInstallProgressInst = 0; @@ -196,7 +194,6 @@ static PyObject *PkgDepCacheSetCandidateVer(PyObject *Self,PyObject *Args) &VersionType, &VersionObj) == 0) return 0; - pkgCache::PkgIterator &Pkg = GetCpp(PackageObj); pkgCache::VerIterator &I = GetCpp(VersionObj); if(I.end()) { return HandleErrors(Py_BuildValue("b",false)); diff --git a/python/indexfile.cc b/python/indexfile.cc index ef88c2f0..73f76ce6 100644 --- a/python/indexfile.cc +++ b/python/indexfile.cc @@ -62,7 +62,7 @@ static PyObject *PackageIndexFileRepr(PyObject *Self) char S[1024]; snprintf(S,sizeof(S),"", File->GetType()->Label, File->Describe().c_str(), File->Exists(), File->HasPackages(), File->Size(), diff --git a/python/pkgsrcrecords.cc b/python/pkgsrcrecords.cc index f75934f9..9707dce2 100644 --- a/python/pkgsrcrecords.cc +++ b/python/pkgsrcrecords.cc @@ -58,7 +58,6 @@ static PyObject *PkgSrcRecordsRestart(PyObject *Self,PyObject *Args) { PkgSrcRecordsStruct &Struct = GetCpp(Self); - char *Name = 0; if (PyArg_ParseTuple(Args,"") == 0) return 0; diff --git a/python/progress.cc b/python/progress.cc index c5035e62..44f27b0c 100644 --- a/python/progress.cc +++ b/python/progress.cc @@ -354,7 +354,6 @@ void PyInstallProgress::FinishUpdate() pkgPackageManager::OrderResult PyInstallProgress::Run(pkgPackageManager *pm) { - void *dummy; pkgPackageManager::OrderResult res; int ret; pid_t child_id; @@ -426,7 +425,6 @@ pkgPackageManager::OrderResult PyInstallProgress::Run(pkgPackageManager *pm) PyErr_Print(); return pkgPackageManager::Failed; } - int child_res; if(!PyArg_Parse(result, "i", &res) ) { std::cerr << "custom waitChild() result could not be parsed?"<< std::endl; return pkgPackageManager::Failed; diff --git a/python/tar.cc b/python/tar.cc index 217554c2..b93ba31a 100644 --- a/python/tar.cc +++ b/python/tar.cc @@ -72,8 +72,12 @@ bool ProcessTar::DoItem(Item &Itm,int &Fd) case Item::FIFO: Type = "FIFO"; break; + + default: + return false; } + if (PyObject_CallFunction(Function,"sssiiiiiii",Type,Itm.Name, Itm.LinkTarget,Itm.Mode,Itm.UID,Itm.GID,Itm.Size, Itm.MTime,Itm.Major,Itm.Minor) == 0) diff --git a/setup.py b/setup.py index 2afd0708..85f4c889 100755 --- a/setup.py +++ b/setup.py @@ -12,12 +12,12 @@ from DistUtilsExtra.command import build_extra, build_i18n # The apt_pkg module files = map(lambda source: "python/"+source, - parse_makefile("python/makefile")["APT_PKG_SRC"].split()) + sorted(parse_makefile("python/makefile")["APT_PKG_SRC"].split())) apt_pkg = Extension("apt_pkg", files, libraries=["apt-pkg"]) # The apt_inst module files = map(lambda source: "python/"+source, - parse_makefile("python/makefile")["APT_INST_SRC"].split()) + sorted(parse_makefile("python/makefile")["APT_INST_SRC"].split())) apt_inst = Extension("apt_inst", files, libraries=["apt-pkg", "apt-inst"]) # Replace the leading _ that is used in the templates for translation -- cgit v1.2.3 From e80500e7173387acc7a6b6be9d7424a4343ec036 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Thu, 25 Jun 2009 18:53:47 +0200 Subject: python: Use PyVarObject_HEAD_INIT() instead of PyObject_HEAD_INIT(). This is related to PEP 3123 and fixes some compiler warnings. --- python/acquire.cc | 17 ++++------------- python/cache.cc | 45 +++++++++------------------------------------ python/cdrom.cc | 5 +---- python/configuration.cc | 15 +++------------ python/depcache.cc | 15 +++------------ python/generic.h | 1 + python/hashstring.cc | 5 +---- python/indexfile.cc | 5 +---- python/indexrecords.cc | 5 +---- python/metaindex.cc | 5 +---- python/pkgmanager.cc | 5 +---- python/pkgrecords.cc | 5 +---- python/pkgsrcrecords.cc | 5 +---- python/policy.cc | 5 +---- python/sourcelist.cc | 5 +---- python/tag.cc | 12 ++++-------- 16 files changed, 34 insertions(+), 121 deletions(-) (limited to 'python') diff --git a/python/acquire.cc b/python/acquire.cc index a36012bc..6c6c2ea4 100644 --- a/python/acquire.cc +++ b/python/acquire.cc @@ -105,10 +105,7 @@ static PyObject *AcquireItemRepr(PyObject *Self) PyTypeObject AcquireItemType = { - PyObject_HEAD_INIT(&PyType_Type) - #if PY_MAJOR_VERSION < 3 - 0, // ob_size - #endif + PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.AcquireItem", // tp_name sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize @@ -267,10 +264,7 @@ static char *doc_PkgAcquire = "Acquire(progress) -> Acquire() object.\n\n" PyTypeObject PkgAcquireType = { - PyObject_HEAD_INIT(&PyType_Type) - #if PY_MAJOR_VERSION < 3 - 0, // ob_size - #endif + PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.Acquire", // tp_name sizeof(CppPyObject), // tp_basicsize 0, // tp_itemsize @@ -360,11 +354,8 @@ static char *doc_PkgAcquireFile = PyTypeObject PkgAcquireFileType = { - PyObject_HEAD_INIT(&PyType_Type) - #if PY_MAJOR_VERSION < 3 - 0, // ob_size - #endif - "apt_pkg.AcquireFile", // tp_name + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "apt_pkg.AcquireFile", // tp_name sizeof(CppOwnedPyObject),// tp_basicsize 0, // tp_itemsize // Methods diff --git a/python/cache.cc b/python/cache.cc index 0f5e27eb..a571788f 100644 --- a/python/cache.cc +++ b/python/cache.cc @@ -299,10 +299,7 @@ static char *doc_PkgCache = "Cache([progress]) -> Cache() object.\n\n" static PyMappingMethods CacheMap = {0,CacheMapOp,0}; PyTypeObject PkgCacheType = { - PyObject_HEAD_INIT(&PyType_Type) - #if PY_MAJOR_VERSION < 3 - 0, // ob_size - #endif + PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.Cache", // tp_name sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize @@ -349,10 +346,7 @@ PyTypeObject PkgCacheType = // --------------------------------------------------------------------- PyTypeObject PkgCacheFileType = { - PyObject_HEAD_INIT(&PyType_Type) - #if PY_MAJOR_VERSION < 3 - 0, // ob_size - #endif + PyVarObject_HEAD_INIT(&PyType_Type, 0) "pkgCacheFile", // tp_name sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize @@ -425,10 +419,7 @@ static PySequenceMethods PkgListSeq = PyTypeObject PkgListType = { - PyObject_HEAD_INIT(&PyType_Type) - #if PY_MAJOR_VERSION < 3 - 0, // ob_size - #endif + PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.PackageList", // tp_name sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize @@ -550,10 +541,7 @@ static PyObject *PackageRepr(PyObject *Self) PyTypeObject PackageType = { - PyObject_HEAD_INIT(&PyType_Type) - #if PY_MAJOR_VERSION < 3 - 0, // ob_size - #endif + PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.Package", // tp_name sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize @@ -641,10 +629,7 @@ static PyObject *DescriptionRepr(PyObject *Self) PyTypeObject DescriptionType = { - PyObject_HEAD_INIT(&PyType_Type) - #if PY_MAJOR_VERSION < 3 - 0, // ob_size - #endif + PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.Description", // tp_name sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize @@ -904,10 +889,7 @@ static PyGetSetDef VersionGetSet[] = { PyTypeObject VersionType = { - PyObject_HEAD_INIT(&PyType_Type) - #if PY_MAJOR_VERSION < 3 - 0, // ob_size - #endif + PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.Version", // tp_name sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize @@ -1068,10 +1050,7 @@ static PyGetSetDef PackageFileGetSet[] = { }; PyTypeObject PackageFileType = { - PyObject_HEAD_INIT(&PyType_Type) - #if PY_MAJOR_VERSION < 3 - 0, // ob_size - #endif + PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.PackageFile", // tp_name sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize @@ -1243,10 +1222,7 @@ static PyGetSetDef DependencyGetSet[] = { PyTypeObject DependencyType = { - PyObject_HEAD_INIT(&PyType_Type) - #if PY_MAJOR_VERSION < 3 - 0, // ob_size - #endif + PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.Dependency", // tp_name sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize @@ -1331,10 +1307,7 @@ static PySequenceMethods RDepListSeq = PyTypeObject RDepListType = { - PyObject_HEAD_INIT(&PyType_Type) - #if PY_MAJOR_VERSION < 3 - 0, // ob_size - #endif + PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.DependencyList", // tp_name sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize diff --git a/python/cdrom.cc b/python/cdrom.cc index e2651670..492afd90 100644 --- a/python/cdrom.cc +++ b/python/cdrom.cc @@ -85,10 +85,7 @@ static PyObject *PkgCdromNew(PyTypeObject *type,PyObject *Args,PyObject *kwds) PyTypeObject PkgCdromType = { - PyObject_HEAD_INIT(&PyType_Type) - #if PY_MAJOR_VERSION < 3 - 0, // ob_size - #endif + PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.Cdrom", // tp_name sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize diff --git a/python/configuration.cc b/python/configuration.cc index 9ef5967b..07f55957 100644 --- a/python/configuration.cc +++ b/python/configuration.cc @@ -503,10 +503,7 @@ static PySequenceMethods ConfigurationSeq = {0,0,0,0,0,0,0,CnfContains,0,0}; static PyMappingMethods ConfigurationMap = {0,CnfMap,CnfMapSet}; PyTypeObject ConfigurationType = { - PyObject_HEAD_INIT(&PyType_Type) - #if PY_MAJOR_VERSION < 3 - 0, // ob_size - #endif + PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.Configuration", // tp_name sizeof(CppPyObject), // tp_basicsize 0, // tp_itemsize @@ -550,10 +547,7 @@ PyTypeObject ConfigurationType = PyTypeObject ConfigurationPtrType = { - PyObject_HEAD_INIT(&PyType_Type) - #if PY_MAJOR_VERSION < 3 - 0, // ob_size - #endif + PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.ConfigurationPtr", // tp_name sizeof(CppPyObject), // tp_basicsize 0, // tp_itemsize @@ -589,10 +583,7 @@ PyTypeObject ConfigurationPtrType = PyTypeObject ConfigurationSubType = { - PyObject_HEAD_INIT(&PyType_Type) - #if PY_MAJOR_VERSION < 3 - 0, // ob_size - #endif + PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.ConfigurationSub", // tp_name sizeof(SubConfiguration), // tp_basicsize 0, // tp_itemsize diff --git a/python/depcache.cc b/python/depcache.cc index 9c0c9a6f..2ce7a595 100644 --- a/python/depcache.cc +++ b/python/depcache.cc @@ -667,10 +667,7 @@ static char *doc_PkgDepCache = "DepCache(cache) -> DepCache() object\n\n" "The parameter *cache* refers to an apt_pkg.Cache() object."; PyTypeObject PkgDepCacheType = { - PyObject_HEAD_INIT(&PyType_Type) - #if PY_MAJOR_VERSION < 3 - 0, // ob_size - #endif + PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.DepCache", // tp_name sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize @@ -858,10 +855,7 @@ static PyMethodDef PkgProblemResolverMethods[] = PyTypeObject PkgProblemResolverType = { - PyObject_HEAD_INIT(&PyType_Type) - #if PY_MAJOR_VERSION < 3 - 0, // ob_size - #endif + PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.ProblemResolver", // tp_name sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize @@ -977,10 +971,7 @@ static char *doc_PkgActionGroup = "ActionGroup(depcache)\n\n" PyTypeObject PkgActionGroupType = { - PyObject_HEAD_INIT(&PyType_Type) - #if PY_MAJOR_VERSION < 3 - 0, // ob_size - #endif + PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.ActionGroup", // tp_name sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize diff --git a/python/generic.h b/python/generic.h index 182b1b53..118917cb 100644 --- a/python/generic.h +++ b/python/generic.h @@ -63,6 +63,7 @@ typedef int Py_ssize_t; #define PyBytes_Check PyString_Check #define PyBytes_AsString PyString_AsString #define PyBytes_AsStringAndSize PyString_AsStringAndSize +#define PyVarObject_HEAD_INIT(type, size) PyObject_HEAD_INIT(type) size, #endif #endif diff --git a/python/hashstring.cc b/python/hashstring.cc index 23212a4b..6f70ac7e 100644 --- a/python/hashstring.cc +++ b/python/hashstring.cc @@ -95,10 +95,7 @@ static char *HashString_doc = " HashString('MD5Sum', '6cc1b6e6655e3555ac47e5b5fe26d04e')\n\n" "Valid options for 'type' are: MD5Sum, SHA1, SHA256."; PyTypeObject PyHashString_Type = { - PyObject_HEAD_INIT(&PyType_Type) -#if PY_MAJOR_VERSION < 3 - 0, // ob_size -#endif + PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.HashString", // tp_name sizeof(CppPyObject), // tp_basicsize 0, // tp_itemsize diff --git a/python/indexfile.cc b/python/indexfile.cc index 73f76ce6..5b526b87 100644 --- a/python/indexfile.cc +++ b/python/indexfile.cc @@ -90,10 +90,7 @@ static PyGetSetDef PackageIndexFileGetSet[] = { PyTypeObject PackageIndexFileType = { - PyObject_HEAD_INIT(&PyType_Type) - #if PY_MAJOR_VERSION < 3 - 0, // ob_size - #endif + PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.PackageIndexFile", // tp_name sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize diff --git a/python/indexrecords.cc b/python/indexrecords.cc index fcb2b85d..588cf883 100644 --- a/python/indexrecords.cc +++ b/python/indexrecords.cc @@ -81,10 +81,7 @@ static PyMethodDef IndexRecords_Methods[] = { static char *IndexRecords_doc = "IndexRecords()\n\n" "Representation of a release file."; PyTypeObject PyIndexRecords_Type = { - PyObject_HEAD_INIT(&PyType_Type) -#if PY_MAJOR_VERSION < 3 - 0, // ob_size -#endif + PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.IndexRecords", // tp_name sizeof(CppPyObject), // tp_basicsize 0, // tp_itemsize diff --git a/python/metaindex.cc b/python/metaindex.cc index b5d194b4..87b1e59a 100644 --- a/python/metaindex.cc +++ b/python/metaindex.cc @@ -72,10 +72,7 @@ static PyObject *MetaIndexRepr(PyObject *Self) PyTypeObject MetaIndexType = { - PyObject_HEAD_INIT(&PyType_Type) - #if PY_MAJOR_VERSION < 3 - 0, // ob_size - #endif + PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.MetaIndex", // tp_name sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize diff --git a/python/pkgmanager.cc b/python/pkgmanager.cc index 668f7cfc..9e9cc32d 100644 --- a/python/pkgmanager.cc +++ b/python/pkgmanager.cc @@ -133,10 +133,7 @@ static PyGetSetDef PkgManagerGetSet[] = { PyTypeObject PkgManagerType = { - PyObject_HEAD_INIT(&PyType_Type) - #if PY_MAJOR_VERSION < 3 - 0, // ob_size - #endif + PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.PackageManager", // tp_name sizeof(CppPyObject), // tp_basicsize 0, // tp_itemsize diff --git a/python/pkgrecords.cc b/python/pkgrecords.cc index 4a3c80db..886bdb58 100644 --- a/python/pkgrecords.cc +++ b/python/pkgrecords.cc @@ -163,10 +163,7 @@ static PyObject *PkgRecordsNew(PyTypeObject *type,PyObject *Args,PyObject *kwds) PyTypeObject PkgRecordsType = { - PyObject_HEAD_INIT(&PyType_Type) - #if PY_MAJOR_VERSION < 3 - 0, // ob_size - #endif + PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.PackageRecords", // tp_name sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize diff --git a/python/pkgsrcrecords.cc b/python/pkgsrcrecords.cc index 9707dce2..187050b7 100644 --- a/python/pkgsrcrecords.cc +++ b/python/pkgsrcrecords.cc @@ -204,10 +204,7 @@ static PyObject *PkgSrcRecordsNew(PyTypeObject *type,PyObject *args,PyObject *kw PyTypeObject PkgSrcRecordsType = { - PyObject_HEAD_INIT(&PyType_Type) - #if PY_MAJOR_VERSION < 3 - 0, // ob_size - #endif + PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.SourceRecords", // tp_name sizeof(CppPyObject), // tp_basicsize 0, // tp_itemsize diff --git a/python/policy.cc b/python/policy.cc index 5150af91..91ed5454 100644 --- a/python/policy.cc +++ b/python/policy.cc @@ -143,10 +143,7 @@ static char *Policy_doc = "Policy(cache)\n\n" "may be some cases where a special policy class is needed."; PyTypeObject PyPolicy_Type = { - PyObject_HEAD_INIT(&PyType_Type) -#if PY_MAJOR_VERSION < 3 - 0, // ob_size -#endif + PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.Policy", // tp_name sizeof(CppOwnedPyObject),// tp_basicsize 0, // tp_itemsize diff --git a/python/sourcelist.cc b/python/sourcelist.cc index 2cf5eea9..0820d5bf 100644 --- a/python/sourcelist.cc +++ b/python/sourcelist.cc @@ -115,10 +115,7 @@ static PyObject *PkgSourceListNew(PyTypeObject *type,PyObject *args,PyObject *kw PyTypeObject PkgSourceListType = { - PyObject_HEAD_INIT(&PyType_Type) - #if PY_MAJOR_VERSION < 3 - 0, // ob_size - #endif + PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.SourceList", // tp_name sizeof(CppPyObject), // tp_basicsize 0, // tp_itemsize diff --git a/python/tag.cc b/python/tag.cc index 1ad0a465..2b71517d 100644 --- a/python/tag.cc +++ b/python/tag.cc @@ -175,6 +175,7 @@ static PyObject *TagSecKeys(PyObject *Self,PyObject *Args) return List; } +#if PY_MAJOR_VERSION < 3 static char *doc_Exists = "Exists(Name) -> integer"; static PyObject *TagSecExists(PyObject *Self,PyObject *Args) { @@ -188,6 +189,7 @@ static PyObject *TagSecExists(PyObject *Self,PyObject *Args) return Py_BuildValue("i",0); return Py_BuildValue("i",1); } +#endif static int TagSecContains(PyObject *Self,PyObject *Arg) { @@ -436,10 +438,7 @@ static char *doc_TagSec = "TagSection(text) -> Create a new object.\n\n" "to the functions provided by the C++ class (e.g. Find)"; PyTypeObject TagSecType = { - PyObject_HEAD_INIT(&PyType_Type) - #if PY_MAJOR_VERSION < 3 - 0, // ob_size - #endif + PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.TagSection", // tp_name sizeof(TagSecData), // tp_basicsize 0, // tp_itemsize @@ -525,10 +524,7 @@ static char *doc_TagFile = "TagFile(file) -> TagFile() object. \n\n" // Type for a Tag File PyTypeObject TagFileType = { - PyObject_HEAD_INIT(&PyType_Type) - #if PY_MAJOR_VERSION < 3 - 0, // ob_size - #endif + PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.TagFile", // tp_name sizeof(TagFileData), // tp_basicsize 0, // tp_itemsize -- cgit v1.2.3 From 2a2d636ca765e737bdbd36ed6b39b2319a466ce9 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Tue, 7 Jul 2009 17:00:38 +0200 Subject: python/policy.cc: Add Policy_ReadPinDir() [APT 0.7.22] --- python/policy.cc | 14 ++++++++++++++ 1 file changed, 14 insertions(+) (limited to 'python') diff --git a/python/policy.cc b/python/policy.cc index 91ed5454..46d73a1a 100644 --- a/python/policy.cc +++ b/python/policy.cc @@ -96,6 +96,18 @@ static PyObject *Policy_ReadPinFile(PyObject *self, PyObject *arg) { return PyBool_FromLong(ReadPinFile(*policy, PyString_AsString(arg))); } +static char *Policy_ReadPinDir_doc = "read_pindir(dirname: str) -> bool\n\n" + "Read the pin files in the given dir (e.g. '/etc/apt/preferences.d') and\n" + "add them to the policy."; + +static PyObject *Policy_ReadPinDir(PyObject *self, PyObject *arg) { + if (!PyString_Check(arg)) + return 0; + pkgPolicy *policy = GetCpp(self); + + return PyBool_FromLong(ReadPinDir(*policy, PyString_AsString(arg))); +} + static char *Policy_CreatePin_doc = "create_pin(type: str, pkg: str, " "data: str, priority: int)\n\n" "Create a pin for the policy. The parameter 'type' refers to one of the\n" @@ -131,6 +143,8 @@ static PyMethodDef Policy_Methods[] = { Policy_GetCandidateVer_doc}, {"read_pinfile",(PyCFunction)Policy_ReadPinFile,METH_O, Policy_ReadPinFile_doc}, + {"read_pindir",(PyCFunction)Policy_ReadPinDir,METH_O, + Policy_ReadPinFile_doc}, {"create_pin",Policy_CreatePin,METH_VARARGS,Policy_CreatePin_doc}, {"get_match",(PyCFunction)Policy_GetMatch,METH_O, Policy_GetMatch_doc}, {} -- cgit v1.2.3 From 3770906714c5e73b844514c431ce07fd9ac416fb Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Wed, 8 Jul 2009 17:43:01 +0200 Subject: python/apt_pkgmodule.cc: Unify dep handling -- part 1: parse_depends() apt_pkg.parse_[src_]depends() now use CompType instead of CompTypeDeb (i.e. < instead of <<) to match the interface of Version.depends_list_str. --- debian/changelog | 4 ++++ python/apt_pkgmodule.cc | 19 ++++++++++++++----- 2 files changed, 18 insertions(+), 5 deletions(-) (limited to 'python') diff --git a/debian/changelog b/debian/changelog index 2b3f0ac1..581e1be1 100644 --- a/debian/changelog +++ b/debian/changelog @@ -22,6 +22,10 @@ python-apt (0.7.92) UNRELEASED; urgency=low * Make AcquireFile a subclass of AcquireItem * Make ConfigurationPtr,ConfigurationSub subclasses of Configuration. * debian/control: Build-Depend on libapt-pkg-dev (>= 0.7.22~). + * Unification of dependency handling: + - apt_pkg.parse_[src_]depends() now use CompType instead of CompTypeDeb + (i.e. < instead of <<) to match the interface of Version.depends_list_str + [ Sebastian Heinlein ] * apt/progress.py: Extract the package name from the status message diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index 9f750996..3f4aae37 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -104,9 +104,10 @@ static char *doc_ParseDepends = "The resulting tuples are (Pkg,Ver,Operation). Each anded dependency is a\n" "list of or'd dependencies\n" "Source depends are evaluated against the curernt arch and only those that\n" -"Match are returned."; +"Match are returned.\n\n" +"apt_pkg.Parse{,Src}Depends() are old forms which return >>,<< instead of >,<"; static PyObject *RealParseDepends(PyObject *Self,PyObject *Args, - bool ParseArchFlags) + bool ParseArchFlags, bool debStyle=false) { string Package; string Version; @@ -143,7 +144,7 @@ static PyObject *RealParseDepends(PyObject *Self,PyObject *Args, PyObject *Obj; PyList_Append(LastRow,Obj = Py_BuildValue("sss",Package.c_str(), Version.c_str(), - pkgCache::CompTypeDeb(Op))); + debStyle ? pkgCache::CompTypeDeb(Op) : pkgCache::CompType(Op))); Py_DECREF(Obj); } @@ -165,6 +166,14 @@ static PyObject *ParseDepends(PyObject *Self,PyObject *Args) static PyObject *ParseSrcDepends(PyObject *Self,PyObject *Args) { return RealParseDepends(Self,Args,true); +} +static PyObject *ParseDepends_old(PyObject *Self,PyObject *Args) +{ + return RealParseDepends(Self,Args,false, true); +} +static PyObject *ParseSrcDepends_old(PyObject *Self,PyObject *Args) +{ + return RealParseDepends(Self,Args,true, true); } /*}}}*/ // md5sum - Compute the md5sum of a file or string /*{{{*/ @@ -444,8 +453,8 @@ static PyMethodDef methods[] = {"parse_depends",ParseDepends,METH_VARARGS,doc_ParseDepends}, {"parse_src_depends",ParseSrcDepends,METH_VARARGS,doc_ParseDepends}, #ifdef COMPAT_0_7 - {"ParseDepends",ParseDepends,METH_VARARGS,doc_ParseDepends}, - {"ParseSrcDepends",ParseSrcDepends,METH_VARARGS,doc_ParseDepends}, + {"ParseDepends",ParseDepends_old,METH_VARARGS,doc_ParseDepends}, + {"ParseSrcDepends",ParseSrcDepends_old,METH_VARARGS,doc_ParseDepends}, #endif // Stuff -- cgit v1.2.3 From d2423e2c28df63cb0a235f822a9588f8a221600a Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Wed, 8 Jul 2009 20:18:36 +0200 Subject: python/pkgsrcrecords.cc: Unify dep handling -- part 2: SourceRecords.build_depends Change apt_pkg.SourceRecords.build_depends to match exactly the interface of Version.depends_list_str just with different keys (e.g. Build-Depends). + Closes: #468123 - there is no need anymore for binding CompType or CompTypeDeb, because we don't return integer values for CompType anymore. --- debian/changelog | 6 +++++- python/pkgsrcrecords.cc | 51 ++++++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 55 insertions(+), 2 deletions(-) (limited to 'python') diff --git a/debian/changelog b/debian/changelog index 581e1be1..8bc3e320 100644 --- a/debian/changelog +++ b/debian/changelog @@ -25,7 +25,11 @@ python-apt (0.7.92) UNRELEASED; urgency=low * Unification of dependency handling: - apt_pkg.parse_[src_]depends() now use CompType instead of CompTypeDeb (i.e. < instead of <<) to match the interface of Version.depends_list_str - + - apt_pkg.SourceRecords.build_depends matches exactly the interface of + Version.depends_list_str just with different keys (e.g. Build-Depends). + + Closes: #468123 - there is no need anymore for binding CompType or + CompTypeDeb, because we don't return integer values for CompType + anymore. [ Sebastian Heinlein ] * apt/progress.py: Extract the package name from the status message diff --git a/python/pkgsrcrecords.cc b/python/pkgsrcrecords.cc index 187050b7..06fd4e3b 100644 --- a/python/pkgsrcrecords.cc +++ b/python/pkgsrcrecords.cc @@ -151,6 +151,54 @@ static PyObject *PkgSrcRecordsGetFiles(PyObject *Self,void*) { } static PyObject *PkgSrcRecordsGetBuildDepends(PyObject *Self,void*) { + PkgSrcRecordsStruct &Struct = GetStruct(Self,"BuildDepends"); + if (Struct.Last == 0) + return 0; + + PyObject *Dict = PyDict_New(); + PyObject *Dep = 0; + PyObject *LastDep = 0; + PyObject *OrGroup = 0; + + vector bd; + if(!Struct.Last->BuildDepends(bd, false /* arch-only*/)) + return NULL; // error + + PyObject *v; + for(unsigned int i=0;i Date: Fri, 10 Jul 2009 18:06:41 +0200 Subject: python/indexrecords.cc: Correctly Decrease refcount for HashString. Create a copy of the HashString() and create a CppPyObject for it. After adding it to the tuple, decrease the reference count. The HashString() copy allows us to deallocate the indexRecords and does not require the PyHashString objects to be CppOwnedPyObject. --- python/indexrecords.cc | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) (limited to 'python') diff --git a/python/indexrecords.cc b/python/indexrecords.cc index 588cf883..9ab052f6 100644 --- a/python/indexrecords.cc +++ b/python/indexrecords.cc @@ -58,9 +58,12 @@ static PyObject *IndexRecords_Lookup(PyObject *self,PyObject *args) PyErr_SetString(PyExc_KeyError,keyname); return 0; } - return Py_BuildValue("(Oi)", - PyHashString_FromCpp((HashString*)&result->Hash), - result->Size); + // Copy the HashString(), to prevent crashes and to not require the + // indexRecords object to exist. + PyObject *py_hash = PyHashString_FromCpp(new HashString(result->Hash)); + PyObject *value = Py_BuildValue("(Oi)",py_hash,result->Size); + Py_DECREF(py_hash); + return value; } static PyObject *IndexRecords_GetDist(PyObject *self) -- cgit v1.2.3 From 2d8f74890d6203c669db960c7108cad7f45c3a70 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Fri, 10 Jul 2009 19:13:16 +0200 Subject: python/generic.h: Introduce NoDelete field in CppPyObject. Setting NoDelete to true causes the deallocation functions to not delete the underlying C++ object. This is useful in situations where the object is already managed somewhere else, e.g. DepCache by CacheFile. It will also assist us in providing a flexible C++ API which only takes ownership if requested. --- python/generic.h | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) (limited to 'python') diff --git a/python/generic.h b/python/generic.h index 118917cb..408529a5 100644 --- a/python/generic.h +++ b/python/generic.h @@ -117,6 +117,11 @@ template struct CppPyObject : public PyObject // So basically having the c'tor here removes the need for T to have a // default c'tor, which is not always desireable. CppPyObject() { }; + + // Flag which causes the underlying object to not be deleted. + bool NoDelete; + + // The underlying C++ object. T Object; }; @@ -209,7 +214,8 @@ void CppDealloc(PyObject *Obj) #ifdef ALLOC_DEBUG std::cerr << "=== DEALLOCATING " << Obj->ob_type->tp_name << " ===\n"; #endif - GetCpp(Obj).~T(); + if (!((CppPyObject*)Obj)->NoDelete) + GetCpp(Obj).~T(); Obj->ob_type->tp_free(Obj); } @@ -220,7 +226,8 @@ void CppOwnedDealloc(PyObject *iObj) std::cerr << "=== DEALLOCATING " << iObj->ob_type->tp_name << "+ ===\n"; #endif CppOwnedPyObject *Obj = (CppOwnedPyObject *)iObj; - Obj->Object.~T(); + if (!((CppPyObject*)Obj)->NoDelete) + Obj->Object.~T(); CppOwnedClear(iObj); iObj->ob_type->tp_free(iObj); } @@ -233,7 +240,8 @@ void CppDeallocPtr(PyObject *Obj) #ifdef ALLOC_DEBUG std::cerr << "=== DEALLOCATING " << Obj->ob_type->tp_name << "* ===\n"; #endif - delete GetCpp(Obj); + if (!((CppPyObject*)Obj)->NoDelete) + delete GetCpp(Obj); Obj->ob_type->tp_free(Obj); } @@ -244,7 +252,8 @@ void CppOwnedDeallocPtr(PyObject *iObj) std::cerr << "=== DEALLOCATING " << iObj->ob_type->tp_name << "*+ ===\n"; #endif CppOwnedPyObject *Obj = (CppOwnedPyObject *)iObj; - delete Obj->Object; + if (!((CppPyObject*)Obj)->NoDelete) + delete Obj->Object; CppOwnedClear(iObj); iObj->ob_type->tp_free(iObj); } -- cgit v1.2.3 From 3c8959ed35b026ae57600c7f0b2ed531a98c7c0b Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Sat, 11 Jul 2009 21:16:11 +0200 Subject: python/depcache.cc: Introduce DepCache.policy property. This property allows you to access the Policy of the DepCache. --- python/depcache.cc | 13 +++++++++++++ 1 file changed, 13 insertions(+) (limited to 'python') diff --git a/python/depcache.cc b/python/depcache.cc index 2ce7a595..17e2bc30 100644 --- a/python/depcache.cc +++ b/python/depcache.cc @@ -621,6 +621,18 @@ static PyObject *PkgDepCacheGetDebSize(PyObject *Self,void*) { } #undef depcache +static PyObject *PkgDepCacheGetPolicy(PyObject *Self,void*) { + PyObject *Owner = GetOwner(Self); + pkgDepCache *DepCache = GetCpp(Self); + pkgPolicy *Policy = (pkgPolicy *)&DepCache->GetPolicy(); + CppOwnedPyObject *PyPolicy = + CppOwnedPyObject_NEW(Owner,&PyPolicy_Type,Policy); + // Policy should not be deleted, it is managed by CacheFile. + PyPolicy->NoDelete = true; + return PyPolicy; +} + + static PyGetSetDef PkgDepCacheGetSet[] = { {"broken_count",PkgDepCacheGetBrokenCount}, {"deb_size",PkgDepCacheGetDebSize}, @@ -628,6 +640,7 @@ static PyGetSetDef PkgDepCacheGetSet[] = { {"inst_count",PkgDepCacheGetInstCount}, {"keep_count",PkgDepCacheGetKeepCount}, {"usr_size",PkgDepCacheGetUsrSize}, + {"policy",PkgDepCacheGetPolicy}, #ifdef COMPAT_0_7 {"BrokenCount",PkgDepCacheGetBrokenCount}, {"DebSize",PkgDepCacheGetDebSize}, -- cgit v1.2.3 From 5867a0fb2a56ebe6b42dd794ac70a51036f9159f Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Sun, 12 Jul 2009 12:46:34 +0200 Subject: python/cache.cc: Py_DECREF the CacheFile, so it can be deleted. --- python/cache.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'python') diff --git a/python/cache.cc b/python/cache.cc index a571788f..a9c1a557 100644 --- a/python/cache.cc +++ b/python/cache.cc @@ -285,7 +285,7 @@ static PyObject *PkgCacheNew(PyTypeObject *type,PyObject *Args,PyObject *kwds) CppOwnedPyObject_NEW(CacheFileObj,type, (pkgCache *)(*Cache)); - //Py_DECREF(CacheFileObj); + Py_DECREF(CacheFileObj); return CacheObj; } -- cgit v1.2.3 From 9150e644afe9fa51d61f31054b3a1990034b0e18 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Sun, 12 Jul 2009 12:48:22 +0200 Subject: python/depcache.cc: Set NoDelete for DepCaches, instead of using the wrong dealloc function. --- python/depcache.cc | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) (limited to 'python') diff --git a/python/depcache.cc b/python/depcache.cc index 17e2bc30..68ca3a3b 100644 --- a/python/depcache.cc +++ b/python/depcache.cc @@ -670,9 +670,11 @@ static PyObject *PkgDepCacheNew(PyTypeObject *type,PyObject *Args,PyObject *kwds CppOwnedPyObject *DepCachePyObj; DepCachePyObj = CppOwnedPyObject_NEW(Owner,type,depcache); - HandleErrors(DepCachePyObj); - return DepCachePyObj; + // Do not delete the underlying pointer, it is managed by the cachefile. + DepCachePyObj->NoDelete = true; + + return HandleErrors(DepCachePyObj); } static char *doc_PkgDepCache = "DepCache(cache) -> DepCache() object\n\n" @@ -685,8 +687,7 @@ PyTypeObject PkgDepCacheType = sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize // Methods - // Not ..Ptr, because the pkgDepCache pointer is managed by the CacheFile. - CppOwnedDealloc, // tp_dealloc + CppOwnedDeallocPtr, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr -- cgit v1.2.3 From ebdbc02bfd5d43246bf837527dd659a435b8bfde Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Sun, 12 Jul 2009 12:50:18 +0200 Subject: python/cache.cc: Set NoDelete for Caches, instead of using the wrong dealloc function. --- python/cache.cc | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'python') diff --git a/python/cache.cc b/python/cache.cc index a9c1a557..40d7b18a 100644 --- a/python/cache.cc +++ b/python/cache.cc @@ -285,6 +285,8 @@ static PyObject *PkgCacheNew(PyTypeObject *type,PyObject *Args,PyObject *kwds) CppOwnedPyObject_NEW(CacheFileObj,type, (pkgCache *)(*Cache)); + // Do not delete the pointer to the pkgCache, it is managed by pkgCacheFile. + CacheObj->NoDelete = true; Py_DECREF(CacheFileObj); return CacheObj; } @@ -304,7 +306,7 @@ PyTypeObject PkgCacheType = sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize // Methods - CppOwnedDealloc, // tp_dealloc + CppOwnedDeallocPtr, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr -- cgit v1.2.3 From 4eb6bf32792b37d97f7d0d50bf2669b04fa77583 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Sun, 12 Jul 2009 13:04:49 +0200 Subject: python/sourcelist.cc: Fix deletion of MetaIndex objects returned in SourceList.list. First of all, make the objects mortal by decreasing their refcount after adding them to the list. Secondly, make the objects owned by SourceList and thirdly, set NoDelete on them, because they are managed by SourceList. --- python/sourcelist.cc | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) (limited to 'python') diff --git a/python/sourcelist.cc b/python/sourcelist.cc index 0820d5bf..aceb19ad 100644 --- a/python/sourcelist.cc +++ b/python/sourcelist.cc @@ -90,9 +90,12 @@ static PyObject *PkgSourceListGetList(PyObject *Self,void*) for (vector::const_iterator I = list->begin(); I != list->end(); I++) { - PyObject *Obj; - Obj = CppPyObject_NEW(&MetaIndexType,*I); + CppOwnedPyObject *Obj; + Obj = CppOwnedPyObject_NEW(Self, &MetaIndexType,*I); + // Never delete metaIndex*, they are managed by the pkgSourceList. + Obj->NoDelete = true; PyList_Append(List,Obj); + Py_DECREF(Obj); } return List; } -- cgit v1.2.3 From c45715cf0269bcef053025f01a1956b75bf3c859 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Sun, 12 Jul 2009 13:26:02 +0200 Subject: python/metaindex.cc: Fix deletion of the IndexFile objects in MetaIndex.index_files First of all, make the objects mortal by decreasing their refcount after adding them to the list. Secondly, make the objects owned by MetaIndex and thirdly, set NoDelete on them, because they are managed by metaIndex. --- python/metaindex.cc | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) (limited to 'python') diff --git a/python/metaindex.cc b/python/metaindex.cc index 87b1e59a..195394d6 100644 --- a/python/metaindex.cc +++ b/python/metaindex.cc @@ -37,9 +37,12 @@ static PyObject *MetaIndexGetIndexFiles(PyObject *Self,void*) { for (vector::const_iterator I = indexFiles->begin(); I != indexFiles->end(); I++) { - PyObject *Obj; - Obj = CppPyObject_NEW(&PackageIndexFileType,*I); + CppOwnedPyObject *Obj; + Obj = CppOwnedPyObject_NEW(Self, &PackageIndexFileType,*I); + // Do not delete pkgIndexFile*, they are managed by metaIndex. + Obj->NoDelete = true; PyList_Append(List,Obj); + Py_DECREF(Obj); } return List; } -- cgit v1.2.3 From cd4dd0427591d6357d875f881573b0b57bc0ae31 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Sun, 12 Jul 2009 13:57:23 +0200 Subject: python/sourcelist.cc: Do not delete the pkgIndexFile*, it is managed elsewhere. --- python/sourcelist.cc | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'python') diff --git a/python/sourcelist.cc b/python/sourcelist.cc index aceb19ad..beb249dc 100644 --- a/python/sourcelist.cc +++ b/python/sourcelist.cc @@ -26,7 +26,7 @@ static PyObject *PkgSourceListFindIndex(PyObject *Self,PyObject *Args) { pkgSourceList *list = GetCpp(Self); PyObject *pyPkgFileIter; - PyObject *pyPkgIndexFile; + CppOwnedPyObject *pyPkgIndexFile; if (PyArg_ParseTuple(Args, "O!", &PackageFileType,&pyPkgFileIter) == 0) return 0; @@ -36,6 +36,8 @@ static PyObject *PkgSourceListFindIndex(PyObject *Self,PyObject *Args) if(list->FindIndex(i, index)) { pyPkgIndexFile = CppOwnedPyObject_NEW(pyPkgFileIter,&PackageIndexFileType,index); + // Do not delete the pkgIndexFile*, it is managed by pkgSourceList. + pyPkgIndexFile->NoDelete = true; return pyPkgIndexFile; } -- cgit v1.2.3 From 704a039393c6b9bf990f1c99befd2555ad41f16f Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Sun, 12 Jul 2009 15:44:32 +0200 Subject: python/pkgsrcrecords.cc: Do not delete the pkgIndexFile*, it is managed by PkgSrcRecords::Parser. APT still has a bug which causes the index file to not be deleted, but we should prepare for the fix. --- python/pkgsrcrecords.cc | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'python') diff --git a/python/pkgsrcrecords.cc b/python/pkgsrcrecords.cc index 06fd4e3b..99711585 100644 --- a/python/pkgsrcrecords.cc +++ b/python/pkgsrcrecords.cc @@ -123,8 +123,12 @@ static PyObject *PkgSrcRecordsGetIndex(PyObject *Self,void*) { if (Struct.Last == 0) return 0; const pkgIndexFile &tmp = Struct.Last->Index(); - return CppOwnedPyObject_NEW(Self,&PackageIndexFileType, + CppOwnedPyObject *PyObj; + PyObj = CppOwnedPyObject_NEW(Self,&PackageIndexFileType, (pkgIndexFile*)&tmp); + // Do not delete the pkgIndexFile*, it is managed by PkgSrcRecords::Parser. + PyObj->NoDelete=true; + return PyObj; } static PyObject *PkgSrcRecordsGetFiles(PyObject *Self,void*) { -- cgit v1.2.3 From 199827e05750509afb8ea98d5400552201f5ef16 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Sun, 12 Jul 2009 15:46:07 +0200 Subject: python/indexfile.cc: Deallocate the pointer correctly. --- python/indexfile.cc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'python') diff --git a/python/indexfile.cc b/python/indexfile.cc index 5b526b87..f2180cd7 100644 --- a/python/indexfile.cc +++ b/python/indexfile.cc @@ -96,7 +96,7 @@ PyTypeObject PackageIndexFileType = 0, // tp_itemsize // Methods // Not ..Ptr, because the pointer is managed somewhere else. - CppOwnedDealloc, // tp_dealloc + CppOwnedDeallocPtr, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr @@ -112,7 +112,7 @@ PyTypeObject PackageIndexFileType = 0, // tp_setattro 0, // tp_as_buffer Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, // tp_flags - "pkgIndexFile Object", // tp_doc + "IndexFile Object", // tp_doc CppOwnedTraverse, // tp_traverse CppOwnedClear, // tp_clear 0, // tp_richcompare -- cgit v1.2.3 From 60aba10689f5f3881a3427619be5bead3808d422 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Sun, 12 Jul 2009 17:23:32 +0200 Subject: python/cdrom.cc: Remove PkgCdromStruct, use pkgCdrom directly. --- python/cdrom.cc | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) (limited to 'python') diff --git a/python/cdrom.cc b/python/cdrom.cc index 492afd90..b5b87758 100644 --- a/python/cdrom.cc +++ b/python/cdrom.cc @@ -12,15 +12,9 @@ #include - -struct PkgCdromStruct -{ - pkgCdrom cdrom; -}; - static PyObject *PkgCdromAdd(PyObject *Self,PyObject *Args) { - PkgCdromStruct &Struct = GetCpp(Self); + pkgCdrom &Cdrom = GetCpp(Self); PyObject *pyCdromProgressInst = 0; if (PyArg_ParseTuple(Args, "O", &pyCdromProgressInst) == 0) { @@ -30,14 +24,14 @@ static PyObject *PkgCdromAdd(PyObject *Self,PyObject *Args) PyCdromProgress progress; progress.setCallbackInst(pyCdromProgressInst); - bool res = Struct.cdrom.Add(&progress); + bool res = Cdrom.Add(&progress); return HandleErrors(Py_BuildValue("b", res)); } static PyObject *PkgCdromIdent(PyObject *Self,PyObject *Args) { - PkgCdromStruct &Struct = GetCpp(Self); + pkgCdrom &Cdrom = GetCpp(Self); PyObject *pyCdromProgressInst = 0; if (PyArg_ParseTuple(Args, "O", &pyCdromProgressInst) == 0) { @@ -48,7 +42,7 @@ static PyObject *PkgCdromIdent(PyObject *Self,PyObject *Args) progress.setCallbackInst(pyCdromProgressInst); string ident; - bool res = Struct.cdrom.Ident(ident, &progress); + bool res = Cdrom.Ident(ident, &progress); PyObject *result = Py_BuildValue("(bs)", res, ident.c_str()); @@ -87,10 +81,10 @@ PyTypeObject PkgCdromType = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.Cdrom", // tp_name - sizeof(CppOwnedPyObject), // tp_basicsize + sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize // Methods - CppOwnedDealloc, // tp_dealloc + CppOwnedDealloc, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr -- cgit v1.2.3 From 64513033774fb0264c601f021da5d5f6345c3dd4 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Sun, 12 Jul 2009 17:30:34 +0200 Subject: python/policy.cc: Disable Policy.read_pindir() on apt < 0.7.22. --- python/policy.cc | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'python') diff --git a/python/policy.cc b/python/policy.cc index 46d73a1a..d086c4fc 100644 --- a/python/policy.cc +++ b/python/policy.cc @@ -96,6 +96,7 @@ static PyObject *Policy_ReadPinFile(PyObject *self, PyObject *arg) { return PyBool_FromLong(ReadPinFile(*policy, PyString_AsString(arg))); } +#if (APT_PKG_MAJOR >= 4 && APT_PKG_MINOR >= 8) static char *Policy_ReadPinDir_doc = "read_pindir(dirname: str) -> bool\n\n" "Read the pin files in the given dir (e.g. '/etc/apt/preferences.d') and\n" "add them to the policy."; @@ -107,6 +108,7 @@ static PyObject *Policy_ReadPinDir(PyObject *self, PyObject *arg) { return PyBool_FromLong(ReadPinDir(*policy, PyString_AsString(arg))); } +#endif static char *Policy_CreatePin_doc = "create_pin(type: str, pkg: str, " "data: str, priority: int)\n\n" @@ -143,8 +145,10 @@ static PyMethodDef Policy_Methods[] = { Policy_GetCandidateVer_doc}, {"read_pinfile",(PyCFunction)Policy_ReadPinFile,METH_O, Policy_ReadPinFile_doc}, +#if (APT_PKG_MAJOR >= 4 && APT_PKG_MINOR >= 8) {"read_pindir",(PyCFunction)Policy_ReadPinDir,METH_O, Policy_ReadPinFile_doc}, +#endif {"create_pin",Policy_CreatePin,METH_VARARGS,Policy_CreatePin_doc}, {"get_match",(PyCFunction)Policy_GetMatch,METH_O, Policy_GetMatch_doc}, {} -- cgit v1.2.3 From 5b489a994d009771d7f4d5beec45bbbb5468cd58 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Sun, 12 Jul 2009 19:07:55 +0200 Subject: python/hashes.cc: Introduce the Hashes class. The Hashes class is a function which calculates all supported hashes for one input. DebImg will use this for calculating the hashes of files. --- debian/changelog | 3 +- doc/source/apt_pkg.rst | 26 +++++++-- python/apt_pkgmodule.cc | 1 + python/apt_pkgmodule.h | 1 + python/hashes.cc | 136 ++++++++++++++++++++++++++++++++++++++++++++++++ python/makefile | 5 +- 6 files changed, 164 insertions(+), 8 deletions(-) create mode 100644 python/hashes.cc (limited to 'python') diff --git a/debian/changelog b/debian/changelog index 8bc3e320..1f43cc8c 100644 --- a/debian/changelog +++ b/debian/changelog @@ -30,6 +30,7 @@ python-apt (0.7.92) UNRELEASED; urgency=low + Closes: #468123 - there is no need anymore for binding CompType or CompTypeDeb, because we don't return integer values for CompType anymore. + * Introduce apt_pkg.Hashes class. [ Sebastian Heinlein ] * apt/progress.py: Extract the package name from the status message @@ -45,7 +46,7 @@ python-apt (0.7.92) UNRELEASED; urgency=low * python/progress.cc: - low level code for update_status_full and pulse_items() - -- Julian Andres Klode Tue, 07 Jul 2009 16:56:44 +0200 + -- Julian Andres Klode Sun, 12 Jul 2009 18:51:57 +0200 python-apt (0.7.91) experimental; urgency=low diff --git a/doc/source/apt_pkg.rst b/doc/source/apt_pkg.rst index 2af934a0..9a14266e 100644 --- a/doc/source/apt_pkg.rst +++ b/doc/source/apt_pkg.rst @@ -1139,15 +1139,31 @@ installation. the file using the parameter *destfile*. You can not combine both. +Hashes +------ +The apt_pkg module also provides several hash functions. If you develop +applications with python-apt it is often easier to use these functions instead +of the ones provides in Python's :mod:`hashlib` module. +.. class:: Hashes(object) + Calculate all supported hashes of the object. *object* may either be a + string, in which cases the hashes of the string are calculated, or a + :class:`file()` object or file descriptor, in which case the hashes of + its contents is calculated. The calculated hashes are then available via + attributes: + .. attribute:: md5 -Hash functions --------------- -The apt_pkg module also provides several hash functions. If you develop -applications with python-apt it is often easier to use these functions instead -of the ones provides in Python's :mod:`hashlib` module. + The MD5 hash of the data, as string. + + .. attribute:: sha1 + + The SHA1 hash of the data, as string. + + .. attribute:: sha256 + + The SHA256 hash of the data, as string. .. function:: md5sum(object) diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index 3f4aae37..4c0fd5ed 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -618,6 +618,7 @@ extern "C" void initapt_pkg() ADDTYPE(Module,"IndexRecords",&PyIndexRecords_Type); ADDTYPE(Module,"HashString",&PyHashString_Type); ADDTYPE(Module,"Policy",&PyPolicy_Type); + ADDTYPE(Module,"Hashes",&PyHashes_Type); // Tag file constants PyModule_AddObject(Module,"REWRITE_PACKAGE_ORDER", CharCharToList(TFRewritePackageOrder)); diff --git a/python/apt_pkgmodule.h b/python/apt_pkgmodule.h index 21355072..1a2f1a1a 100644 --- a/python/apt_pkgmodule.h +++ b/python/apt_pkgmodule.h @@ -116,5 +116,6 @@ extern PyTypeObject PyIndexRecords_Type; // Policy extern PyTypeObject PyPolicy_Type; +extern PyTypeObject PyHashes_Type; #endif diff --git a/python/hashes.cc b/python/hashes.cc new file mode 100644 index 00000000..a1ace6fc --- /dev/null +++ b/python/hashes.cc @@ -0,0 +1,136 @@ +/* hashes.cc - Wrapper around apt-pkg's Hashes. + * + * Copyright 2009 Julian Andres Klode + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + */ +#include +#include "generic.h" +#include "apt_pkgmodule.h" +#include + +static PyObject *hashes_new(PyTypeObject *type,PyObject *args, + PyObject *kwds) +{ + return CppPyObject_NEW(type); +} + +static int hashes_init(PyObject *self, PyObject *args, PyObject *kwds) +{ + PyObject *object = 0; + int Fd; + char *kwlist[] = {"object", NULL}; + + if (PyArg_ParseTupleAndKeywords(args, kwds, "|O:__init__", kwlist, + &object) == 0) + return -1; + if (object == 0) + return 0; + Hashes &hashes = GetCpp(self); + + if (PyBytes_Check(object) != 0) { + char *s; + Py_ssize_t len; + PyBytes_AsStringAndSize(object, &s, &len); + hashes.Add((const unsigned char*)s, len); + } + else if ((Fd = PyObject_AsFileDescriptor(object)) != -1) { + struct stat St; + if (fstat(Fd, &St) != 0 || hashes.AddFD(Fd, St.st_size) == false) { + PyErr_SetFromErrno(PyExc_SystemError); + return -1; + } + } + else { + PyErr_SetString(PyExc_TypeError, "__init__() only understand strings" + " and files"); + return -1; + } + return 0; +} + +static PyObject *hashes_get_md5(PyObject *self, void*) +{ + return CppPyString(GetCpp(self).MD5.Result().Value()); +} + +static PyObject *hashes_get_sha1(PyObject *self, void*) +{ + return CppPyString(GetCpp(self).SHA1.Result().Value()); +} + +static PyObject *hashes_get_sha256(PyObject *self, void*) +{ + return CppPyString(GetCpp(self).SHA256.Result().Value()); +} + +static PyGetSetDef hashes_getset[] = { + {"md5",hashes_get_md5,0,"The MD5Sum of the file as a string."}, + {"sha1",hashes_get_sha1,0,"The SHA1Sum of the file as a string."}, + {"sha256",hashes_get_sha256,0,"The SHA256Sum of the file as a string."}, + {} +}; + +static char *hashes_doc = + "Hashes([object: (bytes, file)])\n\n" + "Calculate hashes for the given object. It can be used to create all\n" + "supported hashes for a file.\n\n" + "The parameter *object* can be a bytes (3.X) / str (2.X) object, or an\n" + "object providing the fileno() method or an integer describing a file\n" + "descriptor."; + +PyTypeObject PyHashes_Type = { + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "apt_pkg.Hashes", // tp_name + sizeof(CppPyObject), // tp_basicsize + 0, // tp_itemsize + // Methods + CppDealloc, // tp_dealloc + 0, // tp_print + 0, // tp_getattr + 0, // tp_setattr + 0, // tp_compare + 0, // tp_repr + 0, // tp_as_number + 0, // tp_as_sequence + 0, // tp_as_mapping + 0, // tp_hash + 0, // tp_call + 0, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + Py_TPFLAGS_DEFAULT | // tp_flags + Py_TPFLAGS_BASETYPE, + hashes_doc, // tp_doc + 0, // tp_traverse + 0, // tp_clear + 0, // tp_richcompare + 0, // tp_weaklistoffset + 0, // tp_iter + 0, // tp_iternext + 0, // tp_methods + 0, // tp_members + hashes_getset, // tp_getset + 0, // tp_base + 0, // tp_dict + 0, // tp_descr_get + 0, // tp_descr_set + 0, // tp_dictoffset + hashes_init, // tp_init + 0, // tp_alloc + hashes_new, // tp_new +}; diff --git a/python/makefile b/python/makefile index 6799d749..fff3a2e8 100644 --- a/python/makefile +++ b/python/makefile @@ -11,8 +11,9 @@ SLIBS = -lapt-pkg LIB_MAKES = apt-pkg/makefile APT_PKG_SRC = apt_pkgmodule.cc configuration.cc generic.cc tag.cc string.cc \ cache.cc pkgrecords.cc pkgsrcrecords.cc sourcelist.cc \ - depcache.cc progress.cc cdrom.cc acquire.cc pkgmanager.cc \ - indexfile.cc metaindex.cc hashstring.cc indexrecords.cc policy.cc + depcache.cc progress.cc cdrom.cc acquire.cc pkgmanager.cc \ + indexfile.cc metaindex.cc hashstring.cc indexrecords.cc \ + policy.cc hashes.cc SOURCE := $(APT_PKG_SRC) include $(PYTHON_H) progress.h -- cgit v1.2.3 From b0abeea43f6e51c452af68d8ec9bf3d0f701d772 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Sun, 12 Jul 2009 21:22:58 +0200 Subject: python/acquire.cc: Fix segmentation faults, introduce PyAcquireObject. Make AcquireItem objects raise ValueError instead of segfaulting when the Acquire() object is shut down or the main object (e.g. AcquireFile) is deallocated. This is implemented by using a vector of the AcquireItem objects, and setting AcquireItem->Object = NULL, when the memory 'Object' previously pointed to is going to be deleted. --- debian/changelog | 4 ++- python/acquire.cc | 96 ++++++++++++++++++++++++++++++++++++++++--------------- 2 files changed, 73 insertions(+), 27 deletions(-) (limited to 'python') diff --git a/debian/changelog b/debian/changelog index 1f43cc8c..304237c1 100644 --- a/debian/changelog +++ b/debian/changelog @@ -31,6 +31,8 @@ python-apt (0.7.92) UNRELEASED; urgency=low CompTypeDeb, because we don't return integer values for CompType anymore. * Introduce apt_pkg.Hashes class. + * Make AcquireItem objects raise ValueError instead of segfaulting when the Acquire() + object is shut down or the main object (e.g. AcquireFile) is deallocated. [ Sebastian Heinlein ] * apt/progress.py: Extract the package name from the status message @@ -46,7 +48,7 @@ python-apt (0.7.92) UNRELEASED; urgency=low * python/progress.cc: - low level code for update_status_full and pulse_items() - -- Julian Andres Klode Sun, 12 Jul 2009 18:51:57 +0200 + -- Julian Andres Klode Sun, 12 Jul 2009 21:19:40 +0200 python-apt (0.7.91) experimental; urgency=low diff --git a/python/acquire.cc b/python/acquire.cc index 6c6c2ea4..054956ea 100644 --- a/python/acquire.cc +++ b/python/acquire.cc @@ -12,15 +12,27 @@ #include +typedef CppPyObject PyAcquireItemObject; + +// Keep a vector to PyAcquireItemObject pointers, so we can set the Object +// pointers to NULL when deallocating the main object (mostly AcquireFile). +struct PyAcquireObject : public CppPyObject { + vector items; +}; + +inline pkgAcquire::Item *PyAcquireItem_ToCpp(PyObject *self) { + pkgAcquire::Item *itm = GetCpp(self); + if (itm == 0) + PyErr_SetString(PyExc_ValueError, "Acquire() has been shut down or " + "the AcquireFile() object has been deallocated."); + return itm; +} + #define MkGet(PyFunc,Ret) static PyObject *PyFunc(PyObject *Self,void*) \ { \ - pkgAcquire::Item *Itm; \ - if (PyObject_TypeCheck(Self, &PkgAcquireFileType)) { \ - Itm = GetCpp(Self); \ - } else { \ - pkgAcquire::ItemIterator &I = GetCpp(Self); \ - Itm = *I; \ - } \ + pkgAcquire::Item *Itm = PyAcquireItem_ToCpp(Self); \ + if (Itm == 0) \ + return 0; \ return Ret; \ } @@ -30,7 +42,7 @@ MkGet(AcquireItemGetDescURI,Safe_FromString(Itm->DescURI().c_str())); MkGet(AcquireItemGetDestFile,Safe_FromString(Itm->DestFile.c_str())); MkGet(AcquireItemGetErrorText,Safe_FromString(Itm->ErrorText.c_str())); MkGet(AcquireItemGetFileSize,Py_BuildValue("i",Itm->FileSize)); -MkGet(AcquireItemGetID,Py_BuildValue("i",Itm->ID)); +MkGet(AcquireItemGetID,Py_BuildValue("i",Itm)); MkGet(AcquireItemGetIsTrusted,Py_BuildValue("i",Itm->IsTrusted())); MkGet(AcquireItemGetLocal,Py_BuildValue("i",Itm->Local)); MkGet(AcquireItemGetStatus,Py_BuildValue("i",Itm->Status)); @@ -82,14 +94,9 @@ static PyGetSetDef AcquireItemGetSet[] = { static PyObject *AcquireItemRepr(PyObject *Self) { - pkgAcquire::Item *Itm; - if (PyObject_TypeCheck(Self, &PkgAcquireFileType)) { - Itm = GetCpp(Self); - } else { - pkgAcquire::ItemIterator &I = GetCpp(Self); - Itm = *I; - } - + pkgAcquire::Item *Itm = PyAcquireItem_ToCpp(Self); + if (Itm == 0) + return 0; char S[300]; snprintf(S,sizeof(S),"<%s object: " "Status: %i Complete: %i Local: %i IsTrusted: %i " @@ -102,15 +109,45 @@ static PyObject *AcquireItemRepr(PyObject *Self) return PyString_FromString(S); } +static void AcquireItemDealloc(PyObject *self) { + pkgAcquire::Item *file = GetCpp(self); + PyAcquireObject *owner = (PyAcquireObject *)GetOwner(self); + vector &items = owner->items; + bool DeletePtr = !((CppPyObject *)self)->NoDelete; + + // Cleanup the other objects as well... + for (vector::iterator I = items.begin(); + I != items.end(); I++) { + // If it is the current object, remove it from the vector. + if ((*I) == self) { + items.erase(I); + I--; // erase() moved it one forward, move back + } + // If we delete the object below, set all other pointers to it to NULL, + // and remove them from the vector. + else if (DeletePtr && (*I)->Object == file) { + if ((*I) != self) + (*I)->Object = NULL; + items.erase(I); + I--; // erase() moved it one forward, move back + } + } +#ifdef ALLOC_DEBUG + std::cerr << "ITEMS: " << items.size() << "\n"; +#endif + CppOwnedDeallocPtr(self); +} + + PyTypeObject AcquireItemType = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.AcquireItem", // tp_name - sizeof(CppOwnedPyObject), // tp_basicsize + sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize // Methods - CppOwnedDealloc, // tp_dealloc + AcquireItemDealloc, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr @@ -139,6 +176,7 @@ PyTypeObject AcquireItemType = }; + static PyObject *PkgAcquireRun(PyObject *Self,PyObject *Args) { pkgAcquire *fetcher = GetCpp(Self); @@ -161,6 +199,11 @@ static PyObject *PkgAcquireShutdown(PyObject *Self,PyObject *Args) fetcher->Shutdown(); + vector items = ((PyAcquireObject *)Self)->items; + for (vector::iterator I = items.begin(); + I != items.end(); I++) + (*I)->Object = NULL; + Py_INCREF(Py_None); return HandleErrors(Py_None); } @@ -194,12 +237,12 @@ static PyObject *PkgAcquireGetItems(PyObject *Self,void*) for (pkgAcquire::ItemIterator I = fetcher->ItemsBegin(); I != fetcher->ItemsEnd(); I++) { - PyObject *Obj; - Obj = CppOwnedPyObject_NEW(Self, - &AcquireItemType,I); + PyAcquireItemObject *Obj; + Obj = CppOwnedPyObject_NEW(Self,&AcquireItemType,*I); + Obj->NoDelete = true; PyList_Append(List,Obj); + ((PyAcquireObject *)Self)->items.push_back(Obj); Py_DECREF(Obj); - } return List; } @@ -266,7 +309,7 @@ PyTypeObject PkgAcquireType = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.Acquire", // tp_name - sizeof(CppPyObject), // tp_basicsize + sizeof(PyAcquireObject), // tp_basicsize 0, // tp_itemsize // Methods CppDeallocPtr, // tp_dealloc @@ -341,6 +384,8 @@ static PyObject *PkgAcquireFileNew(PyTypeObject *type, PyObject *Args, PyObject destFile); // short-desc CppOwnedPyObject *AcqFileObj = CppOwnedPyObject_NEW(pyfetcher, type); AcqFileObj->Object = af; + ((PyAcquireObject *)pyfetcher)->items.push_back((PyAcquireItemObject *)AcqFileObj); + return AcqFileObj; } @@ -359,9 +404,7 @@ PyTypeObject PkgAcquireFileType = sizeof(CppOwnedPyObject),// tp_basicsize 0, // tp_itemsize // Methods - // Not ..Ptr, because this would cause the item to be removed from the - // fetcher, which would be incompatible to previous behaviour. - CppOwnedDealloc, // tp_dealloc + AcquireItemDealloc, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr @@ -431,6 +474,7 @@ PyObject *GetPkgAcqFile(PyObject *Self, PyObject *Args, PyObject * kwds) destFile); // short-desc CppPyObject *AcqFileObj = CppPyObject_NEW(&PkgAcquireFileType); AcqFileObj->Object = af; + AcqFileObj->NoDelete = true; return AcqFileObj; } -- cgit v1.2.3 From dabc8c6796afdaf0e2918db77117a07eae8b1fd4 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Mon, 13 Jul 2009 14:25:06 +0200 Subject: python: Rename all PyTypeObject's to conform to PEP 7. This is the first step towards implementing coding guidelines for the C++ code and providing an usable C++ API. --- python/acquire.cc | 18 +++++++------- python/apt_pkgmodule.cc | 62 +++++++++++++++++++++++------------------------ python/apt_pkgmodule.h | 60 +++++++++++++++++++++++----------------------- python/cache.cc | 60 +++++++++++++++++++++++----------------------- python/cdrom.cc | 4 ++-- python/configuration.cc | 16 ++++++------- python/depcache.cc | 64 ++++++++++++++++++++++++------------------------- python/indexfile.cc | 2 +- python/metaindex.cc | 4 ++-- python/pkgmanager.cc | 12 +++++----- python/pkgrecords.cc | 8 +++---- python/pkgsrcrecords.cc | 6 ++--- python/policy.cc | 12 +++++----- python/sourcelist.cc | 14 +++++------ python/tag.cc | 12 +++++----- 15 files changed, 177 insertions(+), 177 deletions(-) (limited to 'python') diff --git a/python/acquire.cc b/python/acquire.cc index 054956ea..4329e790 100644 --- a/python/acquire.cc +++ b/python/acquire.cc @@ -140,7 +140,7 @@ static void AcquireItemDealloc(PyObject *self) { -PyTypeObject AcquireItemType = +PyTypeObject PyAcquireItem_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.AcquireItem", // tp_name @@ -238,7 +238,7 @@ static PyObject *PkgAcquireGetItems(PyObject *Self,void*) I != fetcher->ItemsEnd(); I++) { PyAcquireItemObject *Obj; - Obj = CppOwnedPyObject_NEW(Self,&AcquireItemType,*I); + Obj = CppOwnedPyObject_NEW(Self,&PyAcquireItem_Type,*I); Obj->NoDelete = true; PyList_Append(List,Obj); ((PyAcquireObject *)Self)->items.push_back(Obj); @@ -305,7 +305,7 @@ static char *doc_PkgAcquire = "Acquire(progress) -> Acquire() object.\n\n" "specify a apt.progress.FetchProgress() object, which will display the\n" "progress of the fetching."; -PyTypeObject PkgAcquireType = +PyTypeObject PyAcquire_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.Acquire", // tp_name @@ -354,7 +354,7 @@ PyObject *GetAcquire(PyObject *Self,PyObject *Args) { PyErr_WarnEx(PyExc_DeprecationWarning,"apt_pkg.GetAcquire() is deprecated." " Please see apt_pkg.Acquire() for the replacement.", 1); - return PkgAcquireNew(&PkgAcquireType,Args,0); + return PkgAcquireNew(&PyAcquire_Type,Args,0); } #endif @@ -369,7 +369,7 @@ static PyObject *PkgAcquireFileNew(PyTypeObject *type, PyObject *Args, PyObject "destdir", "destfile", NULL}; if (PyArg_ParseTupleAndKeywords(Args, kwds, "O!s|sissss", kwlist, - &PkgAcquireType, &pyfetcher, &uri, &md5, + &PyAcquire_Type, &pyfetcher, &uri, &md5, &size, &descr, &shortDescr, &destDir, &destFile) == 0) return 0; @@ -397,7 +397,7 @@ static char *doc_PkgAcquireFile = "The parameter *owner* refers to an apt_pkg.Acquire() object. You can use\n" "*destdir* OR *destfile* to specify the destination directory/file."; -PyTypeObject PkgAcquireFileType = +PyTypeObject PyAcquireFile_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.AcquireFile", // tp_name @@ -432,7 +432,7 @@ PyTypeObject PkgAcquireFileType = 0, // tp_methods 0, // tp_members 0, // tp_getset - &AcquireItemType, // tp_base + &PyAcquireItem_Type, // tp_base 0, // tp_dict 0, // tp_descr_get 0, // tp_descr_set @@ -459,7 +459,7 @@ PyObject *GetPkgAcqFile(PyObject *Self, PyObject *Args, PyObject * kwds) "destDir", "destFile", NULL}; if (PyArg_ParseTupleAndKeywords(Args, kwds, "O!s|sissss", kwlist, - &PkgAcquireType, &pyfetcher, &uri, &md5, + &PyAcquire_Type, &pyfetcher, &uri, &md5, &size, &descr, &shortDescr, &destDir, &destFile) == 0) return 0; @@ -472,7 +472,7 @@ PyObject *GetPkgAcqFile(PyObject *Self, PyObject *Args, PyObject * kwds) shortDescr, destDir, destFile); // short-desc - CppPyObject *AcqFileObj = CppPyObject_NEW(&PkgAcquireFileType); + CppPyObject *AcqFileObj = CppPyObject_NEW(&PyAcquireFile_Type); AcqFileObj->Object = af; AcqFileObj->NoDelete = true; diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index 4c0fd5ed..d236820a 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -36,7 +36,7 @@ static PyObject *newConfiguration(PyObject *self,PyObject *args) { PyErr_WarnEx(PyExc_DeprecationWarning, "apt_pkg.newConfiguration() is " "deprecated. Use apt_pkg.Configuration() instead.", 1); - return CppPyObject_NEW(&ConfigurationType); + return CppPyObject_NEW(&PyConfiguration_Type); } #endif /*}}}*/ @@ -556,9 +556,9 @@ extern "C" void initapt_pkg() #endif { // Finalize our types to add slots, etc. - if (PyType_Ready(&ConfigurationPtrType) == -1) INIT_ERROR; - if (PyType_Ready(&ConfigurationSubType) == -1) INIT_ERROR; - if (PyType_Ready(&PkgCacheFileType) == -1) INIT_ERROR; + if (PyType_Ready(&PyConfigurationPtr_Type) == -1) INIT_ERROR; + if (PyType_Ready(&PyConfigurationSub_Type) == -1) INIT_ERROR; + if (PyType_Ready(&PyCacheFile_Type) == -1) INIT_ERROR; // Initialize the module #if PY_MAJOR_VERSION >= 3 @@ -568,7 +568,7 @@ extern "C" void initapt_pkg() #endif // Global variable linked to the global configuration class - CppPyObject *Config = CppPyObject_NEW(&ConfigurationPtrType); + CppPyObject *Config = CppPyObject_NEW(&PyConfigurationPtr_Type); Config->Object = _config; PyModule_AddObject(Module,"config",Config); #ifdef COMPAT_0_7 @@ -578,43 +578,43 @@ extern "C" void initapt_pkg() // Add our classes. /* ============================ tag.cc ============================ */ - ADDTYPE(Module,"TagSection",&TagSecType); - ADDTYPE(Module,"TagFile",&TagFileType); + ADDTYPE(Module,"TagSection",&PyTagSection_Type); + ADDTYPE(Module,"TagFile",&PyTagFile_Type); /* ============================ acquire.cc ============================ */ - ADDTYPE(Module,"Acquire",&PkgAcquireType); - ADDTYPE(Module,"AcquireFile",&PkgAcquireFileType); - ADDTYPE(Module,"AcquireItem",&AcquireItemType); // NO __new__() + ADDTYPE(Module,"Acquire",&PyAcquire_Type); + ADDTYPE(Module,"AcquireFile",&PyAcquireFile_Type); + ADDTYPE(Module,"AcquireItem",&PyAcquireItem_Type); // NO __new__() /* ============================ cache.cc ============================ */ - ADDTYPE(Module,"Cache",&PkgCacheType); - ADDTYPE(Module,"Dependency",&DependencyType); // NO __new__() - ADDTYPE(Module,"Description",&DescriptionType); // NO __new__() - ADDTYPE(Module,"PackageFile",&PackageFileType); // NO __new__() - ADDTYPE(Module,"PackageList",&PkgListType); // NO __new__(), internal - ADDTYPE(Module,"DependencyList",&RDepListType); // NO __new__(), internal - ADDTYPE(Module,"Package",&PackageType); // NO __new__() - ADDTYPE(Module,"Version",&VersionType); // NO __new__() + ADDTYPE(Module,"Cache",&PyCache_Type); + ADDTYPE(Module,"Dependency",&PyDependency_Type); // NO __new__() + ADDTYPE(Module,"Description",&PyDescription_Type); // NO __new__() + ADDTYPE(Module,"PackageFile",&PyPackageFile_Type); // NO __new__() + ADDTYPE(Module,"PackageList",&PyPackageList_Type); // NO __new__(), internal + ADDTYPE(Module,"DependencyList",&PyDependencyList_Type); // NO __new__(), internal + ADDTYPE(Module,"Package",&PyPackage_Type); // NO __new__() + ADDTYPE(Module,"Version",&PyVersion_Type); // NO __new__() /* ============================ cdrom.cc ============================ */ - ADDTYPE(Module,"Cdrom",&PkgCdromType); + ADDTYPE(Module,"Cdrom",&PyCdrom_Type); /* ========================= configuration.cc ========================= */ - ADDTYPE(Module,"Configuration",&ConfigurationType); - //ADDTYPE(Module,"ConfigurationSub",&ConfigurationSubType); // NO __new__() - //ADDTYPE(Module,"ConfigurationPtr",&ConfigurationPtrType); // NO __new__() + ADDTYPE(Module,"Configuration",&PyConfiguration_Type); + //ADDTYPE(Module,"ConfigurationSub",&PyConfigurationSub_Type); // NO __new__() + //ADDTYPE(Module,"ConfigurationPtr",&PyConfigurationPtr_Type); // NO __new__() /* ========================= depcache.cc ========================= */ - ADDTYPE(Module,"ActionGroup",&PkgActionGroupType); - ADDTYPE(Module,"DepCache",&PkgDepCacheType); - ADDTYPE(Module,"ProblemResolver",&PkgProblemResolverType); + ADDTYPE(Module,"ActionGroup",&PyActionGroup_Type); + ADDTYPE(Module,"DepCache",&PyDepCache_Type); + ADDTYPE(Module,"ProblemResolver",&PyProblemResolver_Type); /* ========================= indexfile.cc ========================= */ - ADDTYPE(Module,"PackageIndexFile",&PackageIndexFileType); // NO __new__() + ADDTYPE(Module,"PackageIndexFile",&PyPackageIndexFile_Type); // NO __new__() /* ========================= metaindex.cc ========================= */ - ADDTYPE(Module,"MetaIndex",&MetaIndexType); // NO __new__() + ADDTYPE(Module,"MetaIndex",&PyMetaIndex_Type); // NO __new__() /* ========================= pkgmanager.cc ========================= */ - ADDTYPE(Module,"PackageManager",&PkgManagerType); + ADDTYPE(Module,"PackageManager",&PyPackageManager_Type); /* ========================= pkgrecords.cc ========================= */ - ADDTYPE(Module,"PackageRecords",&PkgRecordsType); + ADDTYPE(Module,"PackageRecords",&PyPackageRecords_Type); /* ========================= pkgsrcrecords.cc ========================= */ - ADDTYPE(Module,"SourceRecords",&PkgSrcRecordsType); + ADDTYPE(Module,"SourceRecords",&PySourceRecords_Type); /* ========================= sourcelist.cc ========================= */ - ADDTYPE(Module,"SourceList",&PkgSourceListType); + ADDTYPE(Module,"SourceList",&PySourceList_Type); ADDTYPE(Module,"IndexRecords",&PyIndexRecords_Type); ADDTYPE(Module,"HashString",&PyHashString_Type); ADDTYPE(Module,"Policy",&PyPolicy_Type); diff --git a/python/apt_pkgmodule.h b/python/apt_pkgmodule.h index 1a2f1a1a..7b835ca8 100644 --- a/python/apt_pkgmodule.h +++ b/python/apt_pkgmodule.h @@ -14,13 +14,13 @@ #include // Configuration Stuff -#define Configuration_Check(op) ((op)->ob_type == &ConfigurationType || \ - (op)->ob_type == &ConfigurationPtrType || \ - (op)->ob_type == &ConfigurationSubType) -extern PyTypeObject ConfigurationType; -extern PyTypeObject ConfigurationPtrType; -extern PyTypeObject ConfigurationSubType; -extern PyTypeObject VersionType; +#define Configuration_Check(op) ((op)->ob_type == &PyConfiguration_Type || \ + (op)->ob_type == &PyConfigurationPtr_Type || \ + (op)->ob_type == &PyConfigurationSub_Type) +extern PyTypeObject PyConfiguration_Type; +extern PyTypeObject PyConfigurationPtr_Type; +extern PyTypeObject PyConfigurationSub_Type; +extern PyTypeObject PyVersion_Type; extern char *doc_LoadConfig; extern char *doc_LoadConfigISC; @@ -32,8 +32,8 @@ PyObject *LoadConfigDir(PyObject *Self,PyObject *Args); PyObject *ParseCommandLine(PyObject *Self,PyObject *Args); // Tag File Stuff -extern PyTypeObject TagSecType; -extern PyTypeObject TagFileType; +extern PyTypeObject PyTagSection_Type; +extern PyTypeObject PyTagFile_Type; extern char *doc_ParseSection; extern char *doc_ParseTagFile; extern char *doc_RewriteSection; @@ -54,58 +54,58 @@ PyObject *StrStrToTime(PyObject *self,PyObject *Args); PyObject *StrCheckDomainList(PyObject *Self,PyObject *Args); // Cache Stuff -extern PyTypeObject PkgCacheType; -extern PyTypeObject PkgCacheFileType; -extern PyTypeObject PkgListType; -extern PyTypeObject DescriptionType; -extern PyTypeObject PackageType; -extern PyTypeObject PackageFileType; -extern PyTypeObject DependencyType; -extern PyTypeObject RDepListType; +extern PyTypeObject PyCache_Type; +extern PyTypeObject PyCacheFile_Type; +extern PyTypeObject PyPackageList_Type; +extern PyTypeObject PyDescription_Type; +extern PyTypeObject PyPackage_Type; +extern PyTypeObject PyPackageFile_Type; +extern PyTypeObject PyDependency_Type; +extern PyTypeObject PyDependencyList_Type; PyObject *TmpGetCache(PyObject *Self,PyObject *Args); // DepCache -extern PyTypeObject PkgDepCacheType; +extern PyTypeObject PyDepCache_Type; PyObject *GetDepCache(PyObject *Self,PyObject *Args); // pkgProblemResolver -extern PyTypeObject PkgProblemResolverType; +extern PyTypeObject PyProblemResolver_Type; PyObject *GetPkgProblemResolver(PyObject *Self, PyObject *Args); PyObject *GetPkgActionGroup(PyObject *Self, PyObject *Args); -extern PyTypeObject PkgActionGroupType; +extern PyTypeObject PyActionGroup_Type; // cdrom -extern PyTypeObject PkgCdromType; +extern PyTypeObject PyCdrom_Type; PyObject *GetCdrom(PyObject *Self,PyObject *Args); // acquire -extern PyTypeObject AcquireItemType; -extern PyTypeObject PkgAcquireType; -extern PyTypeObject PkgAcquireFileType; +extern PyTypeObject PyAcquireItem_Type; +extern PyTypeObject PyAcquire_Type; +extern PyTypeObject PyAcquireFile_Type; extern char *doc_GetPkgAcqFile; PyObject *GetAcquire(PyObject *Self,PyObject *Args); PyObject *GetPkgAcqFile(PyObject *Self, PyObject *Args, PyObject *kwds); // packagemanager -extern PyTypeObject PkgManagerType; +extern PyTypeObject PyPackageManager_Type; PyObject *GetPkgManager(PyObject *Self,PyObject *Args); // PkgRecords Stuff -extern PyTypeObject PkgRecordsType; -extern PyTypeObject PkgSrcRecordsType; +extern PyTypeObject PyPackageRecords_Type; +extern PyTypeObject PySourceRecords_Type; PyObject *GetPkgRecords(PyObject *Self,PyObject *Args); PyObject *GetPkgSrcRecords(PyObject *Self,PyObject *Args); // pkgSourceList -extern PyTypeObject PkgSourceListType; +extern PyTypeObject PySourceList_Type; PyObject *GetPkgSourceList(PyObject *Self,PyObject *Args); // pkgSourceList -extern PyTypeObject PackageIndexFileType; +extern PyTypeObject PyPackageIndexFile_Type; // metaIndex -extern PyTypeObject MetaIndexType; +extern PyTypeObject PyMetaIndex_Type; // HashString PyObject *PyHashString_FromCpp(HashString *obj); diff --git a/python/cache.cc b/python/cache.cc index 40d7b18a..d3a8a949 100644 --- a/python/cache.cc +++ b/python/cache.cc @@ -62,7 +62,7 @@ static PyObject *CreateProvides(PyObject *Owner,pkgCache::PrvIterator I) { PyObject *Obj; PyObject *Ver; - Ver = CppOwnedPyObject_NEW(Owner,&VersionType, + Ver = CppOwnedPyObject_NEW(Owner,&PyVersion_Type, I.OwnerVer()); Obj = Py_BuildValue("ssN",I.ParentPkg().Name(),I.ProvideVersion(), Ver); @@ -150,7 +150,7 @@ static PyMethodDef PkgCacheMethods[] = static PyObject *PkgCacheGetPackages(PyObject *Self, void*) { pkgCache *Cache = GetCpp(Self); - return CppOwnedPyObject_NEW(Self,&PkgListType,Cache->PkgBegin()); + return CppOwnedPyObject_NEW(Self,&PyPackageList_Type,Cache->PkgBegin()); } static PyObject *PkgCacheGetPackageCount(PyObject *Self, void*) { @@ -188,7 +188,7 @@ static PyObject *PkgCacheGetFileList(PyObject *Self, void*) { for (pkgCache::PkgFileIterator I = Cache->FileBegin(); I.end() == false; I++) { PyObject *Obj; - Obj = CppOwnedPyObject_NEW(Self,&PackageFileType,I); + Obj = CppOwnedPyObject_NEW(Self,&PyPackageFile_Type,I); PyList_Append(List,Obj); Py_DECREF(Obj); } @@ -238,7 +238,7 @@ static PyObject *CacheMapOp(PyObject *Self,PyObject *Arg) return 0; } - return CppOwnedPyObject_NEW(Self,&PackageType,Pkg); + return CppOwnedPyObject_NEW(Self,&PyPackage_Type,Pkg); } static PyObject *PkgCacheNew(PyTypeObject *type,PyObject *Args,PyObject *kwds) @@ -279,7 +279,7 @@ static PyObject *PkgCacheNew(PyTypeObject *type,PyObject *Args,PyObject *kwds) } CppOwnedPyObject *CacheFileObj = - CppOwnedPyObject_NEW(0,&PkgCacheFileType, Cache); + CppOwnedPyObject_NEW(0,&PyCacheFile_Type, Cache); CppOwnedPyObject *CacheObj = CppOwnedPyObject_NEW(CacheFileObj,type, @@ -299,7 +299,7 @@ static char *doc_PkgCache = "Cache([progress]) -> Cache() object.\n\n" "If not specified, the progress is displayed in simple text form."; static PyMappingMethods CacheMap = {0,CacheMapOp,0}; -PyTypeObject PkgCacheType = +PyTypeObject PyCache_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.Cache", // tp_name @@ -346,7 +346,7 @@ PyTypeObject PkgCacheType = /*}}}*/ // PkgCacheFile Class /*{{{*/ // --------------------------------------------------------------------- -PyTypeObject PkgCacheFileType = +PyTypeObject PyCacheFile_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "pkgCacheFile", // tp_name @@ -404,7 +404,7 @@ static PyObject *PkgListItem(PyObject *iSelf,Py_ssize_t Index) } } - return CppOwnedPyObject_NEW(GetOwner(iSelf),&PackageType, + return CppOwnedPyObject_NEW(GetOwner(iSelf),&PyPackage_Type, Self.Iter); } @@ -419,7 +419,7 @@ static PySequenceMethods PkgListSeq = 0 // assign slice }; -PyTypeObject PkgListType = +PyTypeObject PyPackageList_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.PackageList", // tp_name @@ -457,7 +457,7 @@ PyTypeObject PkgListType = MkGet(PackageGetName,PyString_FromString(Pkg.Name())); MkGet(PackageGetSection,Safe_FromString(Pkg.Section())); MkGet(PackageGetRevDependsList,CppOwnedPyObject_NEW(Owner, - &RDepListType, Pkg.RevDependsList())); + &PyDependencyList_Type, Pkg.RevDependsList())); MkGet(PackageGetProvidesList,CreateProvides(Owner,Pkg.ProvidesList())); MkGet(PackageGetSelectedState,Py_BuildValue("i",Pkg->SelectedState)); MkGet(PackageGetInstState,Py_BuildValue("i",Pkg->InstState)); @@ -479,7 +479,7 @@ static PyObject *PackageGetVersionList(PyObject *Self,void*) for (pkgCache::VerIterator I = Pkg.VersionList(); I.end() == false; I++) { PyObject *Obj; - Obj = CppOwnedPyObject_NEW(Owner,&VersionType,I); + Obj = CppOwnedPyObject_NEW(Owner,&PyVersion_Type,I); PyList_Append(List,Obj); Py_DECREF(Obj); } @@ -494,7 +494,7 @@ static PyObject *PackageGetCurrentVer(PyObject *Self,void*) Py_INCREF(Py_None); return Py_None; } - return CppOwnedPyObject_NEW(Owner,&VersionType, + return CppOwnedPyObject_NEW(Owner,&PyVersion_Type, Pkg.CurrentVer()); } @@ -541,7 +541,7 @@ static PyObject *PackageRepr(PyObject *Self) return PyString_FromString(S); } -PyTypeObject PackageType = +PyTypeObject PyPackage_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.Package", // tp_name @@ -599,7 +599,7 @@ static PyObject *DescriptionGetFileList(PyObject *Self,void*) { PyObject *DescFile; PyObject *Obj; - DescFile = CppOwnedPyObject_NEW(Owner,&PackageFileType,I.File()); + DescFile = CppOwnedPyObject_NEW(Owner,&PyPackageFile_Type,I.File()); Obj = Py_BuildValue("Nl",DescFile,I.Index()); PyList_Append(List,Obj); Py_DECREF(Obj); @@ -629,7 +629,7 @@ static PyObject *DescriptionRepr(PyObject *Self) return PyString_FromString(S); } -PyTypeObject DescriptionType = +PyTypeObject PyDescription_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.Description", // tp_name @@ -711,7 +711,7 @@ static PyObject *MakeDepends(PyObject *Owner,pkgCache::VerIterator &Ver, { PyObject *Obj; if (AsObj == true) - Obj = CppOwnedPyObject_NEW(Owner,&DependencyType, + Obj = CppOwnedPyObject_NEW(Owner,&PyDependency_Type, Start); else { @@ -763,7 +763,7 @@ static PyObject *VersionGetFileList(PyObject *Self, void*) { { PyObject *PkgFile; PyObject *Obj; - PkgFile = CppOwnedPyObject_NEW(Owner,&PackageFileType,I.File()); + PkgFile = CppOwnedPyObject_NEW(Owner,&PyPackageFile_Type,I.File()); Obj = Py_BuildValue("Nl",PkgFile,I.Index()); PyList_Append(List,Obj); Py_DECREF(Obj); @@ -783,7 +783,7 @@ static PyObject *VersionGetDependsList(PyObject *Self, void*) { } static PyObject *VersionGetParentPkg(PyObject *Self, void*) { PyObject *Owner = GetOwner(Self); - return CppOwnedPyObject_NEW(Owner,&PackageType, + return CppOwnedPyObject_NEW(Owner,&PyPackage_Type, Version_GetVer(Self).ParentPkg()); } static PyObject *VersionGetProvidesList(PyObject *Self, void*) { @@ -815,7 +815,7 @@ static PyObject *VersionGetTranslatedDescription(PyObject *Self, void*) { pkgCache::VerIterator &Ver = GetCpp(Self); PyObject *Owner = GetOwner(Self); return CppOwnedPyObject_NEW(Owner, - &DescriptionType, + &PyDescription_Type, Ver.TranslatedDescription()); } @@ -889,7 +889,7 @@ static PyGetSetDef VersionGetSet[] = { {} }; -PyTypeObject VersionType = +PyTypeObject PyVersion_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.Version", // tp_name @@ -1051,7 +1051,7 @@ static PyGetSetDef PackageFileGetSet[] = { {} }; -PyTypeObject PackageFileType = { +PyTypeObject PyPackageFile_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.PackageFile", // tp_name sizeof(CppOwnedPyObject), // tp_basicsize @@ -1113,7 +1113,7 @@ static PyObject *DepSmartTargetPkg(PyObject *Self,PyObject *Args) return Py_None; } - return CppOwnedPyObject_NEW(Owner,&PackageType,P); + return CppOwnedPyObject_NEW(Owner,&PyPackage_Type,P); } static PyObject *DepAllTargets(PyObject *Self,PyObject *Args) @@ -1129,7 +1129,7 @@ static PyObject *DepAllTargets(PyObject *Self,PyObject *Args) for (pkgCache::Version **I = Vers; *I != 0; I++) { PyObject *Obj; - Obj = CppOwnedPyObject_NEW(Owner,&VersionType, + Obj = CppOwnedPyObject_NEW(Owner,&PyVersion_Type, pkgCache::VerIterator(*Dep.Cache(),*I)); PyList_Append(List,Obj); Py_DECREF(Obj); @@ -1163,7 +1163,7 @@ static PyObject *DependencyGetTargetPkg(PyObject *Self,void*) { pkgCache::DepIterator &Dep = GetCpp(Self); PyObject *Owner = GetOwner(Self); - return CppOwnedPyObject_NEW(Owner,&PackageType, + return CppOwnedPyObject_NEW(Owner,&PyPackage_Type, Dep.TargetPkg()); } @@ -1171,7 +1171,7 @@ static PyObject *DependencyGetParentVer(PyObject *Self,void*) { pkgCache::DepIterator &Dep = GetCpp(Self); PyObject *Owner = GetOwner(Self); - return CppOwnedPyObject_NEW(Owner,&VersionType, + return CppOwnedPyObject_NEW(Owner,&PyVersion_Type, Dep.ParentVer()); } @@ -1179,7 +1179,7 @@ static PyObject *DependencyGetParentPkg(PyObject *Self,void*) { pkgCache::DepIterator &Dep = GetCpp(Self); PyObject *Owner = GetOwner(Self); - return CppOwnedPyObject_NEW(Owner,&PackageType, + return CppOwnedPyObject_NEW(Owner,&PyPackage_Type, Dep.ParentPkg()); } @@ -1222,7 +1222,7 @@ static PyGetSetDef DependencyGetSet[] = { }; -PyTypeObject DependencyType = +PyTypeObject PyDependency_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.Dependency", // tp_name @@ -1293,7 +1293,7 @@ static PyObject *RDepListItem(PyObject *iSelf,Py_ssize_t Index) } return CppOwnedPyObject_NEW(GetOwner(iSelf), - &DependencyType,Self.Iter); + &PyDependency_Type,Self.Iter); } static PySequenceMethods RDepListSeq = @@ -1307,7 +1307,7 @@ static PySequenceMethods RDepListSeq = 0 // assign slice }; -PyTypeObject RDepListType = +PyTypeObject PyDependencyList_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.DependencyList", // tp_name @@ -1343,6 +1343,6 @@ PyObject *TmpGetCache(PyObject *Self,PyObject *Args) { PyErr_WarnEx(PyExc_DeprecationWarning, "apt_pkg.GetCache() is deprecated. " "Please see apt_pkg.Cache() for the replacement.", 1); - return PkgCacheNew(&PkgCacheType,Args,0); + return PkgCacheNew(&PyCache_Type,Args,0); } #endif diff --git a/python/cdrom.cc b/python/cdrom.cc index b5b87758..84d7179f 100644 --- a/python/cdrom.cc +++ b/python/cdrom.cc @@ -77,7 +77,7 @@ static PyObject *PkgCdromNew(PyTypeObject *type,PyObject *Args,PyObject *kwds) } -PyTypeObject PkgCdromType = +PyTypeObject PyCdrom_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.Cdrom", // tp_name @@ -126,7 +126,7 @@ PyObject *GetCdrom(PyObject *Self,PyObject *Args) { PyErr_WarnEx(PyExc_DeprecationWarning, "apt_pkg.GetCdrom() is deprecated. " "Please see apt_pkg.Cdrom() for the replacement.", 1); - return PkgCdromNew(&PkgCdromType,Args,0); + return PkgCdromNew(&PyCdrom_Type,Args,0); } #endif diff --git a/python/configuration.cc b/python/configuration.cc index 07f55957..c7d7d796 100644 --- a/python/configuration.cc +++ b/python/configuration.cc @@ -49,7 +49,7 @@ void CnfSubFree(PyObject *Obj) /* */ static inline Configuration &GetSelf(PyObject *Obj) { - if (Obj->ob_type == &ConfigurationPtrType) + if (Obj->ob_type == &PyConfigurationPtr_Type) return *GetCpp(Obj); return GetCpp(Obj); } @@ -161,8 +161,8 @@ static PyObject *CnfSubTree(PyObject *Self,PyObject *Args) } // Create a new sub configuration. - SubConfiguration *New = (SubConfiguration*)(&ConfigurationSubType) - ->tp_alloc(&ConfigurationSubType,0); + SubConfiguration *New = (SubConfiguration*)(&PyConfigurationSub_Type) + ->tp_alloc(&PyConfigurationSub_Type,0); new (&New->Object) Configuration(Itm); New->Owner = Self; Py_INCREF(Self); @@ -501,7 +501,7 @@ static PyObject *CnfNew(PyTypeObject *type, PyObject *args, PyObject *kwds) { // Type for a Normal Configuration object static PySequenceMethods ConfigurationSeq = {0,0,0,0,0,0,0,CnfContains,0,0}; static PyMappingMethods ConfigurationMap = {0,CnfMap,CnfMapSet}; -PyTypeObject ConfigurationType = +PyTypeObject PyConfiguration_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.Configuration", // tp_name @@ -545,7 +545,7 @@ PyTypeObject ConfigurationType = CnfNew, // tp_new }; -PyTypeObject ConfigurationPtrType = +PyTypeObject PyConfigurationPtr_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.ConfigurationPtr", // tp_name @@ -578,10 +578,10 @@ PyTypeObject ConfigurationPtrType = CnfMethods, // tp_methods 0, // tp_members 0, // tp_getset - &ConfigurationType, // tp_base + &PyConfiguration_Type, // tp_base }; -PyTypeObject ConfigurationSubType = +PyTypeObject PyConfigurationSub_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.ConfigurationSub", // tp_name @@ -614,6 +614,6 @@ PyTypeObject ConfigurationSubType = CnfMethods, // tp_methods 0, // tp_members 0, // tp_getset - &ConfigurationType, // tp_base + &PyConfiguration_Type, // tp_base }; diff --git a/python/depcache.cc b/python/depcache.cc index 68ca3a3b..2d72a82a 100644 --- a/python/depcache.cc +++ b/python/depcache.cc @@ -190,8 +190,8 @@ static PyObject *PkgDepCacheSetCandidateVer(PyObject *Self,PyObject *Args) PyObject *PackageObj; PyObject *VersionObj; if (PyArg_ParseTuple(Args,"O!O!", - &PackageType, &PackageObj, - &VersionType, &VersionObj) == 0) + &PyPackage_Type, &PackageObj, + &PyVersion_Type, &VersionObj) == 0) return 0; pkgCache::VerIterator &I = GetCpp(VersionObj); @@ -208,7 +208,7 @@ static PyObject *PkgDepCacheGetCandidateVer(PyObject *Self,PyObject *Args) pkgDepCache *depcache = GetCpp(Self); PyObject *PackageObj; PyObject *CandidateObj; - if (PyArg_ParseTuple(Args,"O!",&PackageType,&PackageObj) == 0) + if (PyArg_ParseTuple(Args,"O!",&PyPackage_Type,&PackageObj) == 0) return 0; pkgCache::PkgIterator &Pkg = GetCpp(PackageObj); @@ -219,7 +219,7 @@ static PyObject *PkgDepCacheGetCandidateVer(PyObject *Self,PyObject *Args) Py_INCREF(Py_None); return Py_None; } - CandidateObj = CppOwnedPyObject_NEW(PackageObj,&VersionType,I); + CandidateObj = CppOwnedPyObject_NEW(PackageObj,&PyVersion_Type,I); return CandidateObj; } @@ -300,7 +300,7 @@ static PyObject *PkgDepCacheMarkKeep(PyObject *Self,PyObject *Args) pkgDepCache *depcache = GetCpp(Self); PyObject *PackageObj; - if (PyArg_ParseTuple(Args,"O!",&PackageType,&PackageObj) == 0) + if (PyArg_ParseTuple(Args,"O!",&PyPackage_Type,&PackageObj) == 0) return 0; pkgCache::PkgIterator &Pkg = GetCpp(PackageObj); @@ -316,7 +316,7 @@ static PyObject *PkgDepCacheSetReInstall(PyObject *Self,PyObject *Args) PyObject *PackageObj; char value = 0; - if (PyArg_ParseTuple(Args,"O!b",&PackageType,&PackageObj, &value) == 0) + if (PyArg_ParseTuple(Args,"O!b",&PyPackage_Type,&PackageObj, &value) == 0) return 0; pkgCache::PkgIterator &Pkg = GetCpp(PackageObj); @@ -333,7 +333,7 @@ static PyObject *PkgDepCacheMarkDelete(PyObject *Self,PyObject *Args) PyObject *PackageObj; char purge = 0; - if (PyArg_ParseTuple(Args,"O!|b",&PackageType,&PackageObj, &purge) == 0) + if (PyArg_ParseTuple(Args,"O!|b",&PyPackage_Type,&PackageObj, &purge) == 0) return 0; pkgCache::PkgIterator &Pkg = GetCpp(PackageObj); @@ -351,7 +351,7 @@ static PyObject *PkgDepCacheMarkInstall(PyObject *Self,PyObject *Args) PyObject *PackageObj; char autoInst=1; char fromUser=1; - if (PyArg_ParseTuple(Args,"O!|bb",&PackageType,&PackageObj, + if (PyArg_ParseTuple(Args,"O!|bb",&PyPackage_Type,&PackageObj, &autoInst, &fromUser) == 0) return 0; @@ -370,7 +370,7 @@ static PyObject *PkgDepCacheMarkAuto(PyObject *Self,PyObject *Args) PyObject *PackageObj; char value = 0; - if (PyArg_ParseTuple(Args,"O!b",&PackageType,&PackageObj, &value) == 0) + if (PyArg_ParseTuple(Args,"O!b",&PyPackage_Type,&PackageObj, &value) == 0) return 0; pkgCache::PkgIterator &Pkg = GetCpp(PackageObj); @@ -386,7 +386,7 @@ static PyObject *PkgDepCacheIsUpgradable(PyObject *Self,PyObject *Args) pkgDepCache *depcache = GetCpp(Self); PyObject *PackageObj; - if (PyArg_ParseTuple(Args,"O!",&PackageType,&PackageObj) == 0) + if (PyArg_ParseTuple(Args,"O!",&PyPackage_Type,&PackageObj) == 0) return 0; pkgCache::PkgIterator &Pkg = GetCpp(PackageObj); @@ -400,7 +400,7 @@ static PyObject *PkgDepCacheIsGarbage(PyObject *Self,PyObject *Args) pkgDepCache *depcache = GetCpp(Self); PyObject *PackageObj; - if (PyArg_ParseTuple(Args,"O!",&PackageType,&PackageObj) == 0) + if (PyArg_ParseTuple(Args,"O!",&PyPackage_Type,&PackageObj) == 0) return 0; pkgCache::PkgIterator &Pkg = GetCpp(PackageObj); @@ -414,7 +414,7 @@ static PyObject *PkgDepCacheIsAutoInstalled(PyObject *Self,PyObject *Args) pkgDepCache *depcache = GetCpp(Self); PyObject *PackageObj; - if (PyArg_ParseTuple(Args,"O!",&PackageType,&PackageObj) == 0) + if (PyArg_ParseTuple(Args,"O!",&PyPackage_Type,&PackageObj) == 0) return 0; pkgCache::PkgIterator &Pkg = GetCpp(PackageObj); @@ -428,7 +428,7 @@ static PyObject *PkgDepCacheIsNowBroken(PyObject *Self,PyObject *Args) pkgDepCache *depcache = GetCpp(Self); PyObject *PackageObj; - if (PyArg_ParseTuple(Args,"O!",&PackageType,&PackageObj) == 0) + if (PyArg_ParseTuple(Args,"O!",&PyPackage_Type,&PackageObj) == 0) return 0; pkgCache::PkgIterator &Pkg = GetCpp(PackageObj); @@ -442,7 +442,7 @@ static PyObject *PkgDepCacheIsInstBroken(PyObject *Self,PyObject *Args) pkgDepCache *depcache = GetCpp(Self); PyObject *PackageObj; - if (PyArg_ParseTuple(Args,"O!",&PackageType,&PackageObj) == 0) + if (PyArg_ParseTuple(Args,"O!",&PyPackage_Type,&PackageObj) == 0) return 0; pkgCache::PkgIterator &Pkg = GetCpp(PackageObj); @@ -457,7 +457,7 @@ static PyObject *PkgDepCacheMarkedInstall(PyObject *Self,PyObject *Args) pkgDepCache *depcache = GetCpp(Self); PyObject *PackageObj; - if (PyArg_ParseTuple(Args,"O!",&PackageType,&PackageObj) == 0) + if (PyArg_ParseTuple(Args,"O!",&PyPackage_Type,&PackageObj) == 0) return 0; pkgCache::PkgIterator &Pkg = GetCpp(PackageObj); @@ -472,7 +472,7 @@ static PyObject *PkgDepCacheMarkedUpgrade(PyObject *Self,PyObject *Args) pkgDepCache *depcache = GetCpp(Self); PyObject *PackageObj; - if (PyArg_ParseTuple(Args,"O!",&PackageType,&PackageObj) == 0) + if (PyArg_ParseTuple(Args,"O!",&PyPackage_Type,&PackageObj) == 0) return 0; pkgCache::PkgIterator &Pkg = GetCpp(PackageObj); @@ -486,7 +486,7 @@ static PyObject *PkgDepCacheMarkedDelete(PyObject *Self,PyObject *Args) pkgDepCache *depcache = GetCpp(Self); PyObject *PackageObj; - if (PyArg_ParseTuple(Args,"O!",&PackageType,&PackageObj) == 0) + if (PyArg_ParseTuple(Args,"O!",&PyPackage_Type,&PackageObj) == 0) return 0; pkgCache::PkgIterator &Pkg = GetCpp(PackageObj); @@ -500,7 +500,7 @@ static PyObject *PkgDepCacheMarkedKeep(PyObject *Self,PyObject *Args) pkgDepCache *depcache = GetCpp(Self); PyObject *PackageObj; - if (PyArg_ParseTuple(Args,"O!",&PackageType,&PackageObj) == 0) + if (PyArg_ParseTuple(Args,"O!",&PyPackage_Type,&PackageObj) == 0) return 0; pkgCache::PkgIterator &Pkg = GetCpp(PackageObj); @@ -514,7 +514,7 @@ static PyObject *PkgDepCacheMarkedDowngrade(PyObject *Self,PyObject *Args) pkgDepCache *depcache = GetCpp(Self); PyObject *PackageObj; - if (PyArg_ParseTuple(Args,"O!",&PackageType,&PackageObj) == 0) + if (PyArg_ParseTuple(Args,"O!",&PyPackage_Type,&PackageObj) == 0) return 0; pkgCache::PkgIterator &Pkg = GetCpp(PackageObj); @@ -528,7 +528,7 @@ static PyObject *PkgDepCacheMarkedReinstall(PyObject *Self,PyObject *Args) pkgDepCache *depcache = GetCpp(Self); PyObject *PackageObj; - if (PyArg_ParseTuple(Args,"O!",&PackageType,&PackageObj) == 0) + if (PyArg_ParseTuple(Args,"O!",&PyPackage_Type,&PackageObj) == 0) return 0; pkgCache::PkgIterator &Pkg = GetCpp(PackageObj); @@ -656,7 +656,7 @@ static PyObject *PkgDepCacheNew(PyTypeObject *type,PyObject *Args,PyObject *kwds { PyObject *Owner; static char *kwlist[] = {"cache", 0}; - if (PyArg_ParseTupleAndKeywords(Args,kwds,"O!",kwlist,&PkgCacheType, + if (PyArg_ParseTupleAndKeywords(Args,kwds,"O!",kwlist,&PyCache_Type, &Owner) == 0) return 0; @@ -680,7 +680,7 @@ static PyObject *PkgDepCacheNew(PyTypeObject *type,PyObject *Args,PyObject *kwds static char *doc_PkgDepCache = "DepCache(cache) -> DepCache() object\n\n" "A DepCache() holds extra information on the state of the packages.\n\n" "The parameter *cache* refers to an apt_pkg.Cache() object."; -PyTypeObject PkgDepCacheType = +PyTypeObject PyDepCache_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.DepCache", // tp_name @@ -730,7 +730,7 @@ PyObject *GetDepCache(PyObject *Self,PyObject *Args) { PyErr_WarnEx(PyExc_DeprecationWarning,"apt_pkg.GetDepCache() is deprecated" ". Please see apt_pkg.DepCache() for the replacement.",1); - return PkgDepCacheNew(&PkgDepCacheType,Args,0); + return PkgDepCacheNew(&PyDepCache_Type,Args,0); } #endif @@ -745,7 +745,7 @@ static PyObject *PkgProblemResolverNew(PyTypeObject *type,PyObject *Args,PyObjec { PyObject *Owner; static char *kwlist[] = {"depcache",0}; - if (PyArg_ParseTupleAndKeywords(Args,kwds,"O!",kwlist,&PkgDepCacheType, + if (PyArg_ParseTupleAndKeywords(Args,kwds,"O!",kwlist,&PyDepCache_Type, &Owner) == 0) return 0; @@ -765,7 +765,7 @@ PyObject *GetPkgProblemResolver(PyObject *Self,PyObject *Args) { PyErr_WarnEx(PyExc_DeprecationWarning, "apt_pkg.GetPkgProblemResolver() is" " deprecated. Please see apt_pkg.ProblemResolver() for the " "replacement.", 1); - return PkgProblemResolverNew(&PkgProblemResolverType,Args,0); + return PkgProblemResolverNew(&PyProblemResolver_Type,Args,0); } #endif @@ -803,7 +803,7 @@ static PyObject *PkgProblemResolverProtect(PyObject *Self,PyObject *Args) { pkgProblemResolver *fixer = GetCpp(Self); PyObject *PackageObj; - if (PyArg_ParseTuple(Args,"O!",&PackageType,&PackageObj) == 0) + if (PyArg_ParseTuple(Args,"O!",&PyPackage_Type,&PackageObj) == 0) return 0; pkgCache::PkgIterator &Pkg = GetCpp(PackageObj); fixer->Protect(Pkg); @@ -815,7 +815,7 @@ static PyObject *PkgProblemResolverRemove(PyObject *Self,PyObject *Args) { pkgProblemResolver *fixer = GetCpp(Self); PyObject *PackageObj; - if (PyArg_ParseTuple(Args,"O!",&PackageType,&PackageObj) == 0) + if (PyArg_ParseTuple(Args,"O!",&PyPackage_Type,&PackageObj) == 0) return 0; pkgCache::PkgIterator &Pkg = GetCpp(PackageObj); fixer->Remove(Pkg); @@ -827,7 +827,7 @@ static PyObject *PkgProblemResolverClear(PyObject *Self,PyObject *Args) { pkgProblemResolver *fixer = GetCpp(Self); PyObject *PackageObj; - if (PyArg_ParseTuple(Args,"O!",&PackageType,&PackageObj) == 0) + if (PyArg_ParseTuple(Args,"O!",&PyPackage_Type,&PackageObj) == 0) return 0; pkgCache::PkgIterator &Pkg = GetCpp(PackageObj); fixer->Clear(Pkg); @@ -867,7 +867,7 @@ static PyMethodDef PkgProblemResolverMethods[] = {} }; -PyTypeObject PkgProblemResolverType = +PyTypeObject PyProblemResolver_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.ProblemResolver", // tp_name @@ -953,7 +953,7 @@ static PyObject *PkgActionGroupNew(PyTypeObject *type,PyObject *Args,PyObject *k { PyObject *Owner; static char *kwlist[] = {"depcache", 0}; - if (PyArg_ParseTupleAndKeywords(Args,kwds,"O!",kwlist,&PkgDepCacheType, + if (PyArg_ParseTupleAndKeywords(Args,kwds,"O!",kwlist,&PyDepCache_Type, &Owner) == 0) return 0; @@ -983,7 +983,7 @@ static char *doc_PkgActionGroup = "ActionGroup(depcache)\n\n" "automatically released from the cache."; -PyTypeObject PkgActionGroupType = +PyTypeObject PyActionGroup_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.ActionGroup", // tp_name @@ -1034,7 +1034,7 @@ PyObject *GetPkgActionGroup(PyObject *Self,PyObject *Args) PyErr_WarnEx(PyExc_DeprecationWarning, "apt_pkg.GetPkgActionGroup() is " "deprecated. Please see apt_pkg.ActionGroup() for the " "replacement.", 1); - return PkgActionGroupNew(&PkgActionGroupType,Args,0); + return PkgActionGroupNew(&PyActionGroup_Type,Args,0); } #endif diff --git a/python/indexfile.cc b/python/indexfile.cc index f2180cd7..7bf646d0 100644 --- a/python/indexfile.cc +++ b/python/indexfile.cc @@ -88,7 +88,7 @@ static PyGetSetDef PackageIndexFileGetSet[] = { {} }; -PyTypeObject PackageIndexFileType = +PyTypeObject PyPackageIndexFile_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.PackageIndexFile", // tp_name diff --git a/python/metaindex.cc b/python/metaindex.cc index 195394d6..d67c0ada 100644 --- a/python/metaindex.cc +++ b/python/metaindex.cc @@ -38,7 +38,7 @@ static PyObject *MetaIndexGetIndexFiles(PyObject *Self,void*) { I != indexFiles->end(); I++) { CppOwnedPyObject *Obj; - Obj = CppOwnedPyObject_NEW(Self, &PackageIndexFileType,*I); + Obj = CppOwnedPyObject_NEW(Self, &PyPackageIndexFile_Type,*I); // Do not delete pkgIndexFile*, they are managed by metaIndex. Obj->NoDelete = true; PyList_Append(List,Obj); @@ -73,7 +73,7 @@ static PyObject *MetaIndexRepr(PyObject *Self) return PyString_FromString(S); } -PyTypeObject MetaIndexType = +PyTypeObject PyMetaIndex_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.MetaIndex", // tp_name diff --git a/python/pkgmanager.cc b/python/pkgmanager.cc index 9e9cc32d..f4f84a2b 100644 --- a/python/pkgmanager.cc +++ b/python/pkgmanager.cc @@ -24,7 +24,7 @@ static PyObject *PkgManagerNew(PyTypeObject *type,PyObject *Args,PyObject *kwds) { PyObject *Owner; char *kwlist[] = {"depcache",0}; - if (PyArg_ParseTupleAndKeywords(Args,kwds,"O!",kwlist,&PkgDepCacheType, + if (PyArg_ParseTupleAndKeywords(Args,kwds,"O!",kwlist,&PyDepCache_Type, &Owner) == 0) return 0; @@ -42,7 +42,7 @@ PyObject *GetPkgManager(PyObject *Self,PyObject *Args) PyErr_WarnEx(PyExc_DeprecationWarning, "apt_pkg.GetPackageManager() is " "deprecated. Please see apt_pkg.PackageManager() for the " "replacement.", 1); - return PkgManagerNew(&PkgManagerType,Args,0); + return PkgManagerNew(&PyPackageManager_Type,Args,0); } #endif @@ -53,9 +53,9 @@ static PyObject *PkgManagerGetArchives(PyObject *Self,PyObject *Args) PyObject *fetcher, *list, *recs; if (PyArg_ParseTuple(Args, "O!O!O!", - &PkgAcquireType,&fetcher, - &PkgSourceListType, &list, - &PkgRecordsType, &recs) == 0) + &PyAcquire_Type,&fetcher, + &PySourceList_Type, &list, + &PyPackageRecords_Type, &recs) == 0) return 0; pkgAcquire *s_fetcher = GetCpp(fetcher); @@ -131,7 +131,7 @@ static PyGetSetDef PkgManagerGetSet[] = { {} }; -PyTypeObject PkgManagerType = +PyTypeObject PyPackageManager_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.PackageManager", // tp_name diff --git a/python/pkgrecords.cc b/python/pkgrecords.cc index 886bdb58..d34ba0d2 100644 --- a/python/pkgrecords.cc +++ b/python/pkgrecords.cc @@ -27,7 +27,7 @@ static PyObject *PkgRecordsLookup(PyObject *Self,PyObject *Args) PyObject *PkgFObj; long int Index; - if (PyArg_ParseTuple(Args,"(O!l)",&PackageFileType,&PkgFObj,&Index) == 0) + if (PyArg_ParseTuple(Args,"(O!l)",&PyPackageFile_Type,&PkgFObj,&Index) == 0) return 0; // Get the index and check to make sure it is reasonable @@ -153,7 +153,7 @@ static PyObject *PkgRecordsNew(PyTypeObject *type,PyObject *Args,PyObject *kwds) { PyObject *Owner; char *kwlist[] = {"cache",0}; - if (PyArg_ParseTupleAndKeywords(Args,kwds,"O!",kwlist,&PkgCacheType, + if (PyArg_ParseTupleAndKeywords(Args,kwds,"O!",kwlist,&PyCache_Type, &Owner) == 0) return 0; @@ -161,7 +161,7 @@ static PyObject *PkgRecordsNew(PyTypeObject *type,PyObject *Args,PyObject *kwds) GetCpp(Owner))); } -PyTypeObject PkgRecordsType = +PyTypeObject PyPackageRecords_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.PackageRecords", // tp_name @@ -215,6 +215,6 @@ PyObject *GetPkgRecords(PyObject *Self,PyObject *Args) PyErr_WarnEx(PyExc_DeprecationWarning, "apt_pkg.GetPkgRecords() is " "deprecated. Please see apt_pkg.Records() for the " "replacement.", 1); - return PkgRecordsNew(&PkgRecordsType,Args,0); + return PkgRecordsNew(&PyPackageRecords_Type,Args,0); } #endif diff --git a/python/pkgsrcrecords.cc b/python/pkgsrcrecords.cc index 99711585..fbc9a293 100644 --- a/python/pkgsrcrecords.cc +++ b/python/pkgsrcrecords.cc @@ -124,7 +124,7 @@ static PyObject *PkgSrcRecordsGetIndex(PyObject *Self,void*) { return 0; const pkgIndexFile &tmp = Struct.Last->Index(); CppOwnedPyObject *PyObj; - PyObj = CppOwnedPyObject_NEW(Self,&PackageIndexFileType, + PyObj = CppOwnedPyObject_NEW(Self,&PyPackageIndexFile_Type, (pkgIndexFile*)&tmp); // Do not delete the pkgIndexFile*, it is managed by PkgSrcRecords::Parser. PyObj->NoDelete=true; @@ -255,7 +255,7 @@ static PyObject *PkgSrcRecordsNew(PyTypeObject *type,PyObject *args,PyObject *kw return HandleErrors(CppPyObject_NEW(type)); } -PyTypeObject PkgSrcRecordsType = +PyTypeObject PySourceRecords_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.SourceRecords", // tp_name @@ -310,6 +310,6 @@ PyObject *GetPkgSrcRecords(PyObject *Self,PyObject *Args) if (PyArg_ParseTuple(Args,"") == 0) return 0; - return HandleErrors(CppPyObject_NEW(&PkgSrcRecordsType)); + return HandleErrors(CppPyObject_NEW(&PySourceRecords_Type)); } #endif diff --git a/python/policy.cc b/python/policy.cc index d086c4fc..faf53b38 100644 --- a/python/policy.cc +++ b/python/policy.cc @@ -29,7 +29,7 @@ static PyObject *Policy_NEW(PyTypeObject *type,PyObject *Args, char *kwlist[] = {"cache", NULL}; if (PyArg_ParseTupleAndKeywords(Args, kwds, "O", kwlist, &cache) == 0) return 0; - if (!PyObject_TypeCheck(cache, &PkgCacheType)) { + if (!PyObject_TypeCheck(cache, &PyCache_Type)) { PyErr_SetString(PyExc_TypeError,"`cache` must be a apt_pkg.Cache()."); return 0; } @@ -43,7 +43,7 @@ static char *Policy_GetPriority_doc = "get_priority(package: apt_pkg.Package)" PyObject *Policy_GetPriority(PyObject *self, PyObject *arg) { pkgPolicy *policy = GetCpp(self); - if (PyObject_TypeCheck(arg, &PackageType)) { + if (PyObject_TypeCheck(arg, &PyPackage_Type)) { pkgCache::PkgIterator pkg = GetCpp(arg); return Py_BuildValue("i", policy->GetPriority(pkg)); } else { @@ -57,11 +57,11 @@ static char *Policy_GetCandidateVer_doc = "get_match(package: apt_pkg.Package)" "Get the best package for the job."; PyObject *Policy_GetCandidateVer(PyObject *self, PyObject *arg) { - if (PyObject_TypeCheck(arg, &PackageType)) { + if (PyObject_TypeCheck(arg, &PyPackage_Type)) { pkgPolicy *policy = GetCpp(self); pkgCache::PkgIterator pkg = GetCpp(arg); pkgCache::VerIterator ver = policy->GetCandidateVer(pkg); - return CppOwnedPyObject_NEW(arg,&VersionType, + return CppOwnedPyObject_NEW(arg,&PyVersion_Type, ver); } else { PyErr_SetString(PyExc_TypeError,"Argument must be of Package()."); @@ -74,14 +74,14 @@ static char *Policy_GetMatch_doc = "get_match(package: apt_pkg.Package) -> " "Return a matching version for the given package."; static PyObject *Policy_GetMatch(PyObject *self, PyObject *arg) { - if (PyObject_TypeCheck(arg, &PackageType) == 0) { + if (PyObject_TypeCheck(arg, &PyPackage_Type) == 0) { PyErr_SetString(PyExc_TypeError,"Argument must be of Package()."); return 0; } pkgPolicy *policy = GetCpp(self); pkgCache::PkgIterator pkg = GetCpp(arg); pkgCache::VerIterator ver = policy->GetMatch(pkg); - return CppOwnedPyObject_NEW(arg,&VersionType,ver); + return CppOwnedPyObject_NEW(arg,&PyVersion_Type,ver); } static char *Policy_ReadPinFile_doc = "read_pinfile(filename: str) -> bool\n\n" diff --git a/python/sourcelist.cc b/python/sourcelist.cc index beb249dc..e86f7fd3 100644 --- a/python/sourcelist.cc +++ b/python/sourcelist.cc @@ -28,20 +28,20 @@ static PyObject *PkgSourceListFindIndex(PyObject *Self,PyObject *Args) PyObject *pyPkgFileIter; CppOwnedPyObject *pyPkgIndexFile; - if (PyArg_ParseTuple(Args, "O!", &PackageFileType,&pyPkgFileIter) == 0) + if (PyArg_ParseTuple(Args, "O!", &PyPackageFile_Type,&pyPkgFileIter) == 0) return 0; pkgCache::PkgFileIterator &i = GetCpp(pyPkgFileIter); pkgIndexFile *index; if(list->FindIndex(i, index)) { - pyPkgIndexFile = CppOwnedPyObject_NEW(pyPkgFileIter,&PackageIndexFileType,index); + pyPkgIndexFile = CppOwnedPyObject_NEW(pyPkgFileIter,&PyPackageIndexFile_Type,index); // Do not delete the pkgIndexFile*, it is managed by pkgSourceList. pyPkgIndexFile->NoDelete = true; return pyPkgIndexFile; } - //&PackageIndexFileType,&pyPkgIndexFile) + //&PyPackageIndexFile_Type,&pyPkgIndexFile) Py_INCREF(Py_None); return Py_None; @@ -63,7 +63,7 @@ static PyObject *PkgSourceListGetIndexes(PyObject *Self,PyObject *Args) PyObject *pyFetcher; char all = 0; - if (PyArg_ParseTuple(Args, "O!|b",&PkgAcquireType,&pyFetcher, &all) == 0) + if (PyArg_ParseTuple(Args, "O!|b",&PyAcquire_Type,&pyFetcher, &all) == 0) return 0; pkgAcquire *fetcher = GetCpp(pyFetcher); @@ -93,7 +93,7 @@ static PyObject *PkgSourceListGetList(PyObject *Self,void*) I != list->end(); I++) { CppOwnedPyObject *Obj; - Obj = CppOwnedPyObject_NEW(Self, &MetaIndexType,*I); + Obj = CppOwnedPyObject_NEW(Self, &PyMetaIndex_Type,*I); // Never delete metaIndex*, they are managed by the pkgSourceList. Obj->NoDelete = true; PyList_Append(List,Obj); @@ -118,7 +118,7 @@ static PyObject *PkgSourceListNew(PyTypeObject *type,PyObject *args,PyObject *kw return CppPyObject_NEW(type,new pkgSourceList()); } -PyTypeObject PkgSourceListType = +PyTypeObject PySourceList_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.SourceList", // tp_name @@ -168,6 +168,6 @@ PyObject *GetPkgSourceList(PyObject *Self,PyObject *Args) PyErr_WarnEx(PyExc_DeprecationWarning, "apt_pkg.GetPkgSourceList() is " "deprecated. Please see apt_pkg.SourceList() for the " "replacement.", 1); - return PkgSourceListNew(&PkgSourceListType,Args,0); + return PkgSourceListNew(&PySourceList_Type,Args,0); } #endif diff --git a/python/tag.cc b/python/tag.cc index 2b71517d..573e8ce2 100644 --- a/python/tag.cc +++ b/python/tag.cc @@ -290,7 +290,7 @@ PyObject *ParseSection(PyObject *self,PyObject *Args) PyErr_WarnEx(PyExc_DeprecationWarning, "apt_pkg.ParseSection() is " "deprecated. Please see apt_pkg.TagSection() for the " "replacement.", 1); - return TagSecNew(&TagSecType,Args,0); + return TagSecNew(&PyTagSection_Type,Args,0); } #endif /*}}}*/ @@ -315,7 +315,7 @@ static PyObject *TagFileNew(PyTypeObject *type,PyObject *Args,PyObject *kwds) new (&New->Object) pkgTagFile(&New->Fd); // Create the section - New->Section = (TagSecData*)(&TagSecType)->tp_alloc(&TagSecType, 0); + New->Section = (TagSecData*)(&PyTagSection_Type)->tp_alloc(&PyTagSection_Type, 0); new (&New->Section->Object) pkgTagSection(); New->Section->Owner = New; Py_INCREF(New->Section->Owner); @@ -329,7 +329,7 @@ PyObject *ParseTagFile(PyObject *self,PyObject *Args) { PyErr_WarnEx(PyExc_DeprecationWarning, "apt_pkg.ParseTagFile() is " "deprecated. Please see apt_pkg.TagFile() for the " "replacement.", 1); - return TagFileNew(&TagFileType,Args,0); + return TagFileNew(&PyTagFile_Type,Args,0); } #endif /*}}}*/ @@ -357,7 +357,7 @@ PyObject *RewriteSection(PyObject *self,PyObject *Args) PyObject *Section; PyObject *Order; PyObject *Rewrite; - if (PyArg_ParseTuple(Args,"O!O!O!",&TagSecType,&Section, + if (PyArg_ParseTuple(Args,"O!O!O!",&PyTagSection_Type,&Section, &PyList_Type,&Order,&PyList_Type,&Rewrite) == 0) return 0; @@ -436,7 +436,7 @@ static char *doc_TagSec = "TagSection(text) -> Create a new object.\n\n" "header sections, like those in debian/control or Packages files.\n\n" "TagSection() behave like read-only dictionaries and also provide access\n" "to the functions provided by the C++ class (e.g. Find)"; -PyTypeObject TagSecType = +PyTypeObject PyTagSection_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.TagSection", // tp_name @@ -522,7 +522,7 @@ static char *doc_TagFile = "TagFile(file) -> TagFile() object. \n\n" "a file descriptor (an integer)"; // Type for a Tag File -PyTypeObject TagFileType = +PyTypeObject PyTagFile_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.TagFile", // tp_name -- cgit v1.2.3 From 8e3c0bf27b47835069a1e78c6dc4180c6efa883b Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Mon, 13 Jul 2009 14:33:39 +0200 Subject: python/apt_pkgmodule.cc: ParseDepends_old only needed in COMPAT_0_7. --- python/apt_pkgmodule.cc | 2 ++ 1 file changed, 2 insertions(+) (limited to 'python') diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index d236820a..3146298b 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -167,6 +167,7 @@ static PyObject *ParseSrcDepends(PyObject *Self,PyObject *Args) { return RealParseDepends(Self,Args,true); } +#ifdef COMPAT_0_7 static PyObject *ParseDepends_old(PyObject *Self,PyObject *Args) { return RealParseDepends(Self,Args,false, true); @@ -175,6 +176,7 @@ static PyObject *ParseSrcDepends_old(PyObject *Self,PyObject *Args) { return RealParseDepends(Self,Args,true, true); } +#endif /*}}}*/ // md5sum - Compute the md5sum of a file or string /*{{{*/ // --------------------------------------------------------------------- -- cgit v1.2.3 From f883d8f68487728946fd12bcfaa6a7e234288f4c Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Mon, 13 Jul 2009 15:14:32 +0200 Subject: python/apt_pkgmodule.cc, python/apt_instmodule.cc: Remove useless state. This was copied over from "Porting Extension Modules to 3.0", and is not really needed. --- python/apt_instmodule.cc | 27 ++++++--------------------- python/apt_pkgmodule.cc | 29 +++++++---------------------- 2 files changed, 13 insertions(+), 43 deletions(-) (limited to 'python') diff --git a/python/apt_instmodule.cc b/python/apt_instmodule.cc index 84479fcb..5aca4e00 100644 --- a/python/apt_instmodule.cc +++ b/python/apt_instmodule.cc @@ -170,31 +170,16 @@ static PyMethodDef methods[] = }; #if PY_MAJOR_VERSION >= 3 -struct module_state { - PyObject *error; -}; -#define GETSTATE(m) ((struct module_state*)PyModule_GetState(m)) - -static int apt_inst_traverse(PyObject *m, visitproc visit, void *arg) { - Py_VISIT(GETSTATE(m)->error); - return 0; -} - -static int apt_inst_clear(PyObject *m) { - Py_CLEAR(GETSTATE(m)->error); - return 0; -} - static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "apt_inst", - NULL, - sizeof(struct module_state), + "Functions for working with packages and ar,tar archives (apt-inst)", + -1, methods, - NULL, - apt_inst_traverse, - apt_inst_clear, - NULL + 0, + 0, + 0, + 0 }; extern "C" PyObject * PyInit_apt_inst() diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index 3146298b..7ffe1236 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -522,32 +522,17 @@ static PyMethodDef methods[] = #if PY_MAJOR_VERSION >= 3 -struct module_state { - PyObject *error; -}; - -#define GETSTATE(m) ((struct module_state*)PyModule_GetState(m)) - -static int apt_inst_traverse(PyObject *m, visitproc visit, void *arg) { - Py_VISIT(GETSTATE(m)->error); - return 0; -} - -static int apt_inst_clear(PyObject *m) { - Py_CLEAR(GETSTATE(m)->error); - return 0; -} - static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "apt_pkg", - NULL, - sizeof(struct module_state), + "Classes and functions wrapping the apt-pkg library.\n\n" + "The apt_pkg module provides...", + -1, methods, - NULL, - apt_inst_traverse, - apt_inst_clear, - NULL + 0, + 0, + 0, + 0, }; #define INIT_ERROR return 0 -- cgit v1.2.3 From a0ebd7b076fc359dd1f2f892aa8e70ee4ef4de2a Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Mon, 13 Jul 2009 15:40:07 +0200 Subject: python/generic.h: Use PyBytes_AS_STRING instead of PyBytes_AsString in PyUnicode_AsString. --- python/generic.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'python') diff --git a/python/generic.h b/python/generic.h index 408529a5..639578c5 100644 --- a/python/generic.h +++ b/python/generic.h @@ -61,6 +61,7 @@ typedef int Py_ssize_t; // Compatibility for Python 2.5 and previous. #if (PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION <= 5) #define PyBytes_Check PyString_Check +#define PyBytes_AS_STRING PyString_AS_STRING #define PyBytes_AsString PyString_AsString #define PyBytes_AsStringAndSize PyString_AsStringAndSize #define PyVarObject_HEAD_INIT(type, size) PyObject_HEAD_INIT(type) size, @@ -78,7 +79,7 @@ static inline const char *PyUnicode_AsString(PyObject *op) { PyObject *bytes = PyUnicode_AsEncodedString(op,0,0); if (!bytes) return 0; - const char *result = PyBytes_AsString(bytes); + const char *result = PyBytes_AS_STRING(bytes); Py_DECREF(bytes); return result; } -- cgit v1.2.3 From 10abd1b8297b92e47ba9123ff7426f0913268f45 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Mon, 13 Jul 2009 16:03:04 +0200 Subject: python/apt_pkgmodule.cc: Add function name to ParseDepends and friends. --- python/apt_pkgmodule.cc | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) (limited to 'python') diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index 7ffe1236..cf232fa2 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -107,7 +107,8 @@ static char *doc_ParseDepends = "Match are returned.\n\n" "apt_pkg.Parse{,Src}Depends() are old forms which return >>,<< instead of >,<"; static PyObject *RealParseDepends(PyObject *Self,PyObject *Args, - bool ParseArchFlags, bool debStyle=false) + bool ParseArchFlags, string name, + bool debStyle=false) { string Package; string Version; @@ -117,7 +118,7 @@ static PyObject *RealParseDepends(PyObject *Self,PyObject *Args, const char *Stop; int Len; - if (PyArg_ParseTuple(Args,"s#",&Start,&Len) == 0) + if (PyArg_ParseTuple(Args,("s#:" + name).c_str(),&Start,&Len) == 0) return 0; Stop = Start + Len; PyObject *List = PyList_New(0); @@ -161,20 +162,20 @@ static PyObject *RealParseDepends(PyObject *Self,PyObject *Args, } static PyObject *ParseDepends(PyObject *Self,PyObject *Args) { - return RealParseDepends(Self,Args,false); + return RealParseDepends(Self, Args, false, "parse_depends"); } static PyObject *ParseSrcDepends(PyObject *Self,PyObject *Args) { - return RealParseDepends(Self,Args,true); + return RealParseDepends(Self, Args, true, "parse_src_depends"); } #ifdef COMPAT_0_7 static PyObject *ParseDepends_old(PyObject *Self,PyObject *Args) { - return RealParseDepends(Self,Args,false, true); + return RealParseDepends(Self, Args, false, "ParseDepends", true); } static PyObject *ParseSrcDepends_old(PyObject *Self,PyObject *Args) { - return RealParseDepends(Self,Args,true, true); + return RealParseDepends(Self, Args, true, "ParseSrcDepends", true); } #endif /*}}}*/ -- cgit v1.2.3 From f444dc5877a59869fef079309a7bb9b1aa0572e6 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Mon, 13 Jul 2009 16:12:09 +0200 Subject: python/apt_pkgmodule.cc: Fix build on Python 2.4 --- python/apt_pkgmodule.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'python') diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index cf232fa2..1a2980b8 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -118,7 +118,7 @@ static PyObject *RealParseDepends(PyObject *Self,PyObject *Args, const char *Stop; int Len; - if (PyArg_ParseTuple(Args,("s#:" + name).c_str(),&Start,&Len) == 0) + if (PyArg_ParseTuple(Args,(char *)("s#:" + name).c_str(),&Start,&Len) == 0) return 0; Stop = Start + Len; PyObject *List = PyList_New(0); -- cgit v1.2.3 From 320e896920fcb9f2ebc46aa3b2d9ce8e4acab83e Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Mon, 13 Jul 2009 16:12:50 +0200 Subject: python/apt_pkgmodule.cc: Remove all dependendy type constants, and cleanup. The dependency type constants have no use, because we do not export values anywhere. The cleanup moves all #ifdef COMPAT_0_7 together into one section. --- python/apt_pkgmodule.cc | 128 ++++++++++++++++-------------------------------- 1 file changed, 41 insertions(+), 87 deletions(-) (limited to 'python') diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index 1a2980b8..3f18f785 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -401,64 +401,32 @@ static PyObject *PkgSystemUnLock(PyObject *Self,PyObject *Args) static PyMethodDef methods[] = { // Constructors - #ifdef COMPAT_0_7 - {"newConfiguration",newConfiguration,METH_VARARGS,doc_newConfiguration}, - #endif {"init",Init,METH_VARARGS,doc_Init}, {"init_config",InitConfig,METH_VARARGS,doc_InitConfig}, {"init_system",InitSystem,METH_VARARGS,doc_InitSystem}, - #ifdef COMPAT_0_7 - {"InitConfig",InitConfig,METH_VARARGS,doc_InitConfig}, - {"InitSystem",InitSystem,METH_VARARGS,doc_InitSystem}, - #endif // Tag File - #ifdef COMPAT_0_7 - {"ParseSection",ParseSection,METH_VARARGS,doc_ParseSection}, - {"ParseTagFile",ParseTagFile,METH_VARARGS,doc_ParseTagFile}, - {"RewriteSection",RewriteSection,METH_VARARGS,doc_RewriteSection}, - #endif {"rewrite_section",RewriteSection,METH_VARARGS,doc_RewriteSection}, // Locking {"get_lock",GetLock,METH_VARARGS,doc_GetLock}, {"pkgsystem_lock",PkgSystemLock,METH_VARARGS,doc_PkgSystemLock}, {"pkgsystem_unlock",PkgSystemUnLock,METH_VARARGS,doc_PkgSystemUnLock}, - #ifdef COMPAT_0_7 - {"GetLock",GetLock,METH_VARARGS,doc_GetLock}, - {"PkgSystemLock",PkgSystemLock,METH_VARARGS,doc_PkgSystemLock}, - {"PkgSystemUnLock",PkgSystemUnLock,METH_VARARGS,doc_PkgSystemUnLock}, - #endif // Command line {"read_config_file",LoadConfig,METH_VARARGS,doc_LoadConfig}, {"read_config_dir",LoadConfigDir,METH_VARARGS,doc_LoadConfigDir}, {"read_config_file_isc",LoadConfigISC,METH_VARARGS,doc_LoadConfig}, {"parse_commandline",ParseCommandLine,METH_VARARGS,doc_ParseCommandLine}, - #ifdef COMPAT_0_7 - {"ReadConfigFile",LoadConfig,METH_VARARGS,doc_LoadConfig}, - {"ReadConfigDir",LoadConfigDir,METH_VARARGS,doc_LoadConfigDir}, - {"ReadConfigFileISC",LoadConfigISC,METH_VARARGS,doc_LoadConfig}, - {"ParseCommandLine",ParseCommandLine,METH_VARARGS,doc_ParseCommandLine}, - #endif // Versioning {"version_compare",VersionCompare,METH_VARARGS,doc_VersionCompare}, {"check_dep",CheckDep,METH_VARARGS,doc_CheckDep}, {"upstream_version",UpstreamVersion,METH_VARARGS,doc_UpstreamVersion}, - #ifdef COMPAT_0_7 - {"VersionCompare",VersionCompare,METH_VARARGS,doc_VersionCompare}, - {"CheckDep",CheckDep,METH_VARARGS,doc_CheckDep}, - {"UpstreamVersion",UpstreamVersion,METH_VARARGS,doc_UpstreamVersion}, - #endif // Depends {"parse_depends",ParseDepends,METH_VARARGS,doc_ParseDepends}, {"parse_src_depends",ParseSrcDepends,METH_VARARGS,doc_ParseDepends}, - #ifdef COMPAT_0_7 - {"ParseDepends",ParseDepends_old,METH_VARARGS,doc_ParseDepends}, - {"ParseSrcDepends",ParseSrcDepends_old,METH_VARARGS,doc_ParseDepends}, - #endif // Stuff {"md5sum",md5sum,METH_VARARGS,doc_md5sum}, @@ -476,7 +444,33 @@ static PyMethodDef methods[] = {"string_to_bool",StrStringToBool,METH_VARARGS,"StringToBool(String) -> int"}, {"time_rfc1123",StrTimeRFC1123,METH_VARARGS,"TimeRFC1123(int) -> String"}, {"str_to_time",StrStrToTime,METH_VARARGS,"StrToTime(String) -> Int"}, + + // DEPRECATED #ifdef COMPAT_0_7 + {"newConfiguration",newConfiguration,METH_VARARGS,doc_newConfiguration}, + {"InitConfig",InitConfig,METH_VARARGS,doc_InitConfig}, + {"InitSystem",InitSystem,METH_VARARGS,doc_InitSystem}, + + {"ParseSection",ParseSection,METH_VARARGS,doc_ParseSection}, + {"ParseTagFile",ParseTagFile,METH_VARARGS,doc_ParseTagFile}, + {"RewriteSection",RewriteSection,METH_VARARGS,doc_RewriteSection}, + + {"GetLock",GetLock,METH_VARARGS,doc_GetLock}, + {"PkgSystemLock",PkgSystemLock,METH_VARARGS,doc_PkgSystemLock}, + {"PkgSystemUnLock",PkgSystemUnLock,METH_VARARGS,doc_PkgSystemUnLock}, + + {"ReadConfigFile",LoadConfig,METH_VARARGS,doc_LoadConfig}, + {"ReadConfigDir",LoadConfigDir,METH_VARARGS,doc_LoadConfigDir}, + {"ReadConfigFileISC",LoadConfigISC,METH_VARARGS,doc_LoadConfig}, + {"ParseCommandLine",ParseCommandLine,METH_VARARGS,doc_ParseCommandLine}, + + {"VersionCompare",VersionCompare,METH_VARARGS,doc_VersionCompare}, + {"CheckDep",CheckDep,METH_VARARGS,doc_CheckDep}, + {"UpstreamVersion",UpstreamVersion,METH_VARARGS,doc_UpstreamVersion}, + + {"ParseDepends",ParseDepends_old,METH_VARARGS,doc_ParseDepends}, + {"ParseSrcDepends",ParseSrcDepends_old,METH_VARARGS,doc_ParseDepends}, + {"CheckDomainList",StrCheckDomainList,METH_VARARGS,"CheckDomainList(String,String) -> Bool"}, {"QuoteString",StrQuoteString,METH_VARARGS,"QuoteString(String,String) -> String"}, {"DeQuoteString",StrDeQuote,METH_VARARGS,"DeQuoteString(String) -> String"}, @@ -487,28 +481,17 @@ static PyMethodDef methods[] = {"StringToBool",StrStringToBool,METH_VARARGS,"StringToBool(String) -> int"}, {"TimeRFC1123",StrTimeRFC1123,METH_VARARGS,"TimeRFC1123(int) -> String"}, {"StrToTime",StrStrToTime,METH_VARARGS,"StrToTime(String) -> Int"}, - #endif - - // Cache - #ifdef COMPAT_0_7 + {"GetCache",TmpGetCache,METH_VARARGS,"GetCache() -> PkgCache"}, {"GetDepCache",GetDepCache,METH_VARARGS,"GetDepCache(Cache) -> DepCache"}, {"GetPkgRecords",GetPkgRecords,METH_VARARGS,"GetPkgRecords(Cache) -> PkgRecords"}, {"GetPkgSrcRecords",GetPkgSrcRecords,METH_VARARGS,"GetPkgSrcRecords() -> PkgSrcRecords"}, {"GetPkgSourceList",GetPkgSourceList,METH_VARARGS,"GetPkgSourceList() -> PkgSourceList"}, - - // misc {"GetPkgProblemResolver",GetPkgProblemResolver,METH_VARARGS,"GetDepProblemResolver(DepCache) -> PkgProblemResolver"}, {"GetPkgActionGroup",GetPkgActionGroup,METH_VARARGS,"GetPkgActionGroup(DepCache) -> PkgActionGroup"}, - - // Cdrom {"GetCdrom",GetCdrom,METH_VARARGS,"GetCdrom() -> Cdrom"}, - - // Acquire {"GetAcquire",GetAcquire,METH_VARARGS,"GetAcquire() -> Acquire"}, {"GetPkgAcqFile",(PyCFunction)GetPkgAcqFile,METH_KEYWORDS|METH_VARARGS, doc_GetPkgAcqFile}, - - // PkgManager {"GetPackageManager",GetPkgManager,METH_VARARGS,"GetPackageManager(DepCache) -> PackageManager"}, #endif @@ -613,56 +596,19 @@ extern "C" void initapt_pkg() PyModule_AddObject(Module,"REWRITE_SOURCE_ORDER", CharCharToList(TFRewriteSourceOrder)); -#ifdef COMPAT_0_7 - PyModule_AddObject(Module,"RewritePackageOrder", - CharCharToList(TFRewritePackageOrder)); - - PyModule_AddObject(Module,"RewriteSourceOrder", - CharCharToList(TFRewriteSourceOrder)); -#endif // Version.. PyModule_AddStringConstant(Module,"VERSION",(char *)pkgVersion); PyModule_AddStringConstant(Module,"LIB_VERSION",(char *)pkgLibVersion); PyModule_AddStringConstant(Module,"DATE",__DATE__); PyModule_AddStringConstant(Module,"TIME",__TIME__); -#ifdef COMPAT_0_7 - //PyModule_AddStringConstant(Module,"Version",(char *)pkgVersion); - PyModule_AddStringConstant(Module,"LibVersion",(char *)pkgLibVersion); - PyModule_AddStringConstant(Module,"Date",__DATE__); - PyModule_AddStringConstant(Module,"Time",__TIME__); -#endif // My constants - PyModule_AddIntConstant(Module,"DEP_DEPENDS",pkgCache::Dep::Depends); - PyModule_AddIntConstant(Module,"DEP_PRE_DEPENDS",pkgCache::Dep::PreDepends); - PyModule_AddIntConstant(Module,"DEP_SUGGESTS",pkgCache::Dep::Suggests); - PyModule_AddIntConstant(Module,"DEP_RECOMMENDS",pkgCache::Dep::Recommends); - PyModule_AddIntConstant(Module,"DEP_CONFLICTS",pkgCache::Dep::Conflicts); - PyModule_AddIntConstant(Module,"DEP_REPLACES",pkgCache::Dep::Replaces); - PyModule_AddIntConstant(Module,"DEP_OBSOLTES",pkgCache::Dep::Obsoletes); -#ifdef COMPAT_0_7 - PyModule_AddIntConstant(Module,"DepDepends",pkgCache::Dep::Depends); - PyModule_AddIntConstant(Module,"DepPreDepends",pkgCache::Dep::PreDepends); - PyModule_AddIntConstant(Module,"DepSuggests",pkgCache::Dep::Suggests); - PyModule_AddIntConstant(Module,"DepRecommends",pkgCache::Dep::Recommends); - PyModule_AddIntConstant(Module,"DepConflicts",pkgCache::Dep::Conflicts); - PyModule_AddIntConstant(Module,"DepReplaces",pkgCache::Dep::Replaces); - PyModule_AddIntConstant(Module,"DepObsoletes",pkgCache::Dep::Obsoletes); -#endif - PyModule_AddIntConstant(Module,"PRI_IMPORTANT",pkgCache::State::Important); PyModule_AddIntConstant(Module,"PRI_REQUIRED",pkgCache::State::Required); PyModule_AddIntConstant(Module,"PRI_STANDARD",pkgCache::State::Standard); PyModule_AddIntConstant(Module,"PRI_OPTIONAL",pkgCache::State::Optional); PyModule_AddIntConstant(Module,"PRI_EXTRA",pkgCache::State::Extra); -#ifdef COMPAT_0_7 - PyModule_AddIntConstant(Module,"PriImportant",pkgCache::State::Important); - PyModule_AddIntConstant(Module,"PriRequired",pkgCache::State::Required); - PyModule_AddIntConstant(Module,"PriStandard",pkgCache::State::Standard); - PyModule_AddIntConstant(Module,"PriOptional",pkgCache::State::Optional); - PyModule_AddIntConstant(Module,"PriExtra",pkgCache::State::Extra); -#endif // CurState PyModule_AddIntConstant(Module,"CURSTATE_NOT_INSTALLED",pkgCache::State::NotInstalled); PyModule_AddIntConstant(Module,"CURSTATE_UNPACKED",pkgCache::State::UnPacked); @@ -682,27 +628,35 @@ extern "C" void initapt_pkg() PyModule_AddIntConstant(Module,"INSTSTATE_HOLD",pkgCache::State::Hold); PyModule_AddIntConstant(Module,"INSTSTATE_HOLD_REINSTREQ",pkgCache::State::HoldReInstReq); -#ifdef COMPAT_0_7 + // DEPRECATED API + #ifdef COMPAT_0_7 + PyModule_AddObject(Module,"RewritePackageOrder", + CharCharToList(TFRewritePackageOrder)); + PyModule_AddObject(Module,"RewriteSourceOrder", + CharCharToList(TFRewriteSourceOrder)); + PyModule_AddStringConstant(Module,"LibVersion",(char *)pkgLibVersion); + PyModule_AddStringConstant(Module,"Date",__DATE__); + PyModule_AddStringConstant(Module,"Time",__TIME__); + PyModule_AddIntConstant(Module,"PriImportant",pkgCache::State::Important); + PyModule_AddIntConstant(Module,"PriRequired",pkgCache::State::Required); + PyModule_AddIntConstant(Module,"PriStandard",pkgCache::State::Standard); + PyModule_AddIntConstant(Module,"PriOptional",pkgCache::State::Optional); + PyModule_AddIntConstant(Module,"PriExtra",pkgCache::State::Extra); PyModule_AddIntConstant(Module,"CurStateNotInstalled",pkgCache::State::NotInstalled); PyModule_AddIntConstant(Module,"CurStateUnPacked",pkgCache::State::UnPacked); PyModule_AddIntConstant(Module,"CurStateHalfConfigured",pkgCache::State::HalfConfigured); PyModule_AddIntConstant(Module,"CurStateHalfInstalled",pkgCache::State::HalfInstalled); PyModule_AddIntConstant(Module,"CurStateConfigFiles",pkgCache::State::ConfigFiles); PyModule_AddIntConstant(Module,"CurStateInstalled",pkgCache::State::Installed); - PyModule_AddIntConstant(Module,"SelStateUnknown",pkgCache::State::Unknown); PyModule_AddIntConstant(Module,"SelStateInstall",pkgCache::State::Install); PyModule_AddIntConstant(Module,"SelStateHold",pkgCache::State::Hold); PyModule_AddIntConstant(Module,"SelStateDeInstall",pkgCache::State::DeInstall); PyModule_AddIntConstant(Module,"SelStatePurge",pkgCache::State::Purge); - PyModule_AddIntConstant(Module,"InstStateOk",pkgCache::State::Ok); PyModule_AddIntConstant(Module,"InstStateReInstReq",pkgCache::State::ReInstReq); PyModule_AddIntConstant(Module,"InstStateHold",pkgCache::State::Hold); PyModule_AddIntConstant(Module,"InstStateHoldReInstReq",pkgCache::State::HoldReInstReq); -#endif - - #ifdef COMPAT_0_7 PyModule_AddIntConstant(Module,"_COMPAT_0_7",1); #else PyModule_AddIntConstant(Module,"_COMPAT_0_7",0); -- cgit v1.2.3 From e8d06358310f09ea2c28e7640af8dce615040df7 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Mon, 13 Jul 2009 16:16:09 +0200 Subject: python/hashes.cc: Adapt to style guidelines. --- python/hashes.cc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'python') diff --git a/python/hashes.cc b/python/hashes.cc index a1ace6fc..0086c17a 100644 --- a/python/hashes.cc +++ b/python/hashes.cc @@ -55,8 +55,8 @@ static int hashes_init(PyObject *self, PyObject *args, PyObject *kwds) } } else { - PyErr_SetString(PyExc_TypeError, "__init__() only understand strings" - " and files"); + PyErr_SetString(PyExc_TypeError, + "__init__() only understand strings and files"); return -1; } return 0; -- cgit v1.2.3 From 85165f89d3df8ad1c66bd9c842795885c407069e Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Mon, 13 Jul 2009 17:47:45 +0200 Subject: python: No zero-size arrays for char *kwlist[]. --- python/acquire.cc | 2 +- python/cache.cc | 2 +- python/cdrom.cc | 2 +- python/configuration.cc | 2 +- python/depcache.cc | 6 +++--- python/tag.cc | 4 ++-- 6 files changed, 9 insertions(+), 9 deletions(-) (limited to 'python') diff --git a/python/acquire.cc b/python/acquire.cc index 4329e790..8b6de173 100644 --- a/python/acquire.cc +++ b/python/acquire.cc @@ -281,7 +281,7 @@ static PyObject *PkgAcquireNew(PyTypeObject *type,PyObject *Args,PyObject *kwds) pkgAcquire *fetcher; PyObject *pyFetchProgressInst = NULL; - static char *kwlist[] = {"progress", 0}; + char *kwlist[] = {"progress", 0}; if (PyArg_ParseTupleAndKeywords(Args,kwds,"|O",kwlist,&pyFetchProgressInst) == 0) return 0; diff --git a/python/cache.cc b/python/cache.cc index d3a8a949..c160cf69 100644 --- a/python/cache.cc +++ b/python/cache.cc @@ -244,7 +244,7 @@ static PyObject *CacheMapOp(PyObject *Self,PyObject *Arg) static PyObject *PkgCacheNew(PyTypeObject *type,PyObject *Args,PyObject *kwds) { PyObject *pyCallbackInst = 0; - static char *kwlist[] = {"progress", 0}; + char *kwlist[] = {"progress", 0}; if (PyArg_ParseTupleAndKeywords (Args, kwds, "|O", kwlist, &pyCallbackInst) == 0) return 0; diff --git a/python/cdrom.cc b/python/cdrom.cc index 84d7179f..50d1b4b1 100644 --- a/python/cdrom.cc +++ b/python/cdrom.cc @@ -66,7 +66,7 @@ static PyObject *PkgCdromNew(PyTypeObject *type,PyObject *Args,PyObject *kwds) { pkgCdrom *cdrom = new pkgCdrom(); - static char *kwlist[] = {}; + char *kwlist[] = {NULL}; if (PyArg_ParseTupleAndKeywords(Args,kwds,"",kwlist) == 0) return 0; diff --git a/python/configuration.cc b/python/configuration.cc index c7d7d796..ba075133 100644 --- a/python/configuration.cc +++ b/python/configuration.cc @@ -492,7 +492,7 @@ static PyMethodDef CnfMethods[] = }; static PyObject *CnfNew(PyTypeObject *type, PyObject *args, PyObject *kwds) { - static char *kwlist[] = {}; + char *kwlist[] = {NULL}; if (PyArg_ParseTupleAndKeywords(args,kwds,"",kwlist) == 0) return 0; return CppPyObject_NEW(type); diff --git a/python/depcache.cc b/python/depcache.cc index 2d72a82a..e78b9f4e 100644 --- a/python/depcache.cc +++ b/python/depcache.cc @@ -655,7 +655,7 @@ static PyGetSetDef PkgDepCacheGetSet[] = { static PyObject *PkgDepCacheNew(PyTypeObject *type,PyObject *Args,PyObject *kwds) { PyObject *Owner; - static char *kwlist[] = {"cache", 0}; + char *kwlist[] = {"cache", 0}; if (PyArg_ParseTupleAndKeywords(Args,kwds,"O!",kwlist,&PyCache_Type, &Owner) == 0) return 0; @@ -744,7 +744,7 @@ PyObject *GetDepCache(PyObject *Self,PyObject *Args) static PyObject *PkgProblemResolverNew(PyTypeObject *type,PyObject *Args,PyObject *kwds) { PyObject *Owner; - static char *kwlist[] = {"depcache",0}; + char *kwlist[] = {"depcache",0}; if (PyArg_ParseTupleAndKeywords(Args,kwds,"O!",kwlist,&PyDepCache_Type, &Owner) == 0) return 0; @@ -952,7 +952,7 @@ static PyMethodDef PkgActionGroupMethods[] = static PyObject *PkgActionGroupNew(PyTypeObject *type,PyObject *Args,PyObject *kwds) { PyObject *Owner; - static char *kwlist[] = {"depcache", 0}; + char *kwlist[] = {"depcache", 0}; if (PyArg_ParseTupleAndKeywords(Args,kwds,"O!",kwlist,&PyDepCache_Type, &Owner) == 0) return 0; diff --git a/python/tag.cc b/python/tag.cc index 573e8ce2..b393effe 100644 --- a/python/tag.cc +++ b/python/tag.cc @@ -260,7 +260,7 @@ static PyObject *TagFileJump(PyObject *Self,PyObject *Args) // --------------------------------------------------------------------- static PyObject *TagSecNew(PyTypeObject *type,PyObject *Args,PyObject *kwds) { char *Data; - static char *kwlist[] = {"text", 0}; + char *kwlist[] = {"text", 0}; if (PyArg_ParseTupleAndKeywords(Args,kwds,"s",kwlist,&Data) == 0) return 0; @@ -301,7 +301,7 @@ PyObject *ParseSection(PyObject *self,PyObject *Args) static PyObject *TagFileNew(PyTypeObject *type,PyObject *Args,PyObject *kwds) { PyObject *File; - static char *kwlist[] = {"file", 0}; + char *kwlist[] = {"file", 0}; if (PyArg_ParseTupleAndKeywords(Args,kwds,"O",kwlist,&File) == 0) return 0; int fileno = PyObject_AsFileDescriptor(File); -- cgit v1.2.3 From 6b9a8176d06bbe0e00b9c0d37b33c7a4e6fe4054 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Tue, 14 Jul 2009 18:43:50 +0200 Subject: python/acquire.cc: Check that an owner exists in AcquireItemDealloc. --- python/acquire.cc | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'python') diff --git a/python/acquire.cc b/python/acquire.cc index 8b6de173..9104644d 100644 --- a/python/acquire.cc +++ b/python/acquire.cc @@ -112,6 +112,12 @@ static PyObject *AcquireItemRepr(PyObject *Self) static void AcquireItemDealloc(PyObject *self) { pkgAcquire::Item *file = GetCpp(self); PyAcquireObject *owner = (PyAcquireObject *)GetOwner(self); + + // Simply deallocate the object if we have no owner. + if (owner == NULL) { + CppOwnedDeallocPtr(self); + return; + } vector &items = owner->items; bool DeletePtr = !((CppPyObject *)self)->NoDelete; -- cgit v1.2.3 From 18265daee119d7606a2102d8b20d9599f598d88c Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Tue, 14 Jul 2009 18:48:36 +0200 Subject: python/acquire.cc: Replace PyAcquireItem_ToCpp with acquireitem_tocpp. --- python/acquire.cc | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'python') diff --git a/python/acquire.cc b/python/acquire.cc index 9104644d..c3f2fc5d 100644 --- a/python/acquire.cc +++ b/python/acquire.cc @@ -20,7 +20,7 @@ struct PyAcquireObject : public CppPyObject { vector items; }; -inline pkgAcquire::Item *PyAcquireItem_ToCpp(PyObject *self) { +inline pkgAcquire::Item *acquireitem_tocpp(PyObject *self) { pkgAcquire::Item *itm = GetCpp(self); if (itm == 0) PyErr_SetString(PyExc_ValueError, "Acquire() has been shut down or " @@ -30,7 +30,7 @@ inline pkgAcquire::Item *PyAcquireItem_ToCpp(PyObject *self) { #define MkGet(PyFunc,Ret) static PyObject *PyFunc(PyObject *Self,void*) \ { \ - pkgAcquire::Item *Itm = PyAcquireItem_ToCpp(Self); \ + pkgAcquire::Item *Itm = acquireitem_tocpp(Self); \ if (Itm == 0) \ return 0; \ return Ret; \ @@ -94,7 +94,7 @@ static PyGetSetDef AcquireItemGetSet[] = { static PyObject *AcquireItemRepr(PyObject *Self) { - pkgAcquire::Item *Itm = PyAcquireItem_ToCpp(Self); + pkgAcquire::Item *Itm = acquireitem_tocpp(Self); if (Itm == 0) return 0; char S[300]; -- cgit v1.2.3 From e3745827634d8334f796a1506e575ab6f5efdaee Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Tue, 14 Jul 2009 20:37:29 +0200 Subject: python/generic.h: Use Py_XINCREF instead of Py_INCREF in CppOwnedPyObject_NEW. Reason: Owner may be NULL. --- python/generic.h | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) (limited to 'python') diff --git a/python/generic.h b/python/generic.h index 639578c5..7f3a3809 100644 --- a/python/generic.h +++ b/python/generic.h @@ -176,7 +176,7 @@ inline CppOwnedPyObject *CppOwnedPyObject_NEW(PyObject *Owner, CppOwnedPyObject *New = (CppOwnedPyObject*)Type->tp_alloc(Type, 0); new (&New->Object) T; New->Owner = Owner; - Py_INCREF(Owner); + Py_XINCREF(Owner); return New; } @@ -190,8 +190,7 @@ inline CppOwnedPyObject *CppOwnedPyObject_NEW(PyObject *Owner, CppOwnedPyObject *New = (CppOwnedPyObject*)Type->tp_alloc(Type, 0); new (&New->Object) T(Arg); New->Owner = Owner; - if (Owner != 0) - Py_INCREF(Owner); + Py_XINCREF(Owner); return New; } -- cgit v1.2.3 From 8430dbf041ce70dcba81101678beee0492252fd2 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Tue, 14 Jul 2009 20:43:56 +0200 Subject: python/configuration.cc: Unify all Configuration,ConfigurationPtr,ConfigurationSub into one type. This makes the whole API easier. The disadvantage is that we require 8 bytes (??) more per object for the owner object pointer, which is NULL for most cases (the only exception being objects created by Configuration.sub_tree). --- debian/changelog | 3 +- python/apt_pkgmodule.cc | 9 ++-- python/apt_pkgmodule.h | 6 +-- python/configuration.cc | 116 ++++-------------------------------------------- 4 files changed, 15 insertions(+), 119 deletions(-) (limited to 'python') diff --git a/debian/changelog b/debian/changelog index 304237c1..4ae6e574 100644 --- a/debian/changelog +++ b/debian/changelog @@ -33,6 +33,7 @@ python-apt (0.7.92) UNRELEASED; urgency=low * Introduce apt_pkg.Hashes class. * Make AcquireItem objects raise ValueError instead of segfaulting when the Acquire() object is shut down or the main object (e.g. AcquireFile) is deallocated. + * Unify all Configuration,ConfigurationPtr,ConfigurationSub into one type. [ Sebastian Heinlein ] * apt/progress.py: Extract the package name from the status message @@ -48,7 +49,7 @@ python-apt (0.7.92) UNRELEASED; urgency=low * python/progress.cc: - low level code for update_status_full and pulse_items() - -- Julian Andres Klode Sun, 12 Jul 2009 21:19:40 +0200 + -- Julian Andres Klode Tue, 14 Jul 2009 20:42:03 +0200 python-apt (0.7.91) experimental; urgency=low diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index 3f18f785..e4fd0dfc 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -527,8 +527,7 @@ extern "C" void initapt_pkg() #endif { // Finalize our types to add slots, etc. - if (PyType_Ready(&PyConfigurationPtr_Type) == -1) INIT_ERROR; - if (PyType_Ready(&PyConfigurationSub_Type) == -1) INIT_ERROR; + if (PyType_Ready(&PyConfiguration_Type) == -1) INIT_ERROR; if (PyType_Ready(&PyCacheFile_Type) == -1) INIT_ERROR; // Initialize the module @@ -539,8 +538,10 @@ extern "C" void initapt_pkg() #endif // Global variable linked to the global configuration class - CppPyObject *Config = CppPyObject_NEW(&PyConfigurationPtr_Type); + CppOwnedPyObject *Config = CppOwnedPyObject_NEW(NULL, &PyConfiguration_Type); Config->Object = _config; + // Global configuration, should never be deleted. + Config->NoDelete = true; PyModule_AddObject(Module,"config",Config); #ifdef COMPAT_0_7 Py_INCREF(Config); @@ -568,8 +569,6 @@ extern "C" void initapt_pkg() ADDTYPE(Module,"Cdrom",&PyCdrom_Type); /* ========================= configuration.cc ========================= */ ADDTYPE(Module,"Configuration",&PyConfiguration_Type); - //ADDTYPE(Module,"ConfigurationSub",&PyConfigurationSub_Type); // NO __new__() - //ADDTYPE(Module,"ConfigurationPtr",&PyConfigurationPtr_Type); // NO __new__() /* ========================= depcache.cc ========================= */ ADDTYPE(Module,"ActionGroup",&PyActionGroup_Type); ADDTYPE(Module,"DepCache",&PyDepCache_Type); diff --git a/python/apt_pkgmodule.h b/python/apt_pkgmodule.h index 7b835ca8..f77c5e73 100644 --- a/python/apt_pkgmodule.h +++ b/python/apt_pkgmodule.h @@ -14,12 +14,8 @@ #include // Configuration Stuff -#define Configuration_Check(op) ((op)->ob_type == &PyConfiguration_Type || \ - (op)->ob_type == &PyConfigurationPtr_Type || \ - (op)->ob_type == &PyConfigurationSub_Type) +#define Configuration_Check(op) ((op)->ob_type == &PyConfiguration_Type) extern PyTypeObject PyConfiguration_Type; -extern PyTypeObject PyConfigurationPtr_Type; -extern PyTypeObject PyConfigurationSub_Type; extern PyTypeObject PyVersion_Type; extern char *doc_LoadConfig; diff --git a/python/configuration.cc b/python/configuration.cc index ba075133..e7e31cc8 100644 --- a/python/configuration.cc +++ b/python/configuration.cc @@ -5,11 +5,8 @@ Configuration - Binding for the configuration object. - There are three seperate classes.. - Configuration - A stand alone configuration instance - ConfigurationPtr - A pointer to a configuration instance, used only - for the global instance (_config) - ConfigurationSub - A subtree - has a reference to its owner. + The Configuration object can have an owner (a parent Configuration object), + and it always uses a pointer. The wrapping is mostly 1:1 with the C++ code, but there are additions to wrap the linked tree walking into nice flat sequence walking. @@ -25,33 +22,13 @@ #include /*}}}*/ -/* If we create a sub tree then it is of this type, the Owner is used - to manage reference counting. */ -struct SubConfiguration : public CppPyObject -{ - PyObject *Owner; -}; - - /*}}}*/ -// CnfSubFree - Free a sub configuration /*{{{*/ -// --------------------------------------------------------------------- -/* */ -void CnfSubFree(PyObject *Obj) -{ - SubConfiguration *Self = (SubConfiguration *)Obj; - Py_DECREF(Self->Owner); - CppDealloc(Obj); -} - /*}}}*/ // GetSelf - Convert PyObject to Configuration /*{{{*/ // --------------------------------------------------------------------- /* */ static inline Configuration &GetSelf(PyObject *Obj) { - if (Obj->ob_type == &PyConfigurationPtr_Type) - return *GetCpp(Obj); - return GetCpp(Obj); + return *GetCpp(Obj); } /*}}}*/ @@ -160,13 +137,8 @@ static PyObject *CnfSubTree(PyObject *Self,PyObject *Args) return 0; } - // Create a new sub configuration. - SubConfiguration *New = (SubConfiguration*)(&PyConfigurationSub_Type) - ->tp_alloc(&PyConfigurationSub_Type,0); - new (&New->Object) Configuration(Itm); - New->Owner = Self; - Py_INCREF(Self); - return New; + return CppOwnedPyObject_NEW(Self,&PyConfiguration_Type, + new Configuration(Itm)); } // Return a list of items at a specific level @@ -495,7 +467,7 @@ static PyObject *CnfNew(PyTypeObject *type, PyObject *args, PyObject *kwds) { char *kwlist[] = {NULL}; if (PyArg_ParseTupleAndKeywords(args,kwds,"",kwlist) == 0) return 0; - return CppPyObject_NEW(type); + return CppOwnedPyObject_NEW(NULL, type, new Configuration()); } // Type for a Normal Configuration object @@ -505,10 +477,10 @@ PyTypeObject PyConfiguration_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.Configuration", // tp_name - sizeof(CppPyObject), // tp_basicsize + sizeof(CppOwnedPyObject), // tp_basicsize 0, // tp_itemsize // Methods - CppDealloc, // tp_dealloc + CppOwnedDeallocPtr, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr @@ -545,75 +517,3 @@ PyTypeObject PyConfiguration_Type = CnfNew, // tp_new }; -PyTypeObject PyConfigurationPtr_Type = -{ - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "apt_pkg.ConfigurationPtr", // tp_name - sizeof(CppPyObject), // tp_basicsize - 0, // tp_itemsize - // Methods - (destructor)PyObject_Free, // tp_dealloc - 0, // tp_print - 0, // tp_getattr - 0, // tp_setattr - 0, // tp_compare - 0, // tp_repr - 0, // tp_as_number - &ConfigurationSeq, // tp_as_sequence - &ConfigurationMap, // tp_as_mapping - 0, // tp_hash - 0, // tp_call - 0, // tp_str - 0, // tp_getattro - 0, // tp_setattro - 0, // tp_as_buffer - Py_TPFLAGS_DEFAULT, // tp_flags - "ConfigurationPtr Object", // tp_doc - 0, // tp_traverse - 0, // tp_clear - 0, // tp_richcompare - 0, // tp_weaklistoffset - 0, // tp_iter - 0, // tp_iternext - CnfMethods, // tp_methods - 0, // tp_members - 0, // tp_getset - &PyConfiguration_Type, // tp_base -}; - -PyTypeObject PyConfigurationSub_Type = -{ - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "apt_pkg.ConfigurationSub", // tp_name - sizeof(SubConfiguration), // tp_basicsize - 0, // tp_itemsize - // Methods - CnfSubFree, // tp_dealloc - 0, // tp_print - 0, // tp_getattr - 0, // tp_setattr - 0, // tp_compare - 0, // tp_repr - 0, // tp_as_number - &ConfigurationSeq, // tp_as_sequence - &ConfigurationMap, // tp_as_mapping - 0, // tp_hash - 0, // tp_call - 0, // tp_str - 0, // tp_getattro - 0, // tp_setattro - 0, // tp_as_buffer - Py_TPFLAGS_DEFAULT, // tp_flags - "ConfigurationSub Object", // tp_doc - 0, // tp_traverse - 0, // tp_clear - 0, // tp_richcompare - 0, // tp_weaklistoffset - 0, // tp_iter - 0, // tp_iternext - CnfMethods, // tp_methods - 0, // tp_members - 0, // tp_getset - &PyConfiguration_Type, // tp_base -}; - -- cgit v1.2.3 From 9e3bab4299962d51cabce425e8b82804008b73e6 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Tue, 14 Jul 2009 23:38:17 +0200 Subject: python/tag.cc: TagFileData is now subclassed from CppOwnedPyObject. --- python/tag.cc | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) (limited to 'python') diff --git a/python/tag.cc b/python/tag.cc index b393effe..24a43320 100644 --- a/python/tag.cc +++ b/python/tag.cc @@ -39,10 +39,9 @@ struct TagSecData : public CppOwnedPyObject char *Data; }; -struct TagFileData : public PyObject +// The owner of the TagFile is a Python file object. +struct TagFileData : public CppOwnedPyObject { - pkgTagFile Object; - PyObject *File; TagSecData *Section; FileFd Fd; }; @@ -50,11 +49,13 @@ struct TagFileData : public PyObject // Traversal and Clean for owned objects int TagFileTraverse(PyObject *self, visitproc visit, void* arg) { Py_VISIT(((TagFileData *)self)->Section); + Py_VISIT(((TagFileData *)self)->Owner); return 0; } int TagFileClear(PyObject *self) { Py_CLEAR(((TagFileData *)self)->Section); + Py_CLEAR(((TagFileData *)self)->Owner); return 0; } @@ -79,10 +80,10 @@ void TagFileFree(PyObject *Obj) std::cerr << "=== DEALLOCATING " << Obj->ob_type->tp_name << "^ ===\n"; #endif TagFileData *Self = (TagFileData *)Obj; - TagFileClear(Obj); + Py_CLEAR(Self->Section); Self->Object.~pkgTagFile(); Self->Fd.~FileFd(); - Py_DECREF(Self->File); + Py_CLEAR(Self->Owner); Obj->ob_type->tp_free(Obj); } /*}}}*/ @@ -310,8 +311,8 @@ static PyObject *TagFileNew(PyTypeObject *type,PyObject *Args,PyObject *kwds) TagFileData *New = (TagFileData*)type->tp_alloc(type, 0); new (&New->Fd) FileFd(fileno,false); - New->File = File; - Py_INCREF(New->File); + New->Owner = File; + Py_INCREF(New->Owner); new (&New->Object) pkgTagFile(&New->Fd); // Create the section -- cgit v1.2.3 From 7009c7dff71064526dafd0ed114f39c970448da0 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Wed, 15 Jul 2009 00:46:48 +0200 Subject: python/hashstring.cc: Do not use const char*, but use char* with default to NULL. --- python/hashstring.cc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'python') diff --git a/python/hashstring.cc b/python/hashstring.cc index 6f70ac7e..d303049a 100644 --- a/python/hashstring.cc +++ b/python/hashstring.cc @@ -25,8 +25,8 @@ static PyObject *HashString_NEW(PyTypeObject *type,PyObject *Args, PyObject *kwds) { - const char *Hash; - const char *Type; + char *Type = NULL; + char *Hash = NULL; char *kwlist[] = {"type", "hash", NULL}; if (PyArg_ParseTupleAndKeywords(Args, kwds, "s|s", kwlist, &Type, &Hash) == 0) -- cgit v1.2.3 From 360477dcc304b8a18c467e59435d8c766bbb76bb Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Wed, 15 Jul 2009 14:14:44 +0200 Subject: python/python-apt.h: Introduce the C++ API The C++ API provides support for creating Python objects from C++ objects given by pointer or reference (depending on the implementation of the Python object) and for retrieving the underlying C++ object from the Python object and for checking the type of the Python object. --- debian/changelog | 1 + debian/control | 11 ++ debian/python-apt-dev.examples | 1 + debian/python-apt-dev.install | 2 + doc/client-example.cc | 46 ++++++++ python/apt_pkgmodule.cc | 38 ++++++ python/apt_pkgmodule.h | 4 +- python/hashstring.cc | 5 - python/python-apt.h | 259 +++++++++++++++++++++++++++++++++++++++++ 9 files changed, 360 insertions(+), 7 deletions(-) create mode 100644 debian/python-apt-dev.examples create mode 100644 debian/python-apt-dev.install create mode 100644 doc/client-example.cc create mode 100644 python/python-apt.h (limited to 'python') diff --git a/debian/changelog b/debian/changelog index 4ae6e574..415ebdd2 100644 --- a/debian/changelog +++ b/debian/changelog @@ -3,6 +3,7 @@ python-apt (0.7.92) UNRELEASED; urgency=low [ Julian Andres Klode ] * Add apt_pkg.HashString and apt_pkg.IndexRecords (Closes: #456141) * Add apt_pkg.Policy class (Closes: #382725) + * Provide a C++ API in the package python-apt-dev (Closes: #334923) * Allow types providing __new__() to be subclassed. * Bugfix: Delete pointers correctly, fixing memory leaks. (LP: #370149) * apt/package.py: Return VersionList objects in Package.versions, which diff --git a/debian/control b/debian/control index 10b9bc31..a16ae10e 100644 --- a/debian/control +++ b/debian/control @@ -54,3 +54,14 @@ Description: Python interface to libapt-pkg (debug extension) variety of functions. . This package contains the extension built for the Python debug interpreter. + +Package: python-apt-dev +Architecture: all +Depends: python-apt (>= ${source:Version}), libapt-pkg-dev (>= 0.7.10) +Description: Python interface to libapt-pkg (development files) + The apt_pkg Python interface will provide full access to the internal + libapt-pkg structures allowing Python programs to easily perform a + variety of functions. + . + This package contains the header files needed to use python-apt objects from + C++ applications. diff --git a/debian/python-apt-dev.examples b/debian/python-apt-dev.examples new file mode 100644 index 00000000..39f7bf97 --- /dev/null +++ b/debian/python-apt-dev.examples @@ -0,0 +1 @@ +doc/client-example.cc diff --git a/debian/python-apt-dev.install b/debian/python-apt-dev.install new file mode 100644 index 00000000..2a1405fd --- /dev/null +++ b/debian/python-apt-dev.install @@ -0,0 +1,2 @@ +python/python-apt.h usr/include/python-apt/ +python/generic.h usr/include/python-apt/ diff --git a/doc/client-example.cc b/doc/client-example.cc new file mode 100644 index 00000000..7fa6672f --- /dev/null +++ b/doc/client-example.cc @@ -0,0 +1,46 @@ +/* + * client-example.cc - A simple example for using the python-apt C++ API. + * + * Copyright 2009 Julian Andres Klode + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + */ +#include + +int main(int argc, char *argv[]) { + Py_Initialize(); + if (import_apt_pkg() < 0) + return 1; + + // Initialize a module. + PyObject *Module = Py_InitModule("client", NULL); + + // Create a HashString, which will be added to the module. + HashString *hash = new HashString("0966a120bb936bdc6fdeac445707aa6b"); + // Create a Python object for the hashstring and add it to the module + PyModule_AddObject(Module, "hash", PyHashString_FromCpp(hash)); + + // Another example: Add the HashString type to the module. + Py_INCREF(&PyHashString_Type); + PyModule_AddObject(Module, "HashString", (PyObject*)(&PyHashString_Type)); + + // Run IPython, adding the client module to the namespace. + PySys_SetArgv(argc, argv); + PyRun_SimpleString("from IPython.Shell import start\n"); + PyRun_SimpleString("import client\n"); + PyRun_SimpleString("start(user_ns=dict(client=client)).mainloop()\n"); + Py_Finalize(); +} diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index e4fd0dfc..bc2f4258 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -498,6 +498,38 @@ static PyMethodDef methods[] = {} }; +static struct _PyAptPkgAPIStruct API = { + &PyAcquire_Type, // acquire_type + &PyAcquireFile_Type, // acquirefile_type + &PyAcquireItem_Type, // acquireitem_type + &PyActionGroup_Type, // actiongroup_type + &PyCache_Type, // cache_type + &PyCacheFile_Type, // cachefile_type + &PyCdrom_Type, // cdrom_type + &PyConfiguration_Type, // configuration_type + &PyDepCache_Type, // depcache_type + &PyDependency_Type, // dependency_type + &PyDependencyList_Type, // dependencylist_type + &PyDescription_Type, // description_type + &PyHashes_Type, // hashes_type + &PyHashString_Type, // hashstring_type + &PyIndexRecords_Type, // indexrecords_type + &PyMetaIndex_Type, // metaindex_type + &PyPackage_Type, // package_type + &PyPackageFile_Type, // packagefile_type + &PyPackageIndexFile_Type, // packageindexfile_type + &PyPackageList_Type, // packagelist_type + &PyPackageManager_Type, // packagemanager_type + &PyPackageRecords_Type, // packagerecords_type + &PyPolicy_Type, // policy_type + &PyProblemResolver_Type, // problemresolver_type + &PySourceList_Type, // sourcelist_type + &PySourceRecords_Type, // sourcerecords_type + &PyTagFile_Type, // tagfile_type + &PyTagSection_Type, // tagsection_type + &PyVersion_Type, // version_type +}; + #define ADDTYPE(mod,name,type) { \ if (PyType_Ready(type) == -1) INIT_ERROR; \ @@ -596,6 +628,12 @@ extern "C" void initapt_pkg() PyModule_AddObject(Module,"REWRITE_SOURCE_ORDER", CharCharToList(TFRewriteSourceOrder)); +#if PY_MAJOR_VERSION >= 3 && PY_MINOR_VERSION >= 1 + PyObject *PyCapsule = PyCapsule_New(&API, "apt_pkg._C_API", NULL); +#else + PyObject *PyCapsule = PyCObject_FromVoidPtr(&API, NULL); +#endif + PyModule_AddObject(Module, "_C_API", PyCapsule); // Version.. PyModule_AddStringConstant(Module,"VERSION",(char *)pkgVersion); PyModule_AddStringConstant(Module,"LIB_VERSION",(char *)pkgLibVersion); diff --git a/python/apt_pkgmodule.h b/python/apt_pkgmodule.h index f77c5e73..97be5d5c 100644 --- a/python/apt_pkgmodule.h +++ b/python/apt_pkgmodule.h @@ -104,7 +104,6 @@ extern PyTypeObject PyPackageIndexFile_Type; extern PyTypeObject PyMetaIndex_Type; // HashString -PyObject *PyHashString_FromCpp(HashString *obj); extern PyTypeObject PyHashString_Type; // IndexRecord @@ -113,5 +112,6 @@ extern PyTypeObject PyIndexRecords_Type; // Policy extern PyTypeObject PyPolicy_Type; extern PyTypeObject PyHashes_Type; - +#include "python-apt.h" #endif + diff --git a/python/hashstring.cc b/python/hashstring.cc index d303049a..b76dc127 100644 --- a/python/hashstring.cc +++ b/python/hashstring.cc @@ -39,11 +39,6 @@ static PyObject *HashString_NEW(PyTypeObject *type,PyObject *Args, return PyObj; } -PyObject *PyHashString_FromCpp(HashString *obj) -{ - return CppPyObject_NEW(&PyHashString_Type, obj); -} - static PyObject *HashString_Repr(PyObject *self) { HashString *hash = GetCpp(self); diff --git a/python/python-apt.h b/python/python-apt.h new file mode 100644 index 00000000..557f5a3b --- /dev/null +++ b/python/python-apt.h @@ -0,0 +1,259 @@ +/* + * python-apt.h - Header file for the public interface. + * + * Copyright 2009 Julian Andres Klode + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + */ + +#ifndef PYTHON_APT_H +#define PYTHON_APT_H +#include +#include +#include "generic.h" + +struct _PyAptPkgAPIStruct { + PyTypeObject *acquire_type; + PyTypeObject *acquirefile_type; + PyTypeObject *acquireitem_type; + PyTypeObject *actiongroup_type; + PyTypeObject *cache_type; + PyTypeObject *cachefile_type; + PyTypeObject *cdrom_type; + PyTypeObject *configuration_type; + PyTypeObject *depcache_type; + PyTypeObject *dependency_type; + PyTypeObject *dependencylist_type; + PyTypeObject *description_type; + PyTypeObject *hashes_type; + PyTypeObject *hashstring_type; + PyTypeObject *indexrecords_type; + PyTypeObject *metaindex_type; + PyTypeObject *package_type; + PyTypeObject *packagefile_type; + PyTypeObject *packageindexfile_type; + PyTypeObject *packagelist_type; + PyTypeObject *packagemanager_type; + PyTypeObject *packagerecords_type; + PyTypeObject *policy_type; + PyTypeObject *problemresolver_type; + PyTypeObject *sourcelist_type; + PyTypeObject *sourcerecords_type; + PyTypeObject *tagfile_type; + PyTypeObject *tagsection_type; + PyTypeObject *version_type; +}; + +# ifndef APT_PKGMODULE_H +# define PyAcquire_Type *(_PyAptPkg_API->acquire_type) +# define PyAcquireFile_Type *(_PyAptPkg_API->acquirefile_type) +# define PyAcquireItem_Type *(_PyAptPkg_API->acquireitem_type) +# define PyActionGroup_Type *(_PyAptPkg_API->actiongroup_type) +# define PyCache_Type *(_PyAptPkg_API->cache_type) +# define PyCacheFile_Type *(_PyAptPkg_API->cachefile_type) +# define PyCdrom_Type *(_PyAptPkg_API->cdrom_type) +# define PyConfiguration_Type *(_PyAptPkg_API->configuration_type) +# define PyDepCache_Type *(_PyAptPkg_API->depcache_type) +# define PyDependency_Type *(_PyAptPkg_API->dependency_type) +# define PyDependencyList_Type *(_PyAptPkg_API->dependencylist_type) +# define PyDescription_Type *(_PyAptPkg_API->description_type) +# define PyHashes_Type *(_PyAptPkg_API->hashes_type) +# define PyHashString_Type *(_PyAptPkg_API->hashstring_type) +# define PyIndexRecords_Type *(_PyAptPkg_API->indexrecords_type) +# define PyMetaIndex_Type *(_PyAptPkg_API->metaindex_type) +# define PyPackage_Type *(_PyAptPkg_API->package_type) +# define PyPackageFile_Type *(_PyAptPkg_API->packagefile_type) +# define PyPackageIndexFile_Type *(_PyAptPkg_API->packageindexfile_type) +# define PyPackageList_Type *(_PyAptPkg_API->packagelist_type) +# define PyPackageManager_Type *(_PyAptPkg_API->packagemanager_type) +# define PyPackageRecords_Type *(_PyAptPkg_API->packagerecords_type) +# define PyPolicy_Type *(_PyAptPkg_API->policy_type) +# define PyProblemResolver_Type *(_PyAptPkg_API->problemresolver_type) +# define PySourceList_Type *(_PyAptPkg_API->sourcelist_type) +# define PySourceRecords_Type *(_PyAptPkg_API->sourcerecords_type) +# define PyTagFile_Type *(_PyAptPkg_API->tagfile_type) +# define PyTagSection_Type *(_PyAptPkg_API->tagsection_type) +# define PyVersion_Type *(_PyAptPkg_API->version_type) + +// Creating + +static struct _PyAptPkgAPIStruct *_PyAptPkg_API; + +static int import_apt_pkg(void) { +# if PY_MAJOR_VERSION >= 3 && PY_MINOR_VERSION >= 1 + _PyAptPkg_API = (_PyAptPkgAPIStruct *)PyCapsule_Import("apt_pkg._C_API", 0); + return (_PyAptPkg_API != NULL) ? 0 : -1; +# else + + PyObject *module = PyImport_ImportModule("apt_pkg"); + + if (module == NULL) { + return -1; + } + if (module != NULL) { + PyObject *c_api_object = PyObject_GetAttrString(module, "_C_API"); + if (c_api_object == NULL) + return -1; + if (PyCObject_Check(c_api_object)) + _PyAptPkg_API = (struct _PyAptPkgAPIStruct *)PyCObject_AsVoidPtr(c_api_object); + Py_DECREF(c_api_object); + } + return 0; +# endif // PY_MAJOR_VERSION >= 3 && PY_MINOR_VERSION >= 1 +} +# endif // APT_PKGMODULE_H + +// Checking macros. +# define PyAcquire_Check(op) PyObject_TypeCheck(op, &PyAcquire_Type) +# define PyAcquireFile_Check(op) PyObject_TypeCheck(op, &PyAcquireFile_Type) +# define PyAcquireItem_Check(op) PyObject_TypeCheck(op, &PyAcquireItem_Type) +# define PyActionGroup_Check(op) PyObject_TypeCheck(op, &PyActionGroup_Type) +# define PyCache_Check(op) PyObject_TypeCheck(op, &PyCache_Type) +# define PyCacheFile_Check(op) PyObject_TypeCheck(op, &PyCacheFile_Type) +# define PyCdrom_Check(op) PyObject_TypeCheck(op, &PyCdrom_Type) +# define PyConfiguration_Check(op) PyObject_TypeCheck(op, &PyConfiguration_Type) +# define PyDepCache_Check(op) PyObject_TypeCheck(op, &PyDepCache_Type) +# define PyDependency_Check(op) PyObject_TypeCheck(op, &PyDependency_Type) +# define PyDependencyList_Check(op) PyObject_TypeCheck(op, &PyDependencyList_Type) +# define PyDescription_Check(op) PyObject_TypeCheck(op, &PyDescription_Type) +# define PyHashes_Check(op) PyObject_TypeCheck(op, &PyHashes_Type) +# define PyHashString_Check(op) PyObject_TypeCheck(op, &PyHashString_Type) +# define PyIndexRecords_Check(op) PyObject_TypeCheck(op, &PyIndexRecords_Type) +# define PyMetaIndex_Check(op) PyObject_TypeCheck(op, &PyMetaIndex_Type) +# define PyPackage_Check(op) PyObject_TypeCheck(op, &PyPackage_Type) +# define PyPackageFile_Check(op) PyObject_TypeCheck(op, &PyPackageFile_Type) +# define PyPackageIndexFile_Check(op) PyObject_TypeCheck(op, &PyPackageIndexFile_Type) +# define PyPackageList_Check(op) PyObject_TypeCheck(op, &PyPackageList_Type) +# define PyPackageManager_Check(op) PyObject_TypeCheck(op, &PyPackageManager_Type) +# define PyPackageRecords_Check(op) PyObject_TypeCheck(op, &PyPackageRecords_Type) +# define PyPolicy_Check(op) PyObject_TypeCheck(op, &PyPolicy_Type) +# define PyProblemResolver_Check(op) PyObject_TypeCheck(op, &PyProblemResolver_Type) +# define PySourceList_Check(op) PyObject_TypeCheck(op, &PySourceList_Type) +# define PySourceRecords_Check(op) PyObject_TypeCheck(op, &PySourceRecords_Type) +# define PyTagFile_Check(op) PyObject_TypeCheck(op, &PyTagFile_Type) +# define PyTagSection_Check(op) PyObject_TypeCheck(op, &PyTagSection_Type) +# define PyVersion_Check(op) PyObject_TypeCheck(op, &PyVersion_Type) +// Exact check macros. +# define PyAcquire_CheckExact(op) (Py_TYPE(op) == &PyAcquire_Type) +# define PyAcquireFile_CheckExact(op) (Py_TYPE(op) == &PyAcquireFile_Type) +# define PyAcquireItem_CheckExact(op) (Py_TYPE(op) == &PyAcquireItem_Type) +# define PyActionGroup_CheckExact(op) (Py_TYPE(op) == &PyActionGroup_Type) +# define PyCache_CheckExact(op) (Py_TYPE(op) == &PyCache_Type) +# define PyCacheFile_CheckExact(op) (Py_TYPE(op) == &PyCacheFile_Type) +# define PyCdrom_CheckExact(op) (Py_TYPE(op) == &PyCdrom_Type) +# define PyConfiguration_CheckExact(op) (Py_TYPE(op) == &PyConfiguration_Type) +# define PyDepCache_CheckExact(op) (Py_TYPE(op) == &PyDepCache_Type) +# define PyDependency_CheckExact(op) (Py_TYPE(op) == &PyDependency_Type) +# define PyDependencyList_CheckExact(op) (Py_TYPE(op) == &PyDependencyList_Type) +# define PyDescription_CheckExact(op) (Py_TYPE(op) == &PyDescription_Type) +# define PyHashes_CheckExact(op) (Py_TYPE(op) == &PyHashes_Type) +# define PyHashString_CheckExact(op) (Py_TYPE(op) == &PyHashString_Type) +# define PyIndexRecords_CheckExact(op) (Py_TYPE(op) == &PyIndexRecords_Type) +# define PyMetaIndex_CheckExact(op) (Py_TYPE(op) == &PyMetaIndex_Type) +# define PyPackage_CheckExact(op) (Py_TYPE(op) == &PyPackage_Type) +# define PyPackageFile_CheckExact(op) (Py_TYPE(op) == &PyPackageFile_Type) +# define PyPackageIndexFile_CheckExact(op) (Py_TYPE(op) == &PyPackageIndexFile_Type) +# define PyPackageList_CheckExact(op) (Py_TYPE(op) == &PyPackageList_Type) +# define PyPackageManager_CheckExact(op) (Py_TYPE(op) == &PyPackageManager_Type) +# define PyPackageRecords_CheckExact(op) (Py_TYPE(op) == &PyPackageRecords_Type) +# define PyPolicy_CheckExact(op) (Py_TYPE(op) == &PyPolicy_Type) +# define PyProblemResolver_CheckExact(op) (Py_TYPE(op) == &PyProblemResolver_Type) +# define PySourceList_CheckExact(op) (Py_TYPE(op) == &PySourceList_Type) +# define PySourceRecords_CheckExact(op) (Py_TYPE(op) == &PySourceRecords_Type) +# define PyTagFile_CheckExact(op) (Py_TYPE(op) == &PyTagFile_Type) +# define PyTagSection_CheckExact(op) (Py_TYPE(op) == &PyTagSection_Type) +# define PyVersion_CheckExact(op) (Py_TYPE(op) == &PyVersion_Type) + +// Get the underlying C++ reference or pointer from the Python object. +# define PyAcquire_ToCpp GetCpp +# define PyAcquireFile_ToCpp GetCpp +# define PyAcquireItem_ToCpp GetCpp +# define PyActionGroup_ToCpp GetCpp +# define PyCache_ToCpp GetCpp +# define PyCacheFile_ToCpp GetCpp +# define PyCdrom_ToCpp GetCpp +# define PyConfiguration_ToCpp GetCpp +# define PyDepCache_ToCpp GetCpp +# define PyDependency_ToCpp GetCpp +//# define PyDependencyList_ToCpp GetCpp // NOT EXPORTED +# define PyDescription_ToCpp GetCpp +# define PyHashes_ToCpp GetCpp +# define PyHashString_ToCpp GetCpp +# define PyIndexRecords_ToCpp GetCpp +# define PyMetaIndex_ToCpp GetCpp +# define PyPackage_ToCpp GetCpp +# define PyPackageFile_ToCpp GetCpp +# define PyPackageIndexFile_ToCpp GetCpp +//# define PyPackageList_ToCpp GetCpp // NOT EXPORTED. +# define PyPackageManager_ToCpp GetCpp +//# define PyPackageRecords_ToCpp GetCpp // NOT EXPORTED +# define PyPolicy_ToCpp GetCpp +# define PyProblemResolver_ToCpp GetCpp +# define PySourceList_ToCpp GetCpp +//# define PySourceRecords_ToCpp GetCpp // NOT EXPORTED +# define PyTagFile_ToCpp GetCpp +# define PyTagSection_ToCpp GetCpp +# define PyVersion_ToCpp GetCpp + +// Python object creation, using two inline template functions and one variadic +// macro per type. +template +inline PyObject *FromCpp(PyTypeObject *pytype, Cpp obj, bool Delete=false) +{ + CppPyObject *Obj = CppPyObject_NEW(pytype, obj); + Obj->NoDelete = (!Delete); + return Obj; +} + +template +inline PyObject *FromCppOwned(PyTypeObject *pytype, Cpp const &obj, + bool Delete=false, PyObject *Owner=NULL) +{ + CppOwnedPyObject *Obj = CppOwnedPyObject_NEW(Owner, pytype, obj); + Obj->NoDelete = (!Delete); + return Obj; +} + +# define PyAcquire_FromCpp(...) FromCpp(&PyAcquire_Type, ##__VA_ARGS__) +# define PyAcquireFile_FromCpp(...) FromCppOwned(&PyAcquireFile_Type, ##__VA_ARGS__) +# define PyAcquireItem_FromCpp(...) FromCppOwned(&PyAcquireItemType,##__VA_ARGS__) +# define PyActionGroup_FromCpp(...) FromCppOwned(&PyActionGroup_Type,##__VA_ARGS__) +# define PyCache_FromCpp(...) FromCppOwned(&PyCache_Type,##__VA_ARGS__) +# define PyCacheFile_FromCpp(...) FromCpp(&PyCacheFile_Type,##__VA_ARGS__) +# define PyCdrom_FromCpp(...) FromCpp(&PyCdromType,##__VA_ARGS__) +# define PyConfiguration_FromCpp(...) FromCppOwned(&PyConfiguration_Type, ##__VA_ARGS__) +# define PyDepCache_FromCpp(...) FromCppOwned(&PyDepCache_Type,##__VA_ARGS__) +# define PyDependency_FromCpp(...) FromCppOwned(&PyDependency_Type,##__VA_ARGS__) +//# define PyDependencyList_FromCpp(...) FromCppOwned(&PyDependencyList_Type,##__VA_ARGS__) +# define PyDescription_FromCpp(...) FromCppOwned(&PyDescription_Type,##__VA_ARGS__) +# define PyHashes_FromCpp(...) FromCpp(&PyHashes_Type,##__VA_ARGS__) +# define PyHashString_FromCpp(...) FromCpp(&PyHashString_Type,##__VA_ARGS__) +# define PyIndexRecords_FromCpp(...) FromCpp(&PyIndexRecords_Type,##__VA_ARGS__) +# define PyMetaIndex_FromCpp(...) FromCppOwned(&PyMetaIndex_Type,##__VA_ARGS__) +# define PyPackage_FromCpp(...) FromCppOwned(&PyPackage_Type,##__VA_ARGS__) +# define PyPackageIndexFile_FromCpp(...) FromCppOwned(&PyPackageIndexFile_Type,##__VA_ARGS__) +# define PyPackageFile_FromCpp(...) FromCppOwned(&PyPackageFile_Type,##__VA_ARGS__) +//# define PyPackageList_FromCpp(...) FromCppOwned(&PyPackageList_Type,##__VA_ARGS__) +# define PyPackageManager_FromCpp(...) FromCpp(&PyPackageManagerType,##__VA_ARGS__) +//# define PyPackageRecords_FromCpp(...) FromCppOwned(&PyPackageRecords_Type,##__VA_ARGS__) +# define PyPolicy_FromCpp(...) FromCppOwned(&PyPolicy_Type,##__VA_ARGS__) +# define PyProblemResolver_FromCpp(...) FromCppOwned(&PyProblemResolver_Type,##__VA_ARGS__) +# define PySourceList_FromCpp(...) FromCpp(&PySourceList_Type,##__VA_ARGS__) +//# define PySourceRecords_FromCpp(...) FromCpp(&PySourceRecords_Type,##__VA_ARGS__) +//# define PyTagFile_FromCpp(...) FromCppOwned(&PyTagFile_Type,##__VA_ARGS__) +# define PyTagSection_FromCpp(...) FromCppOwned(&PyTagSection_Type,##__VA_ARGS__) +# define PyVersion_FromCpp(...) FromCppOwned(&PyVersion_Type,##__VA_ARGS__) +#endif -- cgit v1.2.3 From 7581c5fb8a8d8e1e0a79c343cbd23725475f846c Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Wed, 15 Jul 2009 17:02:34 +0200 Subject: Simplify the whole building, build all Python versions with setup.py --- debian/changelog | 1 + debian/control | 4 +-- debian/python-apt.doc-base | 3 -- debian/python-apt.docs | 3 +- debian/rules | 35 +++------------------ po/python-apt.pot | 2 +- python/makefile | 27 ---------------- setup.py | 73 ++++++++++++++++++++----------------------- setup3.py | 77 ---------------------------------------------- 9 files changed, 43 insertions(+), 182 deletions(-) delete mode 100644 python/makefile mode change 100755 => 100644 setup.py delete mode 100644 setup3.py (limited to 'python') diff --git a/debian/changelog b/debian/changelog index 70157470..5e3ec667 100644 --- a/debian/changelog +++ b/debian/changelog @@ -38,6 +38,7 @@ python-apt (0.7.92) UNRELEASED; urgency=low * Upgrade to debhelper 7 and remove debian/tmp in python-apt.install, to work around a bug in debhelper. * Build-Depend on python-all-dev (>= 2.5.4-3), so we build for Python 2.6 + * Simplify the whole building, build all Python versions with setup.py [ Sebastian Heinlein ] * apt/progress.py: Extract the package name from the status message diff --git a/debian/control b/debian/control index 9e0fe3ea..36a4d8d8 100644 --- a/debian/control +++ b/debian/control @@ -8,13 +8,13 @@ XS-Python-Version: >= 2.5 Build-Depends: apt-utils, cdbs, debhelper (>= 7), - libapt-pkg-dev (>= 0.7.22~), + libapt-pkg-dev (>= 0.7.12~), python-all-dbg (>= 2.5.4-3), python-all-dev (>= 2.5.4-3), python3.1-dev, python3.1-dbg, python-central (>= 0.5), - python-distutils-extra (>= 1.9.0), + python-distutils-extra (>= 2.0), python-gtk2, python-sphinx (>= 0.5), python-vte diff --git a/debian/python-apt.doc-base b/debian/python-apt.doc-base index d25926b7..e9b2040c 100644 --- a/debian/python-apt.doc-base +++ b/debian/python-apt.doc-base @@ -6,6 +6,3 @@ Section: Programming/Python Format: HTML Index: /usr/share/doc/python-apt/html/index.html Files: /usr/share/doc/python-apt/html/* - -Format: Text -Files: /usr/share/doc/python-apt/text/* diff --git a/debian/python-apt.docs b/debian/python-apt.docs index 6ba083f5..29219341 100644 --- a/debian/python-apt.docs +++ b/debian/python-apt.docs @@ -1,5 +1,4 @@ README apt/README.apt data/templates/README.templates -build/doc/html/ -build/doc/text/ +build/sphinx/html/ diff --git a/debian/rules b/debian/rules index f9b08384..967da911 100755 --- a/debian/rules +++ b/debian/rules @@ -11,56 +11,29 @@ DEB_PYTHON_PACKAGES_EXCLUDE=python-apt-dbg include /usr/share/cdbs/1/rules/debhelper.mk include /usr/share/cdbs/1/class/python-distutils.mk -PY3K_VERSIONS := $(shell find /usr/bin/python3.? | sed s/.*python//) -2TO3_VERSION := $(lastword $(PY3K_VERSIONS)) +# Add python3 versions to the list of python versions +cdbs_python_build_versions += $(shell find /usr/bin/python3.? | sed s/.*python//) + -PKG=python-apt DEBVER=$(shell dpkg-parsechangelog |sed -n -e '/^Version:/s/^Version: //p') DEB_COMPRESS_EXCLUDE:=.html .js _static/* _sources/* _sources/*/* .inv DEB_PYTHON_INSTALL_ARGS_ALL=--no-compile --install-layout=deb -DEB_BUILD_PROG:=debuild --preserve-envvar PATH --preserve-envvar CCACHE_DIR -us -uc $(DEB_BUILD_PROG_OPTS) # Define COMPAT_0_7 to get all the deprecated interfaces. export CFLAGS+=-DCOMPAT_0_7 -Wno-write-strings export DEBVER -build/python-apt:: - set -e; for i in $(PY3K_VERSIONS); do \ - python$$i setup3.py build; \ - done - -install/python-apt:: - set -e; for i in $(PY3K_VERSIONS); do \ - python$$i ./setup3.py install --root $(CURDIR)/debian/python-apt \ - --install-layout=deb --no-compile; \ - done - -ifneq ($(PY3K_VERSIONS),) - find $(CURDIR)/debian/python-apt/usr/lib/python3*/dist-packages/ -name '*.py' \ - | xargs 2to3-$(2TO3_VERSION)| patch -p0 -endif - build/python-apt-dbg:: set -e; \ for i in $(cdbs_python_build_versions); do \ python$$i-dbg ./setup.py build; \ done - set -e; for i in $(PY3K_VERSIONS); do \ - python$$i-dbg setup3.py build; \ - done - install/python-apt-dbg:: for i in $(cdbs_python_build_versions); do \ python$$i-dbg ./setup.py install --root $(CURDIR)/debian/python-apt-dbg \ - --no-compile; \ + $(DEB_PYTHON_INSTALL_ARGS_ALL); \ done - - set -e; for i in $(PY3K_VERSIONS); do \ - python$$i-dbg ./setup3.py install --root $(CURDIR)/debian/python-apt-dbg \ - --install-layout=deb --no-compile; \ - done - find debian/python-apt-dbg \ ! -type d ! -name '*_d.so' | xargs rm -f find debian/python-apt-dbg -depth -empty -exec rmdir {} \; diff --git a/po/python-apt.pot b/po/python-apt.pot index 3f4fbb6b..3becb5e1 100644 --- a/po/python-apt.pot +++ b/po/python-apt.pot @@ -8,7 +8,7 @@ msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2009-07-15 15:17+0200\n" +"POT-Creation-Date: 2009-07-15 16:51+0200\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" diff --git a/python/makefile b/python/makefile deleted file mode 100644 index fff3a2e8..00000000 --- a/python/makefile +++ /dev/null @@ -1,27 +0,0 @@ -# -*- make -*- -BASE=.. -SUBDIR=python - -# Bring in the default rules -include ../buildlib/defaults.mak - -# The apt_pkg module -MODULE=apt_pkg -SLIBS = -lapt-pkg -LIB_MAKES = apt-pkg/makefile -APT_PKG_SRC = apt_pkgmodule.cc configuration.cc generic.cc tag.cc string.cc \ - cache.cc pkgrecords.cc pkgsrcrecords.cc sourcelist.cc \ - depcache.cc progress.cc cdrom.cc acquire.cc pkgmanager.cc \ - indexfile.cc metaindex.cc hashstring.cc indexrecords.cc \ - policy.cc hashes.cc -SOURCE := $(APT_PKG_SRC) -include $(PYTHON_H) progress.h - -# The apt_int module.. -MODULE=apt_inst -SLIBS = -lapt-inst -lapt-pkg -LIB_MAKES = apt-inst/makefile -APT_INST_SRC = apt_instmodule.cc tar.cc generic.cc -SOURCE := $(APT_INST_SRC) -include $(PYTHON_H) - diff --git a/setup.py b/setup.py old mode 100755 new mode 100644 index 85f4c889..77853a4e --- a/setup.py +++ b/setup.py @@ -1,50 +1,59 @@ -#! /usr/bin/env python +#!/usr/bin/python +# Builds on python2.X and python3 # $Id: setup.py,v 1.2 2002/01/08 07:13:21 jgg Exp $ import glob import os -import shutil import sys from distutils.core import setup, Extension -from distutils.sysconfig import parse_makefile -from DistUtilsExtra.command import build_extra, build_i18n +cmdclass = {} +try: + from DistUtilsExtra.command import build_extra, build_i18n + from DistUtilsExtra.auto import clean_build_tree + cmdclass['build'] = build_extra.build_extra + cmdclass['build_i18n'] = build_i18n.build_i18n + cmdclass['clean'] = clean_build_tree + build_extra.build_extra.sub_commands.append(("build_sphinx", + lambda x: 'build_sphinx' in cmdclass)) +except ImportError: + print('W: [python%s] DistUtilsExtra import error.' % sys.version[:3]) -# The apt_pkg module -files = map(lambda source: "python/"+source, - sorted(parse_makefile("python/makefile")["APT_PKG_SRC"].split())) +try: + from sphinx.setup_command import BuildDoc + cmdclass['build_sphinx'] = BuildDoc +except ImportError: + print('W: [python%s] Sphinx import error.' % sys.version[:3]) + +if sys.version_info[0] == 3: + from distutils.command.build_py import build_py_2to3 + cmdclass['build_py'] = build_py_2to3 + +# The apt_pkg module. +files = ['apt_pkgmodule.cc', 'acquire.cc', 'cache.cc', 'cdrom.cc', + 'configuration.c', 'depcache.cc', 'generic.cc', 'hashes.cc', + 'hashstring.cc', 'indexfile.cc', 'indexrecords.cc', 'metaindex.cc', + 'pkgmanager.cc', 'pkgrecords.cc', 'pkgsrcrecords.cc', 'policy.cc', + 'progress.cc', 'sourcelist.cc', 'string.cc', 'tag.cc'] +files = ['python/' + fname for fname in files] apt_pkg = Extension("apt_pkg", files, libraries=["apt-pkg"]) # The apt_inst module -files = map(lambda source: "python/"+source, - sorted(parse_makefile("python/makefile")["APT_INST_SRC"].split())) +files = ["python/apt_instmodule.cc", "python/generic.cc", "python/tar.cc"] apt_inst = Extension("apt_inst", files, libraries=["apt-pkg", "apt-inst"]) # Replace the leading _ that is used in the templates for translation -templates = [] - -# build doc if len(sys.argv) > 1 and sys.argv[1] == "build": if not os.path.exists("build/data/templates/"): os.makedirs("build/data/templates") for template in glob.glob('data/templates/*.info.in'): source = open(template, "r") - build = open(os.path.join("build", template[:-3]), "w") - lines = source.readlines() - for line in lines: + build = open("build/" + template[:-3], "w") + for line in source: build.write(line.lstrip("_")) source.close() build.close() - -if len(sys.argv) > 1 and sys.argv[1] == "clean" and '-a' in sys.argv: - for dirname in "build/doc", "doc/build", "build/data", "build/mo": - if os.path.exists(dirname): - print "Removing", dirname - shutil.rmtree(dirname) - else: - print "Not removing", dirname, "because it does not exist" - setup(name="python-apt", description="Python bindings for APT", version=os.environ.get('DEBVER'), @@ -56,20 +65,6 @@ setup(name="python-apt", glob.glob('build/data/templates/*.info')), ('share/python-apt/templates', glob.glob('data/templates/*.mirrors'))], - cmdclass = {"build": build_extra.build_extra, - "build_i18n": build_i18n.build_i18n}, + cmdclass = cmdclass, license = 'GNU GPL', platforms = 'posix') - -if len(sys.argv) > 1 and sys.argv[1] == "build": - import sphinx - try: - import pygtk - except ImportError: - print >> sys.stderr, ('W: Not building documentation because python-' - 'gtk2 is not available at the moment.') - sys.exit(0) - sphinx.main(["sphinx", "-b", "html", "-d", "build/doc/doctrees", - os.path.abspath("doc/source"), "build/doc/html"]) - sphinx.main(["sphinx", "-b", "text", "-d", "build/doc/doctrees", - os.path.abspath("doc/source"), "build/doc/text"]) diff --git a/setup3.py b/setup3.py deleted file mode 100644 index a3cbdc8e..00000000 --- a/setup3.py +++ /dev/null @@ -1,77 +0,0 @@ -#! /usr/bin/env python3 -# $Id: setup.py,v 1.2 2002/01/08 07:13:21 jgg Exp $ -import glob -import os -import shutil -import sys - -from distutils.core import setup, Extension -from distutils.sysconfig import parse_makefile -#from DistUtilsExtra.command import build_extra, build_i18n - - -# The apt_pkg module -files = ["python/"+source for source in parse_makefile("python/makefile")["APT_PKG_SRC"].split()] -apt_pkg = Extension("apt_pkg", files, libraries=["apt-pkg"]) - -# The apt_inst module -files = ["python/"+source for source in parse_makefile("python/makefile")["APT_INST_SRC"].split()] -apt_inst = Extension("apt_inst", files, libraries=["apt-pkg", "apt-inst"]) - -# Replace the leading _ that is used in the templates for translation -templates = [] - -# build doc -if len(sys.argv) > 1 and sys.argv[1] == "build": - if not os.path.exists("build/data/templates/"): - os.makedirs("build/data/templates") - for template in glob.glob('data/templates/*.info.in'): - source = open(template, "r") - build = open(os.path.join("build", template[:-3]), "w") - lines = source.readlines() - for line in lines: - build.write(line.lstrip("_")) - source.close() - build.close() - - -if len(sys.argv) > 1 and sys.argv[1] == "clean" and '-a' in sys.argv: - for dirname in "build/doc", "doc/build", "build/data", "build/mo": - if os.path.exists(dirname): - print("Removing", dirname) - shutil.rmtree(dirname) - else: - print("Not removing", dirname, "because it does not exist") - -setup(name="python-apt", - description="Python bindings for APT", - version=os.environ.get('DEBVER'), - author="APT Development Team", - author_email="deity@lists.debian.org", - ext_modules=[apt_pkg, apt_inst], - packages=['apt', 'apt.progress', 'aptsources'], - data_files = [('share/python-apt/templates', - glob.glob('build/data/templates/*.info')), - ('share/python-apt/templates', - glob.glob('data/templates/*.mirrors'))], -# cmdclass = {"build": build_extra.build_extra, -# "build_i18n": build_i18n.build_i18n}, - license = 'GNU GPL', - platforms = 'posix') - -if len(sys.argv) > 1 and sys.argv[1] == "build": - try: - import sphinx - except ImportError: - print(('W: Sphinx not available - Not building' - 'documentation'), file=sys.stderr) - try: - import pygtk - except ImportError: - print(('W: Not building documentation because python-' - 'gtk2 is not available at the moment.'), file=sys.stderr) - sys.exit(0) - sphinx.main(["sphinx", "-b", "html", "-d", "build/doc/doctrees", - os.path.abspath("doc/source"), "build/doc/html"]) - sphinx.main(["sphinx", "-b", "text", "-d", "build/doc/doctrees", - os.path.abspath("doc/source"), "build/doc/text"]) -- cgit v1.2.3 From 03d50af0b317fb6501be1cd1f5be1a1ff3526703 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Wed, 15 Jul 2009 20:37:31 +0200 Subject: python/python-apt.h: Do not include apt-pkg/hashes.h. Users of the API should include the bits themselves. We don't need to include them, because we only use macros. --- python/python-apt.h | 1 - 1 file changed, 1 deletion(-) (limited to 'python') diff --git a/python/python-apt.h b/python/python-apt.h index 557f5a3b..16734238 100644 --- a/python/python-apt.h +++ b/python/python-apt.h @@ -22,7 +22,6 @@ #ifndef PYTHON_APT_H #define PYTHON_APT_H #include -#include #include "generic.h" struct _PyAptPkgAPIStruct { -- cgit v1.2.3 From aaf5907863bed9a044fa0e3e2eacd1ca2de53c59 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Wed, 15 Jul 2009 21:36:58 +0200 Subject: Introduce new progress (base) classes in apt_pkg: - apt_pkg.AcquireProgress - apt_pkg.OpProgress --- debian/changelog | 3 + python/acquireprogress.cc | 198 ++++++++++++++++++++++++++++++++++++++++++++++ python/apt_pkgmodule.cc | 2 + python/apt_pkgmodule.h | 2 + python/opprogress.cc | 173 ++++++++++++++++++++++++++++++++++++++++ python/progress.cc | 14 +++- setup.py | 5 +- 7 files changed, 393 insertions(+), 4 deletions(-) create mode 100644 python/acquireprogress.cc create mode 100644 python/opprogress.cc (limited to 'python') diff --git a/debian/changelog b/debian/changelog index 5e3ec667..b2936ba1 100644 --- a/debian/changelog +++ b/debian/changelog @@ -39,6 +39,9 @@ python-apt (0.7.92) UNRELEASED; urgency=low work around a bug in debhelper. * Build-Depend on python-all-dev (>= 2.5.4-3), so we build for Python 2.6 * Simplify the whole building, build all Python versions with setup.py + * Introduce new progress (base) classes in apt_pkg: + - apt_pkg.AcquireProgress + - apt_pkg.OpProgress [ Sebastian Heinlein ] * apt/progress.py: Extract the package name from the status message diff --git a/python/acquireprogress.cc b/python/acquireprogress.cc new file mode 100644 index 00000000..ac3b8fd9 --- /dev/null +++ b/python/acquireprogress.cc @@ -0,0 +1,198 @@ +/* acquireprogress.cc - Base class for FetchProgress classes. + * + * Copyright 2009 Julian Andres Klode + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + */ + +#include "generic.h" +#include +#include + +typedef struct { + PyObject_HEAD + double last_bytes; + double current_cps; + double current_bytes; + double total_bytes; + double fetched_bytes; + unsigned long elapsed_time; + unsigned long total_items; + unsigned long current_items; +} PyAcquireProgressObject; + + +// DUMMY IMPLEMENTATIONS. +static char *acquireprogress_media_change_doc = + "media_change(media: str, drive: str) -> bool\n\n" + "Invoked when the user should be prompted to change the inserted\n" + "removable media.\n\n" + "This method should not return until the user has confirmed to the user\n" + "interface that the media change is complete.\n\n" + ":param:media The name of the media type that should be changed.\n" + ":param:drive The identifying name of the drive whose media should be\n" + " changed.\n\n" + "Return True if the user confirms the media change, False if it is\n" + "cancelled."; +static PyObject *acquireprogress_media_change(PyObject *self, PyObject *args) +{ + Py_RETURN_FALSE; +} + +static char *acquireprogress_ims_hit_doc = "ims_hit(item: AcquireItemDesc)\n\n" + "Invoked when an item is confirmed to be up-to-date. For instance,\n" + "when an HTTP download is informed that the file on the server was\n" + "not modified."; +static PyObject *acquireprogress_ims_hit(PyObject *self, PyObject *arg) +{ + // TODO: Add type check. + Py_RETURN_NONE; +} + +static char *acquireprogress_fetch_doc = "fetch(item: AcquireItemDesc)\n\n" + "Invoked when some of an item's data is fetched."; +static PyObject *acquireprogress_fetch(PyObject *self, PyObject *args) +{ + // TODO: Add type check. + Py_RETURN_NONE; +} + +static char *acquireprogress_done_doc = "done(item: AcquireItemDesc)\n\n" + "Invoked when an item is successfully and completely fetched."; +static PyObject *acquireprogress_done(PyObject *self, PyObject *args) +{ + // TODO: Add type check. + Py_RETURN_NONE; +} + +static char *acquireprogress_fail_doc = "fail(item: AcquireItemDesc)\n\n" + "Invoked when the process of fetching an item encounters a fatal error."; +static PyObject *acquireprogress_fail(PyObject *self, PyObject *args) +{ + // TODO: Add type check. + Py_RETURN_NONE; +} + +static char *acquireprogress_pulse_doc = "pulse(owner: Acquire) -> bool\n\n" + "Periodically invoked while the Acquire process is underway.\n\n" + "Return False if the user asked to cancel the whole Acquire process."; +static PyObject *acquireprogress_pulse(PyObject *self, PyObject *args) +{ + // TODO: Add type check. + Py_RETURN_TRUE; +} + +static char *acquireprogress_start_doc = "start()\n\n" + "Invoked when the Acquire process starts running."; +static PyObject *acquireprogress_start(PyObject *self, PyObject *args) +{ + Py_RETURN_NONE; +} + +static char *acquireprogress_stop_doc = "stop()\n\n" + "Invoked when the Acquire process stops running."; +static PyObject *acquireprogress_stop(PyObject *self, PyObject *args) +{ + Py_RETURN_NONE; +} + +static PyMethodDef acquireprogress_methods[] = { + {"media_change", acquireprogress_media_change, METH_VARARGS, + acquireprogress_media_change_doc}, + {"ims_hit",acquireprogress_ims_hit,METH_VARARGS, + acquireprogress_ims_hit_doc}, + {"fetch",acquireprogress_fetch,METH_VARARGS,acquireprogress_fetch_doc}, + {"done",acquireprogress_done,METH_VARARGS,acquireprogress_done_doc}, + {"fail",acquireprogress_fail,METH_VARARGS,acquireprogress_fail_doc}, + {"pulse",acquireprogress_pulse,METH_VARARGS,acquireprogress_pulse_doc}, + {"start",acquireprogress_start,METH_NOARGS,acquireprogress_start_doc}, + {"stop",acquireprogress_stop,METH_NOARGS,acquireprogress_stop_doc}, + {NULL} +}; + +static PyMemberDef acquireprogress_members[] = { + {"last_bytes", T_DOUBLE, offsetof(PyAcquireProgressObject, last_bytes), 0, + "The number of bytes fetched as of the previous call to pulse(),\n" + "including local items."}, + {"current_cps", T_DOUBLE, offsetof(PyAcquireProgressObject, current_cps), 0, + "The current rate of download, in bytes per second."}, + {"current_bytes", T_DOUBLE, offsetof(PyAcquireProgressObject, current_bytes), + 0, "The number of bytes fetched."}, + {"total_bytes", T_DOUBLE, offsetof(PyAcquireProgressObject, total_bytes), 0, + "The total number of bytes that need to be fetched. This member is\n" + "inaccurate, as new items might be enqueued while the download is\n" + "in progress!"}, + {"fetched_bytes", T_DOUBLE,offsetof(PyAcquireProgressObject, fetched_bytes), + 0, "The total number of bytes accounted for by items that were\n" + "successfully fetched."}, + {"elapsed_time", T_ULONG, offsetof(PyAcquireProgressObject, elapsed_time),0, + "The amount of time that has elapsed since the download started."}, + {"total_items", T_ULONG, offsetof(PyAcquireProgressObject, total_items),0, + "The total number of items that need to be fetched. This member is\n" + "inaccurate, as new items might be enqueued while the download is\n" + "in progress!"}, + {"current_items", T_ULONG, offsetof(PyAcquireProgressObject, current_items), + 0, "The number of items that have been successfully downloaded."}, + {NULL} +}; + +static char *acquireprogress_doc = "AcquireProgress()\n\n" + "A monitor object for downloads controlled by the Acquire class. This is\n" + "an mostly abstract class. You should subclass it and implement the\n" + "methods to get something useful."; + +PyTypeObject PyAcquireProgress_Type = { + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "apt_pkg.AcquireProgress", // tp_name + sizeof(PyAcquireProgressObject), // tp_basicsize + 0, // tp_itemsize + // Methods + 0, // tp_dealloc + 0, // tp_print + 0, // tp_getattr + 0, // tp_setattr + 0, // tp_compare + 0, // tp_repr + 0, // tp_as_number + 0, // tp_as_sequence + 0, // tp_as_mapping + 0, // tp_hash + 0, // tp_call + 0, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + Py_TPFLAGS_DEFAULT | // tp_flags + Py_TPFLAGS_BASETYPE, + acquireprogress_doc, // tp_doc + 0, // tp_traverse + 0, // tp_clear + 0, // tp_richcompare + 0, // tp_weaklistoffset + 0, // tp_iter + 0, // tp_iternext + acquireprogress_methods, // tp_methods + acquireprogress_members, // tp_members + 0, // tp_getset + 0, // tp_base + 0, // tp_dict + 0, // tp_descr_get + 0, // tp_descr_set + 0, // tp_dictoffset + 0, // tp_init + 0, // tp_alloc + PyType_GenericNew, // tp_new +}; diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index bc2f4258..4f948847 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -621,6 +621,8 @@ extern "C" void initapt_pkg() ADDTYPE(Module,"HashString",&PyHashString_Type); ADDTYPE(Module,"Policy",&PyPolicy_Type); ADDTYPE(Module,"Hashes",&PyHashes_Type); + ADDTYPE(Module,"OpProgress",&PyOpProgress_Type); + ADDTYPE(Module,"AcquireProgress",&PyAcquireProgress_Type); // Tag file constants PyModule_AddObject(Module,"REWRITE_PACKAGE_ORDER", CharCharToList(TFRewritePackageOrder)); diff --git a/python/apt_pkgmodule.h b/python/apt_pkgmodule.h index 97be5d5c..34bc2ae5 100644 --- a/python/apt_pkgmodule.h +++ b/python/apt_pkgmodule.h @@ -112,6 +112,8 @@ extern PyTypeObject PyIndexRecords_Type; // Policy extern PyTypeObject PyPolicy_Type; extern PyTypeObject PyHashes_Type; +extern PyTypeObject PyOpProgress_Type; +extern PyTypeObject PyAcquireProgress_Type; #include "python-apt.h" #endif diff --git a/python/opprogress.cc b/python/opprogress.cc new file mode 100644 index 00000000..450e290a --- /dev/null +++ b/python/opprogress.cc @@ -0,0 +1,173 @@ +/* op-progress.cc - Base class for OpProgress classes. + * + * Copyright 2009 Julian Andres Klode + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + */ + +#include "generic.h" +#include +#include + +typedef struct { + PyObject_HEAD + PyObject *op; + PyObject *subop; + int major_change; + float percent; +} PyOpProgressObject; + +static PyObject *opprogress_update(PyObject *Self, PyObject *args) +{ + Py_RETURN_NONE; +} + +static PyObject *opprogress_done(PyObject *Self, PyObject *args) +{ + Py_RETURN_NONE; +} + +static PyObject *opprogress_get_op(PyOpProgressObject *self, void *closure) +{ + return self->op; +} + +static int opprogress_set_op(PyOpProgressObject *self, PyObject *value, + void *closure) +{ + if (value == NULL) { + PyErr_SetString(PyExc_TypeError, "Cannot delete 'op'"); + return -1; + } + if (!PyString_Check(value)) { + PyErr_SetString(PyExc_TypeError,"'op' must be a string."); + return -1; + } + Py_DECREF(self->op); + Py_INCREF(value); + + self->op = value; + return 0; +} + +static PyObject *opprogress_get_subop(PyOpProgressObject *self, void *closure) +{ + return self->subop; +} + +static int opprogress_set_subop(PyOpProgressObject *self, PyObject *value, + void *closure) +{ + if (value == NULL) { + PyErr_SetString(PyExc_TypeError, "Cannot delete 'subop'."); + return -1; + } + if (!PyString_Check(value)) { + PyErr_SetString(PyExc_TypeError,"'subop' must be a string."); + return -1; + } + Py_DECREF(self->subop); + Py_INCREF(value); + self->subop = value; + return 0; +} + +static PyMethodDef opprogress_methods[] = { + {"update",opprogress_update,METH_NOARGS,"update()\n\nCalled periodically."}, + {"done",opprogress_done,METH_NOARGS,"update()\n\nCalled when done."}, + {NULL}, +}; + +static PyMemberDef opprogress_members[] = { + {"major_change", T_INT, offsetof(PyOpProgressObject, major_change), 0, + "Boolean value indicating whether the change is a major change."}, + {"percent", T_FLOAT, offsetof(PyOpProgressObject, percent), 0, + "Percentage of completion (float value)."}, + {NULL} +}; + +static PyGetSetDef opprogress_getset[] = { + {"op", (getter)opprogress_get_op, (setter)opprogress_set_op, + "Description of the current operation"}, + {"subop", (getter)opprogress_get_subop, (setter)opprogress_set_subop, + "Description of the current sub-operation"}, + {NULL}, +}; + +static void opprogress_dealloc(PyObject *self) +{ + Py_XDECREF(((PyOpProgressObject *)self)->op); + Py_XDECREF(((PyOpProgressObject *)self)->subop); + self->ob_type->tp_free(self); +} + +static PyObject *opprogress_new(PyTypeObject *type, PyObject *args, + PyObject *kwds) +{ + PyOpProgressObject *res = (PyOpProgressObject *)type->tp_alloc(type, 0); + res->op = PyString_FromString(""); + res->subop = PyString_FromString(""); + return (PyObject *)res; +} + +static char *opprogress_doc = "OpProgress()\n\n" + "A base class for writing custom operation progress classes. Subclasses\n" + "should override all the methods (and call the parent ones) but shall\n" + "not override any of the inherited descriptors because they may be\n" + "ignored."; + +PyTypeObject PyOpProgress_Type = { + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "apt_pkg.OpProgress", // tp_name + sizeof(PyOpProgressObject), // tp_basicsize + 0, // tp_itemsize + // Methods + opprogress_dealloc, // tp_dealloc + 0, // tp_print + 0, // tp_getattr + 0, // tp_setattr + 0, // tp_compare + 0, // tp_repr + 0, // tp_as_number + 0, // tp_as_sequence + 0, // tp_as_mapping + 0, // tp_hash + 0, // tp_call + 0, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + Py_TPFLAGS_DEFAULT | // tp_flags + Py_TPFLAGS_BASETYPE, + opprogress_doc, // tp_doc + 0, // tp_traverse + 0, // tp_clear + 0, // tp_richcompare + 0, // tp_weaklistoffset + 0, // tp_iter + 0, // tp_iternext + opprogress_methods, // tp_methods + opprogress_members, // tp_members + opprogress_getset, // tp_getset + 0, // tp_base + 0, // tp_dict + 0, // tp_descr_get + 0, // tp_descr_set + 0, // tp_dictoffset + 0, // tp_init + 0, // tp_alloc + opprogress_new, // tp_new +}; diff --git a/python/progress.cc b/python/progress.cc index 44f27b0c..b1845f0a 100644 --- a/python/progress.cc +++ b/python/progress.cc @@ -15,6 +15,7 @@ #include #include "progress.h" #include "generic.h" +#include "apt_pkgmodule.h" // generic bool PyCallbackObj::RunSimpleCallback(const char* method_name, @@ -75,11 +76,20 @@ void PyOpProgress::Update() PyObject_SetAttrString(callbackInst, "majorChange", o); Py_XDECREF(o); + + // Build up the argument list... if(CheckChange(0.05)) { - PyObject *arglist = Py_BuildValue("(f)", Percent); - RunSimpleCallback("update", arglist); + if (PyObject_TypeCheck(callbackInst, &PyOpProgress_Type)) { + o = Py_BuildValue("f", Percent); + PyObject_SetAttrString(callbackInst, "percent", o); + RunSimpleCallback("update"); + Py_XDECREF(o); + } else { + PyObject *arglist = Py_BuildValue("(f)", Percent); + RunSimpleCallback("update", arglist); + } } }; diff --git a/setup.py b/setup.py index af373632..b6dde3f9 100644 --- a/setup.py +++ b/setup.py @@ -34,8 +34,9 @@ files = ['apt_pkgmodule.cc', 'acquire.cc', 'cache.cc', 'cdrom.cc', 'configuration.cc', 'depcache.cc', 'generic.cc', 'hashes.cc', 'hashstring.cc', 'indexfile.cc', 'indexrecords.cc', 'metaindex.cc', 'pkgmanager.cc', 'pkgrecords.cc', 'pkgsrcrecords.cc', 'policy.cc', - 'progress.cc', 'sourcelist.cc', 'string.cc', 'tag.cc'] -files = ['python/' + fname for fname in files] + 'progress.cc', 'sourcelist.cc', 'string.cc', 'tag.cc', + 'opprogress.cc', 'acquireprogress.cc'] +files = sorted(['python/' + fname for fname in files]) apt_pkg = Extension("apt_pkg", files, libraries=["apt-pkg"]) # The apt_inst module -- cgit v1.2.3 From 48097301f9cc685a8ad1229a28f34d36ad19665b Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Wed, 15 Jul 2009 22:20:02 +0200 Subject: python/acquire.cc: Add AcquireItemDesc. --- python/acquire.cc | 73 ++++++++++++++++++++++++++++++++++++++++++++++++- python/apt_pkgmodule.cc | 2 ++ python/apt_pkgmodule.h | 1 + python/python-apt.h | 6 ++++ 4 files changed, 81 insertions(+), 1 deletion(-) (limited to 'python') diff --git a/python/acquire.cc b/python/acquire.cc index c3f2fc5d..6c4baf9c 100644 --- a/python/acquire.cc +++ b/python/acquire.cc @@ -20,6 +20,78 @@ struct PyAcquireObject : public CppPyObject { vector items; }; +static PyObject *acquireitemdesc_get_uri(PyObject *self, void *closure) +{ + return CppPyString(GetCpp(self).URI); +} +static PyObject *acquireitemdesc_get_description(PyObject *self, void *closure) +{ + return CppPyString(GetCpp(self).Description); +} +static PyObject *acquireitemdesc_get_shortdesc(PyObject *self, void *closure) +{ + return CppPyString(GetCpp(self).ShortDesc); +} +static PyObject *acquireitemdesc_get_owner(PyObject *self, void *closure) +{ + return GetOwner(self); +} + +static PyGetSetDef acquireitemdesc_getset[] = { + {"uri",acquireitemdesc_get_uri,0,"The URI from which to download this item."}, + {"description",acquireitemdesc_get_description}, + {"shortdesc",acquireitemdesc_get_shortdesc}, + {"owner",acquireitemdesc_get_owner}, + {NULL} +}; + +static char *acquireitemdesc_doc = + "Represent an AcquireItemDesc"; + +PyTypeObject PyAcquireItemDesc_Type = +{ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "apt_pkg.AcquireItemDesc", // tp_name + sizeof(CppOwnedPyObject),// tp_basicsize + 0, // tp_itemsize + // Methods + CppOwnedDealloc, // tp_dealloc + 0, // tp_print + 0, // tp_getattr + 0, // tp_setattr + 0, // tp_compare + 0, // tp_repr + 0, // tp_as_number + 0, // tp_as_sequence + 0, // tp_as_mapping + 0, // tp_hash + 0, // tp_call + 0, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + (Py_TPFLAGS_DEFAULT | // tp_flags + Py_TPFLAGS_HAVE_GC), + acquireitemdesc_doc, // tp_doc + CppOwnedTraverse,// tp_traverse + CppOwnedClear, // tp_clear + 0, // tp_richcompare + 0, // tp_weaklistoffset + 0, // tp_iter + 0, // tp_iternext + 0, // tp_methods + 0, // tp_members + acquireitemdesc_getset, // tp_getset + 0, // tp_base + 0, // tp_dict + 0, // tp_descr_get + 0, // tp_descr_set + 0, // tp_dictoffset + 0, // tp_init + 0, // tp_alloc + 0, // tp_new +}; + inline pkgAcquire::Item *acquireitem_tocpp(PyObject *self) { pkgAcquire::Item *itm = GetCpp(self); if (itm == 0) @@ -47,7 +119,6 @@ MkGet(AcquireItemGetIsTrusted,Py_BuildValue("i",Itm->IsTrusted())); MkGet(AcquireItemGetLocal,Py_BuildValue("i",Itm->Local)); MkGet(AcquireItemGetStatus,Py_BuildValue("i",Itm->Status)); - // Constants MkGet(AcquireItemGetStatIdle,Py_BuildValue("i", pkgAcquire::Item::StatIdle)); MkGet(AcquireItemGetStatFetching,Py_BuildValue("i", pkgAcquire::Item::StatFetching)); diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index 4f948847..5d7b6c47 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -502,6 +502,7 @@ static struct _PyAptPkgAPIStruct API = { &PyAcquire_Type, // acquire_type &PyAcquireFile_Type, // acquirefile_type &PyAcquireItem_Type, // acquireitem_type + &PyAcquireItemDesc_Type, // acquireitemdesc_type &PyActionGroup_Type, // actiongroup_type &PyCache_Type, // cache_type &PyCacheFile_Type, // cachefile_type @@ -623,6 +624,7 @@ extern "C" void initapt_pkg() ADDTYPE(Module,"Hashes",&PyHashes_Type); ADDTYPE(Module,"OpProgress",&PyOpProgress_Type); ADDTYPE(Module,"AcquireProgress",&PyAcquireProgress_Type); + ADDTYPE(Module,"AcquireItemDesc",&PyAcquireItemDesc_Type); // Tag file constants PyModule_AddObject(Module,"REWRITE_PACKAGE_ORDER", CharCharToList(TFRewritePackageOrder)); diff --git a/python/apt_pkgmodule.h b/python/apt_pkgmodule.h index 34bc2ae5..835cfd9b 100644 --- a/python/apt_pkgmodule.h +++ b/python/apt_pkgmodule.h @@ -114,6 +114,7 @@ extern PyTypeObject PyPolicy_Type; extern PyTypeObject PyHashes_Type; extern PyTypeObject PyOpProgress_Type; extern PyTypeObject PyAcquireProgress_Type; +extern PyTypeObject PyAcquireItemDesc_Type; #include "python-apt.h" #endif diff --git a/python/python-apt.h b/python/python-apt.h index 16734238..53f6b0bb 100644 --- a/python/python-apt.h +++ b/python/python-apt.h @@ -28,6 +28,7 @@ struct _PyAptPkgAPIStruct { PyTypeObject *acquire_type; PyTypeObject *acquirefile_type; PyTypeObject *acquireitem_type; + PyTypeObject *acquireitemdesc_type; PyTypeObject *actiongroup_type; PyTypeObject *cache_type; PyTypeObject *cachefile_type; @@ -60,6 +61,7 @@ struct _PyAptPkgAPIStruct { # define PyAcquire_Type *(_PyAptPkg_API->acquire_type) # define PyAcquireFile_Type *(_PyAptPkg_API->acquirefile_type) # define PyAcquireItem_Type *(_PyAptPkg_API->acquireitem_type) +# define PyAcquireItemDesc_Type *(_PyAptPkg_API->acquireitemdesc_type) # define PyActionGroup_Type *(_PyAptPkg_API->actiongroup_type) # define PyCache_Type *(_PyAptPkg_API->cache_type) # define PyCacheFile_Type *(_PyAptPkg_API->cachefile_type) @@ -119,6 +121,7 @@ static int import_apt_pkg(void) { # define PyAcquire_Check(op) PyObject_TypeCheck(op, &PyAcquire_Type) # define PyAcquireFile_Check(op) PyObject_TypeCheck(op, &PyAcquireFile_Type) # define PyAcquireItem_Check(op) PyObject_TypeCheck(op, &PyAcquireItem_Type) +# define PyAcquireItemDesc_Check(op) PyObject_TypeCheck(op, &PyAcquireItemDesc_Type) # define PyActionGroup_Check(op) PyObject_TypeCheck(op, &PyActionGroup_Type) # define PyCache_Check(op) PyObject_TypeCheck(op, &PyCache_Type) # define PyCacheFile_Check(op) PyObject_TypeCheck(op, &PyCacheFile_Type) @@ -149,6 +152,7 @@ static int import_apt_pkg(void) { # define PyAcquire_CheckExact(op) (Py_TYPE(op) == &PyAcquire_Type) # define PyAcquireFile_CheckExact(op) (Py_TYPE(op) == &PyAcquireFile_Type) # define PyAcquireItem_CheckExact(op) (Py_TYPE(op) == &PyAcquireItem_Type) +# define PyAcquireItemDesc_CheckExact(op) (Py_TYPE(op) == &PyAcquireItemDesc_Type) # define PyActionGroup_CheckExact(op) (Py_TYPE(op) == &PyActionGroup_Type) # define PyCache_CheckExact(op) (Py_TYPE(op) == &PyCache_Type) # define PyCacheFile_CheckExact(op) (Py_TYPE(op) == &PyCacheFile_Type) @@ -180,6 +184,7 @@ static int import_apt_pkg(void) { # define PyAcquire_ToCpp GetCpp # define PyAcquireFile_ToCpp GetCpp # define PyAcquireItem_ToCpp GetCpp +# define PyAcquireItemDesc_ToCpp GetCpp # define PyActionGroup_ToCpp GetCpp # define PyCache_ToCpp GetCpp # define PyCacheFile_ToCpp GetCpp @@ -229,6 +234,7 @@ inline PyObject *FromCppOwned(PyTypeObject *pytype, Cpp const &obj, # define PyAcquire_FromCpp(...) FromCpp(&PyAcquire_Type, ##__VA_ARGS__) # define PyAcquireFile_FromCpp(...) FromCppOwned(&PyAcquireFile_Type, ##__VA_ARGS__) # define PyAcquireItem_FromCpp(...) FromCppOwned(&PyAcquireItemType,##__VA_ARGS__) +# define PyAcquireItemDesc_FromCpp(...) FromCppOwned(&PyAcquireItemDesc_Type,##__VA_ARGS__) # define PyActionGroup_FromCpp(...) FromCppOwned(&PyActionGroup_Type,##__VA_ARGS__) # define PyCache_FromCpp(...) FromCppOwned(&PyCache_Type,##__VA_ARGS__) # define PyCacheFile_FromCpp(...) FromCpp(&PyCacheFile_Type,##__VA_ARGS__) -- cgit v1.2.3 From c12a853032583a8ed829e2d0ac6752bc14efdc80 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Wed, 15 Jul 2009 22:21:23 +0200 Subject: python/progress.cc: Add support for PyAcquireProgress. --- python/progress.cc | 38 ++++++++++++++++++++++++++++++++++---- 1 file changed, 34 insertions(+), 4 deletions(-) (limited to 'python') diff --git a/python/progress.cc b/python/progress.cc index b1845f0a..c53a2ea5 100644 --- a/python/progress.cc +++ b/python/progress.cc @@ -17,6 +17,7 @@ #include "generic.h" #include "apt_pkgmodule.h" +#define TUPLEIZE(op) Py_BuildValue("(O)", op) // generic bool PyCallbackObj::RunSimpleCallback(const char* method_name, PyObject *arglist, @@ -151,17 +152,26 @@ void PyFetchProgress::UpdateStatus(pkgAcquire::ItemDesc &Itm, int status) void PyFetchProgress::IMSHit(pkgAcquire::ItemDesc &Itm) { - UpdateStatus(Itm, DLHit); + if (PyObject_TypeCheck(callbackInst,&PyAcquireProgress_Type)) + RunSimpleCallback("ims_hit", TUPLEIZE(PyAcquireItemDesc_FromCpp(Itm))); + else + UpdateStatus(Itm, DLHit); } void PyFetchProgress::Fetch(pkgAcquire::ItemDesc &Itm) { - UpdateStatus(Itm, DLQueued); + if (PyObject_TypeCheck(callbackInst,&PyAcquireProgress_Type)) + RunSimpleCallback("fetch", TUPLEIZE(PyAcquireItemDesc_FromCpp(Itm))); + else + UpdateStatus(Itm, DLQueued); } void PyFetchProgress::Done(pkgAcquire::ItemDesc &Itm) { - UpdateStatus(Itm, DLDone); + if (PyObject_TypeCheck(callbackInst,&PyAcquireProgress_Type)) + RunSimpleCallback("done", TUPLEIZE(PyAcquireItemDesc_FromCpp(Itm))); + else + UpdateStatus(Itm, DLDone); } void PyFetchProgress::Fail(pkgAcquire::ItemDesc &Itm) @@ -175,7 +185,11 @@ void PyFetchProgress::Fail(pkgAcquire::ItemDesc &Itm) UpdateStatus(Itm, DLIgnored); } - UpdateStatus(Itm, DLFailed); + + if (PyObject_TypeCheck(callbackInst,&PyAcquireProgress_Type)) + RunSimpleCallback("fail", TUPLEIZE(PyAcquireItemDesc_FromCpp(Itm))); + else + UpdateStatus(Itm, DLFailed); } void PyFetchProgress::Start() @@ -183,6 +197,9 @@ void PyFetchProgress::Start() //std::cout << "Start" << std::endl; pkgAcquireStatus::Start(); + if (PyObject_TypeCheck(callbackInst,&PyAcquireProgress_Type)) + goto end; + // These attributes should be initialized before the first callback (start) // is invoked. // -- Stephan @@ -198,12 +215,14 @@ void PyFetchProgress::Start() PyObject_SetAttrString(callbackInst, "currentItems", o); Py_XDECREF(o); o = Py_BuildValue("i", 0); + PyObject_SetAttrString(callbackInst, "totalItems", o); Py_XDECREF(o); o = Py_BuildValue("f", 0.0f); PyObject_SetAttrString(callbackInst, "totalBytes", o); Py_XDECREF(o); +end: RunSimpleCallback("start"); } @@ -256,6 +275,17 @@ bool PyFetchProgress::Pulse(pkgAcquire * Owner) PyObject_SetAttrString(callbackInst, "totalBytes", o); Py_XDECREF(o); + if (PyObject_TypeCheck(callbackInst, &PyAcquireProgress_Type)) { + PyObject *result1; + bool res1 = true; + if (RunSimpleCallback("pulse", TUPLEIZE(PyAcquire_FromCpp(Owner)), &result1)) { + if (result1 != NULL && PyArg_Parse(result1, "b", &res1) && res1 == false) { + // the user returned a explicit false here, stop + return false; + } + } + return true; + } // Go through the list of items and add active items to the // activeItems vector. map activeItemMap; -- cgit v1.2.3 From 732914877a2c96b954e9d998deaa6e3a56bf932f Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Thu, 16 Jul 2009 13:23:09 +0200 Subject: python/acquireprogress.cc: Check the arguments. --- python/acquireprogress.cc | 50 +++++++++++++++++++++++++++++++++-------------- 1 file changed, 35 insertions(+), 15 deletions(-) (limited to 'python') diff --git a/python/acquireprogress.cc b/python/acquireprogress.cc index ac3b8fd9..eb02d018 100644 --- a/python/acquireprogress.cc +++ b/python/acquireprogress.cc @@ -18,7 +18,7 @@ * MA 02110-1301, USA. */ -#include "generic.h" +#include "apt_pkgmodule.h" #include #include @@ -58,40 +58,60 @@ static char *acquireprogress_ims_hit_doc = "ims_hit(item: AcquireItemDesc)\n\n" "not modified."; static PyObject *acquireprogress_ims_hit(PyObject *self, PyObject *arg) { - // TODO: Add type check. + if (!PyAcquireItemDesc_Check(arg)) { + PyErr_SetString(PyExc_TypeError, "ims_hit() argument must be " + "apt_pkg.AcquireItemDesc"); + return 0; + } Py_RETURN_NONE; } static char *acquireprogress_fetch_doc = "fetch(item: AcquireItemDesc)\n\n" "Invoked when some of an item's data is fetched."; -static PyObject *acquireprogress_fetch(PyObject *self, PyObject *args) +static PyObject *acquireprogress_fetch(PyObject *self, PyObject *arg) { - // TODO: Add type check. + if (!PyAcquireItemDesc_Check(arg)) { + PyErr_SetString(PyExc_TypeError, "fetch() argument must be " + "apt_pkg.AcquireItemDesc"); + return 0; + } Py_RETURN_NONE; } static char *acquireprogress_done_doc = "done(item: AcquireItemDesc)\n\n" "Invoked when an item is successfully and completely fetched."; -static PyObject *acquireprogress_done(PyObject *self, PyObject *args) +static PyObject *acquireprogress_done(PyObject *self, PyObject *arg) { - // TODO: Add type check. + if (!PyAcquireItemDesc_Check(arg)) { + PyErr_SetString(PyExc_TypeError, "done() argument must be " + "apt_pkg.AcquireItemDesc"); + return 0; + } Py_RETURN_NONE; } static char *acquireprogress_fail_doc = "fail(item: AcquireItemDesc)\n\n" "Invoked when the process of fetching an item encounters a fatal error."; -static PyObject *acquireprogress_fail(PyObject *self, PyObject *args) +static PyObject *acquireprogress_fail(PyObject *self, PyObject *arg) { - // TODO: Add type check. + if (!PyAcquireItemDesc_Check(arg)) { + PyErr_SetString(PyExc_TypeError, "fail() argument must be " + "apt_pkg.AcquireItemDesc"); + return 0; + } Py_RETURN_NONE; } static char *acquireprogress_pulse_doc = "pulse(owner: Acquire) -> bool\n\n" "Periodically invoked while the Acquire process is underway.\n\n" "Return False if the user asked to cancel the whole Acquire process."; -static PyObject *acquireprogress_pulse(PyObject *self, PyObject *args) +static PyObject *acquireprogress_pulse(PyObject *self, PyObject *arg) { - // TODO: Add type check. + if (!PyAcquire_Check(arg)) { + PyErr_SetString(PyExc_TypeError, "pulse() argument must be " + "apt_pkg.Acquire"); + return 0; + } Py_RETURN_TRUE; } @@ -112,12 +132,12 @@ static PyObject *acquireprogress_stop(PyObject *self, PyObject *args) static PyMethodDef acquireprogress_methods[] = { {"media_change", acquireprogress_media_change, METH_VARARGS, acquireprogress_media_change_doc}, - {"ims_hit",acquireprogress_ims_hit,METH_VARARGS, + {"ims_hit",acquireprogress_ims_hit,METH_O, acquireprogress_ims_hit_doc}, - {"fetch",acquireprogress_fetch,METH_VARARGS,acquireprogress_fetch_doc}, - {"done",acquireprogress_done,METH_VARARGS,acquireprogress_done_doc}, - {"fail",acquireprogress_fail,METH_VARARGS,acquireprogress_fail_doc}, - {"pulse",acquireprogress_pulse,METH_VARARGS,acquireprogress_pulse_doc}, + {"fetch",acquireprogress_fetch,METH_O,acquireprogress_fetch_doc}, + {"done",acquireprogress_done,METH_O,acquireprogress_done_doc}, + {"fail",acquireprogress_fail,METH_O,acquireprogress_fail_doc}, + {"pulse",acquireprogress_pulse,METH_O,acquireprogress_pulse_doc}, {"start",acquireprogress_start,METH_NOARGS,acquireprogress_start_doc}, {"stop",acquireprogress_stop,METH_NOARGS,acquireprogress_stop_doc}, {NULL} -- cgit v1.2.3 From 6c9876724542889c6ee1542cf529b88ffa2cf456 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Thu, 16 Jul 2009 13:47:30 +0200 Subject: python/progress.cc: Fix the types of the attributes. --- python/progress.cc | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) (limited to 'python') diff --git a/python/progress.cc b/python/progress.cc index c53a2ea5..c33db502 100644 --- a/python/progress.cc +++ b/python/progress.cc @@ -205,20 +205,20 @@ void PyFetchProgress::Start() // -- Stephan PyObject *o; - o = Py_BuildValue("f", 0.0f); + o = Py_BuildValue("d", 0.0f); PyObject_SetAttrString(callbackInst, "currentCPS", o); Py_XDECREF(o); - o = Py_BuildValue("f", 0.0f); + o = Py_BuildValue("d", 0.0f); PyObject_SetAttrString(callbackInst, "currentBytes", o); Py_XDECREF(o); - o = Py_BuildValue("i", 0); + o = Py_BuildValue("k", 0); PyObject_SetAttrString(callbackInst, "currentItems", o); Py_XDECREF(o); - o = Py_BuildValue("i", 0); + o = Py_BuildValue("k", 0); PyObject_SetAttrString(callbackInst, "totalItems", o); Py_XDECREF(o); - o = Py_BuildValue("f", 0.0f); + o = Py_BuildValue("d", 0.0f); PyObject_SetAttrString(callbackInst, "totalBytes", o); Py_XDECREF(o); @@ -244,31 +244,31 @@ bool PyFetchProgress::Pulse(pkgAcquire * Owner) // set stats PyObject *o; - o = Py_BuildValue("f", CurrentCPS); + o = Py_BuildValue("d", CurrentCPS); if(PyObject_HasAttrString(callbackInst, "current_cps")) PyObject_SetAttrString(callbackInst, "current_cps", o); else PyObject_SetAttrString(callbackInst, "currentCPS", o); Py_XDECREF(o); - o = Py_BuildValue("f", CurrentBytes); + o = Py_BuildValue("d", CurrentBytes); if(PyObject_HasAttrString(callbackInst, "current_bytes")) PyObject_SetAttrString(callbackInst, "current_bytes", o); else PyObject_SetAttrString(callbackInst, "currentBytes", o); Py_XDECREF(o); - o = Py_BuildValue("i", CurrentItems); + o = Py_BuildValue("k", CurrentItems); if(PyObject_HasAttrString(callbackInst, "current_items")) PyObject_SetAttrString(callbackInst, "current_items", o); else PyObject_SetAttrString(callbackInst, "currentItems", o); Py_XDECREF(o); - o = Py_BuildValue("i", TotalItems); + o = Py_BuildValue("k", TotalItems); if(PyObject_HasAttrString(callbackInst, "total_items")) PyObject_SetAttrString(callbackInst, "total_items", o); else PyObject_SetAttrString(callbackInst, "totalItems", o); Py_XDECREF(o); - o = Py_BuildValue("f", TotalBytes); + o = Py_BuildValue("d", TotalBytes); if(PyObject_HasAttrString(callbackInst, "total_bytes")) PyObject_SetAttrString(callbackInst, "total_bytes", o); else -- cgit v1.2.3 From c6858a77337cc03f403b7d09c7eac0575db08942 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Thu, 16 Jul 2009 14:49:41 +0200 Subject: python/opprogress.cc: Increase the reference count before returning values. --- python/opprogress.cc | 2 ++ 1 file changed, 2 insertions(+) (limited to 'python') diff --git a/python/opprogress.cc b/python/opprogress.cc index 450e290a..ba9acd14 100644 --- a/python/opprogress.cc +++ b/python/opprogress.cc @@ -42,6 +42,7 @@ static PyObject *opprogress_done(PyObject *Self, PyObject *args) static PyObject *opprogress_get_op(PyOpProgressObject *self, void *closure) { + Py_INCREF(self->op); return self->op; } @@ -65,6 +66,7 @@ static int opprogress_set_op(PyOpProgressObject *self, PyObject *value, static PyObject *opprogress_get_subop(PyOpProgressObject *self, void *closure) { + Py_INCREF(self->subop); return self->subop; } -- cgit v1.2.3 From 20fadc70639593001e1a9174333331afa3b4982b Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Thu, 16 Jul 2009 15:18:15 +0200 Subject: python/progress.cc: Make PyOpProgress::Update() behave more like OpTextProgress. --- python/progress.cc | 35 +++++++++++++++++++---------------- 1 file changed, 19 insertions(+), 16 deletions(-) (limited to 'python') diff --git a/python/progress.cc b/python/progress.cc index c33db502..753949af 100644 --- a/python/progress.cc +++ b/python/progress.cc @@ -60,6 +60,11 @@ bool PyCallbackObj::RunSimpleCallback(const char* method_name, // OpProgress interface void PyOpProgress::Update() { + // Build up the argument list... + if(!CheckChange(0.7)) + return; + + PyObject *o; o = Py_BuildValue("s", Op.c_str()); PyObject_SetAttrString(callbackInst, "op", o); @@ -77,21 +82,19 @@ void PyOpProgress::Update() PyObject_SetAttrString(callbackInst, "majorChange", o); Py_XDECREF(o); - - - // Build up the argument list... - if(CheckChange(0.05)) - { - if (PyObject_TypeCheck(callbackInst, &PyOpProgress_Type)) { - o = Py_BuildValue("f", Percent); - PyObject_SetAttrString(callbackInst, "percent", o); - RunSimpleCallback("update"); - Py_XDECREF(o); - } else { - PyObject *arglist = Py_BuildValue("(f)", Percent); - RunSimpleCallback("update", arglist); - } + + + + if (PyObject_TypeCheck(callbackInst, &PyOpProgress_Type)) { + o = Py_BuildValue("f", Percent); + PyObject_SetAttrString(callbackInst, "percent", o); + RunSimpleCallback("update"); + Py_XDECREF(o); } + else { + PyObject *arglist = Py_BuildValue("(f)", Percent); + RunSimpleCallback("update", arglist); + } }; void PyOpProgress::Done() @@ -185,7 +188,7 @@ void PyFetchProgress::Fail(pkgAcquire::ItemDesc &Itm) UpdateStatus(Itm, DLIgnored); } - + if (PyObject_TypeCheck(callbackInst,&PyAcquireProgress_Type)) RunSimpleCallback("fail", TUPLEIZE(PyAcquireItemDesc_FromCpp(Itm))); else @@ -215,7 +218,7 @@ void PyFetchProgress::Start() PyObject_SetAttrString(callbackInst, "currentItems", o); Py_XDECREF(o); o = Py_BuildValue("k", 0); - + PyObject_SetAttrString(callbackInst, "totalItems", o); Py_XDECREF(o); o = Py_BuildValue("d", 0.0f); -- cgit v1.2.3 From 16995d9f7f53d93f08ae0b438c70ea9d5e4d35e1 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Thu, 16 Jul 2009 15:42:50 +0200 Subject: python/python-apt: PyAcquireItem_Type, not PyAcquireItemType. --- python/python-apt.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'python') diff --git a/python/python-apt.h b/python/python-apt.h index 53f6b0bb..fa589c55 100644 --- a/python/python-apt.h +++ b/python/python-apt.h @@ -233,7 +233,7 @@ inline PyObject *FromCppOwned(PyTypeObject *pytype, Cpp const &obj, # define PyAcquire_FromCpp(...) FromCpp(&PyAcquire_Type, ##__VA_ARGS__) # define PyAcquireFile_FromCpp(...) FromCppOwned(&PyAcquireFile_Type, ##__VA_ARGS__) -# define PyAcquireItem_FromCpp(...) FromCppOwned(&PyAcquireItemType,##__VA_ARGS__) +# define PyAcquireItem_FromCpp(...) FromCppOwned(&PyAcquireItem_Type,##__VA_ARGS__) # define PyAcquireItemDesc_FromCpp(...) FromCppOwned(&PyAcquireItemDesc_Type,##__VA_ARGS__) # define PyActionGroup_FromCpp(...) FromCppOwned(&PyActionGroup_Type,##__VA_ARGS__) # define PyCache_FromCpp(...) FromCppOwned(&PyCache_Type,##__VA_ARGS__) -- cgit v1.2.3 From ef106396218522fce5856744741c7b3f87261cc2 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Thu, 16 Jul 2009 16:03:02 +0200 Subject: python/acquire.cc: Introduce PyAcquireWorker_Type, make PyAcquireItemDesc_Type contain a pointer. --- python/acquire.cc | 108 +++++++++++++++++++++++++++++++++++++++++++----- python/apt_pkgmodule.cc | 13 +++--- python/apt_pkgmodule.h | 1 + python/progress.cc | 8 ++-- python/python-apt.h | 4 +- 5 files changed, 112 insertions(+), 22 deletions(-) (limited to 'python') diff --git a/python/acquire.cc b/python/acquire.cc index 6c4baf9c..25b10b06 100644 --- a/python/acquire.cc +++ b/python/acquire.cc @@ -11,6 +11,7 @@ #include "progress.h" #include +#include typedef CppPyObject PyAcquireItemObject; @@ -20,21 +21,93 @@ struct PyAcquireObject : public CppPyObject { vector items; }; + +static PyObject *acquireworker_get_current_item(PyObject *self, void *closure) +{ + return PyAcquireItemDesc_FromCpp((GetCpp(self)->CurrentItem),false,self); +} + +static PyObject *acquireworker_get_status(PyObject *self, void *closure) +{ + return CppPyString(GetCpp(self)->Status); +} + +static PyObject *acquireworker_get_current_size(PyObject *self, void *closure) +{ + return Py_BuildValue("k",GetCpp(self)->CurrentSize); +} + +static PyObject *acquireworker_get_total_size(PyObject *self, void *closure) +{ + return Py_BuildValue("k",GetCpp(self)->TotalSize); +} + +static PyObject *acquireworker_get_resumepoint(PyObject *self, void *closure) +{ + return Py_BuildValue("k",GetCpp(self)->ResumePoint); +} + +static PyGetSetDef acquireworker_getset[] = { + {"current_item",acquireworker_get_current_item}, + {"status",acquireworker_get_status}, + {"current_size",acquireworker_get_current_size}, + {"total_size",acquireworker_get_total_size}, + {"resumepoint",acquireworker_get_resumepoint}, + {NULL} +}; + + +PyTypeObject PyAcquireWorker_Type = +{ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "apt_pkg.AcquireWorker", // tp_name + sizeof(CppOwnedPyObject),// tp_basicsize + 0, // tp_itemsize + // Methods + CppOwnedDealloc, // tp_dealloc + 0, // tp_print + 0, // tp_getattr + 0, // tp_setattr + 0, // tp_compare + 0, // tp_repr + 0, // tp_as_number + 0, // tp_as_sequence + 0, // tp_as_mapping + 0, // tp_hash + 0, // tp_call + 0, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + Py_TPFLAGS_DEFAULT| // tp_flags + Py_TPFLAGS_HAVE_GC, + 0, // tp_doc + CppOwnedTraverse, // tp_traverse + CppOwnedClear, // tp_clear + 0, // tp_richcompare + 0, // tp_weaklistoffset + 0, // tp_iter + 0, // tp_iternext + 0, // tp_methods + 0, // tp_members + acquireworker_getset, // tp_getset +}; + static PyObject *acquireitemdesc_get_uri(PyObject *self, void *closure) { - return CppPyString(GetCpp(self).URI); + return CppPyString(GetCpp(self)->URI); } static PyObject *acquireitemdesc_get_description(PyObject *self, void *closure) { - return CppPyString(GetCpp(self).Description); + return CppPyString(GetCpp(self)->Description); } static PyObject *acquireitemdesc_get_shortdesc(PyObject *self, void *closure) { - return CppPyString(GetCpp(self).ShortDesc); + return CppPyString(GetCpp(self)->ShortDesc); } static PyObject *acquireitemdesc_get_owner(PyObject *self, void *closure) { - return GetOwner(self); + return GetOwner(self); } static PyGetSetDef acquireitemdesc_getset[] = { @@ -52,10 +125,10 @@ PyTypeObject PyAcquireItemDesc_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "apt_pkg.AcquireItemDesc", // tp_name - sizeof(CppOwnedPyObject),// tp_basicsize + sizeof(CppOwnedPyObject),// tp_basicsize 0, // tp_itemsize // Methods - CppOwnedDealloc, // tp_dealloc + CppOwnedDealloc, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr @@ -73,8 +146,8 @@ PyTypeObject PyAcquireItemDesc_Type = (Py_TPFLAGS_DEFAULT | // tp_flags Py_TPFLAGS_HAVE_GC), acquireitemdesc_doc, // tp_doc - CppOwnedTraverse,// tp_traverse - CppOwnedClear, // tp_clear + CppOwnedTraverse,// tp_traverse + CppOwnedClear, // tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset 0, // tp_iter @@ -184,13 +257,13 @@ static void AcquireItemDealloc(PyObject *self) { pkgAcquire::Item *file = GetCpp(self); PyAcquireObject *owner = (PyAcquireObject *)GetOwner(self); - // Simply deallocate the object if we have no owner. + // Simply deallocate the object if we have no owner. if (owner == NULL) { CppOwnedDeallocPtr(self); return; } vector &items = owner->items; - bool DeletePtr = !((CppPyObject *)self)->NoDelete; + bool DeletePtr = !((CppPyObject *)self)->NoDelete; // Cleanup the other objects as well... for (vector::iterator I = items.begin(); @@ -307,6 +380,20 @@ static PyObject *PkgAcquireGetPartialPresent(PyObject *Self,void*) { return Py_BuildValue("d", fetcher->PartialPresent()); } #undef fetcher + +static PyObject *PkgAcquireGetWorkers(PyObject *self, void *closure) +{ + PyObject *List = PyList_New(0); + pkgAcquire *Owner = GetCpp(self); + CppOwnedPyObject *PyWorker = NULL; + for(pkgAcquire::Worker *Worker = Owner->WorkersBegin(); + Worker != 0; Worker = Owner->WorkerStep(Worker)) { + PyWorker = CppOwnedPyObject_NEW(self,&PyAcquireWorker_Type, Worker); + PyWorker->NoDelete = true; + PyList_Append(List, PyWorker); + } + return List; +} static PyObject *PkgAcquireGetItems(PyObject *Self,void*) { pkgAcquire *fetcher = GetCpp(Self); @@ -337,6 +424,7 @@ static PyObject *PkgAcquireGetResultCancelled(PyObject *Self,void*) { static PyGetSetDef PkgAcquireGetSet[] = { {"fetch_needed",PkgAcquireGetFetchNeeded}, {"items",PkgAcquireGetItems}, + {"workers",PkgAcquireGetWorkers}, {"partial_present",PkgAcquireGetPartialPresent}, {"result_cancelled",PkgAcquireGetResultCancelled}, {"result_continue",PkgAcquireGetResultContinue}, diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index 5d7b6c47..a7392f58 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -450,27 +450,27 @@ static PyMethodDef methods[] = {"newConfiguration",newConfiguration,METH_VARARGS,doc_newConfiguration}, {"InitConfig",InitConfig,METH_VARARGS,doc_InitConfig}, {"InitSystem",InitSystem,METH_VARARGS,doc_InitSystem}, - + {"ParseSection",ParseSection,METH_VARARGS,doc_ParseSection}, {"ParseTagFile",ParseTagFile,METH_VARARGS,doc_ParseTagFile}, {"RewriteSection",RewriteSection,METH_VARARGS,doc_RewriteSection}, - + {"GetLock",GetLock,METH_VARARGS,doc_GetLock}, {"PkgSystemLock",PkgSystemLock,METH_VARARGS,doc_PkgSystemLock}, {"PkgSystemUnLock",PkgSystemUnLock,METH_VARARGS,doc_PkgSystemUnLock}, - + {"ReadConfigFile",LoadConfig,METH_VARARGS,doc_LoadConfig}, {"ReadConfigDir",LoadConfigDir,METH_VARARGS,doc_LoadConfigDir}, {"ReadConfigFileISC",LoadConfigISC,METH_VARARGS,doc_LoadConfig}, {"ParseCommandLine",ParseCommandLine,METH_VARARGS,doc_ParseCommandLine}, - + {"VersionCompare",VersionCompare,METH_VARARGS,doc_VersionCompare}, {"CheckDep",CheckDep,METH_VARARGS,doc_CheckDep}, {"UpstreamVersion",UpstreamVersion,METH_VARARGS,doc_UpstreamVersion}, {"ParseDepends",ParseDepends_old,METH_VARARGS,doc_ParseDepends}, {"ParseSrcDepends",ParseSrcDepends_old,METH_VARARGS,doc_ParseDepends}, - + {"CheckDomainList",StrCheckDomainList,METH_VARARGS,"CheckDomainList(String,String) -> Bool"}, {"QuoteString",StrQuoteString,METH_VARARGS,"QuoteString(String,String) -> String"}, {"DeQuoteString",StrDeQuote,METH_VARARGS,"DeQuoteString(String) -> String"}, @@ -481,7 +481,7 @@ static PyMethodDef methods[] = {"StringToBool",StrStringToBool,METH_VARARGS,"StringToBool(String) -> int"}, {"TimeRFC1123",StrTimeRFC1123,METH_VARARGS,"TimeRFC1123(int) -> String"}, {"StrToTime",StrStrToTime,METH_VARARGS,"StrToTime(String) -> Int"}, - + {"GetCache",TmpGetCache,METH_VARARGS,"GetCache() -> PkgCache"}, {"GetDepCache",GetDepCache,METH_VARARGS,"GetDepCache(Cache) -> DepCache"}, {"GetPkgRecords",GetPkgRecords,METH_VARARGS,"GetPkgRecords(Cache) -> PkgRecords"}, @@ -589,6 +589,7 @@ extern "C" void initapt_pkg() ADDTYPE(Module,"Acquire",&PyAcquire_Type); ADDTYPE(Module,"AcquireFile",&PyAcquireFile_Type); ADDTYPE(Module,"AcquireItem",&PyAcquireItem_Type); // NO __new__() + ADDTYPE(Module,"AcquireWorker",&PyAcquireWorker_Type); // NO __new__() /* ============================ cache.cc ============================ */ ADDTYPE(Module,"Cache",&PyCache_Type); ADDTYPE(Module,"Dependency",&PyDependency_Type); // NO __new__() diff --git a/python/apt_pkgmodule.h b/python/apt_pkgmodule.h index 835cfd9b..ad1fe9fe 100644 --- a/python/apt_pkgmodule.h +++ b/python/apt_pkgmodule.h @@ -115,6 +115,7 @@ extern PyTypeObject PyHashes_Type; extern PyTypeObject PyOpProgress_Type; extern PyTypeObject PyAcquireProgress_Type; extern PyTypeObject PyAcquireItemDesc_Type; +extern PyTypeObject PyAcquireWorker_Type; #include "python-apt.h" #endif diff --git a/python/progress.cc b/python/progress.cc index 753949af..18e038dd 100644 --- a/python/progress.cc +++ b/python/progress.cc @@ -156,7 +156,7 @@ void PyFetchProgress::UpdateStatus(pkgAcquire::ItemDesc &Itm, int status) void PyFetchProgress::IMSHit(pkgAcquire::ItemDesc &Itm) { if (PyObject_TypeCheck(callbackInst,&PyAcquireProgress_Type)) - RunSimpleCallback("ims_hit", TUPLEIZE(PyAcquireItemDesc_FromCpp(Itm))); + RunSimpleCallback("ims_hit", TUPLEIZE(PyAcquireItemDesc_FromCpp(&Itm))); else UpdateStatus(Itm, DLHit); } @@ -164,7 +164,7 @@ void PyFetchProgress::IMSHit(pkgAcquire::ItemDesc &Itm) void PyFetchProgress::Fetch(pkgAcquire::ItemDesc &Itm) { if (PyObject_TypeCheck(callbackInst,&PyAcquireProgress_Type)) - RunSimpleCallback("fetch", TUPLEIZE(PyAcquireItemDesc_FromCpp(Itm))); + RunSimpleCallback("fetch", TUPLEIZE(PyAcquireItemDesc_FromCpp(&Itm))); else UpdateStatus(Itm, DLQueued); } @@ -172,7 +172,7 @@ void PyFetchProgress::Fetch(pkgAcquire::ItemDesc &Itm) void PyFetchProgress::Done(pkgAcquire::ItemDesc &Itm) { if (PyObject_TypeCheck(callbackInst,&PyAcquireProgress_Type)) - RunSimpleCallback("done", TUPLEIZE(PyAcquireItemDesc_FromCpp(Itm))); + RunSimpleCallback("done", TUPLEIZE(PyAcquireItemDesc_FromCpp(&Itm))); else UpdateStatus(Itm, DLDone); } @@ -190,7 +190,7 @@ void PyFetchProgress::Fail(pkgAcquire::ItemDesc &Itm) if (PyObject_TypeCheck(callbackInst,&PyAcquireProgress_Type)) - RunSimpleCallback("fail", TUPLEIZE(PyAcquireItemDesc_FromCpp(Itm))); + RunSimpleCallback("fail", TUPLEIZE(PyAcquireItemDesc_FromCpp(&Itm))); else UpdateStatus(Itm, DLFailed); } diff --git a/python/python-apt.h b/python/python-apt.h index fa589c55..d2693920 100644 --- a/python/python-apt.h +++ b/python/python-apt.h @@ -184,7 +184,7 @@ static int import_apt_pkg(void) { # define PyAcquire_ToCpp GetCpp # define PyAcquireFile_ToCpp GetCpp # define PyAcquireItem_ToCpp GetCpp -# define PyAcquireItemDesc_ToCpp GetCpp +# define PyAcquireItemDesc_ToCpp GetCpp # define PyActionGroup_ToCpp GetCpp # define PyCache_ToCpp GetCpp # define PyCacheFile_ToCpp GetCpp @@ -234,7 +234,7 @@ inline PyObject *FromCppOwned(PyTypeObject *pytype, Cpp const &obj, # define PyAcquire_FromCpp(...) FromCpp(&PyAcquire_Type, ##__VA_ARGS__) # define PyAcquireFile_FromCpp(...) FromCppOwned(&PyAcquireFile_Type, ##__VA_ARGS__) # define PyAcquireItem_FromCpp(...) FromCppOwned(&PyAcquireItem_Type,##__VA_ARGS__) -# define PyAcquireItemDesc_FromCpp(...) FromCppOwned(&PyAcquireItemDesc_Type,##__VA_ARGS__) +# define PyAcquireItemDesc_FromCpp(...) FromCppOwned(&PyAcquireItemDesc_Type,##__VA_ARGS__) # define PyActionGroup_FromCpp(...) FromCppOwned(&PyActionGroup_Type,##__VA_ARGS__) # define PyCache_FromCpp(...) FromCppOwned(&PyCache_Type,##__VA_ARGS__) # define PyCacheFile_FromCpp(...) FromCpp(&PyCacheFile_Type,##__VA_ARGS__) -- cgit v1.2.3 From c7e8d9705d8b3570c00ed072b0957beb4a47397e Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Thu, 16 Jul 2009 18:23:46 +0200 Subject: python/acquire.cc: Add AcquireItem.mode --- python/acquire.cc | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) (limited to 'python') diff --git a/python/acquire.cc b/python/acquire.cc index 25b10b06..e2fd3181 100644 --- a/python/acquire.cc +++ b/python/acquire.cc @@ -24,7 +24,18 @@ struct PyAcquireObject : public CppPyObject { static PyObject *acquireworker_get_current_item(PyObject *self, void *closure) { - return PyAcquireItemDesc_FromCpp((GetCpp(self)->CurrentItem),false,self); + pkgAcquire::Worker *worker = GetCpp(self); + + if (worker->CurrentItem == NULL) { + Py_RETURN_NONE; + } + + PyAcquireObject *PyCache = (PyAcquireObject *)GetOwner(self); + + pkgAcquire::Item *Item = worker->CurrentItem->Owner; + PyObject *PyItem = PyAcquireItem_FromCpp(Item,false,PyCache); + PyCache->items.push_back((PyAcquireItemObject *)PyItem); + return PyAcquireItemDesc_FromCpp(worker->CurrentItem,false,PyItem); } static PyObject *acquireworker_get_status(PyObject *self, void *closure) @@ -188,6 +199,7 @@ MkGet(AcquireItemGetDestFile,Safe_FromString(Itm->DestFile.c_str())); MkGet(AcquireItemGetErrorText,Safe_FromString(Itm->ErrorText.c_str())); MkGet(AcquireItemGetFileSize,Py_BuildValue("i",Itm->FileSize)); MkGet(AcquireItemGetID,Py_BuildValue("i",Itm)); +MkGet(AcquireItemGetMode,Py_BuildValue("s",Itm->Mode)); MkGet(AcquireItemGetIsTrusted,Py_BuildValue("i",Itm->IsTrusted())); MkGet(AcquireItemGetLocal,Py_BuildValue("i",Itm->Local)); MkGet(AcquireItemGetStatus,Py_BuildValue("i",Itm->Status)); @@ -207,6 +219,7 @@ static PyGetSetDef AcquireItemGetSet[] = { {"error_text",AcquireItemGetErrorText}, {"filesize",AcquireItemGetFileSize}, {"id",AcquireItemGetID}, + {"mode",AcquireItemGetMode}, {"is_trusted",AcquireItemGetIsTrusted}, {"local",AcquireItemGetLocal}, {"status",AcquireItemGetStatus}, -- cgit v1.2.3 From 7e5b2dee624fb0fb7a6536cfdc74d30eeca8ffbe Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Thu, 16 Jul 2009 19:27:46 +0200 Subject: python/acquire.cc, python/progress.cc: More fixes. --- python/acquire.cc | 43 ++++++++++++++++++++++++++++++++++++++----- python/progress.cc | 5 +++++ 2 files changed, 43 insertions(+), 5 deletions(-) (limited to 'python') diff --git a/python/acquire.cc b/python/acquire.cc index e2fd3181..05429d1b 100644 --- a/python/acquire.cc +++ b/python/acquire.cc @@ -116,16 +116,27 @@ static PyObject *acquireitemdesc_get_shortdesc(PyObject *self, void *closure) { return CppPyString(GetCpp(self)->ShortDesc); } -static PyObject *acquireitemdesc_get_owner(PyObject *self, void *closure) +static PyObject *acquireitemdesc_get_owner(CppOwnedPyObject *self, void *closure) { - return GetOwner(self); + + + if (self->Owner != NULL) { + Py_INCREF(self->Owner); + return self->Owner; + } + else if (self->Object && self->Object->Owner != NULL) { + self->Owner = PyAcquireItem_FromCpp(self->Object->Owner); + Py_INCREF(self->Owner); + return self->Owner; + } + Py_RETURN_NONE; } static PyGetSetDef acquireitemdesc_getset[] = { {"uri",acquireitemdesc_get_uri,0,"The URI from which to download this item."}, {"description",acquireitemdesc_get_description}, {"shortdesc",acquireitemdesc_get_shortdesc}, - {"owner",acquireitemdesc_get_owner}, + {"owner",(getter)acquireitemdesc_get_owner}, {NULL} }; @@ -198,7 +209,7 @@ MkGet(AcquireItemGetDescURI,Safe_FromString(Itm->DescURI().c_str())); MkGet(AcquireItemGetDestFile,Safe_FromString(Itm->DestFile.c_str())); MkGet(AcquireItemGetErrorText,Safe_FromString(Itm->ErrorText.c_str())); MkGet(AcquireItemGetFileSize,Py_BuildValue("i",Itm->FileSize)); -MkGet(AcquireItemGetID,Py_BuildValue("i",Itm)); +MkGet(AcquireItemGetID,Py_BuildValue("k",Itm->ID)); MkGet(AcquireItemGetMode,Py_BuildValue("s",Itm->Mode)); MkGet(AcquireItemGetIsTrusted,Py_BuildValue("i",Itm->IsTrusted())); MkGet(AcquireItemGetLocal,Py_BuildValue("i",Itm->Local)); @@ -212,13 +223,35 @@ MkGet(AcquireItemGetStatError,Py_BuildValue("i", pkgAcquire::Item::StatError)); MkGet(AcquireItemGetStatAuthError,Py_BuildValue("i", pkgAcquire::Item::StatAuthError)); #undef MkGet +static int AcquireItemSetID(PyObject *self, PyObject *value, void *closure) +{ + pkgAcquire::Item *Itm = acquireitem_tocpp(self); + if (Itm == 0) + return -1; + if (PyLong_Check(value)) { + Itm->ID = PyLong_AsLong(value); + } + else if (PyInt_Check(value)) { + Itm->ID = PyInt_AsLong(value); + } + else { + PyErr_SetString(PyExc_TypeError, "value must be integer."); + return -1; + } + + + + return 0; +} + + static PyGetSetDef AcquireItemGetSet[] = { {"complete",AcquireItemGetComplete}, {"desc_uri",AcquireItemGetDescURI}, {"destfile",AcquireItemGetDestFile}, {"error_text",AcquireItemGetErrorText}, {"filesize",AcquireItemGetFileSize}, - {"id",AcquireItemGetID}, + {"id",AcquireItemGetID,AcquireItemSetID}, {"mode",AcquireItemGetMode}, {"is_trusted",AcquireItemGetIsTrusted}, {"local",AcquireItemGetLocal}, diff --git a/python/progress.cc b/python/progress.cc index 18e038dd..1f17afdf 100644 --- a/python/progress.cc +++ b/python/progress.cc @@ -247,6 +247,11 @@ bool PyFetchProgress::Pulse(pkgAcquire * Owner) // set stats PyObject *o; + + + o = Py_BuildValue("d", FetchedBytes); + PyObject_SetAttrString(callbackInst, "fetched_bytes", o); + Py_DECREF(o); o = Py_BuildValue("d", CurrentCPS); if(PyObject_HasAttrString(callbackInst, "current_cps")) PyObject_SetAttrString(callbackInst, "current_cps", o); -- cgit v1.2.3 From 0153cede3726849504b04dabdebc8460c1c0fc91 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Thu, 16 Jul 2009 19:36:58 +0200 Subject: python/progress.h: Add Py{Acquire,Op}ProgressObject. --- python/acquireprogress.cc | 12 +------ python/opprogress.cc | 9 ++--- python/progress.cc | 85 ++++++++++++++++++++++++++--------------------- python/progress.h | 20 +++++++++++ 4 files changed, 71 insertions(+), 55 deletions(-) (limited to 'python') diff --git a/python/acquireprogress.cc b/python/acquireprogress.cc index eb02d018..c7db8921 100644 --- a/python/acquireprogress.cc +++ b/python/acquireprogress.cc @@ -19,20 +19,10 @@ */ #include "apt_pkgmodule.h" +#include "progress.h" #include #include -typedef struct { - PyObject_HEAD - double last_bytes; - double current_cps; - double current_bytes; - double total_bytes; - double fetched_bytes; - unsigned long elapsed_time; - unsigned long total_items; - unsigned long current_items; -} PyAcquireProgressObject; // DUMMY IMPLEMENTATIONS. diff --git a/python/opprogress.cc b/python/opprogress.cc index ba9acd14..d3738904 100644 --- a/python/opprogress.cc +++ b/python/opprogress.cc @@ -19,16 +19,11 @@ */ #include "generic.h" +#include "progress.h" #include #include -typedef struct { - PyObject_HEAD - PyObject *op; - PyObject *subop; - int major_change; - float percent; -} PyOpProgressObject; + static PyObject *opprogress_update(PyObject *Self, PyObject *args) { diff --git a/python/progress.cc b/python/progress.cc index 1f17afdf..6f226ef8 100644 --- a/python/progress.cc +++ b/python/progress.cc @@ -245,43 +245,54 @@ bool PyFetchProgress::Pulse(pkgAcquire * Owner) if(callbackInst == 0) return false; - // set stats - PyObject *o; - - - o = Py_BuildValue("d", FetchedBytes); - PyObject_SetAttrString(callbackInst, "fetched_bytes", o); - Py_DECREF(o); - o = Py_BuildValue("d", CurrentCPS); - if(PyObject_HasAttrString(callbackInst, "current_cps")) - PyObject_SetAttrString(callbackInst, "current_cps", o); - else - PyObject_SetAttrString(callbackInst, "currentCPS", o); - Py_XDECREF(o); - o = Py_BuildValue("d", CurrentBytes); - if(PyObject_HasAttrString(callbackInst, "current_bytes")) - PyObject_SetAttrString(callbackInst, "current_bytes", o); - else - PyObject_SetAttrString(callbackInst, "currentBytes", o); - Py_XDECREF(o); - o = Py_BuildValue("k", CurrentItems); - if(PyObject_HasAttrString(callbackInst, "current_items")) - PyObject_SetAttrString(callbackInst, "current_items", o); - else - PyObject_SetAttrString(callbackInst, "currentItems", o); - Py_XDECREF(o); - o = Py_BuildValue("k", TotalItems); - if(PyObject_HasAttrString(callbackInst, "total_items")) - PyObject_SetAttrString(callbackInst, "total_items", o); - else - PyObject_SetAttrString(callbackInst, "totalItems", o); - Py_XDECREF(o); - o = Py_BuildValue("d", TotalBytes); - if(PyObject_HasAttrString(callbackInst, "total_bytes")) - PyObject_SetAttrString(callbackInst, "total_bytes", o); - else - PyObject_SetAttrString(callbackInst, "totalBytes", o); - Py_XDECREF(o); + if (PyObject_TypeCheck(callbackInst, &PyAcquireProgress_Type)) { + PyAcquireProgressObject *obj = (PyAcquireProgressObject *)callbackInst; + obj->last_bytes = LastBytes; + obj->current_cps = CurrentCPS; + obj->current_bytes = CurrentBytes; + obj->total_bytes = TotalBytes; + obj->fetched_bytes = FetchedBytes; + obj->elapsed_time = ElapsedTime; + obj->total_items = TotalItems; + obj->current_items = CurrentItems; + } + else { + // set stats + PyObject *o; + o = Py_BuildValue("d", FetchedBytes); + PyObject_SetAttrString(callbackInst, "fetched_bytes", o); + Py_DECREF(o); + o = Py_BuildValue("d", CurrentCPS); + if(PyObject_HasAttrString(callbackInst, "current_cps")) + PyObject_SetAttrString(callbackInst, "current_cps", o); + else + PyObject_SetAttrString(callbackInst, "currentCPS", o); + Py_XDECREF(o); + o = Py_BuildValue("d", CurrentBytes); + if(PyObject_HasAttrString(callbackInst, "current_bytes")) + PyObject_SetAttrString(callbackInst, "current_bytes", o); + else + PyObject_SetAttrString(callbackInst, "currentBytes", o); + Py_XDECREF(o); + o = Py_BuildValue("k", CurrentItems); + if(PyObject_HasAttrString(callbackInst, "current_items")) + PyObject_SetAttrString(callbackInst, "current_items", o); + else + PyObject_SetAttrString(callbackInst, "currentItems", o); + Py_XDECREF(o); + o = Py_BuildValue("k", TotalItems); + if(PyObject_HasAttrString(callbackInst, "total_items")) + PyObject_SetAttrString(callbackInst, "total_items", o); + else + PyObject_SetAttrString(callbackInst, "totalItems", o); + Py_XDECREF(o); + o = Py_BuildValue("d", TotalBytes); + if(PyObject_HasAttrString(callbackInst, "total_bytes")) + PyObject_SetAttrString(callbackInst, "total_bytes", o); + else + PyObject_SetAttrString(callbackInst, "totalBytes", o); + Py_XDECREF(o); + } if (PyObject_TypeCheck(callbackInst, &PyAcquireProgress_Type)) { PyObject *result1; diff --git a/python/progress.h b/python/progress.h index 5ac67b1c..50fd7f20 100644 --- a/python/progress.h +++ b/python/progress.h @@ -15,6 +15,26 @@ #include #include +typedef struct { + PyObject_HEAD + PyObject *op; + PyObject *subop; + int major_change; + float percent; +} PyOpProgressObject; + +typedef struct { + PyObject_HEAD + double last_bytes; + double current_cps; + double current_bytes; + double total_bytes; + double fetched_bytes; + unsigned long elapsed_time; + unsigned long total_items; + unsigned long current_items; +} PyAcquireProgressObject; + class PyCallbackObj { protected: -- cgit v1.2.3 From 007fd304fe99b0d97b8039a8c1a83ac749e876f9 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Thu, 16 Jul 2009 20:00:27 +0200 Subject: python/progress.cc: Call fail() on AcquireProgress objects. --- python/progress.cc | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'python') diff --git a/python/progress.cc b/python/progress.cc index 6f226ef8..450b7654 100644 --- a/python/progress.cc +++ b/python/progress.cc @@ -179,6 +179,11 @@ void PyFetchProgress::Done(pkgAcquire::ItemDesc &Itm) void PyFetchProgress::Fail(pkgAcquire::ItemDesc &Itm) { + if (PyObject_TypeCheck(callbackInst,&PyAcquireProgress_Type)) { + RunSimpleCallback("fail", TUPLEIZE(PyAcquireItemDesc_FromCpp(&Itm))); + return; + } + // Ignore certain kinds of transient failures (bad code) if (Itm.Owner->Status == pkgAcquire::Item::StatIdle) return; -- cgit v1.2.3 From c7d7fbb650c8ff7c0e52c95723e1e65e295d55cf Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Thu, 16 Jul 2009 21:39:31 +0200 Subject: python/progress.cc: Set members directly, without using Python. --- python/opprogress.cc | 7 ++++++- python/progress.cc | 48 +++++++++++++++++++++++++----------------------- python/progress.h | 5 +++++ 3 files changed, 36 insertions(+), 24 deletions(-) (limited to 'python') diff --git a/python/opprogress.cc b/python/opprogress.cc index d3738904..2ee6a03e 100644 --- a/python/opprogress.cc +++ b/python/opprogress.cc @@ -88,8 +88,13 @@ static PyMethodDef opprogress_methods[] = { {NULL}, }; +#ifndef T_BOOL +# define _T_BOOL T_INT +#else +# define _T_BOOL T_BOOL +#endif static PyMemberDef opprogress_members[] = { - {"major_change", T_INT, offsetof(PyOpProgressObject, major_change), 0, + {"major_change", _T_BOOL, offsetof(PyOpProgressObject, major_change), 0, "Boolean value indicating whether the change is a major change."}, {"percent", T_FLOAT, offsetof(PyOpProgressObject, percent), 0, "Percentage of completion (float value)."}, diff --git a/python/progress.cc b/python/progress.cc index 450b7654..123a1805 100644 --- a/python/progress.cc +++ b/python/progress.cc @@ -65,33 +65,35 @@ void PyOpProgress::Update() return; - PyObject *o; - o = Py_BuildValue("s", Op.c_str()); - PyObject_SetAttrString(callbackInst, "op", o); - Py_XDECREF(o); - o = Py_BuildValue("s", SubOp.c_str()); - if(PyObject_HasAttrString(callbackInst, "sub_op")) - PyObject_SetAttrString(callbackInst, "sub_op", o); - else - PyObject_SetAttrString(callbackInst, "subOp", o); - Py_XDECREF(o); - o = Py_BuildValue("b", MajorChange); - if(PyObject_HasAttrString(callbackInst, "major_change")) - PyObject_SetAttrString(callbackInst, "major_change", o); - else - PyObject_SetAttrString(callbackInst, "majorChange", o); - Py_XDECREF(o); - - - - if (PyObject_TypeCheck(callbackInst, &PyOpProgress_Type)) { - o = Py_BuildValue("f", Percent); - PyObject_SetAttrString(callbackInst, "percent", o); + PyOpProgressObject *obj = (PyOpProgressObject *)callbackInst; + obj->op = CppPyString(Op); + obj->subop = CppPyString(SubOp); +#ifdef T_BOOL + obj->major_change = (char)(MajorChange); +#else + obj->major_change = (int)(MajorChange); +#endif + obj->percent = Percent; RunSimpleCallback("update"); - Py_XDECREF(o); } else { + PyObject *o; + o = Py_BuildValue("s", Op.c_str()); + PyObject_SetAttrString(callbackInst, "op", o); + Py_XDECREF(o); + o = Py_BuildValue("s", SubOp.c_str()); + if(PyObject_HasAttrString(callbackInst, "sub_op")) + PyObject_SetAttrString(callbackInst, "sub_op", o); + else + PyObject_SetAttrString(callbackInst, "subOp", o); + Py_XDECREF(o); + o = Py_BuildValue("b", MajorChange); + if(PyObject_HasAttrString(callbackInst, "major_change")) + PyObject_SetAttrString(callbackInst, "major_change", o); + else + PyObject_SetAttrString(callbackInst, "majorChange", o); + Py_XDECREF(o); PyObject *arglist = Py_BuildValue("(f)", Percent); RunSimpleCallback("update", arglist); } diff --git a/python/progress.h b/python/progress.h index 50fd7f20..e21a5c5a 100644 --- a/python/progress.h +++ b/python/progress.h @@ -15,11 +15,16 @@ #include #include + typedef struct { PyObject_HEAD PyObject *op; PyObject *subop; +#ifdef T_BOOL + char major_change; +#else int major_change; +#endif float percent; } PyOpProgressObject; -- cgit v1.2.3 From b34e27d4ebaf325df6d82fde17b28cf9a008dbfc Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Fri, 17 Jul 2009 16:07:03 +0200 Subject: python: Use PyString_FromFormat instead of snprintf. --- python/acquire.cc | 5 ++-- python/cache.cc | 67 +++++++++++++++++++++++----------------------------- python/generic.h | 1 + python/hashstring.cc | 5 ++-- python/indexfile.cc | 5 +--- python/metaindex.cc | 11 ++++----- 6 files changed, 40 insertions(+), 54 deletions(-) (limited to 'python') diff --git a/python/acquire.cc b/python/acquire.cc index 05429d1b..50bdc949 100644 --- a/python/acquire.cc +++ b/python/acquire.cc @@ -287,8 +287,8 @@ static PyObject *AcquireItemRepr(PyObject *Self) pkgAcquire::Item *Itm = acquireitem_tocpp(Self); if (Itm == 0) return 0; - char S[300]; - snprintf(S,sizeof(S),"<%s object: " + + return PyString_FromFormat("<%s object: " "Status: %i Complete: %i Local: %i IsTrusted: %i " "FileSize: %lu DestFile:'%s' " "DescURI: '%s' ID:%lu ErrorText: '%s'>", @@ -296,7 +296,6 @@ static PyObject *AcquireItemRepr(PyObject *Self) Itm->Status, Itm->Complete, Itm->Local, Itm->IsTrusted(), Itm->FileSize, Itm->DestFile.c_str(), Itm->DescURI().c_str(), Itm->ID,Itm->ErrorText.c_str()); - return PyString_FromString(S); } static void AcquireItemDealloc(PyObject *self) { diff --git a/python/cache.cc b/python/cache.cc index c160cf69..c1f9eb2b 100644 --- a/python/cache.cc +++ b/python/cache.cc @@ -228,7 +228,7 @@ static PyObject *CacheMapOp(PyObject *Self,PyObject *Arg) const char *Name = PyObject_AsString(Arg); if (Name == NULL) return 0; - + // Search for the package pkgCache::PkgIterator Pkg = Cache->FindPkg(Name); @@ -534,11 +534,9 @@ static PyObject *PackageRepr(PyObject *Self) { pkgCache::PkgIterator &Pkg = GetCpp(Self); - char S[300]; - snprintf(S,sizeof(S),"", - Pkg.Name(),Pkg.Section(),Pkg->ID,Pkg->Flags); - return PyString_FromString(S); + return PyString_FromFormat("<%s object: name:'%s' section: " + "'%s' id:%u>", Self->ob_type->tp_name, + Pkg.Name(), Pkg.Section(), Pkg->ID); } PyTypeObject PyPackage_Type = @@ -621,12 +619,9 @@ static PyGetSetDef DescriptionGetSet[] = { static PyObject *DescriptionRepr(PyObject *Self) { pkgCache::DescIterator &Desc = GetCpp(Self); - - char S[300]; - snprintf(S,sizeof(S), - "ob_type->tp_name, Desc.LanguageCode(), + Desc.md5()); } PyTypeObject PyDescription_Type = @@ -840,15 +835,14 @@ static PyObject *VersionGetIsTrusted(PyObject *Self, void*) { static PyObject *VersionRepr(PyObject *Self) { pkgCache::VerIterator &Ver = GetCpp(Self); - - char S[300]; - snprintf(S,sizeof(S),"", - Ver.ParentPkg().Name(),Ver.VerStr(),Ver.Section(),Ver.Arch(), - (unsigned long)Ver->Size,(unsigned long)Ver->InstalledSize, - Ver->Hash,Ver->ID,Ver->Priority); - return PyString_FromString(S); + return PyString_FromFormat("<%s object: Pkg:'%s' Ver:'%s' Section:'%s' " + " Arch:'%s' Size:%lu ISize:%lu Hash:%u ID:%u " + "Priority:%u>", Self->ob_type->tp_name, + Ver.ParentPkg().Name(), Ver.VerStr(), + Ver.Section(), Ver.Arch(), + (unsigned long)Ver->Size, + (unsigned long)Ver->InstalledSize, + Ver->Hash, Ver->ID, Ver->Priority); } static PyGetSetDef VersionGetSet[] = { @@ -1004,20 +998,22 @@ static PyObject *PackageFile_GetID(PyObject *Self,void*) return Py_BuildValue("i",File->ID); } +#define S(s) (s == NULL ? "" : s) static PyObject *PackageFileRepr(PyObject *Self) { pkgCache::PkgFileIterator &File = GetCpp(Self); - char S[300]; - snprintf(S,sizeof(S),"", - File.FileName(),File.Archive(),File.Component(),File.Version(), - File.Origin(),File.Label(),File.Architecture(),File.Site(), - File.IndexType(),File->Size,File->Flags,File->ID); - return PyString_FromString(S); + return PyString_FromFormat("<%s object: filename:'%s'" + " a=%s,c=%s,v=%s,o=%s,l=%s arch='%s' site='%s'" + " IndexType='%s' Size=%lu ID:%u>", + Self->ob_type->tp_name, File.FileName(), + S(File.Archive()), + S(File.Component()),S(File.Version()), + S(File.Origin()),S(File.Label()), + S(File.Architecture()),S(File.Site()), + S(File.IndexType()),File->Size,File->ID); } +#undef S static PyGetSetDef PackageFileGetSet[] = { {(char*)"architecture",PackageFile_GetArchitecture}, @@ -1089,13 +1085,10 @@ static PyObject *DependencyRepr(PyObject *Self) { pkgCache::DepIterator &Dep = GetCpp(Self); - char S[300]; - snprintf(S,sizeof(S),"", - Dep.TargetPkg().Name(), - (Dep.TargetVer() == 0?"":Dep.TargetVer()), - Dep.CompType()); - return PyString_FromString(S); + return PyString_FromFormat("<%s object: pkg:'%s' ver:'%s' comp:'%s'>", + Self->ob_type->tp_name, Dep.TargetPkg().Name(), + (Dep.TargetVer() == 0?"":Dep.TargetVer()), + Dep.CompType()); } static PyObject *DepSmartTargetPkg(PyObject *Self,PyObject *Args) diff --git a/python/generic.h b/python/generic.h index 7f3a3809..4a55e9bf 100644 --- a/python/generic.h +++ b/python/generic.h @@ -53,6 +53,7 @@ typedef int Py_ssize_t; #define PyString_FromString PyUnicode_FromString #define PyString_FromStringAndSize PyUnicode_FromStringAndSize #define PyString_AsString PyUnicode_AsString +#define PyString_FromFormat PyUnicode_FromFormat #define PyInt_Check PyLong_Check #define PyInt_AsLong PyLong_AsLong // Force 0.7 compatibility to be off in Python 3 builds diff --git a/python/hashstring.cc b/python/hashstring.cc index b76dc127..a8d97cd8 100644 --- a/python/hashstring.cc +++ b/python/hashstring.cc @@ -42,9 +42,8 @@ static PyObject *HashString_NEW(PyTypeObject *type,PyObject *Args, static PyObject *HashString_Repr(PyObject *self) { HashString *hash = GetCpp(self); - char repr[100]; - sprintf(repr, "<%s: \"%s\">", self->ob_type->tp_name, hash->toStr().c_str()); - return PyString_FromString(repr); + return PyString_FromFormat("<%s object: \"%s\">", self->ob_type->tp_name, + hash->toStr().c_str()); } static PyObject *HashString_ToStr(PyObject *self) diff --git a/python/indexfile.cc b/python/indexfile.cc index 7bf646d0..74345ec9 100644 --- a/python/indexfile.cc +++ b/python/indexfile.cc @@ -58,16 +58,13 @@ static PyObject *PackageIndexFileGetIsTrusted(PyObject *Self,void*) { static PyObject *PackageIndexFileRepr(PyObject *Self) { pkgIndexFile *File = GetCpp(Self); - - char S[1024]; - snprintf(S,sizeof(S),"", File->GetType()->Label, File->Describe().c_str(), File->Exists(), File->HasPackages(), File->Size(), File->IsTrusted(), File->ArchiveURI("").c_str()); - return PyString_FromString(S); } static PyGetSetDef PackageIndexFileGetSet[] = { diff --git a/python/metaindex.cc b/python/metaindex.cc index d67c0ada..62ff6b90 100644 --- a/python/metaindex.cc +++ b/python/metaindex.cc @@ -64,13 +64,10 @@ static PyGetSetDef MetaIndexGetSet[] = { static PyObject *MetaIndexRepr(PyObject *Self) { metaIndex *meta = GetCpp(Self); - - char S[1024]; - snprintf(S,sizeof(S),"", - meta->GetType(), meta->GetURI().c_str(), meta->GetDist().c_str(), - meta->IsTrusted()); - return PyString_FromString(S); + return PyString_FromFormat("<%s object: type='%s', uri:'%s' dist='%s' " + "is_trusted='%i'>", Self->ob_type->tp_name, + meta->GetType(), meta->GetURI().c_str(), + meta->GetDist().c_str(), meta->IsTrusted()); } PyTypeObject PyMetaIndex_Type = -- cgit v1.2.3 From 769c1d5fa940e70ddb8ac55e8dd5ed8f05ab7e6e Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Fri, 17 Jul 2009 19:04:51 +0200 Subject: python/apt_pkgmodule.cc: Introduce apt_pkg.gettext(). Python's gettext() ignores setlocale() which causes a strange behavior because the values received from apt-pkg respect setlocale(). We circumvent this problem by calling the C version of gettext(). This is also much faster. --- python/apt_pkgmodule.cc | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) (limited to 'python') diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index a7392f58..d6b8e3d1 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -24,10 +24,29 @@ #include #include +#include #include #include /*}}}*/ + +/** + * A Python->C->Python gettext() function. + * + * Python's gettext() ignores setlocale() which causes a strange behavior + * because the values received from apt-pkg respect setlocale(). We circumvent + * this problem by calling the C version of gettext(). This is also much + * faster. + */ +static PyObject *py_gettext(PyObject *self, PyObject *Args) { + const char *msg; + char *domain = "python-apt"; + if (PyArg_ParseTuple(Args,"s|s:gettext",&msg) == 0) + return 0; + + return PyString_FromString(dgettext(domain, msg)); +} + // newConfiguration - Build a new configuration class /*{{{*/ // --------------------------------------------------------------------- #ifdef COMPAT_0_7 @@ -405,6 +424,12 @@ static PyMethodDef methods[] = {"init_config",InitConfig,METH_VARARGS,doc_InitConfig}, {"init_system",InitSystem,METH_VARARGS,doc_InitSystem}, + // Internationalization. + {"gettext",py_gettext,METH_VARARGS, + "gettext(msg: str[, domain: str = 'python-apt']) -> str\n\n" + "Translate the given string. Much Faster than Python's version and only\n" + "does translations after setlocale() has been called."}, + // Tag File {"rewrite_section",RewriteSection,METH_VARARGS,doc_RewriteSection}, -- cgit v1.2.3 From 61481860f4e260e56e123811b759c8d8bd3353db Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Fri, 17 Jul 2009 20:51:27 +0200 Subject: python/cache.cc: Only support new OpProgress() objects in apt_pkg.Cache(). --- python/cache.cc | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) (limited to 'python') diff --git a/python/cache.cc b/python/cache.cc index c1f9eb2b..f5effae9 100644 --- a/python/cache.cc +++ b/python/cache.cc @@ -245,8 +245,16 @@ static PyObject *PkgCacheNew(PyTypeObject *type,PyObject *Args,PyObject *kwds) { PyObject *pyCallbackInst = 0; char *kwlist[] = {"progress", 0}; - if (PyArg_ParseTupleAndKeywords (Args, kwds, "|O", kwlist, &pyCallbackInst) == 0) + + #ifdef COMPAT_0_7 + if (PyArg_ParseTupleAndKeywords(Args, kwds, "|O", kwlist, + &pyCallbackInst) == 0) + return 0; + #else + if (PyArg_ParseTupleAndKeywords(Args, kwds, "|O!", kwlist, + &PyOpProgress_Type, &pyCallbackInst) == 0) return 0; + #endif if (_system == 0) { PyErr_SetString(PyExc_ValueError,"_system not initialized"); -- cgit v1.2.3 From 5c219e07aea347f652cf7949dc74f37282a17144 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Sun, 19 Jul 2009 14:39:41 +0200 Subject: python/cdromprogress.cc: Add apt_pkg.CdromProgress. --- apt/progress/old.py | 22 ++-------- python/apt_pkgmodule.cc | 1 + python/apt_pkgmodule.h | 1 + python/cdrom.cc | 11 +++++ python/cdromprogress.cc | 106 ++++++++++++++++++++++++++++++++++++++++++++++++ python/progress.cc | 12 ++++-- python/progress.h | 6 +++ 7 files changed, 137 insertions(+), 22 deletions(-) create mode 100644 python/cdromprogress.cc (limited to 'python') diff --git a/apt/progress/old.py b/apt/progress/old.py index d4ff5815..63fc5d2e 100644 --- a/apt/progress/old.py +++ b/apt/progress/old.py @@ -343,27 +343,13 @@ class InstallProgress(DumbInstallProgress): updateInterface = function_deprecated_by(update_interface) -class CdromProgress(object): +class CdromProgress(apt_pkg.CdromProgress): """Report the cdrom add progress. - Subclass this class to implement cdrom add progress reporting. + This class has been replaced by apt_pkg.CdromProgress. """ - - def __init__(self): - pass - - def update(self, text, step): - """Called periodically to update the user interface.""" - - def ask_cdrom_name(self): - """Called to ask for the name of the cdrom.""" - - def change_cdrom(self): - """Called to ask for the cdrom to be changed.""" - - if apt_pkg._COMPAT_0_7: - askCdromName = function_deprecated_by(ask_cdrom_name) - changeCdrom = function_deprecated_by(change_cdrom) + askCdromName = function_deprecated_by(apt_pkg.CdromProgress.ask_cdrom_name) + changeCdrom = function_deprecated_by(apt_pkg.CdromProgress.change_cdrom) class DpkgInstallProgress(InstallProgress): diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index d6b8e3d1..b6ae709e 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -651,6 +651,7 @@ extern "C" void initapt_pkg() ADDTYPE(Module,"OpProgress",&PyOpProgress_Type); ADDTYPE(Module,"AcquireProgress",&PyAcquireProgress_Type); ADDTYPE(Module,"AcquireItemDesc",&PyAcquireItemDesc_Type); + ADDTYPE(Module,"CdromProgress",&PyCdromProgress_Type); // Tag file constants PyModule_AddObject(Module,"REWRITE_PACKAGE_ORDER", CharCharToList(TFRewritePackageOrder)); diff --git a/python/apt_pkgmodule.h b/python/apt_pkgmodule.h index ad1fe9fe..1277ab60 100644 --- a/python/apt_pkgmodule.h +++ b/python/apt_pkgmodule.h @@ -114,6 +114,7 @@ extern PyTypeObject PyPolicy_Type; extern PyTypeObject PyHashes_Type; extern PyTypeObject PyOpProgress_Type; extern PyTypeObject PyAcquireProgress_Type; +extern PyTypeObject PyCdromProgress_Type; extern PyTypeObject PyAcquireItemDesc_Type; extern PyTypeObject PyAcquireWorker_Type; #include "python-apt.h" diff --git a/python/cdrom.cc b/python/cdrom.cc index 50d1b4b1..6ee3becd 100644 --- a/python/cdrom.cc +++ b/python/cdrom.cc @@ -34,9 +34,20 @@ static PyObject *PkgCdromIdent(PyObject *Self,PyObject *Args) pkgCdrom &Cdrom = GetCpp(Self); PyObject *pyCdromProgressInst = 0; +#ifdef COMPAT_0_7 if (PyArg_ParseTuple(Args, "O", &pyCdromProgressInst) == 0) { +#else + if (PyArg_ParseTuple(Args, "O!", &PyCdromProgress_Type, + &pyCdromProgressInst) == 0) { +#endif return 0; } +#ifdef COMPAT_0_7 + if (!PyObject_TypeCheck(pyCdromProgressInst, &PyCdromProgress_Type)) { + PyErr_WarnEx(PyExc_DeprecationWarning, "Argument should be a subclass of" + " apt_pkg.CdromProgress.", 1); + } +#endif PyCdromProgress progress; progress.setCallbackInst(pyCdromProgressInst); diff --git a/python/cdromprogress.cc b/python/cdromprogress.cc new file mode 100644 index 00000000..09c76a2a --- /dev/null +++ b/python/cdromprogress.cc @@ -0,0 +1,106 @@ +/* cdromprogress.cc - Base class for CdromProgress classes. + * + * Copyright 2009 Julian Andres Klode + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + */ +#include "apt_pkgmodule.h" +#include "progress.h" +#include +#include + +// Takes two arguments (string, int) +static PyObject *cdromprogress_update(PyObject *self, PyObject *args) +{ + Py_RETURN_NONE; +} + +// Takes no arguments +static PyObject *cdromprogress_change_cdrom(PyObject *self, PyObject *args) +{ + Py_RETURN_FALSE; +} + +// Takes a single PyObject argument as *arg +static PyObject *cdromprogress_ask_cdrom_name(PyObject *self, PyObject *arg) +{ + Py_RETURN_FALSE; +} + +static PyMethodDef cdromprogress_methods[] = { + {"update",cdromprogress_update,METH_VARARGS, + "update(text: str, current: int)\n\nCalled regularly."}, + {"change_cdrom",cdromprogress_change_cdrom,METH_NOARGS, + "change_cdrom() -> bool\n\nAsk for the CD-ROM to be changed.\n" + "Return False if the user requested to cancel the action (default)."}, + {"ask_cdrom_name",cdromprogress_ask_cdrom_name,METH_O, + "ask_cdrom_name(name: str) -> bool\n\nAsk for the name of the CD-ROM.\n" + "Return False if the user requested to cancel the action (default)."}, + {NULL} +}; + +static PyMemberDef cdromprogress_members[] = { + {"total_steps", T_INT, offsetof(PyCdromProgressObject,total_steps), 0, + "The number of total steps to be taken."}, + {NULL} +}; + +static char *cdromprogress_doc = "CdromProgress()\n\n" + "Base class for reporting the progress of adding a cdrom. Can be used\n" + "with apt_pkg.Cdrom to produce an utility like apt-cdrom."; + +PyTypeObject PyCdromProgress_Type = { + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "apt_pkg.CdromProgress", // tp_name + sizeof(PyCdromProgressObject), // tp_basicsize + 0, // tp_itemsize + // Methods + 0, // tp_dealloc + 0, // tp_print + 0, // tp_getattr + 0, // tp_setattr + 0, // tp_compare + 0, // tp_repr + 0, // tp_as_number + 0, // tp_as_sequence + 0, // tp_as_mapping + 0, // tp_hash + 0, // tp_call + 0, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + Py_TPFLAGS_DEFAULT | // tp_flags + Py_TPFLAGS_BASETYPE, + cdromprogress_doc, // tp_doc + 0, // tp_traverse + 0, // tp_clear + 0, // tp_richcompare + 0, // tp_weaklistoffset + 0, // tp_iter + 0, // tp_iternext + cdromprogress_methods, // tp_methods + cdromprogress_members, // tp_members + 0, // tp_getset + 0, // tp_base + 0, // tp_dict + 0, // tp_descr_get + 0, // tp_descr_set + 0, // tp_dictoffset + 0, // tp_init + 0, // tp_alloc + PyType_GenericNew, // tp_new +}; diff --git a/python/progress.cc b/python/progress.cc index 123a1805..b19ab0c7 100644 --- a/python/progress.cc +++ b/python/progress.cc @@ -518,10 +518,14 @@ pkgPackageManager::OrderResult PyInstallProgress::Run(pkgPackageManager *pm) void PyCdromProgress::Update(string text, int current) { PyObject *arglist = Py_BuildValue("(si)", text.c_str(), current); - - PyObject *o = Py_BuildValue("i", totalSteps); - PyObject_SetAttrString(callbackInst, "totalSteps", o); - Py_XDECREF(o); + if (PyObject_TypeCheck(callbackInst, &PyCdromProgress_Type)) { + ((PyCdromProgressObject *)callbackInst)->total_steps = totalSteps; + } + else { + PyObject *o = Py_BuildValue("i", totalSteps); + PyObject_SetAttrString(callbackInst, "totalSteps", o); + Py_XDECREF(o); + } RunSimpleCallback("update", arglist); } diff --git a/python/progress.h b/python/progress.h index e21a5c5a..88bd3552 100644 --- a/python/progress.h +++ b/python/progress.h @@ -28,6 +28,12 @@ typedef struct { float percent; } PyOpProgressObject; + +typedef struct { + PyObject_HEAD + int total_steps; +} PyCdromProgressObject; + typedef struct { PyObject_HEAD double last_bytes; -- cgit v1.2.3 From 92d2315a87d24c51f2f0d3265c87c59f0d9730c3 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Sun, 19 Jul 2009 15:39:53 +0200 Subject: python/apt_pkgmodule.cc: Fix apt_pkg.gettext to not ignore second parameter. --- python/apt_pkgmodule.cc | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'python') diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index b6ae709e..cbf88294 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -29,7 +29,6 @@ #include /*}}}*/ - /** * A Python->C->Python gettext() function. * @@ -41,7 +40,7 @@ static PyObject *py_gettext(PyObject *self, PyObject *Args) { const char *msg; char *domain = "python-apt"; - if (PyArg_ParseTuple(Args,"s|s:gettext",&msg) == 0) + if (PyArg_ParseTuple(Args,"s|s:gettext",&msg, &domain) == 0) return 0; return PyString_FromString(dgettext(domain, msg)); -- cgit v1.2.3 From 48cc0bcaabe824f49987ed3236b9421c583226dd Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Sun, 19 Jul 2009 15:40:40 +0200 Subject: python/progress.cc: CdromProgress.ask_cdrom_name() shall return None on failure. --- python/cdromprogress.cc | 6 +++--- python/progress.cc | 32 ++++++++++++++++++++------------ 2 files changed, 23 insertions(+), 15 deletions(-) (limited to 'python') diff --git a/python/cdromprogress.cc b/python/cdromprogress.cc index 09c76a2a..440b5ce6 100644 --- a/python/cdromprogress.cc +++ b/python/cdromprogress.cc @@ -37,7 +37,7 @@ static PyObject *cdromprogress_change_cdrom(PyObject *self, PyObject *args) // Takes a single PyObject argument as *arg static PyObject *cdromprogress_ask_cdrom_name(PyObject *self, PyObject *arg) { - Py_RETURN_FALSE; + Py_RETURN_NONE; } static PyMethodDef cdromprogress_methods[] = { @@ -47,8 +47,8 @@ static PyMethodDef cdromprogress_methods[] = { "change_cdrom() -> bool\n\nAsk for the CD-ROM to be changed.\n" "Return False if the user requested to cancel the action (default)."}, {"ask_cdrom_name",cdromprogress_ask_cdrom_name,METH_O, - "ask_cdrom_name(name: str) -> bool\n\nAsk for the name of the CD-ROM.\n" - "Return False if the user requested to cancel the action (default)."}, + "ask_cdrom_name() -> str\n\nAsk for the name of the CD-ROM.\n" + "Return None if the user requested to cancel the action (default)."}, {NULL} }; diff --git a/python/progress.cc b/python/progress.cc index b19ab0c7..55ed13f9 100644 --- a/python/progress.cc +++ b/python/progress.cc @@ -548,20 +548,28 @@ bool PyCdromProgress::ChangeCdrom() bool PyCdromProgress::AskCdromName(string &Name) { PyObject *arglist = Py_BuildValue("()"); - PyObject *result; - - if (!RunSimpleCallback("ask_cdrom_name", arglist, &result)) - RunSimpleCallback("askCdromName", arglist, &result); - const char *new_name; bool res; - if(!PyArg_Parse(result, "(bs)", &res, &new_name)) - std::cerr << "AskCdromName: result could not be parsed" << std::endl; - - //std::cerr << "got: " << res << " " << "name: " << new_name << std::endl; + PyObject *result; - // set the new name - Name = string(new_name); + // New style: String on success, None on failure. + if (RunSimpleCallback("ask_cdrom_name", arglist, &result)) { + if(result == Py_None) + return false; + if(!PyArg_Parse(result, "s", &new_name)) + std::cerr << "AskCdromName: result could not be parsed" << std::endl; + else + Name = string(new_name); + return true; + } + // Old style: (True, name) on success, (False, name) on failure. + else { + RunSimpleCallback("askCdromName", arglist, &result); + if(!PyArg_Parse(result, "(bs)", &res, &new_name)) + std::cerr << "AskCdromName: result could not be parsed" << std::endl; + // set the new name + Name = string(new_name); - return res; + return res; + } } -- cgit v1.2.3 From aaa8c4f98eb92bba9418e15560617b78be90b5d6 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Sun, 19 Jul 2009 15:48:14 +0200 Subject: python/cdrom.cc: New style ident returns None on failure. Returning a tuple (bool, str) is useless when one can just return a string or None. --- python/cdrom.cc | 34 ++++++++++++++++++++++++---------- 1 file changed, 24 insertions(+), 10 deletions(-) (limited to 'python') diff --git a/python/cdrom.cc b/python/cdrom.cc index 6ee3becd..bd181af7 100644 --- a/python/cdrom.cc +++ b/python/cdrom.cc @@ -32,22 +32,35 @@ static PyObject *PkgCdromAdd(PyObject *Self,PyObject *Args) static PyObject *PkgCdromIdent(PyObject *Self,PyObject *Args) { pkgCdrom &Cdrom = GetCpp(Self); - PyObject *pyCdromProgressInst = 0; -#ifdef COMPAT_0_7 - if (PyArg_ParseTuple(Args, "O", &pyCdromProgressInst) == 0) { -#else if (PyArg_ParseTuple(Args, "O!", &PyCdromProgress_Type, &pyCdromProgressInst) == 0) { -#endif return 0; } + + PyCdromProgress progress; + progress.setCallbackInst(pyCdromProgressInst); + + string ident; + bool res = Cdrom.Ident(ident, &progress); + + if (res) + return CppPyString(ident); + else { + Py_INCREF(Py_None); + return HandleErrors(Py_None); + } +} + #ifdef COMPAT_0_7 - if (!PyObject_TypeCheck(pyCdromProgressInst, &PyCdromProgress_Type)) { - PyErr_WarnEx(PyExc_DeprecationWarning, "Argument should be a subclass of" - " apt_pkg.CdromProgress.", 1); +static PyObject *PkgCdromIdent_old(PyObject *Self,PyObject *Args) +{ + pkgCdrom &Cdrom = GetCpp(Self); + + PyObject *pyCdromProgressInst = 0; + if (PyArg_ParseTuple(Args, "O", &pyCdromProgressInst) == 0) { + return 0; } -#endif PyCdromProgress progress; progress.setCallbackInst(pyCdromProgressInst); @@ -59,6 +72,7 @@ static PyObject *PkgCdromIdent(PyObject *Self,PyObject *Args) return HandleErrors(result); } +#endif static PyMethodDef PkgCdromMethods[] = @@ -67,7 +81,7 @@ static PyMethodDef PkgCdromMethods[] = {"ident",PkgCdromIdent,METH_VARARGS,"ident(progress) -> Ident a cdrom"}, #ifdef COMPAT_0_7 {"Add",PkgCdromAdd,METH_VARARGS,"Add(progress) -> Add a cdrom"}, - {"Ident",PkgCdromIdent,METH_VARARGS,"Ident(progress) -> Ident a cdrom"}, + {"Ident",PkgCdromIdent_old,METH_VARARGS,"Ident(progress) -> Ident a cdrom"}, #endif {} }; -- cgit v1.2.3 From cbfbbf0728df4d9f7d52685549eb529041184d82 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Sun, 19 Jul 2009 16:37:43 +0200 Subject: python/progress.cc: Use PyObject_CallObject instead of PyEval_CallObject. --- python/progress.cc | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) (limited to 'python') diff --git a/python/progress.cc b/python/progress.cc index 55ed13f9..2feba503 100644 --- a/python/progress.cc +++ b/python/progress.cc @@ -35,7 +35,7 @@ bool PyCallbackObj::RunSimpleCallback(const char* method_name, Py_XDECREF(arglist); return false; } - PyObject *result = PyEval_CallObject(method, arglist); + PyObject *result = PyObject_CallObject(method, arglist); Py_XDECREF(arglist); @@ -44,7 +44,6 @@ bool PyCallbackObj::RunSimpleCallback(const char* method_name, std::cerr << "Error in function " << method_name << std::endl; PyErr_Print(); PyErr_Clear(); - return false; } if(res != NULL) @@ -435,7 +434,7 @@ pkgPackageManager::OrderResult PyInstallProgress::Run(pkgPackageManager *pm) PyObject *method = PyObject_GetAttrString(callbackInst, "fork"); std::cerr << "custom fork found" << std::endl; PyObject *arglist = Py_BuildValue("()"); - PyObject *result = PyEval_CallObject(method, arglist); + PyObject *result = PyObject_CallObject(method, arglist); Py_DECREF(arglist); if (result == NULL) { std::cerr << "fork method invalid" << std::endl; @@ -484,7 +483,7 @@ pkgPackageManager::OrderResult PyInstallProgress::Run(pkgPackageManager *pm) method = PyObject_GetAttrString(callbackInst, "waitChild"); //std::cerr << "custom waitChild found" << std::endl; PyObject *arglist = Py_BuildValue("(i)",child_id); - PyObject *result = PyEval_CallObject(method, arglist); + PyObject *result = PyObject_CallObject(method, arglist); Py_DECREF(arglist); if (result == NULL) { std::cerr << "waitChild method invalid" << std::endl; -- cgit v1.2.3 From 652a7312b21aa7121c0075c3c970d5f68fcdf648 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Mon, 20 Jul 2009 18:04:19 +0200 Subject: python/lock.cc: Introduce apt_pkg.SystemLock context manager. This is the new alternative to pkgsystem_lock() and pkgsystem_unlock(), and is the recommended one. --- python/apt_pkgmodule.cc | 1 + python/apt_pkgmodule.h | 1 + python/lock.cc | 123 ++++++++++++++++++++++++++++++++++++++++++++++++ setup.py | 2 +- 4 files changed, 126 insertions(+), 1 deletion(-) create mode 100644 python/lock.cc (limited to 'python') diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index cbf88294..d4c23d2f 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -651,6 +651,7 @@ extern "C" void initapt_pkg() ADDTYPE(Module,"AcquireProgress",&PyAcquireProgress_Type); ADDTYPE(Module,"AcquireItemDesc",&PyAcquireItemDesc_Type); ADDTYPE(Module,"CdromProgress",&PyCdromProgress_Type); + ADDTYPE(Module,"SystemLock",&PySystemLock_Type); // Tag file constants PyModule_AddObject(Module,"REWRITE_PACKAGE_ORDER", CharCharToList(TFRewritePackageOrder)); diff --git a/python/apt_pkgmodule.h b/python/apt_pkgmodule.h index 1277ab60..de70c056 100644 --- a/python/apt_pkgmodule.h +++ b/python/apt_pkgmodule.h @@ -117,6 +117,7 @@ extern PyTypeObject PyAcquireProgress_Type; extern PyTypeObject PyCdromProgress_Type; extern PyTypeObject PyAcquireItemDesc_Type; extern PyTypeObject PyAcquireWorker_Type; +extern PyTypeObject PySystemLock_Type; #include "python-apt.h" #endif diff --git a/python/lock.cc b/python/lock.cc new file mode 100644 index 00000000..aac2d25a --- /dev/null +++ b/python/lock.cc @@ -0,0 +1,123 @@ +/* + * lock.cc - Context managers for implementing locking. + * + * Copyright 2009 Julian Andres Klode + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + */ +#include +#include +#include +#include "generic.h" + +static PyObject *systemlock_exit(PyObject *self, PyObject *args) +{ + + PyObject *exc_type = 0; + PyObject *exc_value = 0; + PyObject *traceback = 0; + if (!PyArg_UnpackTuple(args, "__exit__", 3, 3, &exc_type, &exc_value, + &traceback)) { + return 0; + } + if ((! exc_type || exc_type == Py_None) && _system->UnLock() == 0) { + return HandleErrors(); + } + Py_RETURN_FALSE; +} + +static PyObject *systemlock_enter(PyObject *self, PyObject *args) +{ + if (!PyArg_ParseTuple(args, "")) + return NULL; + if (!_system->Lock()) + return HandleErrors(); + return self; +} + +static PyObject *systemlock_new(PyTypeObject *type, PyObject *args, + PyObject *kwds) +{ + if (_system == 0) { + PyErr_SetString(PyExc_ValueError,"_system not initialized"); + return 0; + } + return PyType_GenericNew(type,args,kwds); +} + +static PyMethodDef systemlock_methods[] = { + {"__enter__",systemlock_enter,METH_VARARGS,"Lock the system."}, + {"__exit__",systemlock_exit,METH_VARARGS,"Unlock the system."}, + {NULL} +}; + +static char *systemlock_doc = "SystemLock()\n\n" + "Context manager for locking the package system. The lock is established\n" + "as soon as the method __enter__() is called. It is released when\n" + "__exit__() is called.\n\n" + "This should be used via the 'with' statement, e.g.::\n\n" + " with apt_pkg.SystemLock():\n" + " ...\n\n" + "Once the block is left, the lock is released automatically. The object\n" + "can be used multiple times::\n\n" + " lock = apt_pkg.SystemLock()\n" + " with lock:\n" + " ...\n" + " with lock:\n" + " ...\n\n"; + +PyTypeObject PySystemLock_Type = { + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "apt_pkg.SystemLock", // tp_name + 0, // tp_basicsize + 0, // tp_itemsize + // Methods + 0, // tp_dealloc + 0, // tp_print + 0, // tp_getattr + 0, // tp_setattr + 0, // tp_compare + 0, // tp_repr + 0, // tp_as_number + 0, // tp_as_sequence + 0, // tp_as_mapping + 0, // tp_hash + 0, // tp_call + 0, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + (Py_TPFLAGS_DEFAULT | // tp_flags + Py_TPFLAGS_BASETYPE), + systemlock_doc, // tp_doc + 0, // tp_traverse + 0, // tp_clear + 0, // tp_richcompare + 0, // tp_weaklistoffset + 0, // tp_iter + 0, // tp_iternext + systemlock_methods, // tp_methods + 0, // tp_members + 0, // tp_getset + 0, // tp_base + 0, // tp_dict + 0, // tp_descr_get + 0, // tp_descr_set + 0, // tp_dictoffset + 0, // tp_init + 0, // tp_alloc + systemlock_new, // tp_new +}; diff --git a/setup.py b/setup.py index 5cfe3bdc..e07bd83b 100644 --- a/setup.py +++ b/setup.py @@ -35,7 +35,7 @@ files = ['apt_pkgmodule.cc', 'acquire.cc', 'cache.cc', 'cdrom.cc', 'hashstring.cc', 'indexfile.cc', 'indexrecords.cc', 'metaindex.cc', 'pkgmanager.cc', 'pkgrecords.cc', 'pkgsrcrecords.cc', 'policy.cc', 'progress.cc', 'sourcelist.cc', 'string.cc', 'tag.cc', - 'opprogress.cc', 'acquireprogress.cc', 'cdromprogress.cc'] + 'opprogress.cc', 'acquireprogress.cc', 'cdromprogress.cc', 'lock.cc'] files = sorted(['python/' + fname for fname in files]) apt_pkg = Extension("apt_pkg", files, libraries=["apt-pkg"]) -- cgit v1.2.3 From a676f6a0e081e54a0a57dbfca2d14fee381e7d92 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Tue, 21 Jul 2009 16:55:11 +0200 Subject: python/lock.cc: Fix refcount in systemlock_enter and behavior of systemlock_exit. --- python/lock.cc | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) (limited to 'python') diff --git a/python/lock.cc b/python/lock.cc index aac2d25a..75665779 100644 --- a/python/lock.cc +++ b/python/lock.cc @@ -33,9 +33,18 @@ static PyObject *systemlock_exit(PyObject *self, PyObject *args) &traceback)) { return 0; } - if ((! exc_type || exc_type == Py_None) && _system->UnLock() == 0) { - return HandleErrors(); + + if (_system->UnLock() == 0) { + // The unlock failed. If no exception happened within the suite, we + // will raise an error here. Otherwise, we just display the error, so + // Python can handle the original exception instead. + HandleErrors(); + if (exc_type == Py_None) + return NULL; + else + PyErr_WriteUnraisable(self); } + // Return False, as required by the context manager protocol. Py_RETURN_FALSE; } @@ -45,6 +54,7 @@ static PyObject *systemlock_enter(PyObject *self, PyObject *args) return NULL; if (!_system->Lock()) return HandleErrors(); + Py_INCREF(self); return self; } -- cgit v1.2.3 From 9d97c4ef07fe249ed2b5af7d52fe15655bbb9170 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Tue, 21 Jul 2009 17:51:43 +0200 Subject: python/lock.cc: Implement apt_pkg.FileLock(). This is yet another context manager, this time for locking files. It can be used multiple times and features an internal counter. --- doc/source/whatsnew/0.8.0.rst | 6 ++ python/apt_pkgmodule.cc | 1 + python/apt_pkgmodule.h | 1 + python/generic.h | 1 + python/lock.cc | 132 ++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 141 insertions(+) (limited to 'python') diff --git a/doc/source/whatsnew/0.8.0.rst b/doc/source/whatsnew/0.8.0.rst index 8889cbd9..244da388 100644 --- a/doc/source/whatsnew/0.8.0.rst +++ b/doc/source/whatsnew/0.8.0.rst @@ -79,6 +79,12 @@ Yet another context manager is available for locking the package system:: with apt_pkg.SystemLock(): # do your stuff here +There is also one for file based locking: + + with apt_pkg.FileLock(filename): + # do your stuff here + + Unification of dependency handling ---------------------------------- In apt 0.7, there were three different return types of functions parsing diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index d4c23d2f..8b8e9c7f 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -652,6 +652,7 @@ extern "C" void initapt_pkg() ADDTYPE(Module,"AcquireItemDesc",&PyAcquireItemDesc_Type); ADDTYPE(Module,"CdromProgress",&PyCdromProgress_Type); ADDTYPE(Module,"SystemLock",&PySystemLock_Type); + ADDTYPE(Module,"FileLock",&PyFileLock_Type); // Tag file constants PyModule_AddObject(Module,"REWRITE_PACKAGE_ORDER", CharCharToList(TFRewritePackageOrder)); diff --git a/python/apt_pkgmodule.h b/python/apt_pkgmodule.h index de70c056..04bce2cc 100644 --- a/python/apt_pkgmodule.h +++ b/python/apt_pkgmodule.h @@ -118,6 +118,7 @@ extern PyTypeObject PyCdromProgress_Type; extern PyTypeObject PyAcquireItemDesc_Type; extern PyTypeObject PyAcquireWorker_Type; extern PyTypeObject PySystemLock_Type; +extern PyTypeObject PyFileLock_Type; #include "python-apt.h" #endif diff --git a/python/generic.h b/python/generic.h index 4a55e9bf..d7f121ce 100644 --- a/python/generic.h +++ b/python/generic.h @@ -54,6 +54,7 @@ typedef int Py_ssize_t; #define PyString_FromStringAndSize PyUnicode_FromStringAndSize #define PyString_AsString PyUnicode_AsString #define PyString_FromFormat PyUnicode_FromFormat +#define PyString_Type PyUnicode_Type #define PyInt_Check PyLong_Check #define PyInt_AsLong PyLong_AsLong // Force 0.7 compatibility to be off in Python 3 builds diff --git a/python/lock.cc b/python/lock.cc index 75665779..d4d45734 100644 --- a/python/lock.cc +++ b/python/lock.cc @@ -131,3 +131,135 @@ PyTypeObject PySystemLock_Type = { 0, // tp_alloc systemlock_new, // tp_new }; + + +/** + * File Based locking. + * + * The counter is increased by every call to filelock_enter() and decreased by + * every call to filelock_exit(). When the counter reaches 0, the underlying + * file descriptor is closed. + * + * Members: + * @member char* filename The name of the file + * @member int lock_count How many times we have locked it. + * @member int fd The filedescriptor returned by GetLock() or 0. + */ +struct filelock_object { + PyObject_HEAD + char *filename; + int lock_count; + int fd; +}; + +static PyObject *filelock_enter(filelock_object *self, PyObject *args) +{ + self->lock_count++; + // If we have no lock yet, get a lock. + if (self->lock_count == 1) { + self->fd = GetLock(self->filename, true); + if (self->fd == -1) { + self->lock_count--; + return HandleErrors(); + } + } + Py_INCREF(self); + return (PyObject *)self; +} + +static PyObject *filelock_exit(filelock_object *self, PyObject *args) +{ + // Count down the lock_count, if it is less than 0, reset it to 0. + self->lock_count--; + if (self->lock_count < 0) + self->lock_count = 0; + if (self->lock_count == 0 && self->fd != 0 && close(self->fd) == -1) { + return PyErr_SetFromErrno(PyExc_OSError); + } + Py_RETURN_FALSE; +} + +static PyObject *filelock_new(PyTypeObject *type, PyObject *args, PyObject *kwds) +{ + char *filename = 0; + char *kwlist[] = {"filename", NULL}; + if (PyArg_ParseTupleAndKeywords(args, kwds, "s:__init__", kwlist, + &filename) == 0) { + return NULL; + } + filelock_object *self = (filelock_object *)type->tp_alloc(type, 0); + // Copy the string into the object. + self->filename = new char[strlen(filename) + 1]; + strcpy(self->filename, filename); + return (PyObject *)self; +} + +static void filelock_dealloc(filelock_object *self) +{ + delete[] self->filename; + ((PyObject*)self)->ob_type->tp_free(self); +} + +static PyMethodDef filelock_methods[] = { + {"__enter__",(PyCFunction)filelock_enter,METH_VARARGS,"Lock the system."}, + {"__exit__",(PyCFunction)filelock_exit,METH_VARARGS,"Unlock the system."}, + {NULL} +}; + +static char *filelock_doc = "SystemLock(filename: str)\n\n" + "Context manager for locking using a file. The lock is established\n" + "as soon as the method __enter__() is called. It is released when\n" + "__exit__() is called.\n\n" + "This should be used via the 'with' statement, e.g.::\n\n" + " with apt_pkg.FileLock(filename):\n" + " ...\n\n" + "Once the block is left, the lock is released automatically. The object\n" + "can be used multiple times::\n\n" + " lock = apt_pkg.FileLock(filename)\n" + " with lock:\n" + " ...\n" + " with lock:\n" + " ...\n\n"; + +PyTypeObject PyFileLock_Type = { + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "apt_pkg.FileLock", // tp_name + sizeof(filelock_object), // tp_basicsize + 0, // tp_itemsize + // Methods + destructor(filelock_dealloc), // tp_dealloc + 0, // tp_print + 0, // tp_getattr + 0, // tp_setattr + 0, // tp_compare + 0, // tp_repr + 0, // tp_as_number + 0, // tp_as_sequence + 0, // tp_as_mapping + 0, // tp_hash + 0, // tp_call + 0, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + (Py_TPFLAGS_DEFAULT | // tp_flags + Py_TPFLAGS_BASETYPE), + filelock_doc, // tp_doc + 0, // tp_traverse + 0, // tp_clear + 0, // tp_richcompare + 0, // tp_weaklistoffset + 0, // tp_iter + 0, // tp_iternext + filelock_methods, // tp_methods + 0, // tp_members + 0, // tp_getset + 0, // tp_base + 0, // tp_dict + 0, // tp_descr_get + 0, // tp_descr_set + 0, // tp_dictoffset + 0, // tp_init + 0, // tp_alloc + filelock_new, // tp_new +}; -- cgit v1.2.3 From 3e5c628641ae4e82c3433892f1df9ce44e29ae12 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Tue, 21 Jul 2009 17:59:36 +0200 Subject: python/python-apt.h: Export PyAcquireWorker and fix some problems. --- python/apt_pkgmodule.cc | 1 + python/python-apt.h | 12 +++++++++--- 2 files changed, 10 insertions(+), 3 deletions(-) (limited to 'python') diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index 8b8e9c7f..5ee4015c 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -527,6 +527,7 @@ static struct _PyAptPkgAPIStruct API = { &PyAcquireFile_Type, // acquirefile_type &PyAcquireItem_Type, // acquireitem_type &PyAcquireItemDesc_Type, // acquireitemdesc_type + &PyAcquireWorker_Type, // acquireworker_type &PyActionGroup_Type, // actiongroup_type &PyCache_Type, // cache_type &PyCacheFile_Type, // cachefile_type diff --git a/python/python-apt.h b/python/python-apt.h index d2693920..940963cf 100644 --- a/python/python-apt.h +++ b/python/python-apt.h @@ -29,6 +29,7 @@ struct _PyAptPkgAPIStruct { PyTypeObject *acquirefile_type; PyTypeObject *acquireitem_type; PyTypeObject *acquireitemdesc_type; + PyTypeObject *acquireworker_type; PyTypeObject *actiongroup_type; PyTypeObject *cache_type; PyTypeObject *cachefile_type; @@ -62,6 +63,7 @@ struct _PyAptPkgAPIStruct { # define PyAcquireFile_Type *(_PyAptPkg_API->acquirefile_type) # define PyAcquireItem_Type *(_PyAptPkg_API->acquireitem_type) # define PyAcquireItemDesc_Type *(_PyAptPkg_API->acquireitemdesc_type) +# define PyAcquireWorker_Type *(_PyAptPkg_API->acquireworker_type) # define PyActionGroup_Type *(_PyAptPkg_API->actiongroup_type) # define PyCache_Type *(_PyAptPkg_API->cache_type) # define PyCacheFile_Type *(_PyAptPkg_API->cachefile_type) @@ -122,6 +124,7 @@ static int import_apt_pkg(void) { # define PyAcquireFile_Check(op) PyObject_TypeCheck(op, &PyAcquireFile_Type) # define PyAcquireItem_Check(op) PyObject_TypeCheck(op, &PyAcquireItem_Type) # define PyAcquireItemDesc_Check(op) PyObject_TypeCheck(op, &PyAcquireItemDesc_Type) +# define PyAcquireWorker_Check(op) PyObject_TypeCheck(op, &PyAcquireWorker_Type) # define PyActionGroup_Check(op) PyObject_TypeCheck(op, &PyActionGroup_Type) # define PyCache_Check(op) PyObject_TypeCheck(op, &PyCache_Type) # define PyCacheFile_Check(op) PyObject_TypeCheck(op, &PyCacheFile_Type) @@ -153,6 +156,7 @@ static int import_apt_pkg(void) { # define PyAcquireFile_CheckExact(op) (Py_TYPE(op) == &PyAcquireFile_Type) # define PyAcquireItem_CheckExact(op) (Py_TYPE(op) == &PyAcquireItem_Type) # define PyAcquireItemDesc_CheckExact(op) (Py_TYPE(op) == &PyAcquireItemDesc_Type) +# define PyAcquireWorker_CheckExact(op) (Py_TYPE(op) == &PyAcquireWorker_Type) # define PyActionGroup_CheckExact(op) (Py_TYPE(op) == &PyActionGroup_Type) # define PyCache_CheckExact(op) (Py_TYPE(op) == &PyCache_Type) # define PyCacheFile_CheckExact(op) (Py_TYPE(op) == &PyCacheFile_Type) @@ -185,6 +189,7 @@ static int import_apt_pkg(void) { # define PyAcquireFile_ToCpp GetCpp # define PyAcquireItem_ToCpp GetCpp # define PyAcquireItemDesc_ToCpp GetCpp +# define PyAcquireWorker_ToCpp GetCpp # define PyActionGroup_ToCpp GetCpp # define PyCache_ToCpp GetCpp # define PyCacheFile_ToCpp GetCpp @@ -235,10 +240,11 @@ inline PyObject *FromCppOwned(PyTypeObject *pytype, Cpp const &obj, # define PyAcquireFile_FromCpp(...) FromCppOwned(&PyAcquireFile_Type, ##__VA_ARGS__) # define PyAcquireItem_FromCpp(...) FromCppOwned(&PyAcquireItem_Type,##__VA_ARGS__) # define PyAcquireItemDesc_FromCpp(...) FromCppOwned(&PyAcquireItemDesc_Type,##__VA_ARGS__) +# define PyAcquireWorker_FromCpp(...) FromCppOwned(&PyAcquireWorker_Type,##__VA_ARGS__) # define PyActionGroup_FromCpp(...) FromCppOwned(&PyActionGroup_Type,##__VA_ARGS__) # define PyCache_FromCpp(...) FromCppOwned(&PyCache_Type,##__VA_ARGS__) # define PyCacheFile_FromCpp(...) FromCpp(&PyCacheFile_Type,##__VA_ARGS__) -# define PyCdrom_FromCpp(...) FromCpp(&PyCdromType,##__VA_ARGS__) +# define PyCdrom_FromCpp(...) FromCpp(&PyCdrom_Type,##__VA_ARGS__) # define PyConfiguration_FromCpp(...) FromCppOwned(&PyConfiguration_Type, ##__VA_ARGS__) # define PyDepCache_FromCpp(...) FromCppOwned(&PyDepCache_Type,##__VA_ARGS__) # define PyDependency_FromCpp(...) FromCppOwned(&PyDependency_Type,##__VA_ARGS__) @@ -252,13 +258,13 @@ inline PyObject *FromCppOwned(PyTypeObject *pytype, Cpp const &obj, # define PyPackageIndexFile_FromCpp(...) FromCppOwned(&PyPackageIndexFile_Type,##__VA_ARGS__) # define PyPackageFile_FromCpp(...) FromCppOwned(&PyPackageFile_Type,##__VA_ARGS__) //# define PyPackageList_FromCpp(...) FromCppOwned(&PyPackageList_Type,##__VA_ARGS__) -# define PyPackageManager_FromCpp(...) FromCpp(&PyPackageManagerType,##__VA_ARGS__) +# define PyPackageManager_FromCpp(...) FromCpp(&PyPackageManager_Type,##__VA_ARGS__) //# define PyPackageRecords_FromCpp(...) FromCppOwned(&PyPackageRecords_Type,##__VA_ARGS__) # define PyPolicy_FromCpp(...) FromCppOwned(&PyPolicy_Type,##__VA_ARGS__) # define PyProblemResolver_FromCpp(...) FromCppOwned(&PyProblemResolver_Type,##__VA_ARGS__) # define PySourceList_FromCpp(...) FromCpp(&PySourceList_Type,##__VA_ARGS__) //# define PySourceRecords_FromCpp(...) FromCpp(&PySourceRecords_Type,##__VA_ARGS__) -//# define PyTagFile_FromCpp(...) FromCppOwned(&PyTagFile_Type,##__VA_ARGS__) +# define PyTagFile_FromCpp(...) FromCppOwned(&PyTagFile_Type,##__VA_ARGS__) # define PyTagSection_FromCpp(...) FromCppOwned(&PyTagSection_Type,##__VA_ARGS__) # define PyVersion_FromCpp(...) FromCppOwned(&PyVersion_Type,##__VA_ARGS__) #endif -- cgit v1.2.3 From b09ac74c765835edec940389f174169fd8b97a5b Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Tue, 21 Jul 2009 18:58:43 +0200 Subject: python/acquire.cc: Replace items vector with item_map. --- python/acquire.cc | 101 +++++++++++++++++++++++++++++------------------------- 1 file changed, 54 insertions(+), 47 deletions(-) (limited to 'python') diff --git a/python/acquire.cc b/python/acquire.cc index 50bdc949..8f765fc4 100644 --- a/python/acquire.cc +++ b/python/acquire.cc @@ -13,12 +13,23 @@ #include #include -typedef CppPyObject PyAcquireItemObject; +typedef CppOwnedPyObject PyAcquireItemObject; +typedef CppOwnedPyObject PyAcquireItemDescObject; +typedef CppOwnedPyObject PyAcquireFileObject; +typedef CppOwnedPyObject PyAcquireWorkerObject; + + +struct PyAcquireItems { + PyAcquireFileObject *file; + PyAcquireItemObject *item; +}; // Keep a vector to PyAcquireItemObject pointers, so we can set the Object // pointers to NULL when deallocating the main object (mostly AcquireFile). struct PyAcquireObject : public CppPyObject { - vector items; + map item_map; + map itemdesc_map; + map worker_map; }; @@ -30,11 +41,16 @@ static PyObject *acquireworker_get_current_item(PyObject *self, void *closure) Py_RETURN_NONE; } - PyAcquireObject *PyCache = (PyAcquireObject *)GetOwner(self); + PyAcquireObject *PyAcquire = (PyAcquireObject *)GetOwner(self); pkgAcquire::Item *Item = worker->CurrentItem->Owner; - PyObject *PyItem = PyAcquireItem_FromCpp(Item,false,PyCache); - PyCache->items.push_back((PyAcquireItemObject *)PyItem); + + PyObject *PyItem; + if (PyAcquire->item_map[Item].item) + PyItem = PyAcquire->item_map[Item].item; + else + PyItem = PyAcquire->item_map[Item].item = (PyAcquireItemObject*)PyAcquireItem_FromCpp(Item,false,PyAcquire); + return PyAcquireItemDesc_FromCpp(worker->CurrentItem,false,PyItem); } @@ -118,8 +134,6 @@ static PyObject *acquireitemdesc_get_shortdesc(PyObject *self, void *closure) } static PyObject *acquireitemdesc_get_owner(CppOwnedPyObject *self, void *closure) { - - if (self->Owner != NULL) { Py_INCREF(self->Owner); return self->Owner; @@ -238,9 +252,6 @@ static int AcquireItemSetID(PyObject *self, PyObject *value, void *closure) PyErr_SetString(PyExc_TypeError, "value must be integer."); return -1; } - - - return 0; } @@ -303,33 +314,16 @@ static void AcquireItemDealloc(PyObject *self) { PyAcquireObject *owner = (PyAcquireObject *)GetOwner(self); // Simply deallocate the object if we have no owner. - if (owner == NULL) { - CppOwnedDeallocPtr(self); - return; + if (owner != NULL && !((CppPyObject *)self)->NoDelete) { + PyAcquireItems &items = owner->item_map[file]; + + if (items.item && items.item != self) + items.item->Object = NULL; + if (items.file && items.item != self) + items.file->Object = NULL; + owner->item_map.erase(file); } - vector &items = owner->items; - bool DeletePtr = !((CppPyObject *)self)->NoDelete; - // Cleanup the other objects as well... - for (vector::iterator I = items.begin(); - I != items.end(); I++) { - // If it is the current object, remove it from the vector. - if ((*I) == self) { - items.erase(I); - I--; // erase() moved it one forward, move back - } - // If we delete the object below, set all other pointers to it to NULL, - // and remove them from the vector. - else if (DeletePtr && (*I)->Object == file) { - if ((*I) != self) - (*I)->Object = NULL; - items.erase(I); - I--; // erase() moved it one forward, move back - } - } -#ifdef ALLOC_DEBUG - std::cerr << "ITEMS: " << items.size() << "\n"; -#endif CppOwnedDeallocPtr(self); } @@ -394,10 +388,15 @@ static PyObject *PkgAcquireShutdown(PyObject *Self,PyObject *Args) fetcher->Shutdown(); - vector items = ((PyAcquireObject *)Self)->items; - for (vector::iterator I = items.begin(); - I != items.end(); I++) - (*I)->Object = NULL; + // TODO: Delete all objects here + map items = ((PyAcquireObject *)Self)->item_map; + for (map::iterator I = items.begin(); + I != items.end(); I++) { + (*I).second.file->Object = NULL; + (*I).second.item->Object = NULL; + } + + Py_INCREF(Py_None); return HandleErrors(Py_None); @@ -443,15 +442,20 @@ static PyObject *PkgAcquireGetItems(PyObject *Self,void*) { pkgAcquire *fetcher = GetCpp(Self); PyObject *List = PyList_New(0); + PyAcquireItemObject *Obj; for (pkgAcquire::ItemIterator I = fetcher->ItemsBegin(); I != fetcher->ItemsEnd(); I++) { - PyAcquireItemObject *Obj; - Obj = CppOwnedPyObject_NEW(Self,&PyAcquireItem_Type,*I); - Obj->NoDelete = true; - PyList_Append(List,Obj); - ((PyAcquireObject *)Self)->items.push_back(Obj); - Py_DECREF(Obj); + + if (((PyAcquireObject *)Self)->item_map[*I].item) + PyList_Append(List, ((PyAcquireObject *)Self)->item_map[*I].item); + else { + Obj = CppOwnedPyObject_NEW(Self,&PyAcquireItem_Type,*I); + Obj->NoDelete = true; + PyList_Append(List,Obj); + ((PyAcquireObject *)Self)->item_map[*I].item = Obj; + Py_DECREF(Obj); + } } return List; } @@ -504,9 +508,11 @@ static PyObject *PkgAcquireNew(PyTypeObject *type,PyObject *Args,PyObject *kwds) fetcher = new pkgAcquire(); } - CppPyObject *FetcherObj = + PyAcquireObject *FetcherObj = (PyAcquireObject *) CppPyObject_NEW(type, fetcher); + // prepare our map of items. + new (&FetcherObj->item_map) map(); return FetcherObj; } @@ -594,8 +600,9 @@ static PyObject *PkgAcquireFileNew(PyTypeObject *type, PyObject *Args, PyObject destFile); // short-desc CppOwnedPyObject *AcqFileObj = CppOwnedPyObject_NEW(pyfetcher, type); AcqFileObj->Object = af; - ((PyAcquireObject *)pyfetcher)->items.push_back((PyAcquireItemObject *)AcqFileObj); + // Register the file so we can remove it later. + ((PyAcquireObject *)pyfetcher)->item_map[af].file = AcqFileObj; return AcqFileObj; } -- cgit v1.2.3 From 884449db557b4c1751a625772aae2fcdab3b7a7c Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Tue, 21 Jul 2009 20:03:55 +0200 Subject: python/acquire.cc: Hack support for Acquire object created by PyAcquire_FromCpp. --- python/acquire.cc | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) (limited to 'python') diff --git a/python/acquire.cc b/python/acquire.cc index 8f765fc4..78bd016e 100644 --- a/python/acquire.cc +++ b/python/acquire.cc @@ -46,10 +46,17 @@ static PyObject *acquireworker_get_current_item(PyObject *self, void *closure) pkgAcquire::Item *Item = worker->CurrentItem->Owner; PyObject *PyItem; - if (PyAcquire->item_map[Item].item) + // FIXME: PyAcquire_FromCpp needs to initialize item_map. + if (PyAcquire && false && PyAcquire->item_map[Item].item) { + Py_INCREF(PyItem); PyItem = PyAcquire->item_map[Item].item; - else - PyItem = PyAcquire->item_map[Item].item = (PyAcquireItemObject*)PyAcquireItem_FromCpp(Item,false,PyAcquire); + } + else { + PyItem = PyAcquireItem_FromCpp(Item,false,PyAcquire); + // FIXME: PyAcquire_FromCpp needs to initialize item_map. + if (PyAcquire && false) + PyAcquire->item_map[Item].item = (PyAcquireItemObject*)PyItem; + } return PyAcquireItemDesc_FromCpp(worker->CurrentItem,false,PyItem); } -- cgit v1.2.3 From 59ca8fafbe93d5aff7ac4baf54877dd1aa5fa036 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Tue, 21 Jul 2009 20:56:19 +0200 Subject: python/progress.cc: Fix problems with threads. --- python/progress.cc | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) (limited to 'python') diff --git a/python/progress.cc b/python/progress.cc index 3dd104ab..cc0c9ffc 100644 --- a/python/progress.cc +++ b/python/progress.cc @@ -138,11 +138,9 @@ bool PyFetchProgress::MediaChange(string Media, string Drive) void PyFetchProgress::UpdateStatus(pkgAcquire::ItemDesc &Itm, int status) { //std::cout << "UpdateStatus: " << Itm.URI << " " << status << std::endl; - // Added object file size and object partial size to // parameters that are passed to updateStatus. // -- Stephan - PyCbObj_END_ALLOW_THREADS PyObject *arglist = Py_BuildValue("(sssikk)", Itm.URI.c_str(), Itm.Description.c_str(), Itm.ShortDesc.c_str(), @@ -159,35 +157,41 @@ void PyFetchProgress::UpdateStatus(pkgAcquire::ItemDesc &Itm, int status) if(!RunSimpleCallback("update_status", arglist)) RunSimpleCallback("updateStatus", arglist); - PyCbObj_BEGIN_ALLOW_THREADS } void PyFetchProgress::IMSHit(pkgAcquire::ItemDesc &Itm) { + PyCbObj_END_ALLOW_THREADS if (PyObject_TypeCheck(callbackInst,&PyAcquireProgress_Type)) RunSimpleCallback("ims_hit", TUPLEIZE(PyAcquireItemDesc_FromCpp(&Itm))); else UpdateStatus(Itm, DLHit); + PyCbObj_BEGIN_ALLOW_THREADS } void PyFetchProgress::Fetch(pkgAcquire::ItemDesc &Itm) { + PyCbObj_END_ALLOW_THREADS if (PyObject_TypeCheck(callbackInst,&PyAcquireProgress_Type)) RunSimpleCallback("fetch", TUPLEIZE(PyAcquireItemDesc_FromCpp(&Itm))); else UpdateStatus(Itm, DLQueued); + PyCbObj_BEGIN_ALLOW_THREADS } void PyFetchProgress::Done(pkgAcquire::ItemDesc &Itm) { + PyCbObj_END_ALLOW_THREADS if (PyObject_TypeCheck(callbackInst,&PyAcquireProgress_Type)) RunSimpleCallback("done", TUPLEIZE(PyAcquireItemDesc_FromCpp(&Itm))); else UpdateStatus(Itm, DLDone); + PyCbObj_BEGIN_ALLOW_THREADS } void PyFetchProgress::Fail(pkgAcquire::ItemDesc &Itm) { + PyCbObj_END_ALLOW_THREADS if (PyObject_TypeCheck(callbackInst,&PyAcquireProgress_Type)) { RunSimpleCallback("fail", TUPLEIZE(PyAcquireItemDesc_FromCpp(&Itm))); return; @@ -207,6 +211,7 @@ void PyFetchProgress::Fail(pkgAcquire::ItemDesc &Itm) RunSimpleCallback("fail", TUPLEIZE(PyAcquireItemDesc_FromCpp(&Itm))); else UpdateStatus(Itm, DLFailed); + PyCbObj_BEGIN_ALLOW_THREADS } void PyFetchProgress::Start() @@ -258,6 +263,7 @@ void PyFetchProgress::Stop() * PyCbObj_END_ALLOW_THREADS to our previous * PyCbObj_BEGIN_ALLOW_THREADS (Python requires this!). */ + PyCbObj_END_ALLOW_THREADS //std::cout << "Stop" << std::endl; pkgAcquireStatus::Stop(); @@ -328,9 +334,11 @@ bool PyFetchProgress::Pulse(pkgAcquire * Owner) if (RunSimpleCallback("pulse", TUPLEIZE(PyAcquire_FromCpp(Owner)), &result1)) { if (result1 != NULL && PyArg_Parse(result1, "b", &res1) && res1 == false) { // the user returned a explicit false here, stop + PyCbObj_BEGIN_ALLOW_THREADS return false; } } + PyCbObj_BEGIN_ALLOW_THREADS return true; } -- cgit v1.2.3 From 1358664af2c27db4d7d62292680013e811f11750 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Tue, 21 Jul 2009 21:53:36 +0200 Subject: python/progress.cc: Introduce setattr to reduce code duplication. This way, we can replace stuff like PyObject *o = PyBuildValue("i", 0); PyObject_SetAttrString(callbackInst, "attribute", o); Py_DECREF(o) with setattr(callbackInst,"attribute","i",0); --- python/progress.cc | 135 +++++++++++++++++++++-------------------------------- python/progress.h | 3 +- 2 files changed, 55 insertions(+), 83 deletions(-) (limited to 'python') diff --git a/python/progress.cc b/python/progress.cc index cc0c9ffc..305246b7 100644 --- a/python/progress.cc +++ b/python/progress.cc @@ -17,6 +17,24 @@ #include "generic.h" #include "apt_pkgmodule.h" + +/** + * Set an attribute on an object, after creating the value with + * Py_BuildValue(fmt, arg). Afterwards, decrease its refcount and return + * whether setting the attribute was successful. + */ +template +inline bool setattr(PyObject *object, const char *attr, const char *fmt, T arg) +{ + if (!object) + return false; + PyObject *value = Py_BuildValue(fmt, arg); + + int result = PyObject_SetAttrString(object, attr, value); + Py_DECREF(value); + return result != -1; +} + #define TUPLEIZE(op) Py_BuildValue("(O)", op) // generic bool PyCallbackObj::RunSimpleCallback(const char* method_name, @@ -81,22 +99,11 @@ void PyOpProgress::Update() RunSimpleCallback("update"); } else { - PyObject *o; - o = Py_BuildValue("s", Op.c_str()); - PyObject_SetAttrString(callbackInst, "op", o); - Py_XDECREF(o); - o = Py_BuildValue("s", SubOp.c_str()); - if(PyObject_HasAttrString(callbackInst, "sub_op")) - PyObject_SetAttrString(callbackInst, "sub_op", o); - else - PyObject_SetAttrString(callbackInst, "subOp", o); - Py_XDECREF(o); - o = Py_BuildValue("b", MajorChange); - if(PyObject_HasAttrString(callbackInst, "major_change")) - PyObject_SetAttrString(callbackInst, "major_change", o); - else - PyObject_SetAttrString(callbackInst, "majorChange", o); - Py_XDECREF(o); + setattr(callbackInst, "op", "s", Op.c_str()); + setattr(callbackInst, "subop", "s", SubOp.c_str()); + setattr(callbackInst, "subOp", "s", SubOp.c_str()); + setattr(callbackInst, "major_change", "b", MajorChange); + setattr(callbackInst, "majorChange", "b", MajorChange); PyObject *arglist = Py_BuildValue("(f)", Percent); RunSimpleCallback("update", arglist); } @@ -219,35 +226,16 @@ void PyFetchProgress::Start() //std::cout << "Start" << std::endl; pkgAcquireStatus::Start(); +#ifdef COMPAT_0_7 + if (!PyObject_TypeCheck(callbackInst,&PyAcquireProgress_Type)) { + setattr(callbackInst, "currentCPS", "d", 0); + setattr(callbackInst, "currentBytes", "d", 0); + setattr(callbackInst, "currentItems", "k", 0); + setattr(callbackInst, "totalItems", "k", 0); + setattr(callbackInst, "totalBytes", "d", 0); + } +#endif - if (PyObject_TypeCheck(callbackInst,&PyAcquireProgress_Type)) - goto end; - - // These attributes should be initialized before the first callback (start) - // is invoked. - // -- Stephan - PyObject *o; - - o = Py_BuildValue("d", 0); - PyObject_SetAttrString(callbackInst, "currentCPS", o); - Py_XDECREF(o); - - o = Py_BuildValue("d", 0); - PyObject_SetAttrString(callbackInst, "currentBytes", o); - Py_XDECREF(o); - - o = Py_BuildValue("k", 0); - PyObject_SetAttrString(callbackInst, "currentItems", o); - Py_XDECREF(o); - o = Py_BuildValue("k", 0); - PyObject_SetAttrString(callbackInst, "totalItems", o); - Py_XDECREF(o); - - o = Py_BuildValue("d", 0); - PyObject_SetAttrString(callbackInst, "totalBytes", o); - Py_XDECREF(o); - -end: RunSimpleCallback("start"); /* After calling the start method we can safely allow * other Python threads to do their work for now. @@ -291,41 +279,22 @@ bool PyFetchProgress::Pulse(pkgAcquire * Owner) obj->current_items = CurrentItems; } else { - // set stats - PyObject *o; - o = Py_BuildValue("d", FetchedBytes); - PyObject_SetAttrString(callbackInst, "fetched_bytes", o); - Py_DECREF(o); - o = Py_BuildValue("d", CurrentCPS); - if(PyObject_HasAttrString(callbackInst, "current_cps")) - PyObject_SetAttrString(callbackInst, "current_cps", o); - else - PyObject_SetAttrString(callbackInst, "currentCPS", o); - Py_XDECREF(o); - o = Py_BuildValue("d", CurrentBytes); - if(PyObject_HasAttrString(callbackInst, "current_bytes")) - PyObject_SetAttrString(callbackInst, "current_bytes", o); - else - PyObject_SetAttrString(callbackInst, "currentBytes", o); - Py_XDECREF(o); - o = Py_BuildValue("k", CurrentItems); - if(PyObject_HasAttrString(callbackInst, "current_items")) - PyObject_SetAttrString(callbackInst, "current_items", o); - else - PyObject_SetAttrString(callbackInst, "currentItems", o); - Py_XDECREF(o); - o = Py_BuildValue("k", TotalItems); - if(PyObject_HasAttrString(callbackInst, "total_items")) - PyObject_SetAttrString(callbackInst, "total_items", o); - else - PyObject_SetAttrString(callbackInst, "totalItems", o); - Py_XDECREF(o); - o = Py_BuildValue("d", TotalBytes); - if(PyObject_HasAttrString(callbackInst, "total_bytes")) - PyObject_SetAttrString(callbackInst, "total_bytes", o); - else - PyObject_SetAttrString(callbackInst, "totalBytes", o); - Py_XDECREF(o); + setattr(callbackInst, "last_bytes", "d", LastBytes); + setattr(callbackInst, "current_cps", "d", CurrentCPS); + setattr(callbackInst, "current_bytes", "d", CurrentBytes); + setattr(callbackInst, "total_bytes", "d", TotalBytes); + setattr(callbackInst, "fetched_bytes", "d", FetchedBytes); + setattr(callbackInst, "elapsed_time", "k", ElapsedTime); + setattr(callbackInst, "current_items", "k", CurrentItems); + setattr(callbackInst, "total_items", "k", TotalItems); +#ifdef COMPAT_0_7 + setattr(callbackInst, "currentCPS", "d", CurrentCPS); + setattr(callbackInst, "currentBytes", "d", CurrentBytes); + setattr(callbackInst, "totalBytes", "d", TotalBytes); + setattr(callbackInst, "fetchedBytes", "d", FetchedBytes); + setattr(callbackInst, "currentItems", "k", CurrentItems); + setattr(callbackInst, "totalItems", "k", TotalItems); +#endif } if (PyObject_TypeCheck(callbackInst, &PyAcquireProgress_Type)) { @@ -568,9 +537,11 @@ void PyCdromProgress::Update(string text, int current) ((PyCdromProgressObject *)callbackInst)->total_steps = totalSteps; } else { - PyObject *o = Py_BuildValue("i", totalSteps); - PyObject_SetAttrString(callbackInst, "totalSteps", o); - Py_XDECREF(o); + + setattr(callbackInst, "total_steps", "i", totalSteps); +#ifdef COMPAT_0_7 + setattr(callbackInst, "totalSteps", "i", totalSteps); +#endif } RunSimpleCallback("update", arglist); diff --git a/python/progress.h b/python/progress.h index 88c0a21b..e92933a7 100644 --- a/python/progress.h +++ b/python/progress.h @@ -18,7 +18,7 @@ /* PyCbObj_BEGIN_ALLOW_THREADS and PyCbObj_END_ALLOW_THREADS are sligthly * modified versions of Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS. * Instead of storing the thread state in a function-local variable these - * use a class attribute (with the same) name, allowing blocking and + * use a class attribute (with the same) name, allowing blocking and * unblocking from different class methods. * Py_BLOCK_THREADS and Py_UNBLOCK_THREADS do not define their own * local variable but use the one provided by PyCbObj_BEGIN_ALLOW_THREADS @@ -63,6 +63,7 @@ typedef struct { } PyAcquireProgressObject; + class PyCallbackObj { protected: PyObject *callbackInst; -- cgit v1.2.3 From 8e6ce0ce4761404cf13bea468d925fc906ab2143 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Wed, 22 Jul 2009 17:16:01 +0200 Subject: python/python-apt.h: Don't use Py_TYPE(op), but op->op_type. The Py_TYPE macro does not exist in Python < 2.6 and is not documented. --- python/python-apt.h | 62 ++++++++++++++++++++++++++--------------------------- 1 file changed, 31 insertions(+), 31 deletions(-) (limited to 'python') diff --git a/python/python-apt.h b/python/python-apt.h index 940963cf..80ad03bd 100644 --- a/python/python-apt.h +++ b/python/python-apt.h @@ -152,37 +152,37 @@ static int import_apt_pkg(void) { # define PyTagSection_Check(op) PyObject_TypeCheck(op, &PyTagSection_Type) # define PyVersion_Check(op) PyObject_TypeCheck(op, &PyVersion_Type) // Exact check macros. -# define PyAcquire_CheckExact(op) (Py_TYPE(op) == &PyAcquire_Type) -# define PyAcquireFile_CheckExact(op) (Py_TYPE(op) == &PyAcquireFile_Type) -# define PyAcquireItem_CheckExact(op) (Py_TYPE(op) == &PyAcquireItem_Type) -# define PyAcquireItemDesc_CheckExact(op) (Py_TYPE(op) == &PyAcquireItemDesc_Type) -# define PyAcquireWorker_CheckExact(op) (Py_TYPE(op) == &PyAcquireWorker_Type) -# define PyActionGroup_CheckExact(op) (Py_TYPE(op) == &PyActionGroup_Type) -# define PyCache_CheckExact(op) (Py_TYPE(op) == &PyCache_Type) -# define PyCacheFile_CheckExact(op) (Py_TYPE(op) == &PyCacheFile_Type) -# define PyCdrom_CheckExact(op) (Py_TYPE(op) == &PyCdrom_Type) -# define PyConfiguration_CheckExact(op) (Py_TYPE(op) == &PyConfiguration_Type) -# define PyDepCache_CheckExact(op) (Py_TYPE(op) == &PyDepCache_Type) -# define PyDependency_CheckExact(op) (Py_TYPE(op) == &PyDependency_Type) -# define PyDependencyList_CheckExact(op) (Py_TYPE(op) == &PyDependencyList_Type) -# define PyDescription_CheckExact(op) (Py_TYPE(op) == &PyDescription_Type) -# define PyHashes_CheckExact(op) (Py_TYPE(op) == &PyHashes_Type) -# define PyHashString_CheckExact(op) (Py_TYPE(op) == &PyHashString_Type) -# define PyIndexRecords_CheckExact(op) (Py_TYPE(op) == &PyIndexRecords_Type) -# define PyMetaIndex_CheckExact(op) (Py_TYPE(op) == &PyMetaIndex_Type) -# define PyPackage_CheckExact(op) (Py_TYPE(op) == &PyPackage_Type) -# define PyPackageFile_CheckExact(op) (Py_TYPE(op) == &PyPackageFile_Type) -# define PyPackageIndexFile_CheckExact(op) (Py_TYPE(op) == &PyPackageIndexFile_Type) -# define PyPackageList_CheckExact(op) (Py_TYPE(op) == &PyPackageList_Type) -# define PyPackageManager_CheckExact(op) (Py_TYPE(op) == &PyPackageManager_Type) -# define PyPackageRecords_CheckExact(op) (Py_TYPE(op) == &PyPackageRecords_Type) -# define PyPolicy_CheckExact(op) (Py_TYPE(op) == &PyPolicy_Type) -# define PyProblemResolver_CheckExact(op) (Py_TYPE(op) == &PyProblemResolver_Type) -# define PySourceList_CheckExact(op) (Py_TYPE(op) == &PySourceList_Type) -# define PySourceRecords_CheckExact(op) (Py_TYPE(op) == &PySourceRecords_Type) -# define PyTagFile_CheckExact(op) (Py_TYPE(op) == &PyTagFile_Type) -# define PyTagSection_CheckExact(op) (Py_TYPE(op) == &PyTagSection_Type) -# define PyVersion_CheckExact(op) (Py_TYPE(op) == &PyVersion_Type) +# define PyAcquire_CheckExact(op) (op->op_type == &PyAcquire_Type) +# define PyAcquireFile_CheckExact(op) (op->op_type == &PyAcquireFile_Type) +# define PyAcquireItem_CheckExact(op) (op->op_type == &PyAcquireItem_Type) +# define PyAcquireItemDesc_CheckExact(op) (op->op_type == &PyAcquireItemDesc_Type) +# define PyAcquireWorker_CheckExact(op) (op->op_type == &PyAcquireWorker_Type) +# define PyActionGroup_CheckExact(op) (op->op_type == &PyActionGroup_Type) +# define PyCache_CheckExact(op) (op->op_type == &PyCache_Type) +# define PyCacheFile_CheckExact(op) (op->op_type == &PyCacheFile_Type) +# define PyCdrom_CheckExact(op) (op->op_type == &PyCdrom_Type) +# define PyConfiguration_CheckExact(op) (op->op_type == &PyConfiguration_Type) +# define PyDepCache_CheckExact(op) (op->op_type == &PyDepCache_Type) +# define PyDependency_CheckExact(op) (op->op_type == &PyDependency_Type) +# define PyDependencyList_CheckExact(op) (op->op_type == &PyDependencyList_Type) +# define PyDescription_CheckExact(op) (op->op_type == &PyDescription_Type) +# define PyHashes_CheckExact(op) (op->op_type == &PyHashes_Type) +# define PyHashString_CheckExact(op) (op->op_type == &PyHashString_Type) +# define PyIndexRecords_CheckExact(op) (op->op_type == &PyIndexRecords_Type) +# define PyMetaIndex_CheckExact(op) (op->op_type == &PyMetaIndex_Type) +# define PyPackage_CheckExact(op) (op->op_type == &PyPackage_Type) +# define PyPackageFile_CheckExact(op) (op->op_type == &PyPackageFile_Type) +# define PyPackageIndexFile_CheckExact(op) (op->op_type == &PyPackageIndexFile_Type) +# define PyPackageList_CheckExact(op) (op->op_type == &PyPackageList_Type) +# define PyPackageManager_CheckExact(op) (op->op_type == &PyPackageManager_Type) +# define PyPackageRecords_CheckExact(op) (op->op_type == &PyPackageRecords_Type) +# define PyPolicy_CheckExact(op) (op->op_type == &PyPolicy_Type) +# define PyProblemResolver_CheckExact(op) (op->op_type == &PyProblemResolver_Type) +# define PySourceList_CheckExact(op) (op->op_type == &PySourceList_Type) +# define PySourceRecords_CheckExact(op) (op->op_type == &PySourceRecords_Type) +# define PyTagFile_CheckExact(op) (op->op_type == &PyTagFile_Type) +# define PyTagSection_CheckExact(op) (op->op_type == &PyTagSection_Type) +# define PyVersion_CheckExact(op) (op->op_type == &PyVersion_Type) // Get the underlying C++ reference or pointer from the Python object. # define PyAcquire_ToCpp GetCpp -- cgit v1.2.3 From 6ba42d2e31f161fc0ebe5405cf63b616c3e822b4 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Wed, 22 Jul 2009 17:21:08 +0200 Subject: python: First step of fixing acquire stuff. Basically, we only want to have on PyAcquireItem per pkgAcquire::Item, and one PyAcquireItemDesc per pkgAcquire::ItemDesc. Therefore, we store them so we can return them at a later time. --- python/acquire-item.cc | 357 ++++++++++++++++++++++++++++++++++++++++++++++++ python/acquire.cc | 356 ++++++----------------------------------------- python/apt_pkgmodule.cc | 32 +++++ python/progress.cc | 12 +- python/progress.h | 7 + setup.py | 3 +- 6 files changed, 451 insertions(+), 316 deletions(-) create mode 100644 python/acquire-item.cc (limited to 'python') diff --git a/python/acquire-item.cc b/python/acquire-item.cc new file mode 100644 index 00000000..cf0a628e --- /dev/null +++ b/python/acquire-item.cc @@ -0,0 +1,357 @@ +/* + * acquire-item.cc - Wrapper around pkgAcquire::Item and pkgAcqFile. + * + * Copyright 2004-2009 Canonical Ltd. + * Copyright 2009 Julian Andres Klode + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + */ + +#include "generic.h" +#include "apt_pkgmodule.h" + +#include +#include + +using namespace std; + + + +struct PyAcquireItems { + CppOwnedPyObject *file; + CppOwnedPyObject *item; + CppOwnedPyObject *desc; +}; + +typedef map item_map; + +// Keep a vector to PyAcquireItemObject pointers, so we can set the Object +// pointers to NULL when deallocating the main object (mostly AcquireFile). +struct PyAcquireObject : public CppPyObject { + item_map items; +}; + +inline pkgAcquire::Item *acquireitem_tocpp(PyObject *self) +{ + pkgAcquire::Item *itm = GetCpp(self); + if (itm == 0) + PyErr_SetString(PyExc_ValueError, "Acquire() has been shut down or " + "the AcquireFile() object has been deallocated."); + return itm; +} + +static PyObject *acquireitem_get_complete(PyObject *self, void *closure) +{ + pkgAcquire::Item *item = acquireitem_tocpp(self); + return item ? PyBool_FromLong(item->Complete) : 0; +} + +static PyObject *acquireitem_get_desc_uri(PyObject *self, void *closure) +{ + pkgAcquire::Item *item = acquireitem_tocpp(self); + return item ? CppPyString(item->DescURI()) : 0; +} + +static PyObject *acquireitem_get_destfile(PyObject *self, void *closure) +{ + pkgAcquire::Item *item = acquireitem_tocpp(self); + return item ? CppPyString(item->DestFile) : 0; +} + + +static PyObject *acquireitem_get_error_text(PyObject *self, void *closure) +{ + pkgAcquire::Item *item = acquireitem_tocpp(self); + return item ? CppPyString(item->ErrorText) : 0; +} + +static PyObject *acquireitem_get_filesize(PyObject *self, void *closure) +{ + pkgAcquire::Item *item = acquireitem_tocpp(self); + return item ? Py_BuildValue("i", item->FileSize) : 0; +} + +static PyObject *acquireitem_get_id(PyObject *self, void *closure) +{ + pkgAcquire::Item *item = acquireitem_tocpp(self); + return item ? Py_BuildValue("k", item->ID) : 0; +} + +static PyObject *acquireitem_get_mode(PyObject *self, void *closure) +{ + pkgAcquire::Item *item = acquireitem_tocpp(self); + return item ? Py_BuildValue("s", item->Mode) : 0; +} + +static PyObject *acquireitem_get_is_trusted(PyObject *self, void *closure) +{ + pkgAcquire::Item *item = acquireitem_tocpp(self); + return item ? PyBool_FromLong(item->IsTrusted()) : 0; +} + +static PyObject *acquireitem_get_local(PyObject *self, void *closure) +{ + pkgAcquire::Item *item = acquireitem_tocpp(self); + return item ? PyBool_FromLong(item->Local) : 0; +} + +static PyObject *acquireitem_get_status(PyObject *self, void *closure) +{ + pkgAcquire::Item *item = acquireitem_tocpp(self); + return item ? Py_BuildValue("i", item->Status) : 0; +} + +static int acquireitem_set_id(PyObject *self, PyObject *value, void *closure) +{ + pkgAcquire::Item *Itm = acquireitem_tocpp(self); + if (Itm == 0) + return -1; + if (PyLong_Check(value)) { + Itm->ID = PyLong_AsLong(value); + } + else if (PyInt_Check(value)) { + Itm->ID = PyInt_AsLong(value); + } + else { + PyErr_SetString(PyExc_TypeError, "value must be integer."); + return -1; + } + return 0; +} + + +static PyGetSetDef acquireitem_getset[] = { + {"complete",acquireitem_get_complete}, + {"desc_uri",acquireitem_get_desc_uri}, + {"destfile",acquireitem_get_destfile}, + {"error_text",acquireitem_get_error_text}, + {"filesize",acquireitem_get_filesize}, + {"id",acquireitem_get_id,acquireitem_set_id}, + {"mode",acquireitem_get_mode}, + {"is_trusted",acquireitem_get_is_trusted}, + {"local",acquireitem_get_local}, + {"status",acquireitem_get_status}, +#ifdef COMPAT_0_7 + {"Complete",acquireitem_get_complete}, + {"DescURI",acquireitem_get_desc_uri}, + {"DestFile",acquireitem_get_destfile}, + {"ErrorText",acquireitem_get_error_text}, + {"FileSize",acquireitem_get_filesize}, + {"ID",acquireitem_get_id}, + {"IsTrusted",acquireitem_get_is_trusted}, + {"Local",acquireitem_get_local}, + {"Status",acquireitem_get_status}, +#endif + {} +}; + +static PyObject *acquireitem_repr(PyObject *Self) +{ + pkgAcquire::Item *Itm = acquireitem_tocpp(Self); + if (Itm == 0) + return 0; + + return PyString_FromFormat("<%s object: " + "Status: %i Complete: %i Local: %i IsTrusted: %i " + "FileSize: %lu DestFile:'%s' " + "DescURI: '%s' ID:%lu ErrorText: '%s'>", + Self->ob_type->tp_name, + Itm->Status, Itm->Complete, Itm->Local, Itm->IsTrusted(), + Itm->FileSize, Itm->DestFile.c_str(), Itm->DescURI().c_str(), + Itm->ID,Itm->ErrorText.c_str()); +} + +static void acquireitem_dealloc(PyObject *self) +{ + // TODO: Unregister the object in the owner. + if (!((CppOwnedPyObject*)self)->NoDelete) { + pkgAcquire::Item *item = PyAcquireItem_ToCpp(self); + PyAcquireObject *Owner = (PyAcquireObject *)GetOwner(self); + + PyAcquireItems item_struct = Owner->items[item]; + + if (item_struct.file != 0 && item_struct.file != self) + item_struct.file->Object = 0; + if (item_struct.item != 0 && item_struct.item != self) { + item_struct.item->Object = 0; + Py_DECREF(item_struct.item); + } + if (item_struct.desc != 0) { + item_struct.desc->Object = 0; + Py_DECREF(item_struct.desc); + } + Owner->items.erase(item); + } + + CppOwnedDeallocPtr(self); +} + +PyTypeObject PyAcquireItem_Type = { + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "apt_pkg.AcquireItem", // tp_name + sizeof(CppOwnedPyObject), // tp_basicsize + 0, // tp_itemsize + // Methods + acquireitem_dealloc, // tp_dealloc + 0, // tp_print + 0, // tp_getattr + 0, // tp_setattr + 0, // tp_compare + acquireitem_repr, // tp_repr + 0, // tp_as_number + 0, // tp_as_sequence + 0, // tp_as_mapping + 0, // tp_hash + 0, // tp_call + 0, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + Py_TPFLAGS_DEFAULT, // tp_flags + "AcquireItem Object", // tp_doc + 0, // tp_traverse + 0, // tp_clear + 0, // tp_richcompare + 0, // tp_weaklistoffset + 0, // tp_iter + 0, // tp_iternext + 0, // tp_methods + 0, // tp_members + acquireitem_getset, // tp_getset +}; + +static PyObject *acquirefile_new(PyTypeObject *type, PyObject *Args, PyObject * kwds) +{ + PyObject *pyfetcher; + char *uri, *md5, *descr, *shortDescr, *destDir, *destFile; + int size = 0; + uri = md5 = descr = shortDescr = destDir = destFile = ""; + + char *kwlist[] = {"owner","uri", "md5", "size", "descr", "short_descr", + "destdir", "destfile", NULL + }; + + if (PyArg_ParseTupleAndKeywords(Args, kwds, "O!s|sissss", kwlist, + &PyAcquire_Type, &pyfetcher, &uri, &md5, + &size, &descr, &shortDescr, &destDir, &destFile) == 0) + return 0; + + pkgAcquire *fetcher = GetCpp(pyfetcher); + pkgAcqFile *af = new pkgAcqFile(fetcher, // owner + uri, // uri + md5, // md5 + size, // size + descr, // descr + shortDescr, + destDir, + destFile); // short-desc + CppOwnedPyObject *AcqFileObj = CppOwnedPyObject_NEW(pyfetcher, type); + AcqFileObj->Object = af; + + + ((PyAcquireObject *)pyfetcher)->items[af].file = AcqFileObj; + return AcqFileObj; +} + + +static char *acquirefile_doc = + "AcquireFile(owner, uri[, md5, size, descr, short_descr, destdir," + "destfile]) -> New AcquireFile() object\n\n" + "The parameter *owner* refers to an apt_pkg.Acquire() object. You can use\n" + "*destdir* OR *destfile* to specify the destination directory/file."; + +PyTypeObject PyAcquireFile_Type = { + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "apt_pkg.AcquireFile", // tp_name + sizeof(CppOwnedPyObject),// tp_basicsize + 0, // tp_itemsize + // Methods + acquireitem_dealloc, // tp_dealloc + 0, // tp_print + 0, // tp_getattr + 0, // tp_setattr + 0, // tp_compare + 0, // tp_repr + 0, // tp_as_number + 0, // tp_as_sequence + 0, // tp_as_mapping + 0, // tp_hash + 0, // tp_call + 0, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + Py_TPFLAGS_DEFAULT | // tp_flags + Py_TPFLAGS_BASETYPE | + Py_TPFLAGS_HAVE_GC, + acquirefile_doc, // tp_doc + CppOwnedTraverse, // tp_traverse + CppOwnedClear, // tp_clear + 0, // tp_richcompare + 0, // tp_weaklistoffset + 0, // tp_iter + 0, // tp_iternext + 0, // tp_methods + 0, // tp_members + 0, // tp_getset + &PyAcquireItem_Type, // tp_base + 0, // tp_dict + 0, // tp_descr_get + 0, // tp_descr_set + 0, // tp_dictoffset + 0, // tp_init + 0, // tp_alloc + acquirefile_new, // tp_new +}; + +#ifdef COMPAT_0_7 +char *doc_GetPkgAcqFile = + "GetPkgAcqFile(pkgAquire, uri[, md5, size, descr, shortDescr, destDir, destFile]) -> PkgAcqFile\n"; +PyObject *GetPkgAcqFile(PyObject *Self, PyObject *Args, PyObject * kwds) +{ + PyErr_WarnEx(PyExc_DeprecationWarning, "apt_pkg.GetPkgAcqFile() is " + "deprecated. Please see apt_pkg.AcquireFile() for the " + "replacement", 1); + PyObject *pyfetcher; + char *uri, *md5, *descr, *shortDescr, *destDir, *destFile; + int size = 0; + uri = md5 = descr = shortDescr = destDir = destFile = ""; + + char * kwlist[] = {"owner","uri", "md5", "size", "descr", "shortDescr", + "destDir", "destFile", NULL + }; + + if (PyArg_ParseTupleAndKeywords(Args, kwds, "O!s|sissss", kwlist, + &PyAcquire_Type, &pyfetcher, &uri, &md5, + &size, &descr, &shortDescr, &destDir, &destFile) == 0) + return 0; + + pkgAcquire *fetcher = GetCpp(pyfetcher); + pkgAcqFile *af = new pkgAcqFile(fetcher, // owner + uri, // uri + md5, // md5 + size, // size + descr, // descr + shortDescr, + destDir, + destFile); // short-desc + CppPyObject *AcqFileObj = CppPyObject_NEW(&PyAcquireFile_Type); + AcqFileObj->Object = af; + AcqFileObj->NoDelete = true; + + return AcqFileObj; +} +#endif diff --git a/python/acquire.cc b/python/acquire.cc index 78bd016e..5e03586e 100644 --- a/python/acquire.cc +++ b/python/acquire.cc @@ -13,23 +13,22 @@ #include #include -typedef CppOwnedPyObject PyAcquireItemObject; -typedef CppOwnedPyObject PyAcquireItemDescObject; -typedef CppOwnedPyObject PyAcquireFileObject; -typedef CppOwnedPyObject PyAcquireWorkerObject; - +typedef CppOwnedPyObject PyAcquireWorkerObject; struct PyAcquireItems { - PyAcquireFileObject *file; - PyAcquireItemObject *item; + CppOwnedPyObject *file; + CppOwnedPyObject *item; + CppOwnedPyObject *desc; }; +typedef map item_map; +typedef map worker_map; + // Keep a vector to PyAcquireItemObject pointers, so we can set the Object // pointers to NULL when deallocating the main object (mostly AcquireFile). struct PyAcquireObject : public CppPyObject { - map item_map; - map itemdesc_map; - map worker_map; + item_map items; + worker_map workers; }; @@ -47,18 +46,20 @@ static PyObject *acquireworker_get_current_item(PyObject *self, void *closure) PyObject *PyItem; // FIXME: PyAcquire_FromCpp needs to initialize item_map. - if (PyAcquire && false && PyAcquire->item_map[Item].item) { + if (PyAcquire && false && PyAcquire->items[Item].item) { Py_INCREF(PyItem); - PyItem = PyAcquire->item_map[Item].item; + PyItem = PyAcquire->items[Item].item; } else { PyItem = PyAcquireItem_FromCpp(Item,false,PyAcquire); // FIXME: PyAcquire_FromCpp needs to initialize item_map. if (PyAcquire && false) - PyAcquire->item_map[Item].item = (PyAcquireItemObject*)PyItem; + PyAcquire->items[Item].item = (CppOwnedPyObject*)PyItem; } - return PyAcquireItemDesc_FromCpp(worker->CurrentItem,false,PyItem); + PyObject *ret = PyAcquireItemDesc_FromCpp(worker->CurrentItem,false,PyItem); + Py_DECREF(PyItem); + return ret; } static PyObject *acquireworker_get_status(PyObject *self, void *closure) @@ -208,168 +209,6 @@ PyTypeObject PyAcquireItemDesc_Type = 0, // tp_new }; -inline pkgAcquire::Item *acquireitem_tocpp(PyObject *self) { - pkgAcquire::Item *itm = GetCpp(self); - if (itm == 0) - PyErr_SetString(PyExc_ValueError, "Acquire() has been shut down or " - "the AcquireFile() object has been deallocated."); - return itm; -} - -#define MkGet(PyFunc,Ret) static PyObject *PyFunc(PyObject *Self,void*) \ -{ \ - pkgAcquire::Item *Itm = acquireitem_tocpp(Self); \ - if (Itm == 0) \ - return 0; \ - return Ret; \ -} - -// Define our getters -MkGet(AcquireItemGetComplete,Py_BuildValue("i",Itm->Complete)); -MkGet(AcquireItemGetDescURI,Safe_FromString(Itm->DescURI().c_str())); -MkGet(AcquireItemGetDestFile,Safe_FromString(Itm->DestFile.c_str())); -MkGet(AcquireItemGetErrorText,Safe_FromString(Itm->ErrorText.c_str())); -MkGet(AcquireItemGetFileSize,Py_BuildValue("i",Itm->FileSize)); -MkGet(AcquireItemGetID,Py_BuildValue("k",Itm->ID)); -MkGet(AcquireItemGetMode,Py_BuildValue("s",Itm->Mode)); -MkGet(AcquireItemGetIsTrusted,Py_BuildValue("i",Itm->IsTrusted())); -MkGet(AcquireItemGetLocal,Py_BuildValue("i",Itm->Local)); -MkGet(AcquireItemGetStatus,Py_BuildValue("i",Itm->Status)); - -// Constants -MkGet(AcquireItemGetStatIdle,Py_BuildValue("i", pkgAcquire::Item::StatIdle)); -MkGet(AcquireItemGetStatFetching,Py_BuildValue("i", pkgAcquire::Item::StatFetching)); -MkGet(AcquireItemGetStatDone,Py_BuildValue("i", pkgAcquire::Item::StatDone)); -MkGet(AcquireItemGetStatError,Py_BuildValue("i", pkgAcquire::Item::StatError)); -MkGet(AcquireItemGetStatAuthError,Py_BuildValue("i", pkgAcquire::Item::StatAuthError)); -#undef MkGet - -static int AcquireItemSetID(PyObject *self, PyObject *value, void *closure) -{ - pkgAcquire::Item *Itm = acquireitem_tocpp(self); - if (Itm == 0) - return -1; - if (PyLong_Check(value)) { - Itm->ID = PyLong_AsLong(value); - } - else if (PyInt_Check(value)) { - Itm->ID = PyInt_AsLong(value); - } - else { - PyErr_SetString(PyExc_TypeError, "value must be integer."); - return -1; - } - return 0; -} - - -static PyGetSetDef AcquireItemGetSet[] = { - {"complete",AcquireItemGetComplete}, - {"desc_uri",AcquireItemGetDescURI}, - {"destfile",AcquireItemGetDestFile}, - {"error_text",AcquireItemGetErrorText}, - {"filesize",AcquireItemGetFileSize}, - {"id",AcquireItemGetID,AcquireItemSetID}, - {"mode",AcquireItemGetMode}, - {"is_trusted",AcquireItemGetIsTrusted}, - {"local",AcquireItemGetLocal}, - {"status",AcquireItemGetStatus}, - {"stat_idle",AcquireItemGetStatIdle}, - {"stat_fetching",AcquireItemGetStatFetching}, - {"stat_done",AcquireItemGetStatDone}, - {"stat_error",AcquireItemGetStatError}, - {"stat_auth_error",AcquireItemGetStatAuthError}, -#ifdef COMPAT_0_7 - {"Complete",AcquireItemGetComplete}, - {"DescURI",AcquireItemGetDescURI}, - {"DestFile",AcquireItemGetDestFile}, - {"ErrorText",AcquireItemGetErrorText}, - {"FileSize",AcquireItemGetFileSize}, - {"ID",AcquireItemGetID}, - {"IsTrusted",AcquireItemGetIsTrusted}, - {"Local",AcquireItemGetLocal}, - {"Status",AcquireItemGetStatus}, - {"StatIdle",AcquireItemGetStatIdle}, - {"StatFetching",AcquireItemGetStatFetching}, - {"StatDone",AcquireItemGetStatDone}, - {"StatError",AcquireItemGetStatError}, - {"StatAuthError",AcquireItemGetStatAuthError}, -#endif - {} -}; - - - -static PyObject *AcquireItemRepr(PyObject *Self) -{ - pkgAcquire::Item *Itm = acquireitem_tocpp(Self); - if (Itm == 0) - return 0; - - return PyString_FromFormat("<%s object: " - "Status: %i Complete: %i Local: %i IsTrusted: %i " - "FileSize: %lu DestFile:'%s' " - "DescURI: '%s' ID:%lu ErrorText: '%s'>", - Self->ob_type->tp_name, - Itm->Status, Itm->Complete, Itm->Local, Itm->IsTrusted(), - Itm->FileSize, Itm->DestFile.c_str(), Itm->DescURI().c_str(), - Itm->ID,Itm->ErrorText.c_str()); -} - -static void AcquireItemDealloc(PyObject *self) { - pkgAcquire::Item *file = GetCpp(self); - PyAcquireObject *owner = (PyAcquireObject *)GetOwner(self); - - // Simply deallocate the object if we have no owner. - if (owner != NULL && !((CppPyObject *)self)->NoDelete) { - PyAcquireItems &items = owner->item_map[file]; - - if (items.item && items.item != self) - items.item->Object = NULL; - if (items.file && items.item != self) - items.file->Object = NULL; - owner->item_map.erase(file); - } - - CppOwnedDeallocPtr(self); -} - - - -PyTypeObject PyAcquireItem_Type = -{ - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "apt_pkg.AcquireItem", // tp_name - sizeof(CppOwnedPyObject), // tp_basicsize - 0, // tp_itemsize - // Methods - AcquireItemDealloc, // tp_dealloc - 0, // tp_print - 0, // tp_getattr - 0, // tp_setattr - 0, // tp_compare - AcquireItemRepr, // tp_repr - 0, // tp_as_number - 0, // tp_as_sequence - 0, // tp_as_mapping - 0, // tp_hash - 0, // tp_call - 0, // tp_str - 0, // tp_getattro - 0, // tp_setattro - 0, // tp_as_buffer - Py_TPFLAGS_DEFAULT, // tp_flags - "AcquireItem Object", // tp_doc - 0, // tp_traverse - 0, // tp_clear - 0, // tp_richcompare - 0, // tp_weaklistoffset - 0, // tp_iter - 0, // tp_iternext - 0, // tp_methods - 0, // tp_members - AcquireItemGetSet, // tp_getset -}; @@ -396,15 +235,20 @@ static PyObject *PkgAcquireShutdown(PyObject *Self,PyObject *Args) fetcher->Shutdown(); // TODO: Delete all objects here - map items = ((PyAcquireObject *)Self)->item_map; - for (map::iterator I = items.begin(); - I != items.end(); I++) { - (*I).second.file->Object = NULL; - (*I).second.item->Object = NULL; + item_map &items = ((PyAcquireObject *)Self)->items; + for (item_map::iterator I = items.begin(); I != items.end(); I++) { + if ((*I).second.file) + (*I).second.file->Object = NULL; + if ((*I).second.item) { + (*I).second.item->Object = NULL; + Py_DECREF((*I).second.item); + } + if ((*I).second.desc) { + (*I).second.desc->Object = NULL; + Py_DECREF((*I).second.desc); + } } - - - + items.clear(); Py_INCREF(Py_None); return HandleErrors(Py_None); } @@ -442,6 +286,7 @@ static PyObject *PkgAcquireGetWorkers(PyObject *self, void *closure) PyWorker = CppOwnedPyObject_NEW(self,&PyAcquireWorker_Type, Worker); PyWorker->NoDelete = true; PyList_Append(List, PyWorker); + Py_DECREF(PyWorker); } return List; } @@ -449,19 +294,22 @@ static PyObject *PkgAcquireGetItems(PyObject *Self,void*) { pkgAcquire *fetcher = GetCpp(Self); PyObject *List = PyList_New(0); - PyAcquireItemObject *Obj; + CppOwnedPyObject *Obj; for (pkgAcquire::ItemIterator I = fetcher->ItemsBegin(); I != fetcher->ItemsEnd(); I++) { - if (((PyAcquireObject *)Self)->item_map[*I].item) - PyList_Append(List, ((PyAcquireObject *)Self)->item_map[*I].item); + if (((PyAcquireObject *)Self)->items[*I].item) + PyList_Append(List, ((PyAcquireObject *)Self)->items[*I].item); else { Obj = CppOwnedPyObject_NEW(Self,&PyAcquireItem_Type,*I); Obj->NoDelete = true; + PyList_Append(List,Obj); - ((PyAcquireObject *)Self)->item_map[*I].item = Obj; - Py_DECREF(Obj); + ((PyAcquireObject *)Self)->items[*I].item = Obj; + + + // Not DECREFING it, we want to manage it somewhere else. } } return List; @@ -506,9 +354,10 @@ static PyObject *PkgAcquireNew(PyTypeObject *type,PyObject *Args,PyObject *kwds) if (PyArg_ParseTupleAndKeywords(Args,kwds,"|O",kwlist,&pyFetchProgressInst) == 0) return 0; + PyFetchProgress *progress = 0; if (pyFetchProgressInst != NULL) { // FIXME: memleak? - PyFetchProgress *progress = new PyFetchProgress(); + progress = new PyFetchProgress(); progress->setCallbackInst(pyFetchProgressInst); fetcher = new pkgAcquire(progress); } else { @@ -518,8 +367,11 @@ static PyObject *PkgAcquireNew(PyTypeObject *type,PyObject *Args,PyObject *kwds) PyAcquireObject *FetcherObj = (PyAcquireObject *) CppPyObject_NEW(type, fetcher); + if (progress != 0) + progress->setPyAcquire(FetcherObj); // prepare our map of items. - new (&FetcherObj->item_map) map(); + new (&FetcherObj->items) item_map(); + new (&FetcherObj->workers) worker_map(); return FetcherObj; } @@ -581,125 +433,3 @@ PyObject *GetAcquire(PyObject *Self,PyObject *Args) } #endif -static PyObject *PkgAcquireFileNew(PyTypeObject *type, PyObject *Args, PyObject * kwds) -{ - PyObject *pyfetcher; - char *uri, *md5, *descr, *shortDescr, *destDir, *destFile; - int size = 0; - uri = md5 = descr = shortDescr = destDir = destFile = ""; - - char * kwlist[] = {"owner","uri", "md5", "size", "descr", "short_descr", - "destdir", "destfile", NULL}; - - if (PyArg_ParseTupleAndKeywords(Args, kwds, "O!s|sissss", kwlist, - &PyAcquire_Type, &pyfetcher, &uri, &md5, - &size, &descr, &shortDescr, &destDir, &destFile) == 0) - return 0; - - pkgAcquire *fetcher = GetCpp(pyfetcher); - pkgAcqFile *af = new pkgAcqFile(fetcher, // owner - uri, // uri - md5, // md5 - size, // size - descr, // descr - shortDescr, - destDir, - destFile); // short-desc - CppOwnedPyObject *AcqFileObj = CppOwnedPyObject_NEW(pyfetcher, type); - AcqFileObj->Object = af; - - // Register the file so we can remove it later. - ((PyAcquireObject *)pyfetcher)->item_map[af].file = AcqFileObj; - - return AcqFileObj; -} - - -static char *doc_PkgAcquireFile = - "AcquireFile(owner, uri[, md5, size, descr, short_descr, destdir," - "destfile]) -> New AcquireFile() object\n\n" - "The parameter *owner* refers to an apt_pkg.Acquire() object. You can use\n" - "*destdir* OR *destfile* to specify the destination directory/file."; - -PyTypeObject PyAcquireFile_Type = -{ - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "apt_pkg.AcquireFile", // tp_name - sizeof(CppOwnedPyObject),// tp_basicsize - 0, // tp_itemsize - // Methods - AcquireItemDealloc, // tp_dealloc - 0, // tp_print - 0, // tp_getattr - 0, // tp_setattr - 0, // tp_compare - 0, // tp_repr - 0, // tp_as_number - 0, // tp_as_sequence - 0, // tp_as_mapping - 0, // tp_hash - 0, // tp_call - 0, // tp_str - 0, // tp_getattro - 0, // tp_setattro - 0, // tp_as_buffer - (Py_TPFLAGS_DEFAULT | // tp_flags - Py_TPFLAGS_BASETYPE | - Py_TPFLAGS_HAVE_GC), - doc_PkgAcquireFile, // tp_doc - CppOwnedTraverse, // tp_traverse - CppOwnedClear, // tp_clear - 0, // tp_richcompare - 0, // tp_weaklistoffset - 0, // tp_iter - 0, // tp_iternext - 0, // tp_methods - 0, // tp_members - 0, // tp_getset - &PyAcquireItem_Type, // tp_base - 0, // tp_dict - 0, // tp_descr_get - 0, // tp_descr_set - 0, // tp_dictoffset - 0, // tp_init - 0, // tp_alloc - PkgAcquireFileNew, // tp_new -}; - -#ifdef COMPAT_0_7 -char *doc_GetPkgAcqFile = -"GetPkgAcqFile(pkgAquire, uri[, md5, size, descr, shortDescr, destDir, destFile]) -> PkgAcqFile\n"; -PyObject *GetPkgAcqFile(PyObject *Self, PyObject *Args, PyObject * kwds) -{ - PyErr_WarnEx(PyExc_DeprecationWarning, "apt_pkg.GetPkgAcqFile() is " - "deprecated. Please see apt_pkg.AcquireFile() for the " - "replacement", 1); - PyObject *pyfetcher; - char *uri, *md5, *descr, *shortDescr, *destDir, *destFile; - int size = 0; - uri = md5 = descr = shortDescr = destDir = destFile = ""; - - char * kwlist[] = {"owner","uri", "md5", "size", "descr", "shortDescr", - "destDir", "destFile", NULL}; - - if (PyArg_ParseTupleAndKeywords(Args, kwds, "O!s|sissss", kwlist, - &PyAcquire_Type, &pyfetcher, &uri, &md5, - &size, &descr, &shortDescr, &destDir, &destFile) == 0) - return 0; - - pkgAcquire *fetcher = GetCpp(pyfetcher); - pkgAcqFile *af = new pkgAcqFile(fetcher, // owner - uri, // uri - md5, // md5 - size, // size - descr, // descr - shortDescr, - destDir, - destFile); // short-desc - CppPyObject *AcqFileObj = CppPyObject_NEW(&PyAcquireFile_Type); - AcqFileObj->Object = af; - AcqFileObj->NoDelete = true; - - return AcqFileObj; -} -#endif diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index 5ee4015c..0a899efb 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -13,6 +13,7 @@ #include "generic.h" #include +#include #include #include #include @@ -606,6 +607,9 @@ extern "C" void initapt_pkg() PyModule_AddObject(Module,"Config",Config); #endif + + + // Add our classes. /* ============================ tag.cc ============================ */ ADDTYPE(Module,"TagSection",&PyTagSection_Type); @@ -661,6 +665,34 @@ extern "C" void initapt_pkg() PyModule_AddObject(Module,"REWRITE_SOURCE_ORDER", CharCharToList(TFRewriteSourceOrder)); + + // AcquireItem Constants. + + + PyDict_SetItemString(PyAcquireItem_Type.tp_dict, "stat_idle", + Py_BuildValue("i", pkgAcquire::Item::StatIdle)); + PyDict_SetItemString(PyAcquireItem_Type.tp_dict, "stat_fetching", + Py_BuildValue("i", pkgAcquire::Item::StatFetching)); + PyDict_SetItemString(PyAcquireItem_Type.tp_dict, "stat_done", + Py_BuildValue("i", pkgAcquire::Item::StatDone)); + PyDict_SetItemString(PyAcquireItem_Type.tp_dict, "stat_error", + Py_BuildValue("i", pkgAcquire::Item::StatError)); + PyDict_SetItemString(PyAcquireItem_Type.tp_dict, "stat_auth_error", + Py_BuildValue("i", pkgAcquire::Item::StatAuthError)); + +#ifdef COMPAT_0_7 + PyDict_SetItemString(PyAcquireItem_Type.tp_dict, "StatIdle", + Py_BuildValue("i", pkgAcquire::Item::StatIdle)); + PyDict_SetItemString(PyAcquireItem_Type.tp_dict, "StatFetching", + Py_BuildValue("i", pkgAcquire::Item::StatFetching)); + PyDict_SetItemString(PyAcquireItem_Type.tp_dict, "StatDone", + Py_BuildValue("i", pkgAcquire::Item::StatDone)); + PyDict_SetItemString(PyAcquireItem_Type.tp_dict, "StatError", + Py_BuildValue("i", pkgAcquire::Item::StatError)); + PyDict_SetItemString(PyAcquireItem_Type.tp_dict, "StatAuthError", + Py_BuildValue("i", pkgAcquire::Item::StatAuthError)); +#endif + #if PY_MAJOR_VERSION >= 3 && PY_MINOR_VERSION >= 1 PyObject *PyCapsule = PyCapsule_New(&API, "apt_pkg._C_API", NULL); #else diff --git a/python/progress.cc b/python/progress.cc index 305246b7..1b135a75 100644 --- a/python/progress.cc +++ b/python/progress.cc @@ -35,7 +35,12 @@ inline bool setattr(PyObject *object, const char *attr, const char *fmt, T arg) return result != -1; } -#define TUPLEIZE(op) Py_BuildValue("(O)", op) +inline PyObject *TUPLEIZE(PyObject *op) { + PyObject *ret = Py_BuildValue("(O)", op); + Py_DECREF(op); + return ret; +} + // generic bool PyCallbackObj::RunSimpleCallback(const char* method_name, PyObject *arglist, @@ -300,7 +305,10 @@ bool PyFetchProgress::Pulse(pkgAcquire * Owner) if (PyObject_TypeCheck(callbackInst, &PyAcquireProgress_Type)) { PyObject *result1; bool res1 = true; - if (RunSimpleCallback("pulse", TUPLEIZE(PyAcquire_FromCpp(Owner)), &result1)) { + + Py_INCREF(pyAcquire); + + if (RunSimpleCallback("pulse", TUPLEIZE(pyAcquire) , &result1)) { if (result1 != NULL && PyArg_Parse(result1, "b", &res1) && res1 == false) { // the user returned a explicit false here, stop PyCbObj_BEGIN_ALLOW_THREADS diff --git a/python/progress.h b/python/progress.h index e92933a7..bc1bd640 100644 --- a/python/progress.h +++ b/python/progress.h @@ -94,6 +94,9 @@ struct PyOpProgress : public OpProgress, public PyCallbackObj struct PyFetchProgress : public pkgAcquireStatus, public PyCallbackObj { + protected: + PyObject *pyAcquire; + public: enum { DLDone, DLQueued, DLFailed, DLHit, DLIgnored }; @@ -102,6 +105,10 @@ struct PyFetchProgress : public pkgAcquireStatus, public PyCallbackObj virtual bool MediaChange(string Media, string Drive); + void setPyAcquire(PyObject *o) { + pyAcquire = o; + } + /* apt stuff */ virtual void IMSHit(pkgAcquire::ItemDesc &Itm); virtual void Fetch(pkgAcquire::ItemDesc &Itm); diff --git a/setup.py b/setup.py index e07bd83b..93fcb436 100644 --- a/setup.py +++ b/setup.py @@ -35,7 +35,8 @@ files = ['apt_pkgmodule.cc', 'acquire.cc', 'cache.cc', 'cdrom.cc', 'hashstring.cc', 'indexfile.cc', 'indexrecords.cc', 'metaindex.cc', 'pkgmanager.cc', 'pkgrecords.cc', 'pkgsrcrecords.cc', 'policy.cc', 'progress.cc', 'sourcelist.cc', 'string.cc', 'tag.cc', - 'opprogress.cc', 'acquireprogress.cc', 'cdromprogress.cc', 'lock.cc'] + 'opprogress.cc', 'acquireprogress.cc', 'cdromprogress.cc', 'lock.cc', + 'acquire-item.cc'] files = sorted(['python/' + fname for fname in files]) apt_pkg = Extension("apt_pkg", files, libraries=["apt-pkg"]) -- cgit v1.2.3 From 544f14e0f2fb70b5a1f30786a93023a42d88290d Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Wed, 22 Jul 2009 18:16:28 +0200 Subject: python: 2nd part of the acquire fixes (one PyObject per C++ object). --- python/acquire-item.cc | 14 +++++++---- python/acquire.cc | 63 +++++++++++++++++++++++++------------------------- python/apt_pkgmodule.h | 5 ++++ python/progress.cc | 10 ++++---- python/python-apt.h | 5 ++-- 5 files changed, 54 insertions(+), 43 deletions(-) (limited to 'python') diff --git a/python/acquire-item.cc b/python/acquire-item.cc index cf0a628e..1fb66080 100644 --- a/python/acquire-item.cc +++ b/python/acquire-item.cc @@ -176,13 +176,11 @@ static PyObject *acquireitem_repr(PyObject *Self) static void acquireitem_dealloc(PyObject *self) { + pkgAcquire::Item *item = PyAcquireItem_ToCpp(self); + PyAcquireObject *Owner = (PyAcquireObject *)GetOwner(self); + PyAcquireItems item_struct = Owner->items[item]; // TODO: Unregister the object in the owner. if (!((CppOwnedPyObject*)self)->NoDelete) { - pkgAcquire::Item *item = PyAcquireItem_ToCpp(self); - PyAcquireObject *Owner = (PyAcquireObject *)GetOwner(self); - - PyAcquireItems item_struct = Owner->items[item]; - if (item_struct.file != 0 && item_struct.file != self) item_struct.file->Object = 0; if (item_struct.item != 0 && item_struct.item != self) { @@ -195,6 +193,12 @@ static void acquireitem_dealloc(PyObject *self) } Owner->items.erase(item); } + else { + if (item_struct.file == self) + item_struct.file = 0; + if (item_struct.item == self) + item_struct.item = 0; + } CppOwnedDeallocPtr(self); } diff --git a/python/acquire.cc b/python/acquire.cc index 5e03586e..1085d0a2 100644 --- a/python/acquire.cc +++ b/python/acquire.cc @@ -40,26 +40,17 @@ static PyObject *acquireworker_get_current_item(PyObject *self, void *closure) Py_RETURN_NONE; } - PyAcquireObject *PyAcquire = (PyAcquireObject *)GetOwner(self); + PyObject *PyAcquire = GetOwner(self); - pkgAcquire::Item *Item = worker->CurrentItem->Owner; - - PyObject *PyItem; - // FIXME: PyAcquire_FromCpp needs to initialize item_map. - if (PyAcquire && false && PyAcquire->items[Item].item) { - Py_INCREF(PyItem); - PyItem = PyAcquire->items[Item].item; - } + if (PyAcquire) + return PyAcquire_GetItemDesc(PyAcquire, worker->CurrentItem); else { - PyItem = PyAcquireItem_FromCpp(Item,false,PyAcquire); - // FIXME: PyAcquire_FromCpp needs to initialize item_map. - if (PyAcquire && false) - PyAcquire->items[Item].item = (CppOwnedPyObject*)PyItem; + PyObject *PyItem = PyAcquireItem_FromCpp(worker->CurrentItem->Owner); + PyObject *ret = PyAcquireItemDesc_FromCpp(worker->CurrentItem,false, + PyItem); + Py_DECREF(PyItem); + return ret; } - - PyObject *ret = PyAcquireItemDesc_FromCpp(worker->CurrentItem,false,PyItem); - Py_DECREF(PyItem); - return ret; } static PyObject *acquireworker_get_status(PyObject *self, void *closure) @@ -146,7 +137,7 @@ static PyObject *acquireitemdesc_get_owner(CppOwnedPyObjectOwner); return self->Owner; } - else if (self->Object && self->Object->Owner != NULL) { + else if (self->Object) { self->Owner = PyAcquireItem_FromCpp(self->Object->Owner); Py_INCREF(self->Owner); return self->Owner; @@ -210,7 +201,27 @@ PyTypeObject PyAcquireItemDesc_Type = }; +// Acquire + +PyObject *PyAcquire_GetItem(PyObject *self, pkgAcquire::Item *item) { + PyAcquireItems &item_struct = ((PyAcquireObject *)self)->items[item]; + if (! item_struct.item) { + item_struct.item = PyAcquireItem_FromCpp(item,false,self); + } + Py_INCREF(item_struct.item); + return item_struct.item; +} +PyObject *PyAcquire_GetItemDesc(PyObject *self, pkgAcquire::ItemDesc *item) { + PyAcquireItems &item_struct = ((PyAcquireObject *)self)->items[item->Owner]; + if (! item_struct.item) + item_struct.item = PyAcquireItem_FromCpp(item->Owner,false,self); + if (! item_struct.desc) + item_struct.desc = PyAcquireItemDesc_FromCpp(item,false, + item_struct.item); + Py_INCREF(item_struct.desc); + return item_struct.desc; +} static PyObject *PkgAcquireRun(PyObject *Self,PyObject *Args) { @@ -294,23 +305,13 @@ static PyObject *PkgAcquireGetItems(PyObject *Self,void*) { pkgAcquire *fetcher = GetCpp(Self); PyObject *List = PyList_New(0); - CppOwnedPyObject *Obj; + PyObject *Obj; for (pkgAcquire::ItemIterator I = fetcher->ItemsBegin(); I != fetcher->ItemsEnd(); I++) { - - if (((PyAcquireObject *)Self)->items[*I].item) - PyList_Append(List, ((PyAcquireObject *)Self)->items[*I].item); - else { - Obj = CppOwnedPyObject_NEW(Self,&PyAcquireItem_Type,*I); - Obj->NoDelete = true; - + Obj = PyAcquire_GetItem(Self, *I); PyList_Append(List,Obj); - ((PyAcquireObject *)Self)->items[*I].item = Obj; - - - // Not DECREFING it, we want to manage it somewhere else. - } + Py_DECREF(Obj); } return List; } diff --git a/python/apt_pkgmodule.h b/python/apt_pkgmodule.h index 04bce2cc..3edba5d2 100644 --- a/python/apt_pkgmodule.h +++ b/python/apt_pkgmodule.h @@ -12,6 +12,7 @@ #include #include +#include // Configuration Stuff #define Configuration_Check(op) ((op)->ob_type == &PyConfiguration_Type) @@ -49,6 +50,10 @@ PyObject *StrTimeRFC1123(PyObject *self,PyObject *Args); PyObject *StrStrToTime(PyObject *self,PyObject *Args); PyObject *StrCheckDomainList(PyObject *Self,PyObject *Args); +PyObject *PyAcquire_GetItem(PyObject *self, pkgAcquire::Item *item); +PyObject *PyAcquire_GetItemDesc(PyObject *self, pkgAcquire::ItemDesc *item); +bool PyAcquire_DropItem(PyObject *self, pkgAcquire::Item *item); + // Cache Stuff extern PyTypeObject PyCache_Type; extern PyTypeObject PyCacheFile_Type; diff --git a/python/progress.cc b/python/progress.cc index 1b135a75..7873d894 100644 --- a/python/progress.cc +++ b/python/progress.cc @@ -175,7 +175,7 @@ void PyFetchProgress::IMSHit(pkgAcquire::ItemDesc &Itm) { PyCbObj_END_ALLOW_THREADS if (PyObject_TypeCheck(callbackInst,&PyAcquireProgress_Type)) - RunSimpleCallback("ims_hit", TUPLEIZE(PyAcquireItemDesc_FromCpp(&Itm))); + RunSimpleCallback("ims_hit", TUPLEIZE(PyAcquire_GetItemDesc(pyAcquire, &Itm))); else UpdateStatus(Itm, DLHit); PyCbObj_BEGIN_ALLOW_THREADS @@ -185,7 +185,7 @@ void PyFetchProgress::Fetch(pkgAcquire::ItemDesc &Itm) { PyCbObj_END_ALLOW_THREADS if (PyObject_TypeCheck(callbackInst,&PyAcquireProgress_Type)) - RunSimpleCallback("fetch", TUPLEIZE(PyAcquireItemDesc_FromCpp(&Itm))); + RunSimpleCallback("fetch", TUPLEIZE(PyAcquire_GetItemDesc(pyAcquire, &Itm))); else UpdateStatus(Itm, DLQueued); PyCbObj_BEGIN_ALLOW_THREADS @@ -195,7 +195,7 @@ void PyFetchProgress::Done(pkgAcquire::ItemDesc &Itm) { PyCbObj_END_ALLOW_THREADS if (PyObject_TypeCheck(callbackInst,&PyAcquireProgress_Type)) - RunSimpleCallback("done", TUPLEIZE(PyAcquireItemDesc_FromCpp(&Itm))); + RunSimpleCallback("done", TUPLEIZE(PyAcquire_GetItemDesc(pyAcquire, &Itm))); else UpdateStatus(Itm, DLDone); PyCbObj_BEGIN_ALLOW_THREADS @@ -205,7 +205,7 @@ void PyFetchProgress::Fail(pkgAcquire::ItemDesc &Itm) { PyCbObj_END_ALLOW_THREADS if (PyObject_TypeCheck(callbackInst,&PyAcquireProgress_Type)) { - RunSimpleCallback("fail", TUPLEIZE(PyAcquireItemDesc_FromCpp(&Itm))); + RunSimpleCallback("fail", TUPLEIZE(PyAcquire_GetItemDesc(pyAcquire, &Itm))); return; } @@ -220,7 +220,7 @@ void PyFetchProgress::Fail(pkgAcquire::ItemDesc &Itm) if (PyObject_TypeCheck(callbackInst,&PyAcquireProgress_Type)) - RunSimpleCallback("fail", TUPLEIZE(PyAcquireItemDesc_FromCpp(&Itm))); + RunSimpleCallback("fail", TUPLEIZE(PyAcquire_GetItemDesc(pyAcquire, &Itm))); else UpdateStatus(Itm, DLFailed); PyCbObj_BEGIN_ALLOW_THREADS diff --git a/python/python-apt.h b/python/python-apt.h index 80ad03bd..fb84b394 100644 --- a/python/python-apt.h +++ b/python/python-apt.h @@ -220,7 +220,8 @@ static int import_apt_pkg(void) { // Python object creation, using two inline template functions and one variadic // macro per type. template -inline PyObject *FromCpp(PyTypeObject *pytype, Cpp obj, bool Delete=false) +inline CppPyObject *FromCpp(PyTypeObject *pytype, Cpp obj, + bool Delete=false) { CppPyObject *Obj = CppPyObject_NEW(pytype, obj); Obj->NoDelete = (!Delete); @@ -228,7 +229,7 @@ inline PyObject *FromCpp(PyTypeObject *pytype, Cpp obj, bool Delete=false) } template -inline PyObject *FromCppOwned(PyTypeObject *pytype, Cpp const &obj, +inline CppOwnedPyObject *FromCppOwned(PyTypeObject *pytype, Cpp const &obj, bool Delete=false, PyObject *Owner=NULL) { CppOwnedPyObject *Obj = CppOwnedPyObject_NEW(Owner, pytype, obj); -- cgit v1.2.3 From 1195d1d5b3b9c22d1756ba13780cb553c3d4d168 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Thu, 23 Jul 2009 16:47:13 +0200 Subject: python/cdrom.cc: Do not check arguments in PkgCdromNew. --- apt/progress/text.py | 2 +- python/cdrom.cc | 4 ---- 2 files changed, 1 insertion(+), 5 deletions(-) (limited to 'python') diff --git a/apt/progress/text.py b/apt/progress/text.py index a121eaaa..c9e2882b 100644 --- a/apt/progress/text.py +++ b/apt/progress/text.py @@ -245,7 +245,7 @@ class CdromProgress(apt_pkg.CdromProgress, TextProgress): def update(self, text, current): """Set the current progress.""" - apt_pkg.CdromProgress.change_cdrom(self, text, current) + apt_pkg.CdromProgress.update(self, text, current) if text: self._write(text, False) diff --git a/python/cdrom.cc b/python/cdrom.cc index bd181af7..5044f3fa 100644 --- a/python/cdrom.cc +++ b/python/cdrom.cc @@ -91,10 +91,6 @@ static PyObject *PkgCdromNew(PyTypeObject *type,PyObject *Args,PyObject *kwds) { pkgCdrom *cdrom = new pkgCdrom(); - char *kwlist[] = {NULL}; - if (PyArg_ParseTupleAndKeywords(Args,kwds,"",kwlist) == 0) - return 0; - CppOwnedPyObject *CdromObj = CppOwnedPyObject_NEW(0,type, *cdrom); -- cgit v1.2.3 From 22d8199e2d047dc6b258241cf33e67d77aa33ca6 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Thu, 23 Jul 2009 20:38:27 +0200 Subject: python/configuration: Hack-in unicode character support in parse_commandline(). --- python/configuration.cc | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'python') diff --git a/python/configuration.cc b/python/configuration.cc index e7e31cc8..11231a28 100644 --- a/python/configuration.cc +++ b/python/configuration.cc @@ -361,7 +361,11 @@ PyObject *ParseCommandLine(PyObject *Self,PyObject *Args) for (int I = 0; I != Length; I++) { char *Type = 0; + #if PY_MAJOR_VERSION >= 3 + if (PyArg_ParseTuple(PySequence_GetItem(POList,I),"Czs|s", + #else if (PyArg_ParseTuple(PySequence_GetItem(POList,I),"czs|s", + #endif &OList[I].ShortOpt,&OList[I].LongOpt, &OList[I].ConfName,&Type) == 0) { -- cgit v1.2.3 From bc879c4d608aa62e3e69e2e4eb252f6e013a7752 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Fri, 24 Jul 2009 15:01:37 +0200 Subject: python/hashstring.cc: Make hashtype a descriptor, adjust coding style. --- python/hashstring.cc | 54 +++++++++++++++++++++++++++------------------------- 1 file changed, 28 insertions(+), 26 deletions(-) (limited to 'python') diff --git a/python/hashstring.cc b/python/hashstring.cc index a8d97cd8..90c80e4c 100644 --- a/python/hashstring.cc +++ b/python/hashstring.cc @@ -22,13 +22,13 @@ #include "apt_pkgmodule.h" #include -static PyObject *HashString_NEW(PyTypeObject *type,PyObject *Args, +static PyObject *hashstring_new(PyTypeObject *type,PyObject *Args, PyObject *kwds) { char *Type = NULL; char *Hash = NULL; char *kwlist[] = {"type", "hash", NULL}; - if (PyArg_ParseTupleAndKeywords(Args, kwds, "s|s", kwlist, &Type, + if (PyArg_ParseTupleAndKeywords(Args, kwds, "s|s:__new__", kwlist, &Type, &Hash) == 0) return 0; CppPyObject *PyObj = CppPyObject_NEW(type); @@ -39,49 +39,51 @@ static PyObject *HashString_NEW(PyTypeObject *type,PyObject *Args, return PyObj; } -static PyObject *HashString_Repr(PyObject *self) +static PyObject *hashstring_repr(PyObject *self) { HashString *hash = GetCpp(self); return PyString_FromFormat("<%s object: \"%s\">", self->ob_type->tp_name, hash->toStr().c_str()); } -static PyObject *HashString_ToStr(PyObject *self) +static PyObject *hashstring_str(PyObject *self) { HashString *hash = GetCpp(self); return CppPyString(hash->toStr()); } -static PyObject *HashString_HashType(PyObject *self) +static PyObject *hashstring_get_hashtype(PyObject *self) { HashString *hash = GetCpp(self); return CppPyString(hash->HashType()); } -static char *HashString_VerifyFile_doc = - "verify_file(filename: str) --> bool\n\n" +static char *hashstring_verify_file_doc = + "verify_file(filename: str) -> bool\n\n" "Verify that the file indicated by filename matches the hash."; -static PyObject *HashString_VerifyFile(PyObject *self,PyObject *args) +static PyObject *hashstring_verify_file(PyObject *self,PyObject *args) { HashString *hash = GetCpp(self); char *filename; - if (PyArg_ParseTuple(args, "s", &filename) == 0) + if (PyArg_ParseTuple(args, "s:verify_file", &filename) == 0) return 0; return PyBool_FromLong(hash->VerifyFile(filename)); } -static PyMethodDef HashString_Methods[] = { - {"to_str",(PyCFunction)HashString_ToStr,METH_NOARGS, - "to_str() --> str\n\nReturn a string, consisting of type:hash"}, - {"verify_file",HashString_VerifyFile,METH_VARARGS, - HashString_VerifyFile_doc}, - {"hash_type",(PyCFunction)HashString_HashType,METH_NOARGS, - "hash_type() --> str\n\nReturn the type of hash (MD5Sum,SHA1,SHA256)"}, - {} +static PyMethodDef hashstring_methods[] = { + {"verify_file",hashstring_verify_file,METH_VARARGS, + hashstring_verify_file_doc}, + {NULL} }; -static char *HashString_doc = +static PyGetSetDef hashstring_getset[] = { + {"hashtype",(getter)hashstring_get_hashtype,0, + "The type of the hash, as a string (possible: MD5Sum,SHA1,SHA256)."}, + {NULL} +}; + +static char *hashstring_doc = "HashString(type, hash) OR HashString('type:hash')\n\n" "Create a new HashString object. The first form allows you to specify\n" "a type and a hash, and the second form a single string where type and\n" @@ -99,28 +101,28 @@ PyTypeObject PyHashString_Type = { 0, // tp_getattr 0, // tp_setattr 0, // tp_compare - HashString_Repr, // tp_repr + hashstring_repr, // tp_repr 0, // tp_as_number 0, // tp_as_sequence 0, // tp_as_mapping 0, // tp_hash 0, // tp_call - HashString_ToStr, // tp_str + hashstring_str, // tp_str 0, // tp_getattro 0, // tp_setattro 0, // tp_as_buffer - (Py_TPFLAGS_DEFAULT | // tp_flags - Py_TPFLAGS_BASETYPE), - HashString_doc, // tp_doc + Py_TPFLAGS_DEFAULT | // tp_flags + Py_TPFLAGS_BASETYPE, + hashstring_doc, // tp_doc 0, // tp_traverse 0, // tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset 0, // tp_iter 0, // tp_iternext - HashString_Methods, // tp_methods + hashstring_methods, // tp_methods 0, // tp_members - 0, // tp_getset + hashstring_getset, // tp_getset 0, // tp_base 0, // tp_dict 0, // tp_descr_get @@ -128,5 +130,5 @@ PyTypeObject PyHashString_Type = { 0, // tp_dictoffset 0, // tp_init 0, // tp_alloc - HashString_NEW, // tp_new + hashstring_new, // tp_new }; -- cgit v1.2.3 From ea3c7ed73e8fb395d8d315c63e6c8f61e478b711 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Fri, 24 Jul 2009 15:03:51 +0200 Subject: python/cdrom.cc: Adjust to new coding style and add docstrings. --- python/cdrom.cc | 243 +++++++++++++++++++++++++++++--------------------------- 1 file changed, 128 insertions(+), 115 deletions(-) (limited to 'python') diff --git a/python/cdrom.cc b/python/cdrom.cc index 5044f3fa..521937f5 100644 --- a/python/cdrom.cc +++ b/python/cdrom.cc @@ -1,10 +1,26 @@ -// Description /*{{{*/ -// $Id: cdrom.cc,v 1.1 2003/06/03 03:03:23 mvo Exp $ -/* ###################################################################### - - Cdrom - Wrapper for the apt-cdrom support - - ##################################################################### */ +/* cdrom.cc - Wrapper for pkgCdrom. + * + * Copyright 2004-2009 Canonical Ltd. + * Copyright 2009 Julian Andres Klode + * + * Authors: Michael Vogt + * Julian Andres Klode + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + */ #include "generic.h" #include "apt_pkgmodule.h" @@ -12,146 +28,143 @@ #include -static PyObject *PkgCdromAdd(PyObject *Self,PyObject *Args) +static char *cdrom_add_doc = + "add(progress: apt_pkg.CdromProgress) -> bool\n\n" + "Add the given CD-ROM to the sources.list. Returns True on success, may\n" + "raise an error on failure or return False."; +static PyObject *cdrom_add(PyObject *Self,PyObject *Args) { - pkgCdrom &Cdrom = GetCpp(Self); + pkgCdrom &Cdrom = GetCpp(Self); - PyObject *pyCdromProgressInst = 0; - if (PyArg_ParseTuple(Args, "O", &pyCdromProgressInst) == 0) { - return 0; - } + PyObject *pyCdromProgressInst = 0; + if (PyArg_ParseTuple(Args, "O", &pyCdromProgressInst) == 0) { + return 0; + } - PyCdromProgress progress; - progress.setCallbackInst(pyCdromProgressInst); + PyCdromProgress progress; + progress.setCallbackInst(pyCdromProgressInst); - bool res = Cdrom.Add(&progress); + bool res = Cdrom.Add(&progress); - return HandleErrors(Py_BuildValue("b", res)); + return HandleErrors(PyBool_FromLong(res)); } -static PyObject *PkgCdromIdent(PyObject *Self,PyObject *Args) +static char *cdrom_ident_doc = + "ident(progress: apt_pkg.CdromProgress) -> str\n\n" + "Try to identify the CD-ROM and if successful return the identity as a\n" + "string. Otherwise, return None or raise an error."; +static PyObject *cdrom_ident(PyObject *Self,PyObject *Args) { - pkgCdrom &Cdrom = GetCpp(Self); - PyObject *pyCdromProgressInst = 0; - if (PyArg_ParseTuple(Args, "O!", &PyCdromProgress_Type, - &pyCdromProgressInst) == 0) { - return 0; - } - - PyCdromProgress progress; - progress.setCallbackInst(pyCdromProgressInst); - - string ident; - bool res = Cdrom.Ident(ident, &progress); - - if (res) - return CppPyString(ident); - else { - Py_INCREF(Py_None); - return HandleErrors(Py_None); - } + pkgCdrom &Cdrom = GetCpp(Self); + PyObject *pyCdromProgressInst = 0; + if (PyArg_ParseTuple(Args, "O!", &PyCdromProgress_Type, + &pyCdromProgressInst) == 0) { + return 0; + } + + PyCdromProgress progress; + progress.setCallbackInst(pyCdromProgressInst); + + string ident; + bool res = Cdrom.Ident(ident, &progress); + + if (res) + return CppPyString(ident); + else { + Py_INCREF(Py_None); + return HandleErrors(Py_None); + } } #ifdef COMPAT_0_7 -static PyObject *PkgCdromIdent_old(PyObject *Self,PyObject *Args) +static PyObject *cdrom_ident_old(PyObject *Self,PyObject *Args) { - pkgCdrom &Cdrom = GetCpp(Self); + pkgCdrom &Cdrom = GetCpp(Self); - PyObject *pyCdromProgressInst = 0; - if (PyArg_ParseTuple(Args, "O", &pyCdromProgressInst) == 0) { - return 0; - } + PyObject *pyCdromProgressInst = 0; + if (PyArg_ParseTuple(Args, "O", &pyCdromProgressInst) == 0) { + return 0; + } - PyCdromProgress progress; - progress.setCallbackInst(pyCdromProgressInst); + PyCdromProgress progress; + progress.setCallbackInst(pyCdromProgressInst); - string ident; - bool res = Cdrom.Ident(ident, &progress); + string ident; + bool res = Cdrom.Ident(ident, &progress); - PyObject *result = Py_BuildValue("(bs)", res, ident.c_str()); + PyObject *result = Py_BuildValue("(bs)", res, ident.c_str()); - return HandleErrors(result); + return HandleErrors(result); } #endif - -static PyMethodDef PkgCdromMethods[] = -{ - {"add",PkgCdromAdd,METH_VARARGS,"add(progress) -> Add a cdrom"}, - {"ident",PkgCdromIdent,METH_VARARGS,"ident(progress) -> Ident a cdrom"}, +static PyMethodDef cdrom_methods[] = { + {"add",cdrom_add,METH_VARARGS,cdrom_add_doc}, + {"ident",cdrom_ident,METH_VARARGS,cdrom_ident_doc}, #ifdef COMPAT_0_7 - {"Add",PkgCdromAdd,METH_VARARGS,"Add(progress) -> Add a cdrom"}, - {"Ident",PkgCdromIdent_old,METH_VARARGS,"Ident(progress) -> Ident a cdrom"}, + {"Add",cdrom_add,METH_VARARGS,"Add(progress) -> Add a cdrom"}, + {"Ident",cdrom_ident_old,METH_VARARGS,"Ident(progress) -> Ident a cdrom"}, #endif - {} + {} }; - -static PyObject *PkgCdromNew(PyTypeObject *type,PyObject *Args,PyObject *kwds) +static PyObject *cdrom_new(PyTypeObject *type,PyObject *Args,PyObject *kwds) { - pkgCdrom *cdrom = new pkgCdrom(); - - CppOwnedPyObject *CdromObj = - CppOwnedPyObject_NEW(0,type, *cdrom); - - return CdromObj; + return CppPyObject_NEW(type); } - -PyTypeObject PyCdrom_Type = -{ - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "apt_pkg.Cdrom", // tp_name - sizeof(CppOwnedPyObject), // tp_basicsize - 0, // tp_itemsize - // Methods - CppOwnedDealloc, // tp_dealloc - 0, // tp_print - 0, // tp_getattr - 0, // tp_setattr - 0, // tp_compare - 0, // tp_repr - 0, // tp_as_number - 0, // tp_as_sequence - 0, // tp_as_mapping - 0, // tp_hash - 0, // tp_call - 0, // tp_str - 0, // tp_getattro - 0, // tp_setattro - 0, // tp_as_buffer - (Py_TPFLAGS_DEFAULT | // tp_flags - Py_TPFLAGS_BASETYPE), - "Cdrom Object", // tp_doc - 0, // tp_traverse - 0, // tp_clear - 0, // tp_richcompare - 0, // tp_weaklistoffset - 0, // tp_iter - 0, // tp_iternext - PkgCdromMethods, // tp_methods - 0, // tp_members - 0, // tp_getset - 0, // tp_base - 0, // tp_dict - 0, // tp_descr_get - 0, // tp_descr_set - 0, // tp_dictoffset - 0, // tp_init - 0, // tp_alloc - PkgCdromNew, // tp_new +static char *cdrom_doc = + "Cdrom()\n\n" + "Cdrom objects can be used to identify Debian installation media and to\n" + "add them to /etc/apt/sources.list."; +PyTypeObject PyCdrom_Type = { + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "apt_pkg.Cdrom", // tp_name + sizeof(CppPyObject), // tp_basicsize + 0, // tp_itemsize + // Methods + CppDealloc, // tp_dealloc + 0, // tp_print + 0, // tp_getattr + 0, // tp_setattr + 0, // tp_compare + 0, // tp_repr + 0, // tp_as_number + 0, // tp_as_sequence + 0, // tp_as_mapping + 0, // tp_hash + 0, // tp_call + 0, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + Py_TPFLAGS_DEFAULT | // tp_flags + Py_TPFLAGS_BASETYPE, + cdrom_doc, // tp_doc + 0, // tp_traverse + 0, // tp_clear + 0, // tp_richcompare + 0, // tp_weaklistoffset + 0, // tp_iter + 0, // tp_iternext + cdrom_methods, // tp_methods + 0, // tp_members + 0, // tp_getset + 0, // tp_base + 0, // tp_dict + 0, // tp_descr_get + 0, // tp_descr_set + 0, // tp_dictoffset + 0, // tp_init + 0, // tp_alloc + cdrom_new, // tp_new }; #ifdef COMPAT_0_7 PyObject *GetCdrom(PyObject *Self,PyObject *Args) { - PyErr_WarnEx(PyExc_DeprecationWarning, "apt_pkg.GetCdrom() is deprecated. " + PyErr_WarnEx(PyExc_DeprecationWarning, "apt_pkg.GetCdrom() is deprecated. " "Please see apt_pkg.Cdrom() for the replacement.", 1); - return PkgCdromNew(&PyCdrom_Type,Args,0); + return PkgCdromNew(&PyCdrom_Type,Args,0); } #endif - - - - - /*}}}*/ -- cgit v1.2.3 From 03243922edbba16458a0ae51f6cd0d75e752dfd0 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Fri, 24 Jul 2009 15:07:44 +0200 Subject: python/acquire.cc: Adjust coding style. There were two different coding styles in this file, which was a bit confusing. --- python/acquire.cc | 446 ++++++++++++++++++++++++++++-------------------------- 1 file changed, 234 insertions(+), 212 deletions(-) (limited to 'python') diff --git a/python/acquire.cc b/python/acquire.cc index 1085d0a2..7c8c9eea 100644 --- a/python/acquire.cc +++ b/python/acquire.cc @@ -1,10 +1,26 @@ -// Description /*{{{*/ -// $Id: acquire.cc,v 1.1 2003/06/03 03:03:23 mvo Exp $ -/* ###################################################################### - - Acquire - Wrapper for the acquire code - - ##################################################################### */ +/* acquire.cc - Wrapper for pkgAcquire. + * + * Copyright 2004-2009 Canonical Ltd + * Copyright 2009 Julian Andres Klode + * + * Authors: Michael Vogt + * Julian Andres Klode + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + */ #include "generic.h" #include "apt_pkgmodule.h" @@ -47,7 +63,7 @@ static PyObject *acquireworker_get_current_item(PyObject *self, void *closure) else { PyObject *PyItem = PyAcquireItem_FromCpp(worker->CurrentItem->Owner); PyObject *ret = PyAcquireItemDesc_FromCpp(worker->CurrentItem,false, - PyItem); + PyItem); Py_DECREF(PyItem); return ret; } @@ -83,40 +99,39 @@ static PyGetSetDef acquireworker_getset[] = { }; -PyTypeObject PyAcquireWorker_Type = -{ - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "apt_pkg.AcquireWorker", // tp_name - sizeof(CppOwnedPyObject),// tp_basicsize - 0, // tp_itemsize - // Methods - CppOwnedDealloc, // tp_dealloc - 0, // tp_print - 0, // tp_getattr - 0, // tp_setattr - 0, // tp_compare - 0, // tp_repr - 0, // tp_as_number - 0, // tp_as_sequence - 0, // tp_as_mapping - 0, // tp_hash - 0, // tp_call - 0, // tp_str - 0, // tp_getattro - 0, // tp_setattro - 0, // tp_as_buffer - Py_TPFLAGS_DEFAULT| // tp_flags - Py_TPFLAGS_HAVE_GC, - 0, // tp_doc - CppOwnedTraverse, // tp_traverse - CppOwnedClear, // tp_clear - 0, // tp_richcompare - 0, // tp_weaklistoffset - 0, // tp_iter - 0, // tp_iternext - 0, // tp_methods - 0, // tp_members - acquireworker_getset, // tp_getset +PyTypeObject PyAcquireWorker_Type = { + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "apt_pkg.AcquireWorker", // tp_name + sizeof(CppOwnedPyObject),// tp_basicsize + 0, // tp_itemsize + // Methods + CppOwnedDealloc, // tp_dealloc + 0, // tp_print + 0, // tp_getattr + 0, // tp_setattr + 0, // tp_compare + 0, // tp_repr + 0, // tp_as_number + 0, // tp_as_sequence + 0, // tp_as_mapping + 0, // tp_hash + 0, // tp_call + 0, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + Py_TPFLAGS_DEFAULT| // tp_flags + Py_TPFLAGS_HAVE_GC, + 0, // tp_doc + CppOwnedTraverse, // tp_traverse + CppOwnedClear, // tp_clear + 0, // tp_richcompare + 0, // tp_weaklistoffset + 0, // tp_iter + 0, // tp_iternext + 0, // tp_methods + 0, // tp_members + acquireworker_getset, // tp_getset }; static PyObject *acquireitemdesc_get_uri(PyObject *self, void *closure) @@ -146,64 +161,64 @@ static PyObject *acquireitemdesc_get_owner(CppOwnedPyObject),// tp_basicsize - 0, // tp_itemsize - // Methods - CppOwnedDealloc, // tp_dealloc - 0, // tp_print - 0, // tp_getattr - 0, // tp_setattr - 0, // tp_compare - 0, // tp_repr - 0, // tp_as_number - 0, // tp_as_sequence - 0, // tp_as_mapping - 0, // tp_hash - 0, // tp_call - 0, // tp_str - 0, // tp_getattro - 0, // tp_setattro - 0, // tp_as_buffer - (Py_TPFLAGS_DEFAULT | // tp_flags +PyTypeObject PyAcquireItemDesc_Type = { + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "apt_pkg.AcquireItemDesc", // tp_name + sizeof(CppOwnedPyObject),// tp_basicsize + 0, // tp_itemsize + // Methods + CppOwnedDealloc, // tp_dealloc + 0, // tp_print + 0, // tp_getattr + 0, // tp_setattr + 0, // tp_compare + 0, // tp_repr + 0, // tp_as_number + 0, // tp_as_sequence + 0, // tp_as_mapping + 0, // tp_hash + 0, // tp_call + 0, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + (Py_TPFLAGS_DEFAULT | // tp_flags Py_TPFLAGS_HAVE_GC), - acquireitemdesc_doc, // tp_doc - CppOwnedTraverse,// tp_traverse - CppOwnedClear, // tp_clear - 0, // tp_richcompare - 0, // tp_weaklistoffset - 0, // tp_iter - 0, // tp_iternext - 0, // tp_methods - 0, // tp_members - acquireitemdesc_getset, // tp_getset - 0, // tp_base - 0, // tp_dict - 0, // tp_descr_get - 0, // tp_descr_set - 0, // tp_dictoffset - 0, // tp_init - 0, // tp_alloc - 0, // tp_new + acquireitemdesc_doc, // tp_doc + CppOwnedTraverse,// tp_traverse + CppOwnedClear, // tp_clear + 0, // tp_richcompare + 0, // tp_weaklistoffset + 0, // tp_iter + 0, // tp_iternext + 0, // tp_methods + 0, // tp_members + acquireitemdesc_getset, // tp_getset + 0, // tp_base + 0, // tp_dict + 0, // tp_descr_get + 0, // tp_descr_set + 0, // tp_dictoffset + 0, // tp_init + 0, // tp_alloc + 0, // tp_new }; // Acquire -PyObject *PyAcquire_GetItem(PyObject *self, pkgAcquire::Item *item) { +PyObject *PyAcquire_GetItem(PyObject *self, pkgAcquire::Item *item) +{ PyAcquireItems &item_struct = ((PyAcquireObject *)self)->items[item]; if (! item_struct.item) { item_struct.item = PyAcquireItem_FromCpp(item,false,self); @@ -212,43 +227,44 @@ PyObject *PyAcquire_GetItem(PyObject *self, pkgAcquire::Item *item) { return item_struct.item; } -PyObject *PyAcquire_GetItemDesc(PyObject *self, pkgAcquire::ItemDesc *item) { +PyObject *PyAcquire_GetItemDesc(PyObject *self, pkgAcquire::ItemDesc *item) +{ PyAcquireItems &item_struct = ((PyAcquireObject *)self)->items[item->Owner]; if (! item_struct.item) item_struct.item = PyAcquireItem_FromCpp(item->Owner,false,self); if (! item_struct.desc) item_struct.desc = PyAcquireItemDesc_FromCpp(item,false, - item_struct.item); + item_struct.item); Py_INCREF(item_struct.desc); return item_struct.desc; } static PyObject *PkgAcquireRun(PyObject *Self,PyObject *Args) { - pkgAcquire *fetcher = GetCpp(Self); + pkgAcquire *fetcher = GetCpp(Self); - int pulseInterval = 500000; - if (PyArg_ParseTuple(Args, "|i", &pulseInterval) == 0) - return 0; + int pulseInterval = 500000; + if (PyArg_ParseTuple(Args, "|i", &pulseInterval) == 0) + return 0; - pkgAcquire::RunResult run = fetcher->Run(pulseInterval); + pkgAcquire::RunResult run = fetcher->Run(pulseInterval); - return HandleErrors(Py_BuildValue("i",run)); + return HandleErrors(Py_BuildValue("i",run)); } static PyObject *PkgAcquireShutdown(PyObject *Self,PyObject *Args) { - pkgAcquire *fetcher = GetCpp(Self); + pkgAcquire *fetcher = GetCpp(Self); - if (PyArg_ParseTuple(Args, "") == 0) - return 0; + if (PyArg_ParseTuple(Args, "") == 0) + return 0; - fetcher->Shutdown(); + fetcher->Shutdown(); - // TODO: Delete all objects here - item_map &items = ((PyAcquireObject *)Self)->items; - for (item_map::iterator I = items.begin(); I != items.end(); I++) { - if ((*I).second.file) + // TODO: Delete all objects here + item_map &items = ((PyAcquireObject *)Self)->items; + for (item_map::iterator I = items.begin(); I != items.end(); I++) { + if ((*I).second.file) (*I).second.file->Object = NULL; if ((*I).second.item) { (*I).second.item->Object = NULL; @@ -258,32 +274,34 @@ static PyObject *PkgAcquireShutdown(PyObject *Self,PyObject *Args) (*I).second.desc->Object = NULL; Py_DECREF((*I).second.desc); } - } - items.clear(); - Py_INCREF(Py_None); - return HandleErrors(Py_None); + } + items.clear(); + Py_INCREF(Py_None); + return HandleErrors(Py_None); } -static PyMethodDef PkgAcquireMethods[] = -{ - {"run",PkgAcquireRun,METH_VARARGS,"Run the fetcher"}, - {"shutdown",PkgAcquireShutdown, METH_VARARGS,"Shutdown the fetcher"}, - #ifdef COMPAT_0_7 - {"Run",PkgAcquireRun,METH_VARARGS,"Run the fetcher"}, - {"Shutdown",PkgAcquireShutdown, METH_VARARGS,"Shutdown the fetcher"}, - #endif - {} +static PyMethodDef PkgAcquireMethods[] = { + {"run",PkgAcquireRun,METH_VARARGS,"Run the fetcher"}, + {"shutdown",PkgAcquireShutdown, METH_VARARGS,"Shutdown the fetcher"}, +#ifdef COMPAT_0_7 + {"Run",PkgAcquireRun,METH_VARARGS,"Run the fetcher"}, + {"Shutdown",PkgAcquireShutdown, METH_VARARGS,"Shutdown the fetcher"}, +#endif + {} }; #define fetcher (GetCpp(Self)) -static PyObject *PkgAcquireGetTotalNeeded(PyObject *Self,void*) { - return Py_BuildValue("d", fetcher->TotalNeeded()); +static PyObject *PkgAcquireGetTotalNeeded(PyObject *Self,void*) +{ + return Py_BuildValue("d", fetcher->TotalNeeded()); } -static PyObject *PkgAcquireGetFetchNeeded(PyObject *Self,void*) { - return Py_BuildValue("d", fetcher->FetchNeeded()); +static PyObject *PkgAcquireGetFetchNeeded(PyObject *Self,void*) +{ + return Py_BuildValue("d", fetcher->FetchNeeded()); } -static PyObject *PkgAcquireGetPartialPresent(PyObject *Self,void*) { - return Py_BuildValue("d", fetcher->PartialPresent()); +static PyObject *PkgAcquireGetPartialPresent(PyObject *Self,void*) +{ + return Py_BuildValue("d", fetcher->PartialPresent()); } #undef fetcher @@ -292,8 +310,8 @@ static PyObject *PkgAcquireGetWorkers(PyObject *self, void *closure) PyObject *List = PyList_New(0); pkgAcquire *Owner = GetCpp(self); CppOwnedPyObject *PyWorker = NULL; - for(pkgAcquire::Worker *Worker = Owner->WorkersBegin(); - Worker != 0; Worker = Owner->WorkerStep(Worker)) { + for (pkgAcquire::Worker *Worker = Owner->WorkersBegin(); + Worker != 0; Worker = Owner->WorkerStep(Worker)) { PyWorker = CppOwnedPyObject_NEW(self,&PyAcquireWorker_Type, Worker); PyWorker->NoDelete = true; PyList_Append(List, PyWorker); @@ -303,27 +321,29 @@ static PyObject *PkgAcquireGetWorkers(PyObject *self, void *closure) } static PyObject *PkgAcquireGetItems(PyObject *Self,void*) { - pkgAcquire *fetcher = GetCpp(Self); - PyObject *List = PyList_New(0); - PyObject *Obj; - for (pkgAcquire::ItemIterator I = fetcher->ItemsBegin(); - I != fetcher->ItemsEnd(); I++) - { + pkgAcquire *fetcher = GetCpp(Self); + PyObject *List = PyList_New(0); + PyObject *Obj; + for (pkgAcquire::ItemIterator I = fetcher->ItemsBegin(); + I != fetcher->ItemsEnd(); I++) { Obj = PyAcquire_GetItem(Self, *I); PyList_Append(List,Obj); Py_DECREF(Obj); - } - return List; + } + return List; } // some constants -static PyObject *PkgAcquireGetResultContinue(PyObject *Self,void*) { - return Py_BuildValue("i", pkgAcquire::Continue); +static PyObject *PkgAcquireGetResultContinue(PyObject *Self,void*) +{ + return Py_BuildValue("i", pkgAcquire::Continue); } -static PyObject *PkgAcquireGetResultFailed(PyObject *Self,void*) { - return Py_BuildValue("i", pkgAcquire::Failed); +static PyObject *PkgAcquireGetResultFailed(PyObject *Self,void*) +{ + return Py_BuildValue("i", pkgAcquire::Failed); } -static PyObject *PkgAcquireGetResultCancelled(PyObject *Self,void*) { - return Py_BuildValue("i", pkgAcquire::Cancelled); +static PyObject *PkgAcquireGetResultCancelled(PyObject *Self,void*) +{ + return Py_BuildValue("i", pkgAcquire::Cancelled); } static PyGetSetDef PkgAcquireGetSet[] = { @@ -335,7 +355,7 @@ static PyGetSetDef PkgAcquireGetSet[] = { {"result_continue",PkgAcquireGetResultContinue}, {"result_failed",PkgAcquireGetResultFailed}, {"total_needed",PkgAcquireGetTotalNeeded}, - #ifdef COMPAT_0_7 +#ifdef COMPAT_0_7 {"FetchNeeded",PkgAcquireGetFetchNeeded}, {"Items",PkgAcquireGetItems}, {"PartialPresent",PkgAcquireGetPartialPresent}, @@ -343,86 +363,88 @@ static PyGetSetDef PkgAcquireGetSet[] = { {"ResultContinue",PkgAcquireGetResultContinue}, {"ResultFailed",PkgAcquireGetResultFailed}, {"TotalNeeded",PkgAcquireGetTotalNeeded}, - #endif +#endif {} }; -static PyObject *PkgAcquireNew(PyTypeObject *type,PyObject *Args,PyObject *kwds) { - pkgAcquire *fetcher; - - PyObject *pyFetchProgressInst = NULL; - char *kwlist[] = {"progress", 0}; - if (PyArg_ParseTupleAndKeywords(Args,kwds,"|O",kwlist,&pyFetchProgressInst) == 0) - return 0; - - PyFetchProgress *progress = 0; - if (pyFetchProgressInst != NULL) { - // FIXME: memleak? - progress = new PyFetchProgress(); - progress->setCallbackInst(pyFetchProgressInst); - fetcher = new pkgAcquire(progress); - } else { - fetcher = new pkgAcquire(); - } - - PyAcquireObject *FetcherObj = (PyAcquireObject *) - CppPyObject_NEW(type, fetcher); - - if (progress != 0) - progress->setPyAcquire(FetcherObj); - // prepare our map of items. - new (&FetcherObj->items) item_map(); - new (&FetcherObj->workers) worker_map(); - return FetcherObj; +static PyObject *PkgAcquireNew(PyTypeObject *type,PyObject *Args,PyObject *kwds) +{ + pkgAcquire *fetcher; + + PyObject *pyFetchProgressInst = NULL; + char *kwlist[] = {"progress", 0}; + if (PyArg_ParseTupleAndKeywords(Args,kwds,"|O",kwlist,&pyFetchProgressInst) == 0) + return 0; + + PyFetchProgress *progress = 0; + if (pyFetchProgressInst != NULL) { + // FIXME: memleak? + progress = new PyFetchProgress(); + progress->setCallbackInst(pyFetchProgressInst); + fetcher = new pkgAcquire(progress); + } + else { + fetcher = new pkgAcquire(); + } + + PyAcquireObject *FetcherObj = (PyAcquireObject *) + CppPyObject_NEW(type, fetcher); + + if (progress != 0) + progress->setPyAcquire(FetcherObj); + // prepare our map of items. + new (&FetcherObj->items) item_map(); + new (&FetcherObj->workers) worker_map(); + return FetcherObj; } -static char *doc_PkgAcquire = "Acquire(progress) -> Acquire() object.\n\n" +static char *doc_PkgAcquire = + "Acquire(progress: apt_pkg.AcquireProgress) -> Acquire() object.\n\n" "Create a new acquire object. The parameter *progress* can be used to\n" - "specify a apt.progress.FetchProgress() object, which will display the\n" + "specify an apt_pkg.AcquireProgress() object, which will display the\n" "progress of the fetching."; -PyTypeObject PyAcquire_Type = -{ - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "apt_pkg.Acquire", // tp_name - sizeof(PyAcquireObject), // tp_basicsize - 0, // tp_itemsize - // Methods - CppDeallocPtr, // tp_dealloc - 0, // tp_print - 0, // tp_getattr - 0, // tp_setattr - 0, // tp_compare - 0, // tp_repr - 0, // tp_as_number - 0, // tp_as_sequence - 0, // tp_as_mapping - 0, // tp_hash - 0, // tp_call - 0, // tp_str - 0, // tp_getattro - 0, // tp_setattro - 0, // tp_as_buffer - (Py_TPFLAGS_DEFAULT | // tp_flags +PyTypeObject PyAcquire_Type = { + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "apt_pkg.Acquire", // tp_name + sizeof(PyAcquireObject), // tp_basicsize + 0, // tp_itemsize + // Methods + CppDeallocPtr, // tp_dealloc + 0, // tp_print + 0, // tp_getattr + 0, // tp_setattr + 0, // tp_compare + 0, // tp_repr + 0, // tp_as_number + 0, // tp_as_sequence + 0, // tp_as_mapping + 0, // tp_hash + 0, // tp_call + 0, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + (Py_TPFLAGS_DEFAULT | // tp_flags Py_TPFLAGS_BASETYPE), - doc_PkgAcquire, // tp_doc - 0, // tp_traverse - 0, // tp_clear - 0, // tp_richcompare - 0, // tp_weaklistoffset - 0, // tp_iter - 0, // tp_iternext - PkgAcquireMethods, // tp_methods - 0, // tp_members - PkgAcquireGetSet, // tp_getset - 0, // tp_base - 0, // tp_dict - 0, // tp_descr_get - 0, // tp_descr_set - 0, // tp_dictoffset - 0, // tp_init - 0, // tp_alloc - PkgAcquireNew, // tp_new + doc_PkgAcquire, // tp_doc + 0, // tp_traverse + 0, // tp_clear + 0, // tp_richcompare + 0, // tp_weaklistoffset + 0, // tp_iter + 0, // tp_iternext + PkgAcquireMethods, // tp_methods + 0, // tp_members + PkgAcquireGetSet, // tp_getset + 0, // tp_base + 0, // tp_dict + 0, // tp_descr_get + 0, // tp_descr_set + 0, // tp_dictoffset + 0, // tp_init + 0, // tp_alloc + PkgAcquireNew, // tp_new }; #ifdef COMPAT_0_7 -- cgit v1.2.3 From 17427c9ba39b56c178e90fde22387d5f2ec525e1 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Fri, 24 Jul 2009 15:12:49 +0200 Subject: python/python-apt.h: Fix PyCdrom_FromCpp to use pkgCdrom, not pkgCdrom*. --- python/python-apt.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'python') diff --git a/python/python-apt.h b/python/python-apt.h index fb84b394..08242c08 100644 --- a/python/python-apt.h +++ b/python/python-apt.h @@ -245,7 +245,7 @@ inline CppOwnedPyObject *FromCppOwned(PyTypeObject *pytype, Cpp const &obj, # define PyActionGroup_FromCpp(...) FromCppOwned(&PyActionGroup_Type,##__VA_ARGS__) # define PyCache_FromCpp(...) FromCppOwned(&PyCache_Type,##__VA_ARGS__) # define PyCacheFile_FromCpp(...) FromCpp(&PyCacheFile_Type,##__VA_ARGS__) -# define PyCdrom_FromCpp(...) FromCpp(&PyCdrom_Type,##__VA_ARGS__) +# define PyCdrom_FromCpp(...) FromCpp(&PyCdrom_Type,##__VA_ARGS__) # define PyConfiguration_FromCpp(...) FromCppOwned(&PyConfiguration_Type, ##__VA_ARGS__) # define PyDepCache_FromCpp(...) FromCppOwned(&PyDepCache_Type,##__VA_ARGS__) # define PyDependency_FromCpp(...) FromCppOwned(&PyDependency_Type,##__VA_ARGS__) -- cgit v1.2.3 From 7a30c8bb4b70f42cc268b4b3a75dab5b414146c4 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Fri, 24 Jul 2009 17:53:53 +0200 Subject: python/generic.h: Do not deallocate the temporary bytes object in PyUnicode_AsString. --- python/generic.h | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) (limited to 'python') diff --git a/python/generic.h b/python/generic.h index d7f121ce..75520914 100644 --- a/python/generic.h +++ b/python/generic.h @@ -79,11 +79,7 @@ typedef int Py_ssize_t; static inline const char *PyUnicode_AsString(PyObject *op) { // Convert to bytes object, using the default encoding. PyObject *bytes = PyUnicode_AsEncodedString(op,0,0); - if (!bytes) - return 0; - const char *result = PyBytes_AS_STRING(bytes); - Py_DECREF(bytes); - return result; + return bytes ? PyBytes_AS_STRING(bytes) : 0; } // Convert any type of string based object to a const char. -- cgit v1.2.3 From 1db4f4035b23acf6b2452e57b27c3f44571fc489 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Fri, 24 Jul 2009 20:20:22 +0200 Subject: python/apt_pkgmodule.cc: Move all constants here. Now the constants are accessible from the types, and not only from instances. --- python/acquire.cc | 19 ------------------- python/apt_pkgmodule.cc | 35 ++++++++++++++++++++++++++++++++++- python/pkgmanager.cc | 24 +----------------------- 3 files changed, 35 insertions(+), 43 deletions(-) (limited to 'python') diff --git a/python/acquire.cc b/python/acquire.cc index 7c8c9eea..ef8b10b6 100644 --- a/python/acquire.cc +++ b/python/acquire.cc @@ -332,36 +332,17 @@ static PyObject *PkgAcquireGetItems(PyObject *Self,void*) } return List; } -// some constants -static PyObject *PkgAcquireGetResultContinue(PyObject *Self,void*) -{ - return Py_BuildValue("i", pkgAcquire::Continue); -} -static PyObject *PkgAcquireGetResultFailed(PyObject *Self,void*) -{ - return Py_BuildValue("i", pkgAcquire::Failed); -} -static PyObject *PkgAcquireGetResultCancelled(PyObject *Self,void*) -{ - return Py_BuildValue("i", pkgAcquire::Cancelled); -} static PyGetSetDef PkgAcquireGetSet[] = { {"fetch_needed",PkgAcquireGetFetchNeeded}, {"items",PkgAcquireGetItems}, {"workers",PkgAcquireGetWorkers}, {"partial_present",PkgAcquireGetPartialPresent}, - {"result_cancelled",PkgAcquireGetResultCancelled}, - {"result_continue",PkgAcquireGetResultContinue}, - {"result_failed",PkgAcquireGetResultFailed}, {"total_needed",PkgAcquireGetTotalNeeded}, #ifdef COMPAT_0_7 {"FetchNeeded",PkgAcquireGetFetchNeeded}, {"Items",PkgAcquireGetItems}, {"PartialPresent",PkgAcquireGetPartialPresent}, - {"ResultCancelled",PkgAcquireGetResultCancelled}, - {"ResultContinue",PkgAcquireGetResultContinue}, - {"ResultFailed",PkgAcquireGetResultFailed}, {"TotalNeeded",PkgAcquireGetTotalNeeded}, #endif {} diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index 0a899efb..9e486a91 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -14,6 +14,7 @@ #include #include +#include #include #include #include @@ -666,9 +667,41 @@ extern "C" void initapt_pkg() CharCharToList(TFRewriteSourceOrder)); - // AcquireItem Constants. + // Acquire constants. + // some constants + PyDict_SetItemString(PyAcquire_Type.tp_dict, "result_cancelled", + Py_BuildValue("i", pkgAcquire::Cancelled)); + PyDict_SetItemString(PyAcquire_Type.tp_dict, "result_continue", + Py_BuildValue("i", pkgAcquire::Continue)); + PyDict_SetItemString(PyAcquire_Type.tp_dict, "result_failed", + Py_BuildValue("i", pkgAcquire::Failed)); +#ifdef COMPAT_0_7 + PyDict_SetItemString(PyAcquire_Type.tp_dict, "ResultCancelled", + Py_BuildValue("i", pkgAcquire::Cancelled)); + PyDict_SetItemString(PyAcquire_Type.tp_dict, "ResultContinue", + Py_BuildValue("i", pkgAcquire::Continue)); + PyDict_SetItemString(PyAcquire_Type.tp_dict, "ResultFailed", + Py_BuildValue("i", pkgAcquire::Failed)); +#endif + // PackageManager constants + PyDict_SetItemString(PyPackageManager_Type.tp_dict, "result_completed", + Py_BuildValue("i", pkgPackageManager::Completed)); + PyDict_SetItemString(PyPackageManager_Type.tp_dict, "result_failed", + Py_BuildValue("i", pkgPackageManager::Failed)); + PyDict_SetItemString(PyPackageManager_Type.tp_dict, "result_incomplete", + Py_BuildValue("i", pkgPackageManager::Incomplete)); +#ifdef COMPAT_0_7 + PyDict_SetItemString(PyPackageManager_Type.tp_dict, "ResultCompleted", + Py_BuildValue("i", pkgPackageManager::Completed)); + PyDict_SetItemString(PyPackageManager_Type.tp_dict, "ResultFailed", + Py_BuildValue("i", pkgPackageManager::Failed)); + PyDict_SetItemString(PyPackageManager_Type.tp_dict, "ResultIncomplete", + Py_BuildValue("i", pkgPackageManager::Incomplete)); +#endif + + // AcquireItem Constants. PyDict_SetItemString(PyAcquireItem_Type.tp_dict, "stat_idle", Py_BuildValue("i", pkgAcquire::Item::StatIdle)); PyDict_SetItemString(PyAcquireItem_Type.tp_dict, "stat_fetching", diff --git a/python/pkgmanager.cc b/python/pkgmanager.cc index f4f84a2b..58f2aaec 100644 --- a/python/pkgmanager.cc +++ b/python/pkgmanager.cc @@ -109,28 +109,6 @@ static PyMethodDef PkgManagerMethods[] = }; -static PyObject *PkgManagerGetResultCompleted(PyObject *Self,void*) { - return Py_BuildValue("i", pkgPackageManager::Completed); -} -static PyObject *PkgManagerGetResultFailed(PyObject *Self,void*) { - return Py_BuildValue("i", pkgPackageManager::Failed); -} -static PyObject *PkgManagerGetResultIncomplete(PyObject *Self,void*) { - return Py_BuildValue("i", pkgPackageManager::Incomplete); -} - -static PyGetSetDef PkgManagerGetSet[] = { - {"result_completed",PkgManagerGetResultCompleted}, - {"result_failed",PkgManagerGetResultFailed}, - {"result_incomplete",PkgManagerGetResultIncomplete}, -#ifdef COMPAT_0_7 - {"ResultCompleted",PkgManagerGetResultCompleted}, - {"ResultFailed",PkgManagerGetResultFailed}, - {"ResultIncomplete",PkgManagerGetResultIncomplete}, -#endif - {} -}; - PyTypeObject PyPackageManager_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) @@ -164,7 +142,7 @@ PyTypeObject PyPackageManager_Type = 0, // tp_iternext PkgManagerMethods, // tp_methods 0, // tp_members - PkgManagerGetSet, // tp_getset + 0, // tp_getset 0, // tp_base 0, // tp_dict 0, // tp_descr_get -- cgit v1.2.3 From fda01b9ec100db7d2e5f7434edadd1fe84d4fdee Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Fri, 24 Jul 2009 20:40:11 +0200 Subject: python/cache.cc: Fix segfault if Pkg->Section == NULL. --- python/cache.cc | 29 +++++++++++++++-------------- 1 file changed, 15 insertions(+), 14 deletions(-) (limited to 'python') diff --git a/python/cache.cc b/python/cache.cc index f5effae9..30c0e683 100644 --- a/python/cache.cc +++ b/python/cache.cc @@ -462,19 +462,19 @@ PyTypeObject PyPackageList_Type = return Ret; \ } -MkGet(PackageGetName,PyString_FromString(Pkg.Name())); -MkGet(PackageGetSection,Safe_FromString(Pkg.Section())); +MkGet(PackageGetName,PyString_FromString(Pkg.Name())) +MkGet(PackageGetSection,Safe_FromString(Pkg.Section())) MkGet(PackageGetRevDependsList,CppOwnedPyObject_NEW(Owner, - &PyDependencyList_Type, Pkg.RevDependsList())); -MkGet(PackageGetProvidesList,CreateProvides(Owner,Pkg.ProvidesList())); -MkGet(PackageGetSelectedState,Py_BuildValue("i",Pkg->SelectedState)); -MkGet(PackageGetInstState,Py_BuildValue("i",Pkg->InstState)); -MkGet(PackageGetCurrentState,Py_BuildValue("i",Pkg->CurrentState)); -MkGet(PackageGetID,Py_BuildValue("i",Pkg->ID)); + &PyDependencyList_Type, Pkg.RevDependsList())) +MkGet(PackageGetProvidesList,CreateProvides(Owner,Pkg.ProvidesList())) +MkGet(PackageGetSelectedState,Py_BuildValue("i",Pkg->SelectedState)) +MkGet(PackageGetInstState,Py_BuildValue("i",Pkg->InstState)) +MkGet(PackageGetCurrentState,Py_BuildValue("i",Pkg->CurrentState)) +MkGet(PackageGetID,Py_BuildValue("i",Pkg->ID)) # -MkGet(PackageGetAuto,Py_BuildValue("i",(Pkg->Flags & pkgCache::Flag::Auto) != 0)); -MkGet(PackageGetEssential,Py_BuildValue("i",(Pkg->Flags & pkgCache::Flag::Essential) != 0)); -MkGet(PackageGetImportant,Py_BuildValue("i",(Pkg->Flags & pkgCache::Flag::Important) != 0)); +MkGet(PackageGetAuto,Py_BuildValue("i",(Pkg->Flags & pkgCache::Flag::Auto) != 0)) +MkGet(PackageGetEssential,Py_BuildValue("i",(Pkg->Flags & pkgCache::Flag::Essential) != 0)) +MkGet(PackageGetImportant,Py_BuildValue("i",(Pkg->Flags & pkgCache::Flag::Important) != 0)) #undef MkGet #undef Owner @@ -544,7 +544,8 @@ static PyObject *PackageRepr(PyObject *Self) return PyString_FromFormat("<%s object: name:'%s' section: " "'%s' id:%u>", Self->ob_type->tp_name, - Pkg.Name(), Pkg.Section(), Pkg->ID); + Pkg.Name(), (Pkg.Section() ? Pkg.Section() : ""), + Pkg->ID); } PyTypeObject PyPackage_Type = @@ -588,8 +589,8 @@ PyTypeObject PyPackage_Type = return Ret; } Description_MkGet(DescriptionGetLanguageCode, - PyString_FromString(Desc.LanguageCode())); -Description_MkGet(DescriptionGetMd5,Safe_FromString(Desc.md5())); + PyString_FromString(Desc.LanguageCode())) +Description_MkGet(DescriptionGetMd5,Safe_FromString(Desc.md5())) #undef Description_MkGet static PyObject *DescriptionGetFileList(PyObject *Self,void*) -- cgit v1.2.3 From db27b9d050c466eabf6eb72899bfbe696af8852b Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Fri, 24 Jul 2009 20:49:39 +0200 Subject: python: Fix some more possible NULL issues. --- python/cache.cc | 6 ++++-- python/indexfile.cc | 4 +++- python/metaindex.cc | 4 +++- 3 files changed, 10 insertions(+), 4 deletions(-) (limited to 'python') diff --git a/python/cache.cc b/python/cache.cc index 30c0e683..68ee7b9e 100644 --- a/python/cache.cc +++ b/python/cache.cc @@ -840,6 +840,7 @@ static PyObject *VersionGetIsTrusted(PyObject *Self, void*) { } #endif +#define NOTNULL(x) (x ? x : "") static PyObject *VersionRepr(PyObject *Self) { @@ -848,11 +849,12 @@ static PyObject *VersionRepr(PyObject *Self) " Arch:'%s' Size:%lu ISize:%lu Hash:%u ID:%u " "Priority:%u>", Self->ob_type->tp_name, Ver.ParentPkg().Name(), Ver.VerStr(), - Ver.Section(), Ver.Arch(), + NOTNULL(Ver.Section()), NOTNULL(Ver.Arch()), (unsigned long)Ver->Size, (unsigned long)Ver->InstalledSize, Ver->Hash, Ver->ID, Ver->Priority); } +#undef NOTNULL static PyGetSetDef VersionGetSet[] = { {"arch",VersionGetArch}, @@ -1096,7 +1098,7 @@ static PyObject *DependencyRepr(PyObject *Self) return PyString_FromFormat("<%s object: pkg:'%s' ver:'%s' comp:'%s'>", Self->ob_type->tp_name, Dep.TargetPkg().Name(), - (Dep.TargetVer() == 0?"":Dep.TargetVer()), + (Dep.TargetVer() == 0 ? "" : Dep.TargetVer()), Dep.CompType()); } diff --git a/python/indexfile.cc b/python/indexfile.cc index 74345ec9..a6f8904e 100644 --- a/python/indexfile.cc +++ b/python/indexfile.cc @@ -55,6 +55,7 @@ static PyObject *PackageIndexFileGetIsTrusted(PyObject *Self,void*) { } #undef File +#define S(x) (x ? x : "") static PyObject *PackageIndexFileRepr(PyObject *Self) { pkgIndexFile *File = GetCpp(Self); @@ -62,10 +63,11 @@ static PyObject *PackageIndexFileRepr(PyObject *Self) "Label:'%s' Describe='%s' Exists='%i' " "HasPackages='%i' Size='%lu' " "IsTrusted='%i' ArchiveURI='%s'>", - File->GetType()->Label, File->Describe().c_str(), File->Exists(), + S(File->GetType()->Label), File->Describe().c_str(), File->Exists(), File->HasPackages(), File->Size(), File->IsTrusted(), File->ArchiveURI("").c_str()); } +#undef S static PyGetSetDef PackageIndexFileGetSet[] = { {"describe",PackageIndexFileGetDescribe}, diff --git a/python/metaindex.cc b/python/metaindex.cc index 62ff6b90..4e059f0c 100644 --- a/python/metaindex.cc +++ b/python/metaindex.cc @@ -61,14 +61,16 @@ static PyGetSetDef MetaIndexGetSet[] = { {} }; +#define S(x) (x ? x : "") static PyObject *MetaIndexRepr(PyObject *Self) { metaIndex *meta = GetCpp(Self); return PyString_FromFormat("<%s object: type='%s', uri:'%s' dist='%s' " "is_trusted='%i'>", Self->ob_type->tp_name, - meta->GetType(), meta->GetURI().c_str(), + S(meta->GetType()), meta->GetURI().c_str(), meta->GetDist().c_str(), meta->IsTrusted()); } +#undef S PyTypeObject PyMetaIndex_Type = { -- cgit v1.2.3 From 9b52f302a694ee3d7d02110dbdb935bafbf42e55 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Thu, 30 Jul 2009 20:42:44 +0200 Subject: python/cdrom.cc: Fix build failure with COMPAT_0_7. This was introduced during the partial rewrite of this file. --- python/cdrom.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'python') diff --git a/python/cdrom.cc b/python/cdrom.cc index 521937f5..2270b01c 100644 --- a/python/cdrom.cc +++ b/python/cdrom.cc @@ -165,6 +165,6 @@ PyObject *GetCdrom(PyObject *Self,PyObject *Args) { PyErr_WarnEx(PyExc_DeprecationWarning, "apt_pkg.GetCdrom() is deprecated. " "Please see apt_pkg.Cdrom() for the replacement.", 1); - return PkgCdromNew(&PyCdrom_Type,Args,0); + return cdrom_new(&PyCdrom_Type,Args,0); } #endif -- cgit v1.2.3 From c41f809bef5b591d36d6bbb663841a9434eb77fb Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Fri, 31 Jul 2009 14:55:02 +0200 Subject: python/configuration.cc, apt_pkgmodule.cc: Fix Configuration segfaults. In apt_pkgmodule, change the type to Configuration*. In configuration.cc, check that GetSelf(Self).Tree(0) != 0 before doing GetSelf(Self).Tree(0)->Parent. --- python/apt_pkgmodule.cc | 2 +- python/configuration.cc | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) (limited to 'python') diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index 9e486a91..d53f64a6 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -56,7 +56,7 @@ static PyObject *newConfiguration(PyObject *self,PyObject *args) { PyErr_WarnEx(PyExc_DeprecationWarning, "apt_pkg.newConfiguration() is " "deprecated. Use apt_pkg.Configuration() instead.", 1); - return CppPyObject_NEW(&PyConfiguration_Type); + return CppOwnedPyObject_NEW(NULL, &PyConfiguration_Type, new Configuration()); } #endif /*}}}*/ diff --git a/python/configuration.cc b/python/configuration.cc index 11231a28..b2367c3e 100644 --- a/python/configuration.cc +++ b/python/configuration.cc @@ -152,6 +152,8 @@ static PyObject *CnfList(PyObject *Self,PyObject *Args) // Convert the whole configuration space into a list PyObject *List = PyList_New(0); const Configuration::Item *Top = GetSelf(Self).Tree(RootName); + if (!GetSelf(Self).Tree(0)) + return List; const Configuration::Item *Root = GetSelf(Self).Tree(0)->Parent; if (Top != 0 && RootName != 0) Top = Top->Child; @@ -216,7 +218,7 @@ static PyObject *CnfKeys(PyObject *Self,PyObject *Args) const Configuration::Item *Root = 0; if (RootName == 0) Stop = 0; - if (Top != 0) + if (Top != 0 && GetSelf(Self).Tree(0)) Root = GetSelf(Self).Tree(0)->Parent; for (; Top != 0;) { -- cgit v1.2.3 From e3653ead6554eafb9eb3327708944f30171aed6c Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Fri, 31 Jul 2009 14:58:49 +0200 Subject: python/progress.cc: Do not special case apt_pkg.*Progress anymore. --- python/progress.cc | 123 ++++++++++++++++++++++------------------------------- 1 file changed, 51 insertions(+), 72 deletions(-) (limited to 'python') diff --git a/python/progress.cc b/python/progress.cc index 7873d894..c754dd35 100644 --- a/python/progress.cc +++ b/python/progress.cc @@ -91,28 +91,20 @@ void PyOpProgress::Update() return; - if (PyObject_TypeCheck(callbackInst, &PyOpProgress_Type)) { - PyOpProgressObject *obj = (PyOpProgressObject *)callbackInst; - obj->op = CppPyString(Op); - obj->subop = CppPyString(SubOp); -#ifdef T_BOOL - obj->major_change = (char)(MajorChange); + setattr(callbackInst, "op", "s", Op.c_str()); + setattr(callbackInst, "subop", "s", SubOp.c_str()); + setattr(callbackInst, "major_change", "b", MajorChange); +#ifdef COMPAT_0_7 + setattr(callbackInst, "Op", "s", Op.c_str()); + setattr(callbackInst, "subOp", "s", SubOp.c_str()); + setattr(callbackInst, "majorChange", "b", MajorChange); + PyObject *arglist = Py_BuildValue("(f)", Percent); + RunSimpleCallback("update", arglist); #else - obj->major_change = (int)(MajorChange); + setattr(callbackInst, "percent", "f", Percent); + RunSimpleCallback("update"); #endif - obj->percent = Percent; - RunSimpleCallback("update"); - } - else { - setattr(callbackInst, "op", "s", Op.c_str()); - setattr(callbackInst, "subop", "s", SubOp.c_str()); - setattr(callbackInst, "subOp", "s", SubOp.c_str()); - setattr(callbackInst, "major_change", "b", MajorChange); - setattr(callbackInst, "majorChange", "b", MajorChange); - PyObject *arglist = Py_BuildValue("(f)", Percent); - RunSimpleCallback("update", arglist); - } -}; +} void PyOpProgress::Done() { @@ -174,7 +166,7 @@ void PyFetchProgress::UpdateStatus(pkgAcquire::ItemDesc &Itm, int status) void PyFetchProgress::IMSHit(pkgAcquire::ItemDesc &Itm) { PyCbObj_END_ALLOW_THREADS - if (PyObject_TypeCheck(callbackInst,&PyAcquireProgress_Type)) + if (PyObject_HasAttrString(callbackInst, "ims_hit")) RunSimpleCallback("ims_hit", TUPLEIZE(PyAcquire_GetItemDesc(pyAcquire, &Itm))); else UpdateStatus(Itm, DLHit); @@ -184,7 +176,7 @@ void PyFetchProgress::IMSHit(pkgAcquire::ItemDesc &Itm) void PyFetchProgress::Fetch(pkgAcquire::ItemDesc &Itm) { PyCbObj_END_ALLOW_THREADS - if (PyObject_TypeCheck(callbackInst,&PyAcquireProgress_Type)) + if (PyObject_HasAttrString(callbackInst, "fetch")) RunSimpleCallback("fetch", TUPLEIZE(PyAcquire_GetItemDesc(pyAcquire, &Itm))); else UpdateStatus(Itm, DLQueued); @@ -194,7 +186,7 @@ void PyFetchProgress::Fetch(pkgAcquire::ItemDesc &Itm) void PyFetchProgress::Done(pkgAcquire::ItemDesc &Itm) { PyCbObj_END_ALLOW_THREADS - if (PyObject_TypeCheck(callbackInst,&PyAcquireProgress_Type)) + if (PyObject_HasAttrString(callbackInst, "done")) RunSimpleCallback("done", TUPLEIZE(PyAcquire_GetItemDesc(pyAcquire, &Itm))); else UpdateStatus(Itm, DLDone); @@ -204,7 +196,7 @@ void PyFetchProgress::Done(pkgAcquire::ItemDesc &Itm) void PyFetchProgress::Fail(pkgAcquire::ItemDesc &Itm) { PyCbObj_END_ALLOW_THREADS - if (PyObject_TypeCheck(callbackInst,&PyAcquireProgress_Type)) { + if (PyObject_HasAttrString(callbackInst, "fail")) { RunSimpleCallback("fail", TUPLEIZE(PyAcquire_GetItemDesc(pyAcquire, &Itm))); return; } @@ -219,7 +211,7 @@ void PyFetchProgress::Fail(pkgAcquire::ItemDesc &Itm) } - if (PyObject_TypeCheck(callbackInst,&PyAcquireProgress_Type)) + if (PyObject_HasAttrString(callbackInst, "fail")) RunSimpleCallback("fail", TUPLEIZE(PyAcquire_GetItemDesc(pyAcquire, &Itm))); else UpdateStatus(Itm, DLFailed); @@ -232,13 +224,11 @@ void PyFetchProgress::Start() pkgAcquireStatus::Start(); #ifdef COMPAT_0_7 - if (!PyObject_TypeCheck(callbackInst,&PyAcquireProgress_Type)) { - setattr(callbackInst, "currentCPS", "d", 0); - setattr(callbackInst, "currentBytes", "d", 0); - setattr(callbackInst, "currentItems", "k", 0); - setattr(callbackInst, "totalItems", "k", 0); - setattr(callbackInst, "totalBytes", "d", 0); - } + setattr(callbackInst, "currentCPS", "d", 0); + setattr(callbackInst, "currentBytes", "d", 0); + setattr(callbackInst, "currentItems", "k", 0); + setattr(callbackInst, "totalItems", "k", 0); + setattr(callbackInst, "totalBytes", "d", 0); #endif RunSimpleCallback("start"); @@ -272,37 +262,29 @@ bool PyFetchProgress::Pulse(pkgAcquire * Owner) if(callbackInst == 0) return false; - if (PyObject_TypeCheck(callbackInst, &PyAcquireProgress_Type)) { - PyAcquireProgressObject *obj = (PyAcquireProgressObject *)callbackInst; - obj->last_bytes = LastBytes; - obj->current_cps = CurrentCPS; - obj->current_bytes = CurrentBytes; - obj->total_bytes = TotalBytes; - obj->fetched_bytes = FetchedBytes; - obj->elapsed_time = ElapsedTime; - obj->total_items = TotalItems; - obj->current_items = CurrentItems; - } - else { - setattr(callbackInst, "last_bytes", "d", LastBytes); - setattr(callbackInst, "current_cps", "d", CurrentCPS); - setattr(callbackInst, "current_bytes", "d", CurrentBytes); - setattr(callbackInst, "total_bytes", "d", TotalBytes); - setattr(callbackInst, "fetched_bytes", "d", FetchedBytes); - setattr(callbackInst, "elapsed_time", "k", ElapsedTime); - setattr(callbackInst, "current_items", "k", CurrentItems); - setattr(callbackInst, "total_items", "k", TotalItems); + setattr(callbackInst, "last_bytes", "d", LastBytes); + setattr(callbackInst, "current_cps", "d", CurrentCPS); + setattr(callbackInst, "current_bytes", "d", CurrentBytes); + setattr(callbackInst, "total_bytes", "d", TotalBytes); + setattr(callbackInst, "fetched_bytes", "d", FetchedBytes); + setattr(callbackInst, "elapsed_time", "k", ElapsedTime); + setattr(callbackInst, "current_items", "k", CurrentItems); + setattr(callbackInst, "total_items", "k", TotalItems); #ifdef COMPAT_0_7 - setattr(callbackInst, "currentCPS", "d", CurrentCPS); - setattr(callbackInst, "currentBytes", "d", CurrentBytes); - setattr(callbackInst, "totalBytes", "d", TotalBytes); - setattr(callbackInst, "fetchedBytes", "d", FetchedBytes); - setattr(callbackInst, "currentItems", "k", CurrentItems); - setattr(callbackInst, "totalItems", "k", TotalItems); + setattr(callbackInst, "currentCPS", "d", CurrentCPS); + setattr(callbackInst, "currentBytes", "d", CurrentBytes); + setattr(callbackInst, "totalBytes", "d", TotalBytes); + setattr(callbackInst, "fetchedBytes", "d", FetchedBytes); + setattr(callbackInst, "currentItems", "k", CurrentItems); + setattr(callbackInst, "totalItems", "k", TotalItems); #endif - } - if (PyObject_TypeCheck(callbackInst, &PyAcquireProgress_Type)) { + // New style +#ifdef COMPAT_0_7 + if (!PyObject_HasAttrString(callbackInst, "updateStatus")) { +#else + { +#endif PyObject *result1; bool res1 = true; @@ -317,8 +299,11 @@ bool PyFetchProgress::Pulse(pkgAcquire * Owner) } PyCbObj_BEGIN_ALLOW_THREADS return true; - } + + + } +#ifdef COMPAT_0_7 // Go through the list of items and add active items to the // activeItems vector. map activeItemMap; @@ -407,6 +392,7 @@ bool PyFetchProgress::Pulse(pkgAcquire * Owner) PyCbObj_BEGIN_ALLOW_THREADS // fetching can be canceld by returning false return res; +#endif } @@ -541,17 +527,10 @@ pkgPackageManager::OrderResult PyInstallProgress::Run(pkgPackageManager *pm) void PyCdromProgress::Update(string text, int current) { PyObject *arglist = Py_BuildValue("(si)", text.c_str(), current); - if (PyObject_TypeCheck(callbackInst, &PyCdromProgress_Type)) { - ((PyCdromProgressObject *)callbackInst)->total_steps = totalSteps; - } - else { - - setattr(callbackInst, "total_steps", "i", totalSteps); -#ifdef COMPAT_0_7 - setattr(callbackInst, "totalSteps", "i", totalSteps); -#endif - } - + setattr(callbackInst, "total_steps", "i", totalSteps); + #ifdef COMPAT_0_7 + setattr(callbackInst, "totalSteps", "i", totalSteps); + #endif RunSimpleCallback("update", arglist); } -- cgit v1.2.3 From fb8e639a7199a5707ae24c8424e5dc748fe0be37 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Fri, 31 Jul 2009 15:24:09 +0200 Subject: python: Remove the progress classes in apt_pkg. They have been replaced with apt.progress.base, so stuff like GTK+ or Qt progress classes can be written using subclassing. --- apt/cache.py | 6 +- apt/cdrom.py | 3 +- apt/progress/old.py | 28 +++---- apt/progress/text.py | 36 ++++---- python/acquireprogress.cc | 208 ---------------------------------------------- python/apt_pkgmodule.cc | 3 - python/apt_pkgmodule.h | 3 - python/cache.cc | 6 -- python/cdrom.cc | 3 +- python/cdromprogress.cc | 106 ----------------------- python/opprogress.cc | 175 -------------------------------------- python/progress.h | 32 ------- setup.py | 5 +- 13 files changed, 36 insertions(+), 578 deletions(-) delete mode 100644 python/acquireprogress.cc delete mode 100644 python/cdromprogress.cc delete mode 100644 python/opprogress.cc (limited to 'python') diff --git a/apt/cache.py b/apt/cache.py index f507863c..ae4254e0 100644 --- a/apt/cache.py +++ b/apt/cache.py @@ -122,11 +122,7 @@ class Cache(object): size=len(self._cache.packages) for pkg in self._cache.packages: if progress is not None and last+100 < i: - if isinstance(progress, apt_pkg.OpProgress): - progress.percent = i/float(size)*100 - progress.update() - else: - progress.update(i/float(size)*100) + progress.update(i/float(size)*100) last=i # drop stuff with no versions (cruft) if len(pkg.version_list) > 0: diff --git a/apt/cdrom.py b/apt/cdrom.py index 126c54dd..01caa12f 100644 --- a/apt/cdrom.py +++ b/apt/cdrom.py @@ -24,6 +24,7 @@ import glob import apt_pkg from apt.deprecation import AttributeDeprecatedBy +from apt.progress.base import CdromProgress class Cdrom(apt_pkg.Cdrom): @@ -46,7 +47,7 @@ class Cdrom(apt_pkg.Cdrom): def __init__(self, progress=None, mountpoint=None, nomount=True): apt_pkg.Cdrom.__init__(self) if progress is None: - self._progress = apt_pkg.CdromProgress() + self._progress = CdromProgress() else: self._progress = progress # see if we have a alternative mountpoint diff --git a/apt/progress/old.py b/apt/progress/old.py index 88957272..adaf94b2 100644 --- a/apt/progress/old.py +++ b/apt/progress/old.py @@ -34,29 +34,21 @@ import sys import apt_pkg from apt.deprecation import AttributeDeprecatedBy, function_deprecated_by +from apt.progress import base __all__ = [] -class OpProgress(object): +class OpProgress(base.OpProgress): """Abstract class to implement reporting on cache opening. Subclass this class to implement simple Operation progress reporting. """ - def __init__(self): - self.op = None - self.subop = None - - def update(self, percent): - """Called periodically to update the user interface.""" - - def done(self): - """Called once an operation has been completed.""" - if apt_pkg._COMPAT_0_7: subOp = AttributeDeprecatedBy('subop') + Op = AttributeDeprecatedBy('op') class OpTextProgress(OpProgress): @@ -65,13 +57,15 @@ class OpTextProgress(OpProgress): def __init__(self): OpProgress.__init__(self) - def update(self, percent): + def update(self, percent=None): """Called periodically to update the user interface.""" - sys.stdout.write("\r%s: %.2i " % (self.subop, percent)) + OpProgress.update(self, percent) + sys.stdout.write("\r%s: %.2i " % (self.subop, self.percent)) sys.stdout.flush() def done(self): """Called once an operation has been completed.""" + OpProgress.done(self) sys.stdout.write("\r%s: Done\n" % self.op) @@ -349,13 +343,15 @@ class InstallProgress(DumbInstallProgress): updateInterface = function_deprecated_by(update_interface) -class CdromProgress(apt_pkg.CdromProgress): +class CdromProgress(base.CdromProgress): """Report the cdrom add progress. This class has been replaced by apt_pkg.CdromProgress. """ - askCdromName = function_deprecated_by(apt_pkg.CdromProgress.ask_cdrom_name) - changeCdrom = function_deprecated_by(apt_pkg.CdromProgress.change_cdrom) + _basetype = base.CdromProgress + askCdromName = function_deprecated_by(_basetype.ask_cdrom_name) + changeCdrom = function_deprecated_by(_basetype.change_cdrom) + del _basetype class DpkgInstallProgress(InstallProgress): diff --git a/apt/progress/text.py b/apt/progress/text.py index 54a35704..eb474d6d 100644 --- a/apt/progress/text.py +++ b/apt/progress/text.py @@ -18,7 +18,7 @@ import sys import apt_pkg -import apt.progress.base +from apt.progress import base __all__ = ['AcquireProgress', 'CdromProgress', 'OpProgress'] @@ -55,7 +55,7 @@ class TextProgress(object): self._file.flush() -class OpProgress(apt.progress.base.OpProgress, TextProgress): +class OpProgress(base.OpProgress, TextProgress): """Operation progress reporting. This closely resembles OpTextProgress in libapt-pkg. @@ -63,12 +63,12 @@ class OpProgress(apt.progress.base.OpProgress, TextProgress): def __init__(self, outfile=None): TextProgress.__init__(self, outfile) - apt.progress.base.OpProgress.__init__(self) + base.OpProgress.__init__(self) self.old_op = "" def update(self, percent=None): """Called periodically to update the user interface.""" - apt.progress.base.OpProgress.update(self, percent) + base.OpProgress.update(self, percent) if self.major_change and self.old_op: self._write(self.old_op) self._write("%s... %i%%\r" % (self.op, self.percent), False, True) @@ -76,18 +76,18 @@ class OpProgress(apt.progress.base.OpProgress, TextProgress): def done(self): """Called once an operation has been completed.""" - apt.progress.base.OpProgress.done(self) + base.OpProgress.done(self) if self.old_op: self._write(_("%c%s... Done") % ('\r', self.old_op), True, True) self.old_op = "" -class AcquireProgress(apt.progress.base.AcquireProgress, TextProgress): +class AcquireProgress(base.AcquireProgress, TextProgress): """AcquireProgress for the text interface.""" def __init__(self, outfile=None): TextProgress.__init__(self, outfile) - apt.progress.base.AcquireProgress.__init__(self) + base.AcquireProgress.__init__(self) self._signal = None self._width = 80 self._id = 1 @@ -98,7 +98,7 @@ class AcquireProgress(apt.progress.base.AcquireProgress, TextProgress): In this case, the function sets up a signal handler for SIGWINCH, i.e. window resize signals. And it also sets id to 1. """ - apt.progress.base.AcquireProgress.start(self) + base.AcquireProgress.start(self) import signal self._signal = signal.signal(signal.SIGWINCH, self._winch) # Get the window size. @@ -116,7 +116,7 @@ class AcquireProgress(apt.progress.base.AcquireProgress, TextProgress): def ims_hit(self, item): """Called when an item is update (e.g. not modified on the server).""" - apt.progress.base.AcquireProgress.ims_hit(self, item) + base.AcquireProgress.ims_hit(self, item) line = _('Hit ') + item.description if item.owner.filesize: line += ' [%sB]' % apt_pkg.size_to_str(item.owner.filesize) @@ -124,7 +124,7 @@ class AcquireProgress(apt.progress.base.AcquireProgress, TextProgress): def fail(self, item): """Called when an item is failed.""" - apt.progress.base.AcquireProgress.fail(self, item) + base.AcquireProgress.fail(self, item) if item.owner.status == item.owner.stat_done: self._write(_("Ign ") + item.description) else: @@ -133,7 +133,7 @@ class AcquireProgress(apt.progress.base.AcquireProgress, TextProgress): def fetch(self, item): """Called when some of the item's data is fetched.""" - apt.progress.base.AcquireProgress.fetch(self, item) + base.AcquireProgress.fetch(self, item) # It's complete already (e.g. Hit) if item.owner.complete: return @@ -149,7 +149,7 @@ class AcquireProgress(apt.progress.base.AcquireProgress, TextProgress): """Periodically invoked while the Acquire process is underway. Return False if the user asked to cancel the whole Acquire process.""" - apt.progress.base.AcquireProgress.pulse(self, owner) + base.AcquireProgress.pulse(self, owner) percent = (((self.current_bytes + self.current_items) * 100.0) / float(self.total_bytes + self.total_items)) @@ -209,7 +209,7 @@ class AcquireProgress(apt.progress.base.AcquireProgress, TextProgress): def media_change(self, medium, drive): """Prompt the user to change the inserted removable media.""" - apt.progress.base.AcquireProgress.media_change(self, medium, drive) + base.AcquireProgress.media_change(self, medium, drive) self._write(_("Media change: please insert the disc labeled\n" " '%s'\n" "in the drive '%s' and press enter\n") % (medium, drive)) @@ -217,7 +217,7 @@ class AcquireProgress(apt.progress.base.AcquireProgress, TextProgress): def stop(self): """Invoked when the Acquire process stops running.""" - apt.progress.base.AcquireProgress.stop(self) + base.AcquireProgress.stop(self) # Trick for getting a translation from apt self._write((_("Fetched %sB in %s (%sB/s)\n") % ( apt_pkg.size_to_str(self.fetched_bytes), @@ -229,12 +229,12 @@ class AcquireProgress(apt.progress.base.AcquireProgress, TextProgress): signal.signal(signal.SIGWINCH, self._signal) -class CdromProgress(apt.progress.base.CdromProgress, TextProgress): +class CdromProgress(base.CdromProgress, TextProgress): """Text CD-ROM progress.""" def ask_cdrom_name(self): """Ask the user to provide a name for the disc.""" - apt.progress.base.CdromProgress.ask_cdrom_name(self) + base.CdromProgress.ask_cdrom_name(self) self._write(_("Please provide a name for this Disc, such as " "'Debian 2.1r1 Disk 1'"), False) try: @@ -244,13 +244,13 @@ class CdromProgress(apt.progress.base.CdromProgress, TextProgress): def update(self, text, current): """Set the current progress.""" - apt.progress.base.CdromProgress.update(self, text, current) + base.CdromProgress.update(self, text, current) if text: self._write(text, False) def change_cdrom(self): """Ask the user to change the CD-ROM.""" - apt.progress.base.CdromProgress.change_cdrom(self) + base.CdromProgress.change_cdrom(self) self._write(_("Please insert a Disc in the drive and press enter"), False) try: diff --git a/python/acquireprogress.cc b/python/acquireprogress.cc deleted file mode 100644 index c7db8921..00000000 --- a/python/acquireprogress.cc +++ /dev/null @@ -1,208 +0,0 @@ -/* acquireprogress.cc - Base class for FetchProgress classes. - * - * Copyright 2009 Julian Andres Klode - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301, USA. - */ - -#include "apt_pkgmodule.h" -#include "progress.h" -#include -#include - - - -// DUMMY IMPLEMENTATIONS. -static char *acquireprogress_media_change_doc = - "media_change(media: str, drive: str) -> bool\n\n" - "Invoked when the user should be prompted to change the inserted\n" - "removable media.\n\n" - "This method should not return until the user has confirmed to the user\n" - "interface that the media change is complete.\n\n" - ":param:media The name of the media type that should be changed.\n" - ":param:drive The identifying name of the drive whose media should be\n" - " changed.\n\n" - "Return True if the user confirms the media change, False if it is\n" - "cancelled."; -static PyObject *acquireprogress_media_change(PyObject *self, PyObject *args) -{ - Py_RETURN_FALSE; -} - -static char *acquireprogress_ims_hit_doc = "ims_hit(item: AcquireItemDesc)\n\n" - "Invoked when an item is confirmed to be up-to-date. For instance,\n" - "when an HTTP download is informed that the file on the server was\n" - "not modified."; -static PyObject *acquireprogress_ims_hit(PyObject *self, PyObject *arg) -{ - if (!PyAcquireItemDesc_Check(arg)) { - PyErr_SetString(PyExc_TypeError, "ims_hit() argument must be " - "apt_pkg.AcquireItemDesc"); - return 0; - } - Py_RETURN_NONE; -} - -static char *acquireprogress_fetch_doc = "fetch(item: AcquireItemDesc)\n\n" - "Invoked when some of an item's data is fetched."; -static PyObject *acquireprogress_fetch(PyObject *self, PyObject *arg) -{ - if (!PyAcquireItemDesc_Check(arg)) { - PyErr_SetString(PyExc_TypeError, "fetch() argument must be " - "apt_pkg.AcquireItemDesc"); - return 0; - } - Py_RETURN_NONE; -} - -static char *acquireprogress_done_doc = "done(item: AcquireItemDesc)\n\n" - "Invoked when an item is successfully and completely fetched."; -static PyObject *acquireprogress_done(PyObject *self, PyObject *arg) -{ - if (!PyAcquireItemDesc_Check(arg)) { - PyErr_SetString(PyExc_TypeError, "done() argument must be " - "apt_pkg.AcquireItemDesc"); - return 0; - } - Py_RETURN_NONE; -} - -static char *acquireprogress_fail_doc = "fail(item: AcquireItemDesc)\n\n" - "Invoked when the process of fetching an item encounters a fatal error."; -static PyObject *acquireprogress_fail(PyObject *self, PyObject *arg) -{ - if (!PyAcquireItemDesc_Check(arg)) { - PyErr_SetString(PyExc_TypeError, "fail() argument must be " - "apt_pkg.AcquireItemDesc"); - return 0; - } - Py_RETURN_NONE; -} - -static char *acquireprogress_pulse_doc = "pulse(owner: Acquire) -> bool\n\n" - "Periodically invoked while the Acquire process is underway.\n\n" - "Return False if the user asked to cancel the whole Acquire process."; -static PyObject *acquireprogress_pulse(PyObject *self, PyObject *arg) -{ - if (!PyAcquire_Check(arg)) { - PyErr_SetString(PyExc_TypeError, "pulse() argument must be " - "apt_pkg.Acquire"); - return 0; - } - Py_RETURN_TRUE; -} - -static char *acquireprogress_start_doc = "start()\n\n" - "Invoked when the Acquire process starts running."; -static PyObject *acquireprogress_start(PyObject *self, PyObject *args) -{ - Py_RETURN_NONE; -} - -static char *acquireprogress_stop_doc = "stop()\n\n" - "Invoked when the Acquire process stops running."; -static PyObject *acquireprogress_stop(PyObject *self, PyObject *args) -{ - Py_RETURN_NONE; -} - -static PyMethodDef acquireprogress_methods[] = { - {"media_change", acquireprogress_media_change, METH_VARARGS, - acquireprogress_media_change_doc}, - {"ims_hit",acquireprogress_ims_hit,METH_O, - acquireprogress_ims_hit_doc}, - {"fetch",acquireprogress_fetch,METH_O,acquireprogress_fetch_doc}, - {"done",acquireprogress_done,METH_O,acquireprogress_done_doc}, - {"fail",acquireprogress_fail,METH_O,acquireprogress_fail_doc}, - {"pulse",acquireprogress_pulse,METH_O,acquireprogress_pulse_doc}, - {"start",acquireprogress_start,METH_NOARGS,acquireprogress_start_doc}, - {"stop",acquireprogress_stop,METH_NOARGS,acquireprogress_stop_doc}, - {NULL} -}; - -static PyMemberDef acquireprogress_members[] = { - {"last_bytes", T_DOUBLE, offsetof(PyAcquireProgressObject, last_bytes), 0, - "The number of bytes fetched as of the previous call to pulse(),\n" - "including local items."}, - {"current_cps", T_DOUBLE, offsetof(PyAcquireProgressObject, current_cps), 0, - "The current rate of download, in bytes per second."}, - {"current_bytes", T_DOUBLE, offsetof(PyAcquireProgressObject, current_bytes), - 0, "The number of bytes fetched."}, - {"total_bytes", T_DOUBLE, offsetof(PyAcquireProgressObject, total_bytes), 0, - "The total number of bytes that need to be fetched. This member is\n" - "inaccurate, as new items might be enqueued while the download is\n" - "in progress!"}, - {"fetched_bytes", T_DOUBLE,offsetof(PyAcquireProgressObject, fetched_bytes), - 0, "The total number of bytes accounted for by items that were\n" - "successfully fetched."}, - {"elapsed_time", T_ULONG, offsetof(PyAcquireProgressObject, elapsed_time),0, - "The amount of time that has elapsed since the download started."}, - {"total_items", T_ULONG, offsetof(PyAcquireProgressObject, total_items),0, - "The total number of items that need to be fetched. This member is\n" - "inaccurate, as new items might be enqueued while the download is\n" - "in progress!"}, - {"current_items", T_ULONG, offsetof(PyAcquireProgressObject, current_items), - 0, "The number of items that have been successfully downloaded."}, - {NULL} -}; - -static char *acquireprogress_doc = "AcquireProgress()\n\n" - "A monitor object for downloads controlled by the Acquire class. This is\n" - "an mostly abstract class. You should subclass it and implement the\n" - "methods to get something useful."; - -PyTypeObject PyAcquireProgress_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "apt_pkg.AcquireProgress", // tp_name - sizeof(PyAcquireProgressObject), // tp_basicsize - 0, // tp_itemsize - // Methods - 0, // tp_dealloc - 0, // tp_print - 0, // tp_getattr - 0, // tp_setattr - 0, // tp_compare - 0, // tp_repr - 0, // tp_as_number - 0, // tp_as_sequence - 0, // tp_as_mapping - 0, // tp_hash - 0, // tp_call - 0, // tp_str - 0, // tp_getattro - 0, // tp_setattro - 0, // tp_as_buffer - Py_TPFLAGS_DEFAULT | // tp_flags - Py_TPFLAGS_BASETYPE, - acquireprogress_doc, // tp_doc - 0, // tp_traverse - 0, // tp_clear - 0, // tp_richcompare - 0, // tp_weaklistoffset - 0, // tp_iter - 0, // tp_iternext - acquireprogress_methods, // tp_methods - acquireprogress_members, // tp_members - 0, // tp_getset - 0, // tp_base - 0, // tp_dict - 0, // tp_descr_get - 0, // tp_descr_set - 0, // tp_dictoffset - 0, // tp_init - 0, // tp_alloc - PyType_GenericNew, // tp_new -}; diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index d53f64a6..faea423f 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -653,10 +653,7 @@ extern "C" void initapt_pkg() ADDTYPE(Module,"HashString",&PyHashString_Type); ADDTYPE(Module,"Policy",&PyPolicy_Type); ADDTYPE(Module,"Hashes",&PyHashes_Type); - ADDTYPE(Module,"OpProgress",&PyOpProgress_Type); - ADDTYPE(Module,"AcquireProgress",&PyAcquireProgress_Type); ADDTYPE(Module,"AcquireItemDesc",&PyAcquireItemDesc_Type); - ADDTYPE(Module,"CdromProgress",&PyCdromProgress_Type); ADDTYPE(Module,"SystemLock",&PySystemLock_Type); ADDTYPE(Module,"FileLock",&PyFileLock_Type); // Tag file constants diff --git a/python/apt_pkgmodule.h b/python/apt_pkgmodule.h index 3edba5d2..97ba05a7 100644 --- a/python/apt_pkgmodule.h +++ b/python/apt_pkgmodule.h @@ -117,9 +117,6 @@ extern PyTypeObject PyIndexRecords_Type; // Policy extern PyTypeObject PyPolicy_Type; extern PyTypeObject PyHashes_Type; -extern PyTypeObject PyOpProgress_Type; -extern PyTypeObject PyAcquireProgress_Type; -extern PyTypeObject PyCdromProgress_Type; extern PyTypeObject PyAcquireItemDesc_Type; extern PyTypeObject PyAcquireWorker_Type; extern PyTypeObject PySystemLock_Type; diff --git a/python/cache.cc b/python/cache.cc index 68ee7b9e..593bc1c2 100644 --- a/python/cache.cc +++ b/python/cache.cc @@ -246,15 +246,9 @@ static PyObject *PkgCacheNew(PyTypeObject *type,PyObject *Args,PyObject *kwds) PyObject *pyCallbackInst = 0; char *kwlist[] = {"progress", 0}; - #ifdef COMPAT_0_7 if (PyArg_ParseTupleAndKeywords(Args, kwds, "|O", kwlist, &pyCallbackInst) == 0) return 0; - #else - if (PyArg_ParseTupleAndKeywords(Args, kwds, "|O!", kwlist, - &PyOpProgress_Type, &pyCallbackInst) == 0) - return 0; - #endif if (_system == 0) { PyErr_SetString(PyExc_ValueError,"_system not initialized"); diff --git a/python/cdrom.cc b/python/cdrom.cc index 2270b01c..4195c9cb 100644 --- a/python/cdrom.cc +++ b/python/cdrom.cc @@ -57,8 +57,7 @@ static PyObject *cdrom_ident(PyObject *Self,PyObject *Args) { pkgCdrom &Cdrom = GetCpp(Self); PyObject *pyCdromProgressInst = 0; - if (PyArg_ParseTuple(Args, "O!", &PyCdromProgress_Type, - &pyCdromProgressInst) == 0) { + if (PyArg_ParseTuple(Args, "O", &pyCdromProgressInst) == 0) { return 0; } diff --git a/python/cdromprogress.cc b/python/cdromprogress.cc deleted file mode 100644 index 440b5ce6..00000000 --- a/python/cdromprogress.cc +++ /dev/null @@ -1,106 +0,0 @@ -/* cdromprogress.cc - Base class for CdromProgress classes. - * - * Copyright 2009 Julian Andres Klode - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301, USA. - */ -#include "apt_pkgmodule.h" -#include "progress.h" -#include -#include - -// Takes two arguments (string, int) -static PyObject *cdromprogress_update(PyObject *self, PyObject *args) -{ - Py_RETURN_NONE; -} - -// Takes no arguments -static PyObject *cdromprogress_change_cdrom(PyObject *self, PyObject *args) -{ - Py_RETURN_FALSE; -} - -// Takes a single PyObject argument as *arg -static PyObject *cdromprogress_ask_cdrom_name(PyObject *self, PyObject *arg) -{ - Py_RETURN_NONE; -} - -static PyMethodDef cdromprogress_methods[] = { - {"update",cdromprogress_update,METH_VARARGS, - "update(text: str, current: int)\n\nCalled regularly."}, - {"change_cdrom",cdromprogress_change_cdrom,METH_NOARGS, - "change_cdrom() -> bool\n\nAsk for the CD-ROM to be changed.\n" - "Return False if the user requested to cancel the action (default)."}, - {"ask_cdrom_name",cdromprogress_ask_cdrom_name,METH_O, - "ask_cdrom_name() -> str\n\nAsk for the name of the CD-ROM.\n" - "Return None if the user requested to cancel the action (default)."}, - {NULL} -}; - -static PyMemberDef cdromprogress_members[] = { - {"total_steps", T_INT, offsetof(PyCdromProgressObject,total_steps), 0, - "The number of total steps to be taken."}, - {NULL} -}; - -static char *cdromprogress_doc = "CdromProgress()\n\n" - "Base class for reporting the progress of adding a cdrom. Can be used\n" - "with apt_pkg.Cdrom to produce an utility like apt-cdrom."; - -PyTypeObject PyCdromProgress_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "apt_pkg.CdromProgress", // tp_name - sizeof(PyCdromProgressObject), // tp_basicsize - 0, // tp_itemsize - // Methods - 0, // tp_dealloc - 0, // tp_print - 0, // tp_getattr - 0, // tp_setattr - 0, // tp_compare - 0, // tp_repr - 0, // tp_as_number - 0, // tp_as_sequence - 0, // tp_as_mapping - 0, // tp_hash - 0, // tp_call - 0, // tp_str - 0, // tp_getattro - 0, // tp_setattro - 0, // tp_as_buffer - Py_TPFLAGS_DEFAULT | // tp_flags - Py_TPFLAGS_BASETYPE, - cdromprogress_doc, // tp_doc - 0, // tp_traverse - 0, // tp_clear - 0, // tp_richcompare - 0, // tp_weaklistoffset - 0, // tp_iter - 0, // tp_iternext - cdromprogress_methods, // tp_methods - cdromprogress_members, // tp_members - 0, // tp_getset - 0, // tp_base - 0, // tp_dict - 0, // tp_descr_get - 0, // tp_descr_set - 0, // tp_dictoffset - 0, // tp_init - 0, // tp_alloc - PyType_GenericNew, // tp_new -}; diff --git a/python/opprogress.cc b/python/opprogress.cc deleted file mode 100644 index 2ee6a03e..00000000 --- a/python/opprogress.cc +++ /dev/null @@ -1,175 +0,0 @@ -/* op-progress.cc - Base class for OpProgress classes. - * - * Copyright 2009 Julian Andres Klode - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301, USA. - */ - -#include "generic.h" -#include "progress.h" -#include -#include - - - -static PyObject *opprogress_update(PyObject *Self, PyObject *args) -{ - Py_RETURN_NONE; -} - -static PyObject *opprogress_done(PyObject *Self, PyObject *args) -{ - Py_RETURN_NONE; -} - -static PyObject *opprogress_get_op(PyOpProgressObject *self, void *closure) -{ - Py_INCREF(self->op); - return self->op; -} - -static int opprogress_set_op(PyOpProgressObject *self, PyObject *value, - void *closure) -{ - if (value == NULL) { - PyErr_SetString(PyExc_TypeError, "Cannot delete 'op'"); - return -1; - } - if (!PyString_Check(value)) { - PyErr_SetString(PyExc_TypeError,"'op' must be a string."); - return -1; - } - Py_DECREF(self->op); - Py_INCREF(value); - - self->op = value; - return 0; -} - -static PyObject *opprogress_get_subop(PyOpProgressObject *self, void *closure) -{ - Py_INCREF(self->subop); - return self->subop; -} - -static int opprogress_set_subop(PyOpProgressObject *self, PyObject *value, - void *closure) -{ - if (value == NULL) { - PyErr_SetString(PyExc_TypeError, "Cannot delete 'subop'."); - return -1; - } - if (!PyString_Check(value)) { - PyErr_SetString(PyExc_TypeError,"'subop' must be a string."); - return -1; - } - Py_DECREF(self->subop); - Py_INCREF(value); - self->subop = value; - return 0; -} - -static PyMethodDef opprogress_methods[] = { - {"update",opprogress_update,METH_NOARGS,"update()\n\nCalled periodically."}, - {"done",opprogress_done,METH_NOARGS,"update()\n\nCalled when done."}, - {NULL}, -}; - -#ifndef T_BOOL -# define _T_BOOL T_INT -#else -# define _T_BOOL T_BOOL -#endif -static PyMemberDef opprogress_members[] = { - {"major_change", _T_BOOL, offsetof(PyOpProgressObject, major_change), 0, - "Boolean value indicating whether the change is a major change."}, - {"percent", T_FLOAT, offsetof(PyOpProgressObject, percent), 0, - "Percentage of completion (float value)."}, - {NULL} -}; - -static PyGetSetDef opprogress_getset[] = { - {"op", (getter)opprogress_get_op, (setter)opprogress_set_op, - "Description of the current operation"}, - {"subop", (getter)opprogress_get_subop, (setter)opprogress_set_subop, - "Description of the current sub-operation"}, - {NULL}, -}; - -static void opprogress_dealloc(PyObject *self) -{ - Py_XDECREF(((PyOpProgressObject *)self)->op); - Py_XDECREF(((PyOpProgressObject *)self)->subop); - self->ob_type->tp_free(self); -} - -static PyObject *opprogress_new(PyTypeObject *type, PyObject *args, - PyObject *kwds) -{ - PyOpProgressObject *res = (PyOpProgressObject *)type->tp_alloc(type, 0); - res->op = PyString_FromString(""); - res->subop = PyString_FromString(""); - return (PyObject *)res; -} - -static char *opprogress_doc = "OpProgress()\n\n" - "A base class for writing custom operation progress classes. Subclasses\n" - "should override all the methods (and call the parent ones) but shall\n" - "not override any of the inherited descriptors because they may be\n" - "ignored."; - -PyTypeObject PyOpProgress_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "apt_pkg.OpProgress", // tp_name - sizeof(PyOpProgressObject), // tp_basicsize - 0, // tp_itemsize - // Methods - opprogress_dealloc, // tp_dealloc - 0, // tp_print - 0, // tp_getattr - 0, // tp_setattr - 0, // tp_compare - 0, // tp_repr - 0, // tp_as_number - 0, // tp_as_sequence - 0, // tp_as_mapping - 0, // tp_hash - 0, // tp_call - 0, // tp_str - 0, // tp_getattro - 0, // tp_setattro - 0, // tp_as_buffer - Py_TPFLAGS_DEFAULT | // tp_flags - Py_TPFLAGS_BASETYPE, - opprogress_doc, // tp_doc - 0, // tp_traverse - 0, // tp_clear - 0, // tp_richcompare - 0, // tp_weaklistoffset - 0, // tp_iter - 0, // tp_iternext - opprogress_methods, // tp_methods - opprogress_members, // tp_members - opprogress_getset, // tp_getset - 0, // tp_base - 0, // tp_dict - 0, // tp_descr_get - 0, // tp_descr_set - 0, // tp_dictoffset - 0, // tp_init - 0, // tp_alloc - opprogress_new, // tp_new -}; diff --git a/python/progress.h b/python/progress.h index bc1bd640..80cb2785 100644 --- a/python/progress.h +++ b/python/progress.h @@ -32,38 +32,6 @@ #define PyCbObj_BLOCK_THREADS Py_BLOCK_THREADS #define PyCbObj_UNBLOCK_THREADS Py_UNBLOCK_THREADS -typedef struct { - PyObject_HEAD - PyObject *op; - PyObject *subop; -#ifdef T_BOOL - char major_change; -#else - int major_change; -#endif - float percent; -} PyOpProgressObject; - - -typedef struct { - PyObject_HEAD - int total_steps; -} PyCdromProgressObject; - -typedef struct { - PyObject_HEAD - double last_bytes; - double current_cps; - double current_bytes; - double total_bytes; - double fetched_bytes; - unsigned long elapsed_time; - unsigned long total_items; - unsigned long current_items; -} PyAcquireProgressObject; - - - class PyCallbackObj { protected: PyObject *callbackInst; diff --git a/setup.py b/setup.py index 93fcb436..9b33ed5d 100644 --- a/setup.py +++ b/setup.py @@ -35,9 +35,8 @@ files = ['apt_pkgmodule.cc', 'acquire.cc', 'cache.cc', 'cdrom.cc', 'hashstring.cc', 'indexfile.cc', 'indexrecords.cc', 'metaindex.cc', 'pkgmanager.cc', 'pkgrecords.cc', 'pkgsrcrecords.cc', 'policy.cc', 'progress.cc', 'sourcelist.cc', 'string.cc', 'tag.cc', - 'opprogress.cc', 'acquireprogress.cc', 'cdromprogress.cc', 'lock.cc', - 'acquire-item.cc'] -files = sorted(['python/' + fname for fname in files]) + 'lock.cc', 'acquire-item.cc'] +files = sorted(['python/' + fname for fname in files], key=lambda s: s[:-3]) apt_pkg = Extension("apt_pkg", files, libraries=["apt-pkg"]) # The apt_inst module -- cgit v1.2.3 From e526904d0440e720cbeebf895faf884717f3fbb3 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Fri, 7 Aug 2009 17:47:25 +0200 Subject: python/arfile.cc: Introduce apt_inst.ArArchive and apt_inst.ArMember. This is part one of wishlist Bug#536096, introducing classes in apt_inst. --- python/apt_instmodule.cc | 31 ++++- python/apt_instmodule.h | 4 + python/arfile.cc | 323 +++++++++++++++++++++++++++++++++++++++++++++++ python/generic.h | 1 + setup.py | 3 +- 5 files changed, 354 insertions(+), 8 deletions(-) create mode 100644 python/arfile.cc (limited to 'python') diff --git a/python/apt_instmodule.cc b/python/apt_instmodule.cc index 5aca4e00..aedccb47 100644 --- a/python/apt_instmodule.cc +++ b/python/apt_instmodule.cc @@ -169,11 +169,22 @@ static PyMethodDef methods[] = {} }; + +static const char *apt_inst_doc = + "Functions for working with AR,tar archives and .deb packages.\n\n" + "This module provides useful classes and functions to work with\n" + "archives, modelled after the 'TarFile' class in the 'tarfile' module."; +#define ADDTYPE(mod,name,type) { \ + if (PyType_Ready(type) == -1) RETURN(0); \ + Py_INCREF(type); \ + PyModule_AddObject(mod,name,(PyObject *)type); } + + #if PY_MAJOR_VERSION >= 3 static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "apt_inst", - "Functions for working with packages and ar,tar archives (apt-inst)", + apt_inst_doc, -1, methods, 0, @@ -181,14 +192,20 @@ static struct PyModuleDef moduledef = { 0, 0 }; - +#define RETURN(x) return x extern "C" PyObject * PyInit_apt_inst() -{ - return PyModule_Create(&moduledef); -} #else extern "C" void initapt_inst() +#define RETURN(x) +#endif { - Py_InitModule("apt_inst",methods); +#if PY_MAJOR_VERSION >= 3 + PyObject *module = PyModule_Create(&moduledef); +#else + PyObject *module = Py_InitModule3("apt_inst",methods, apt_inst_doc); +#endif + + ADDTYPE(module,"ArMember",&PyArMember_Type); + ADDTYPE(module,"ArArchive",&PyArArchive_Type); + RETURN(module); } -#endif /*}}}*/ diff --git a/python/apt_instmodule.h b/python/apt_instmodule.h index 45ba5f85..e06e344d 100644 --- a/python/apt_instmodule.h +++ b/python/apt_instmodule.h @@ -17,4 +17,8 @@ extern char *doc_debExtract; PyObject *tarExtract(PyObject *Self,PyObject *Args); extern char *doc_tarExtract; + +extern PyTypeObject PyArMember_Type; +extern PyTypeObject PyArArchive_Type; + #endif diff --git a/python/arfile.cc b/python/arfile.cc new file mode 100644 index 00000000..368fb17c --- /dev/null +++ b/python/arfile.cc @@ -0,0 +1,323 @@ +/* + * arfile.cc - Wrapper around ARArchive and ARArchive::Member. + * + * Copyright 2009 Julian Andres Klode + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + */ + +#include +#include "generic.h" +#include +#include + +PyObject *armember_get_name(PyObject *self, void *closure) +{ + return CppPyString(GetCpp(self)->Name); +} + +PyObject *armember_get_mtime(PyObject *self, void *closure) +{ + return Py_BuildValue("k", GetCpp(self)->MTime); +} + +PyObject *armember_get_uid(PyObject *self, void *closure) +{ + return Py_BuildValue("k", GetCpp(self)->UID); +} + +PyObject *armember_get_gid(PyObject *self, void *closure) +{ + return Py_BuildValue("k", GetCpp(self)->GID); +} + +PyObject *armember_get_mode(PyObject *self, void *closure) +{ + return Py_BuildValue("k", GetCpp(self)->Mode); +} + +PyObject *armember_get_size(PyObject *self, void *closure) +{ + return Py_BuildValue("k", GetCpp(self)->Size); +} + +PyObject *armember_get_start(PyObject *self, void *closure) +{ + return Py_BuildValue("k", GetCpp(self)->Start); +} + +PyGetSetDef armember_getset[] = { + {"gid",armember_get_gid,0,"The group id of the owner."}, + {"mode",armember_get_mode,0,"The mode of the file."}, + {"mtime",armember_get_mtime,0,"Last time of modification."}, + {"name",armember_get_name,0,"The name of the file."}, + {"size",armember_get_size,0,"The size of the files."}, + {"start",armember_get_start,0, + "The offset in the archive where the file starts."}, + {"uid",armember_get_uid,0,"The user id of the owner."}, + {NULL} +}; + +static const char *armember_doc = + "An ArMember object represents a single file within an AR archive. For\n" + "Debian packages this can be e.g. control.tar.gz. This class provides\n" + "information about this file, such as the mode and size."; +PyTypeObject PyArMember_Type = { + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "apt_inst.ArMember", // tp_name + sizeof(CppOwnedPyObject), // tp_basicsize + 0, // tp_itemsize + // Methods + CppOwnedDeallocPtr, // tp_dealloc + 0, // tp_print + 0, // tp_getattr + 0, // tp_setattr + 0, // tp_compare + 0, // tp_repr + 0, // tp_as_number + 0, // tp_as_sequence + 0, // tp_as_mapping + 0, // tp_hash + 0, // tp_call + 0, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + Py_TPFLAGS_DEFAULT | // tp_flags + Py_TPFLAGS_HAVE_GC, + armember_doc, // tp_doc + CppOwnedTraverse,// tp_traverse + CppOwnedClear, // tp_clear + 0, // tp_richcompare + 0, // tp_weaklistoffset + 0, // tp_iter + 0, // tp_iternext + 0, // tp_methods + 0, // tp_members + armember_getset, // tp_getset +}; + +struct PyArArchiveObject : public CppOwnedPyObject { + FileFd Fd; +}; + +static const char *ararchive_getmember_doc = + "getmember(name: str) -> ArMember\n\n" + "Return a ArMember object for the member given by name. Raise\n" + "LookupError if there is no ArMember with the given name."; +PyObject *ararchive_getmember(PyArArchiveObject *self, PyObject *arg) +{ + const char *name; + CppOwnedPyObject *ret; + if (! (name = PyObject_AsString(arg))) + return 0; + + const ARArchive::Member *member = self->Object->FindMember(name); + if (!member) { + PyErr_Format(PyExc_LookupError,"No member named '%s'",name); + return 0; + } + + // Create our object. + ret = CppOwnedPyObject_NEW(self,&PyArMember_Type); + ret->Object = const_cast(member); + ret->NoDelete = true; + return ret; +} + +static const char *ararchive_getdata_doc = + "getdata(name: str) -> bytes\n\n" + "Return the contents of the member, as a bytes object. Raise\n" + "LookupError if there is no ArMember with the given name."; +PyObject *ararchive_getdata(PyArArchiveObject *self, PyObject *args) +{ + char *name = 0; + if (PyArg_ParseTuple(args, "s:getdata", &name) == 0) + return 0; + const ARArchive::Member *member = self->Object->FindMember(name); + if (!member) { + PyErr_Format(PyExc_LookupError,"No member named '%s'",name); + return 0; + } + if (!self->Fd.Seek(member->Start)) + return HandleErrors(); + + char* value = new char[member->Size]; + self->Fd.Read(value, member->Size, true); + PyObject *result = PyBytes_FromStringAndSize(value, member->Size); + delete[] value; + return result; +} + +static const char *ararchive_extract_doc = + "extract(name: str[, target: str]) -> bool\n\n" + "Extract the member given by name into the directory given by target.\n" + "If the extraction failed, an error is raised. Otherwise, the method\n" + "returns True if the owner could be set or False if the owner could not\n" + "be changed. It may also raise LookupError if there is member with\n" + "the given name."; +PyObject *ararchive_extract(PyArArchiveObject *self, PyObject *args) +{ + char *name = 0; + char *target = ""; + if (PyArg_ParseTuple(args, "s|s:extract", &name, &target) == 0) + return 0; + + const ARArchive::Member *member = self->Object->FindMember(name); + + if (!member) { + PyErr_Format(PyExc_LookupError,"No member named '%s'",name); + return 0; + } + + if (!self->Fd.Seek(member->Start)) + return HandleErrors(); + + // Open the target file + FileFd outfd(flCombine(target,name), FileFd::WriteAny, member->Mode); + if (_error->PendingError() == true) + return HandleErrors(); + + // Temporary buffer. We should probably split this into smaller parts. + char* value = new char[member->Size]; + + // Read into the buffer + if (!self->Fd.Read(value, member->Size, true)) { + delete[] value; + return HandleErrors(); + } + if (!outfd.Write(value, member->Size)) { + delete[] value; + return HandleErrors(); + } + if (fchown(outfd.Fd(), member->UID, member->GID) == -1) { + delete[] value; + Py_RETURN_FALSE; + } + Py_RETURN_TRUE; +} + +PyMethodDef ararchive_methods[] = { + {"getmember",(PyCFunction)ararchive_getmember,METH_O, + ararchive_getmember_doc}, + {"getdata",(PyCFunction)ararchive_getdata,METH_VARARGS, + ararchive_getdata_doc}, + {"extract",(PyCFunction)ararchive_extract,METH_VARARGS, + ararchive_extract_doc}, + {NULL} +}; + +PyObject *ararchive_new(PyTypeObject *type, PyObject *args, PyObject *kwds) +{ + PyObject *file; + PyArArchiveObject *self; + char *filename = 0; + int fileno; + if (PyArg_ParseTuple(args,"O:__new__",&file) == 0) + return 0; + + // We receive a filename. + if ((filename = (char*)PyObject_AsString(file))) { + self = (PyArArchiveObject *)CppOwnedPyObject_NEW(0,type); + new (&self->Fd) FileFd(filename,FileFd::ReadOnly); + } + // We receive a file object. + else if ((fileno = PyObject_AsFileDescriptor(file)) != -1) { + // Clear the error set by PyObject_AsString(). + PyErr_Clear(); + self = (PyArArchiveObject *)CppOwnedPyObject_NEW(file,type); + new (&self->Fd) FileFd(fileno,false); + } + else { + return 0; + } + self->Object = new ARArchive(self->Fd); + if (_error->PendingError() == true) + return HandleErrors(); + return self; +} + +static void ararchive_dealloc(PyObject *self) { + ((PyArArchiveObject *)(self))->Fd.~FileFd(); + CppOwnedDeallocPtr(self); +} + +// Return bool or -1 (exception). +static int ararchive_contains(PyObject *self, PyObject *arg) +{ + const char *name = PyObject_AsString(arg); + if (!name) + return -1; + return (GetCpp(self)->FindMember(name) != 0); +} + +static PySequenceMethods ararchive_as_sequence = + {0,0,0,0,0,0,0,ararchive_contains,0,0}; + +static PyMappingMethods ararchive_as_mapping = + {0,(PyCFunction)ararchive_getmember,0}; + +static const char *ararchive_doc = + "ArArchive(file: str/int/file)\n\n" + "An ArArchive object represents an archive in the 4.4 BSD AR format, \n" + "which is used for e.g. deb packages.\n\n" + "The parameter 'file' may be a string specifying the path of a file, or\n" + "a file-like object providing the fileno() method. It may also be an int\n" + "specifying a file descriptor (returned by e.g. os.open()).\n" + "The recommended way is to pass in the path to the file."; + +PyTypeObject PyArArchive_Type = { + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "apt_inst.ArArchive", // tp_name + sizeof(PyArArchiveObject), // tp_basicsize + 0, // tp_itemsize + // Methods + ararchive_dealloc, // tp_dealloc + 0, // tp_print + 0, // tp_getattr + 0, // tp_setattr + 0, // tp_compare + 0, // tp_repr + 0, // tp_as_number + &ararchive_as_sequence, // tp_as_sequence + &ararchive_as_mapping, // tp_as_mapping + 0, // tp_hash + 0, // tp_call + 0, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + Py_TPFLAGS_DEFAULT | // tp_flags + Py_TPFLAGS_HAVE_GC, + ararchive_doc, // tp_doc + CppOwnedTraverse, // tp_traverse + CppOwnedClear, // tp_clear + 0, // tp_richcompare + 0, // tp_weaklistoffset + 0, // tp_iter + 0, // tp_iternext + ararchive_methods, // tp_methods + 0, // tp_members + 0, // tp_getset + 0, // tp_base + 0, // tp_dict + 0, // tp_descr_get + 0, // tp_descr_set + 0, // tp_dictoffset + 0, // tp_init + 0, // tp_alloc + ararchive_new // tp_new +}; diff --git a/python/generic.h b/python/generic.h index 75520914..d5d6e9fb 100644 --- a/python/generic.h +++ b/python/generic.h @@ -66,6 +66,7 @@ typedef int Py_ssize_t; #define PyBytes_AS_STRING PyString_AS_STRING #define PyBytes_AsString PyString_AsString #define PyBytes_AsStringAndSize PyString_AsStringAndSize +#define PyBytes_FromStringAndSize PyString_FromStringAndSize #define PyVarObject_HEAD_INIT(type, size) PyObject_HEAD_INIT(type) size, #endif #endif diff --git a/setup.py b/setup.py index 9b33ed5d..4eb6987e 100644 --- a/setup.py +++ b/setup.py @@ -40,7 +40,8 @@ files = sorted(['python/' + fname for fname in files], key=lambda s: s[:-3]) apt_pkg = Extension("apt_pkg", files, libraries=["apt-pkg"]) # The apt_inst module -files = ["python/apt_instmodule.cc", "python/generic.cc", "python/tar.cc"] +files = ["python/apt_instmodule.cc", "python/generic.cc", "python/tar.cc", + "python/arfile.cc"] apt_inst = Extension("apt_inst", files, libraries=["apt-pkg", "apt-inst"]) # Replace the leading _ that is used in the templates for translation -- cgit v1.2.3 From 31d95030344c77d97d3245515a861a73732d0c5c Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Sat, 8 Aug 2009 18:57:34 +0200 Subject: python/tarfile.cc: Introduce wrapper around ExtractTar. --- python/apt_instmodule.cc | 2 + python/apt_instmodule.h | 9 ++ python/tarfile.cc | 412 +++++++++++++++++++++++++++++++++++++++++++++++ setup.py | 2 +- 4 files changed, 424 insertions(+), 1 deletion(-) create mode 100644 python/tarfile.cc (limited to 'python') diff --git a/python/apt_instmodule.cc b/python/apt_instmodule.cc index aedccb47..3baaf985 100644 --- a/python/apt_instmodule.cc +++ b/python/apt_instmodule.cc @@ -207,5 +207,7 @@ extern "C" void initapt_inst() ADDTYPE(module,"ArMember",&PyArMember_Type); ADDTYPE(module,"ArArchive",&PyArArchive_Type); + ADDTYPE(module,"TarFile",&PyTarFile_Type); + ADDTYPE(module,"TarMember",&PyTarMember_Type); RETURN(module); } diff --git a/python/apt_instmodule.h b/python/apt_instmodule.h index e06e344d..94ada0f8 100644 --- a/python/apt_instmodule.h +++ b/python/apt_instmodule.h @@ -11,6 +11,8 @@ #define APT_INSTMODULE_H #include +#include "generic.h" +#include PyObject *debExtract(PyObject *Self,PyObject *Args); extern char *doc_debExtract; @@ -20,5 +22,12 @@ extern char *doc_tarExtract; extern PyTypeObject PyArMember_Type; extern PyTypeObject PyArArchive_Type; +extern PyTypeObject PyTarFile_Type; +extern PyTypeObject PyTarMember_Type; + +struct PyTarFileObject : public CppOwnedPyObject { + int min; + FileFd Fd; +}; #endif diff --git a/python/tarfile.cc b/python/tarfile.cc new file mode 100644 index 00000000..f3e11d2b --- /dev/null +++ b/python/tarfile.cc @@ -0,0 +1,412 @@ +/* + * arfile.cc - Wrapper around ExtractTar which behaves like Python's tarfile. + * + * Copyright 2009 Julian Andres Klode + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + */ + +#include "generic.h" +#include "apt_instmodule.h" +#include +#include +#include + +/** + * A subclass of pkgDirStream which calls a Python callback. + * + * This calls a Python callback in FinishedFile() with the Item as the first + * argument and the data as the second argument. + */ +class PyDirStream : public pkgDirStream +{ + +public: + PyObject *callback; + // Set to true if an error occured in the Python callback. + bool error; + // Place where the copy of the data is stored. + char *copy; + + virtual bool DoItem(Item &Itm,int &Fd); + virtual bool FinishedFile(Item &Itm,int Fd); + virtual bool Process(Item &Itm,const unsigned char *Data, + unsigned long Size,unsigned long Pos); + + PyDirStream(PyObject *callback) : callback(callback), error(false), copy(0) { + Py_INCREF(callback); + } + + virtual ~PyDirStream() { + Py_DECREF(callback); + delete[] copy; + } +}; + +bool PyDirStream::DoItem(Item &Itm, int &Fd) +{ + delete[] copy; + copy = new char[Itm.Size]; + Fd = -2; + return true; +} + +bool PyDirStream::Process(Item &Itm,const unsigned char *Data, + unsigned long Size,unsigned long Pos) +{ + memcpy(copy + Pos, Data,Size); + return true; +} + +bool PyDirStream::FinishedFile(Item &Itm,int Fd) +{ + PyObject *py_member = CppOwnedPyObject_NEW(0,&PyTarMember_Type,&Itm); + + ((CppOwnedPyObject*)py_member)->NoDelete = true; + PyObject *py_data = PyBytes_FromStringAndSize(copy, Itm.Size); + PyObject *result = PyObject_CallFunctionObjArgs(callback, py_member, + py_data, 0); + if (result == 0) + error = true; + return (result != 0); +} + +// The tarfile.TarInfo interface for our TarMember class. +static PyObject *tarmember_isblk(PyObject *self, PyObject *args) +{ + return PyBool_FromLong(GetCpp(self)->Type == + pkgDirStream::Item::BlockDevice); +} +static PyObject *tarmember_ischr(PyObject *self, PyObject *args) +{ + return PyBool_FromLong(GetCpp(self)->Type == + pkgDirStream::Item::CharDevice); +} +static PyObject *tarmember_isdev(PyObject *self, PyObject *args) +{ + pkgDirStream::Item::Type_t type = GetCpp(self)->Type; + return PyBool_FromLong(type == pkgDirStream::Item::CharDevice || + type == pkgDirStream::Item::BlockDevice || + type == pkgDirStream::Item::FIFO); +} + +static PyObject *tarmember_isdir(PyObject *self, PyObject *args) +{ + return PyBool_FromLong(GetCpp(self)->Type == + pkgDirStream::Item::Directory); +} + +static PyObject *tarmember_isfifo(PyObject *self, PyObject *args) +{ + return PyBool_FromLong(GetCpp(self)->Type == + pkgDirStream::Item::FIFO); +} + +static PyObject *tarmember_isfile(PyObject *self, PyObject *args) +{ + return PyBool_FromLong(GetCpp(self)->Type == + pkgDirStream::Item::File); +} +static PyObject *tarmember_islnk(PyObject *self, PyObject *args) +{ + return PyBool_FromLong(GetCpp(self)->Type == + pkgDirStream::Item::HardLink); +} +static PyObject *tarmember_isreg(PyObject *self, PyObject *args) +{ + return tarmember_isfile(self, NULL); +} +static PyObject *tarmember_issym(PyObject *self, PyObject *args) +{ + return PyBool_FromLong(GetCpp(self)->Type == + pkgDirStream::Item::SymbolicLink); +} + +static PyObject *tarmember_get_name(PyObject *self, void *closure) +{ + return PyString_FromString(GetCpp(self)->Name); +} + +static PyObject *tarmember_get_linkname(PyObject *self, void *closure) +{ + return Safe_FromString(GetCpp(self)->LinkTarget); +} + +static PyObject *tarmember_get_mode(PyObject *self, void *closure) +{ + return Py_BuildValue("k", GetCpp(self)->Mode); +} + +static PyObject *tarmember_get_uid(PyObject *self, void *closure) +{ + return Py_BuildValue("k", GetCpp(self)->UID); +} +static PyObject *tarmember_get_gid(PyObject *self, void *closure) +{ + return Py_BuildValue("k", GetCpp(self)->GID); +} +static PyObject *tarmember_get_size(PyObject *self, void *closure) +{ + return Py_BuildValue("k", GetCpp(self)->Size); +} + +static PyObject *tarmember_get_mtime(PyObject *self, void *closure) +{ + return Py_BuildValue("k", GetCpp(self)->MTime); +} + +static PyObject *tarmember_get_major(PyObject *self, void *closure) +{ + return Py_BuildValue("k", GetCpp(self)->Major); +} + +static PyObject *tarmember_get_minor(PyObject *self, void *closure) +{ + return Py_BuildValue("k", GetCpp(self)->Minor); +} + +static PyObject *tarmember_repr(PyObject *self) +{ + return PyString_FromFormat("<%s object: name:'%s'>", + self->ob_type->tp_name, + GetCpp(self)->Name); + +} + + +static PyMethodDef tarmember_methods[] = { + {"isblk",tarmember_isblk,METH_NOARGS, + "Determine whether the member is a block device."}, + {"ischr",tarmember_ischr,METH_NOARGS, + "Determine whether the member is a character device."}, + {"isdev",tarmember_isdev,METH_NOARGS, + "Determine whether the member is a device (block,character or FIFO)."}, + {"isdir",tarmember_isdir,METH_NOARGS, + "Determine whether the member is a directory."}, + {"isfifo",tarmember_isfifo,METH_NOARGS, + "Determine whether the member is a FIFO."}, + {"isfile",tarmember_isfile,METH_NOARGS, + "Determine whether the member is a regular file."}, + {"islnk",tarmember_islnk,METH_NOARGS, + "Determine whether the member is a hardlink."}, + {"isreg",tarmember_isreg,METH_NOARGS, + "Determine whether the member is a regular file, same as isfile()."}, + {"issym",tarmember_issym,METH_NOARGS, + "Determine whether the member is a symbolic link."}, + {NULL} +}; + +static PyGetSetDef tarmember_getset[] = { + {"gid",tarmember_get_gid,0,"The owner's group id"}, + {"linkname",tarmember_get_linkname,0,"The target of the link."}, + {"major",tarmember_get_major,0,"The major ID of the device."}, + {"minor",tarmember_get_minor,0,"The minor ID of the device."}, + {"mode",tarmember_get_mode,0,"The mode (permissions)."}, + {"mtime",tarmember_get_mtime,0,"Last time of modification."}, + {"name",tarmember_get_name,0,"The name of the file."}, + {"size",tarmember_get_size,0,"The size of the file."}, + {"uid",tarmember_get_uid,0,"The owner's user id."}, + {NULL} +}; + +static const char *tarmember_doc = + "Represent a single member of a 'tar' archive.\n\n" + "This class, which has been modelled after 'tarfile.TarInfo', represents\n" + "information about a given member in an archive."; +PyTypeObject PyTarMember_Type = { + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "apt_inst.TarMember", // tp_name + sizeof(CppOwnedPyObject), // tp_basicsize + 0, // tp_itemsize + // Methods + CppOwnedDealloc, // tp_dealloc + 0, // tp_print + 0, // tp_getattr + 0, // tp_setattr + 0, // tp_compare + tarmember_repr, // tp_repr + 0, // tp_as_number + 0, // tp_as_sequence + 0, // tp_as_mapping + 0, // tp_hash + 0, // tp_call + 0, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + Py_TPFLAGS_DEFAULT | // tp_flags + Py_TPFLAGS_HAVE_GC, + tarmember_doc, // tp_doc + CppOwnedTraverse, // tp_traverse + CppOwnedClear, // tp_clear + 0, // tp_richcompare + 0, // tp_weaklistoffset + 0, // tp_iter + 0, // tp_iternext + tarmember_methods, // tp_methods + 0, // tp_members + tarmember_getset // tp_getset +}; + + + +static PyObject *tarfile_new(PyTypeObject *type,PyObject *args,PyObject *kwds) +{ + PyObject *file; + PyTarFileObject *self; + char *filename; + int fileno; + int min = 0; + int max = 0xFFFFFFFF; + char *comp = "gzip"; + + static char *kwlist[] = {"file","min","max","comp",NULL}; + if (PyArg_ParseTupleAndKeywords(args, kwds, "O|iis", kwlist, &file, &min, + &max,&comp) == 0) + return 0; + + self = (PyTarFileObject*)CppOwnedPyObject_NEW(file,type); + + // We receive a filename. + if ((filename = (char*)PyObject_AsString(file))) + new (&self->Fd) FileFd(filename,FileFd::ReadOnly); + else if ((fileno = PyObject_AsFileDescriptor(file)) != -1) { + // clear the error set by PyObject_AsString(). + PyErr_Clear(); + new (&self->Fd) FileFd(fileno,false); + } + else { + Py_DECREF(self); + return 0; + } + + self->min = min; + self->Object = new ExtractTar(self->Fd,max,comp); + if (_error->PendingError() == true) + return HandleErrors(self); + return self; +} + +static const char *tarfile_extractall_doc = + "extractall([rootdir: str]) -> True\n\n" + "Extract the archive in the current directory. The argument 'rootdir'\n" + "can be used to change the target directory."; +static PyObject *tarfile_extractall(PyObject *self, PyObject *args) +{ + string cwd = SafeGetCWD(); + char *rootdir = 0; + if (PyArg_ParseTuple(args,"|s:extractall",&rootdir) == 0) + return 0; + + if (rootdir) { + if (chdir(rootdir) == -1) + return PyErr_SetFromErrnoWithFilename(PyExc_OSError, rootdir); + } + + pkgDirStream Extract; + + ((PyTarFileObject*)self)->Fd.Seek(((PyTarFileObject*)self)->min); + bool res = GetCpp(self)->Go(Extract); + + + + if (rootdir) { + if (chdir(cwd.c_str()) == -1) + return PyErr_SetFromErrnoWithFilename(PyExc_OSError, + (char*)cwd.c_str()); + } + return HandleErrors(PyBool_FromLong(res)); +} + +static const char *tarfile_go_doc = + "go(callback: callable) -> True\n\n" + "Go through the archive and call the callable callback for each\n" + "member with 2 arguments. The first argument is the TarMember and\n" + "the second one is the data, as bytes."; +static PyObject *tarfile_go(PyObject *self, PyObject *arg) +{ + pkgDirStream Extract; + PyDirStream stream(arg); + ((PyTarFileObject*)self)->Fd.Seek(((PyTarFileObject*)self)->min); + bool res = GetCpp(self)->Go(stream); + if (stream.error) + return 0; + return HandleErrors(PyBool_FromLong(res)); +} + +static PyMethodDef tarfile_methods[] = { + {"extractall",tarfile_extractall,METH_VARARGS,tarfile_extractall_doc}, + {"go",tarfile_go,METH_O,tarfile_go_doc}, + {NULL} +}; + +static PyObject *tarfile_repr(PyObject *self) +{ + return PyString_FromFormat("<%s object: %s>", self->ob_type->tp_name, + PyString_AsString(PyObject_Repr(GetOwner(self)))); +} + +static const char *tarfile_doc = + "TarFile(file: str/int/file[, min: int, max: int, comp: str])\n\n" + "The parameter 'file' may be a string specifying the path of a file, or\n" + "a file-like object providing the fileno() method. It may also be an int\n" + "specifying a file descriptor (returned by e.g. os.open()).\n\n" + "The parameter 'min' describes the offset in the file where the archive\n" + "begins and the parameter 'max' is the size of the archive.\n\n" + "The compression of the archive is set by the parameter 'comp'. It can\n" + "be set to any program supporting the -d switch, the default being gzip."; +PyTypeObject PyTarFile_Type = { + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "apt_inst.TarFile", // tp_name + sizeof(PyTarFileObject), // tp_basicsize + 0, // tp_itemsize + // Methods + CppOwnedDealloc, // tp_dealloc + 0, // tp_print + 0, // tp_getattr + 0, // tp_setattr + 0, // tp_compare + tarfile_repr, // tp_repr + 0, // tp_as_number + 0, // tp_as_sequence + 0, // tp_as_mapping + 0, // tp_hash + 0, // tp_call + 0, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + Py_TPFLAGS_DEFAULT | // tp_flags + Py_TPFLAGS_HAVE_GC, + tarfile_doc, // tp_doc + CppOwnedTraverse, // tp_traverse + CppOwnedClear, // tp_clear + 0, // tp_richcompare + 0, // tp_weaklistoffset + 0, // tp_iter + 0, // tp_iternext + tarfile_methods, // tp_methods + 0, // tp_members + 0, // tp_getset + 0, // tp_base + 0, // tp_dict + 0, // tp_descr_get + 0, // tp_descr_set + 0, // tp_dictoffset + 0, // tp_init + 0, // tp_alloc + tarfile_new // tp_new +}; diff --git a/setup.py b/setup.py index 4eb6987e..635fee9b 100644 --- a/setup.py +++ b/setup.py @@ -41,7 +41,7 @@ apt_pkg = Extension("apt_pkg", files, libraries=["apt-pkg"]) # The apt_inst module files = ["python/apt_instmodule.cc", "python/generic.cc", "python/tar.cc", - "python/arfile.cc"] + "python/arfile.cc", "python/tarfile.cc"] apt_inst = Extension("apt_inst", files, libraries=["apt-pkg", "apt-inst"]) # Replace the leading _ that is used in the templates for translation -- cgit v1.2.3 From e4ea031d3338a6c9894b3bd4115fbb852c5f0eee Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Sat, 8 Aug 2009 19:21:40 +0200 Subject: python/arfile.cc: Add ArArchive.getmembers(),getnames() and gettar(). A small hack made it possible to get the list of members from the ARArchive. --- python/arfile.cc | 126 ++++++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 107 insertions(+), 19 deletions(-) (limited to 'python') diff --git a/python/arfile.cc b/python/arfile.cc index 368fb17c..1185c16a 100644 --- a/python/arfile.cc +++ b/python/arfile.cc @@ -21,6 +21,7 @@ #include #include "generic.h" +#include "apt_instmodule.h" #include #include @@ -59,6 +60,13 @@ PyObject *armember_get_start(PyObject *self, void *closure) return Py_BuildValue("k", GetCpp(self)->Start); } +PyObject *armember_repr(PyObject *self) +{ + return PyString_FromFormat("<%s object: name:'%s'>", + self->ob_type->tp_name, + GetCpp(self)->Name.c_str()); +} + PyGetSetDef armember_getset[] = { {"gid",armember_get_gid,0,"The group id of the owner."}, {"mode",armember_get_mode,0,"The mode of the file."}, @@ -86,10 +94,10 @@ PyTypeObject PyArMember_Type = { 0, // tp_getattr 0, // tp_setattr 0, // tp_compare - 0, // tp_repr + armember_repr, // tp_repr 0, // tp_as_number 0, // tp_as_sequence - 0, // tp_as_mapping + 0, // tp_as_mapping 0, // tp_hash 0, // tp_call 0, // tp_str @@ -110,14 +118,24 @@ PyTypeObject PyArMember_Type = { armember_getset, // tp_getset }; -struct PyArArchiveObject : public CppOwnedPyObject { +// We just add an inline method and should thus be ABI compatible in a way that +// we can simply cast ARArchive instances to PyARArchiveHack. +class PyARArchiveHack : public ARArchive +{ +public: + inline Member *Members() { + return List; + } +}; + +struct PyArArchiveObject : public CppOwnedPyObject { FileFd Fd; }; static const char *ararchive_getmember_doc = - "getmember(name: str) -> ArMember\n\n" - "Return a ArMember object for the member given by name. Raise\n" - "LookupError if there is no ArMember with the given name."; + "getmember(name: str) -> ArMember\n\n" + "Return a ArMember object for the member given by name. Raise\n" + "LookupError if there is no ArMember with the given name."; PyObject *ararchive_getmember(PyArArchiveObject *self, PyObject *arg) { const char *name; @@ -140,8 +158,8 @@ PyObject *ararchive_getmember(PyArArchiveObject *self, PyObject *arg) static const char *ararchive_getdata_doc = "getdata(name: str) -> bytes\n\n" - "Return the contents of the member, as a bytes object. Raise\n" - "LookupError if there is no ArMember with the given name."; + "Return the contents of the member, as a bytes object. Raise\n" + "LookupError if there is no ArMember with the given name."; PyObject *ararchive_getdata(PyArArchiveObject *self, PyObject *args) { char *name = 0; @@ -164,11 +182,11 @@ PyObject *ararchive_getdata(PyArArchiveObject *self, PyObject *args) static const char *ararchive_extract_doc = "extract(name: str[, target: str]) -> bool\n\n" - "Extract the member given by name into the directory given by target.\n" - "If the extraction failed, an error is raised. Otherwise, the method\n" - "returns True if the owner could be set or False if the owner could not\n" - "be changed. It may also raise LookupError if there is member with\n" - "the given name."; + "Extract the member given by name into the directory given by target.\n" + "If the extraction failed, an error is raised. Otherwise, the method\n" + "returns True if the owner could be set or False if the owner could not\n" + "be changed. It may also raise LookupError if there is member with\n" + "the given name."; PyObject *ararchive_extract(PyArArchiveObject *self, PyObject *args) { char *name = 0; @@ -210,13 +228,80 @@ PyObject *ararchive_extract(PyArArchiveObject *self, PyObject *args) Py_RETURN_TRUE; } +static const char *ararchive_gettar_doc = + "gettar(name: str, comp: str) -> TarFile\n\n" + "Return a TarFile object for the member given by 'name' which will be\n" + "decompressed using the compression algorithm given by 'comp'.\n" + "This is almost equal to:\n\n" + " member = arfile.getmember(name)\n" + " tarfile = TarFile(file, member.start, member.size, 'gzip')'\n\n" + "It just opens a new TarFile on the given position in the stream."; +static PyObject *ararchive_gettar(PyArArchiveObject *self, PyObject *args) +{ + const char *name; + const char *comp; + if (PyArg_ParseTuple(args, "ss:gettar", &name, &comp) == 0) + return 0; + + const ARArchive::Member *member = self->Object->FindMember(name); + if (!member) { + PyErr_Format(PyExc_LookupError,"No member named '%s'",name); + return 0; + } + + PyTarFileObject *tarfile = (PyTarFileObject*)CppOwnedPyObject_NEW(self,&PyTarFile_Type); + new (&tarfile->Fd) FileFd(self->Fd); + tarfile->min = member->Start; + tarfile->Object = new ExtractTar(self->Fd, member->Size, comp); + return HandleErrors(tarfile); +} + +static const char *ararchive_getmembers_doc = + "getmembers() -> list\n\n" + "Return a list of all members in the AR archive."; +static PyObject *ararchive_getmembers(PyArArchiveObject *self) +{ + PyObject *list = PyList_New(0); + ARArchive::Member *member = self->Object->Members(); + do { + CppOwnedPyObject *ret; + ret = CppOwnedPyObject_NEW(self,&PyArMember_Type); + ret->Object = member; + ret->NoDelete = true; + PyList_Append(list, ret); + Py_DECREF(ret); + } while ((member = member->Next)); + return list; +} + +static const char *ararchive_getnames_doc = + "getnames() -> list\n\n" + "Return a list of the names of all members in the AR archive."; +static PyObject *ararchive_getnames(PyArArchiveObject *self) +{ + PyObject *list = PyList_New(0); + ARArchive::Member *member = self->Object->Members(); + do { + PyObject *item = CppPyString(member->Name); + PyList_Append(list, item); + Py_DECREF(item); + } while ((member = member->Next)); + return list; +} + PyMethodDef ararchive_methods[] = { {"getmember",(PyCFunction)ararchive_getmember,METH_O, ararchive_getmember_doc}, + {"gettar",(PyCFunction)ararchive_gettar,METH_VARARGS, + ararchive_gettar_doc}, {"getdata",(PyCFunction)ararchive_getdata,METH_VARARGS, ararchive_getdata_doc}, {"extract",(PyCFunction)ararchive_extract,METH_VARARGS, ararchive_extract_doc}, + {"getmembers",(PyCFunction)ararchive_getmembers,METH_NOARGS, + ararchive_getmembers_doc}, + {"getnames",(PyCFunction)ararchive_getnames,METH_NOARGS, + ararchive_getnames_doc}, {NULL} }; @@ -244,13 +329,14 @@ PyObject *ararchive_new(PyTypeObject *type, PyObject *args, PyObject *kwds) else { return 0; } - self->Object = new ARArchive(self->Fd); + self->Object = (PyARArchiveHack*)new ARArchive(self->Fd); if (_error->PendingError() == true) return HandleErrors(); return self; } -static void ararchive_dealloc(PyObject *self) { +static void ararchive_dealloc(PyObject *self) +{ ((PyArArchiveObject *)(self))->Fd.~FileFd(); CppOwnedDeallocPtr(self); } @@ -264,11 +350,13 @@ static int ararchive_contains(PyObject *self, PyObject *arg) return (GetCpp(self)->FindMember(name) != 0); } -static PySequenceMethods ararchive_as_sequence = - {0,0,0,0,0,0,0,ararchive_contains,0,0}; +static PySequenceMethods ararchive_as_sequence = { + 0,0,0,0,0,0,0,ararchive_contains,0,0 +}; -static PyMappingMethods ararchive_as_mapping = - {0,(PyCFunction)ararchive_getmember,0}; +static PyMappingMethods ararchive_as_mapping = { + 0,(PyCFunction)ararchive_getmember,0 +}; static const char *ararchive_doc = "ArArchive(file: str/int/file)\n\n" -- cgit v1.2.3 From 58c1b550e9a96dbd1efcf42a8389b6819249aee5 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Sat, 8 Aug 2009 19:34:17 +0200 Subject: python/arfile.cc: Make ArArchive iterable. --- python/arfile.cc | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) (limited to 'python') diff --git a/python/arfile.cc b/python/arfile.cc index 1185c16a..2eb6f1cd 100644 --- a/python/arfile.cc +++ b/python/arfile.cc @@ -289,6 +289,14 @@ static PyObject *ararchive_getnames(PyArArchiveObject *self) return list; } +// Just run getmembers() and return an iterator over the list. +static PyObject *ararchive_iter(PyArArchiveObject *self) { + PyObject *members = ararchive_getmembers(self); + PyObject *iter = PyObject_GetIter(members); + Py_DECREF(members); + return iter; +} + PyMethodDef ararchive_methods[] = { {"getmember",(PyCFunction)ararchive_getmember,METH_O, ararchive_getmember_doc}, @@ -395,7 +403,7 @@ PyTypeObject PyArArchive_Type = { CppOwnedClear, // tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset - 0, // tp_iter + (getiterfunc)ararchive_iter, // tp_iter 0, // tp_iternext ararchive_methods, // tp_methods 0, // tp_members -- cgit v1.2.3 From 931107a69fc1b628f09dd0a04ae0e57f822d1ead Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Sat, 8 Aug 2009 19:36:30 +0200 Subject: python/arfile.cc: Rename getdata() to extractdata(). This makes it more consistent with the interface of tarfile.TarFile, which provides a extractfile() function. Since producing a file-like object is a bit to complicated here, we simply return the string and thus name the method extractdata(). --- python/arfile.cc | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'python') diff --git a/python/arfile.cc b/python/arfile.cc index 2eb6f1cd..4eb651dd 100644 --- a/python/arfile.cc +++ b/python/arfile.cc @@ -156,14 +156,14 @@ PyObject *ararchive_getmember(PyArArchiveObject *self, PyObject *arg) return ret; } -static const char *ararchive_getdata_doc = - "getdata(name: str) -> bytes\n\n" +static const char *ararchive_extractdata_doc = + "extractdata(name: str) -> bytes\n\n" "Return the contents of the member, as a bytes object. Raise\n" "LookupError if there is no ArMember with the given name."; -PyObject *ararchive_getdata(PyArArchiveObject *self, PyObject *args) +PyObject *ararchive_extractdata(PyArArchiveObject *self, PyObject *args) { char *name = 0; - if (PyArg_ParseTuple(args, "s:getdata", &name) == 0) + if (PyArg_ParseTuple(args, "s:extractdata", &name) == 0) return 0; const ARArchive::Member *member = self->Object->FindMember(name); if (!member) { @@ -302,8 +302,8 @@ PyMethodDef ararchive_methods[] = { ararchive_getmember_doc}, {"gettar",(PyCFunction)ararchive_gettar,METH_VARARGS, ararchive_gettar_doc}, - {"getdata",(PyCFunction)ararchive_getdata,METH_VARARGS, - ararchive_getdata_doc}, + {"extractdata",(PyCFunction)ararchive_extractdata,METH_VARARGS, + ararchive_extractdata_doc}, {"extract",(PyCFunction)ararchive_extract,METH_VARARGS, ararchive_extract_doc}, {"getmembers",(PyCFunction)ararchive_getmembers,METH_NOARGS, -- cgit v1.2.3 From e99af4793bc0d346cc059546124d2d963d88a174 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Sat, 8 Aug 2009 21:15:51 +0200 Subject: python/arfile.cc: Rewrite extraction code and add ArArchive.extractall(). The extraction code now reads smaller parts and does not use FileFd anymore, so we can raise OSError with errno and filename if an error occurs. Also add extractall() to ArArchive to make our interface more like tarfile.TarFile's one. --- python/arfile.cc | 97 ++++++++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 76 insertions(+), 21 deletions(-) (limited to 'python') diff --git a/python/arfile.cc b/python/arfile.cc index 4eb651dd..8b4f9c5b 100644 --- a/python/arfile.cc +++ b/python/arfile.cc @@ -24,6 +24,13 @@ #include "apt_instmodule.h" #include #include +#include +#include + +#include +#include +#include +#include PyObject *armember_get_name(PyObject *self, void *closure) { @@ -180,6 +187,55 @@ PyObject *ararchive_extractdata(PyArArchiveObject *self, PyObject *args) return result; } +// Helper class to close the FD automatically. +class IntFD { + public: + int fd; + inline operator int() { return fd; }; + inline IntFD(int fd): fd(fd) { }; + inline ~IntFD() { close(fd); }; +}; + +static PyObject *_extract(FileFd &Fd, const ARArchive::Member *member, + const char *dir) +{ + if (!Fd.Seek(member->Start)) + return HandleErrors(); + + string outfile_str = flCombine(dir,member->Name); + char *outfile = (char*)outfile_str.c_str(); + + // We are not using FileFd here, because we want to raise OSErrror with + // the correct errno and filename. IntFD's are closed automatically. + IntFD outfd(open(outfile, O_NDELAY|O_WRONLY|O_CREAT|O_TRUNC|O_APPEND, + member->Mode)); + if (outfd == -1) + return PyErr_SetFromErrnoWithFilename(PyExc_OSError, outfile); + if (fchmod(outfd, member->Mode) == -1) + return PyErr_SetFromErrnoWithFilename(PyExc_OSError, outfile); + if (fchown(outfd, member->UID, member->GID) != 0 && errno != EPERM) + return PyErr_SetFromErrnoWithFilename(PyExc_OSError, outfile); + + // Read 4 KiB from the file, until all of the file is read. Deallocated + // automatically when the function returns. + SPtrArray value = new char[4096]; + unsigned long size = member->Size; + unsigned long read = 4096; + while (size > 0) { + if (size < read) + read = size; + if (!Fd.Read(value, read, true)) + return HandleErrors(); + if (write(outfd, value, read) != (signed)read) + return PyErr_SetFromErrnoWithFilename(PyExc_OSError, outfile); + size -= read; + } + utimbuf time = {member->MTime, member->MTime}; + if (utime(outfile,&time) == -1) + return PyErr_SetFromErrnoWithFilename(PyExc_OSError, outfile); + Py_RETURN_TRUE; +} + static const char *ararchive_extract_doc = "extract(name: str[, target: str]) -> bool\n\n" "Extract the member given by name into the directory given by target.\n" @@ -200,31 +256,28 @@ PyObject *ararchive_extract(PyArArchiveObject *self, PyObject *args) PyErr_Format(PyExc_LookupError,"No member named '%s'",name); return 0; } + return _extract(self->Fd, member, target); +} - if (!self->Fd.Seek(member->Start)) - return HandleErrors(); +static const char *ararchive_extractall_doc = + "extract([target: str]) -> bool\n\n" + "Extract all into the directory given by target.\n" + "If the extraction failed, an error is raised. Otherwise, the method\n" + "returns True if the owner could be set or False if the owner could not\n" + "be changed."; - // Open the target file - FileFd outfd(flCombine(target,name), FileFd::WriteAny, member->Mode); - if (_error->PendingError() == true) - return HandleErrors(); +static PyObject *ararchive_extractall(PyArArchiveObject *self, PyObject *args) +{ + char *target = ""; + if (PyArg_ParseTuple(args, "|s:extractall", &target) == 0) + return 0; - // Temporary buffer. We should probably split this into smaller parts. - char* value = new char[member->Size]; + const ARArchive::Member *member = self->Object->Members(); - // Read into the buffer - if (!self->Fd.Read(value, member->Size, true)) { - delete[] value; - return HandleErrors(); - } - if (!outfd.Write(value, member->Size)) { - delete[] value; - return HandleErrors(); - } - if (fchown(outfd.Fd(), member->UID, member->GID) == -1) { - delete[] value; - Py_RETURN_FALSE; - } + do { + if (_extract(self->Fd, member, target) == 0) + return 0; + } while ((member = member->Next)); Py_RETURN_TRUE; } @@ -306,6 +359,8 @@ PyMethodDef ararchive_methods[] = { ararchive_extractdata_doc}, {"extract",(PyCFunction)ararchive_extract,METH_VARARGS, ararchive_extract_doc}, + {"extractall",(PyCFunction)ararchive_extractall,METH_VARARGS, + ararchive_extractall_doc}, {"getmembers",(PyCFunction)ararchive_getmembers,METH_NOARGS, ararchive_getmembers_doc}, {"getnames",(PyCFunction)ararchive_getnames,METH_NOARGS, -- cgit v1.2.3 From 6ba67f18808a904f56461f7deec41c87dcf54e86 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Sat, 8 Aug 2009 21:25:05 +0200 Subject: python/arfile.cc: Make functions static where possible. --- python/arfile.cc | 29 +++++++++++++++-------------- 1 file changed, 15 insertions(+), 14 deletions(-) (limited to 'python') diff --git a/python/arfile.cc b/python/arfile.cc index 8b4f9c5b..5ac0f727 100644 --- a/python/arfile.cc +++ b/python/arfile.cc @@ -32,49 +32,49 @@ #include #include -PyObject *armember_get_name(PyObject *self, void *closure) +static PyObject *armember_get_name(PyObject *self, void *closure) { return CppPyString(GetCpp(self)->Name); } -PyObject *armember_get_mtime(PyObject *self, void *closure) +static PyObject *armember_get_mtime(PyObject *self, void *closure) { return Py_BuildValue("k", GetCpp(self)->MTime); } -PyObject *armember_get_uid(PyObject *self, void *closure) +static PyObject *armember_get_uid(PyObject *self, void *closure) { return Py_BuildValue("k", GetCpp(self)->UID); } -PyObject *armember_get_gid(PyObject *self, void *closure) +static PyObject *armember_get_gid(PyObject *self, void *closure) { return Py_BuildValue("k", GetCpp(self)->GID); } -PyObject *armember_get_mode(PyObject *self, void *closure) +static PyObject *armember_get_mode(PyObject *self, void *closure) { return Py_BuildValue("k", GetCpp(self)->Mode); } -PyObject *armember_get_size(PyObject *self, void *closure) +static PyObject *armember_get_size(PyObject *self, void *closure) { return Py_BuildValue("k", GetCpp(self)->Size); } -PyObject *armember_get_start(PyObject *self, void *closure) +static PyObject *armember_get_start(PyObject *self, void *closure) { return Py_BuildValue("k", GetCpp(self)->Start); } -PyObject *armember_repr(PyObject *self) +static PyObject *armember_repr(PyObject *self) { return PyString_FromFormat("<%s object: name:'%s'>", self->ob_type->tp_name, GetCpp(self)->Name.c_str()); } -PyGetSetDef armember_getset[] = { +static PyGetSetDef armember_getset[] = { {"gid",armember_get_gid,0,"The group id of the owner."}, {"mode",armember_get_mode,0,"The mode of the file."}, {"mtime",armember_get_mtime,0,"Last time of modification."}, @@ -143,7 +143,7 @@ static const char *ararchive_getmember_doc = "getmember(name: str) -> ArMember\n\n" "Return a ArMember object for the member given by name. Raise\n" "LookupError if there is no ArMember with the given name."; -PyObject *ararchive_getmember(PyArArchiveObject *self, PyObject *arg) +static PyObject *ararchive_getmember(PyArArchiveObject *self, PyObject *arg) { const char *name; CppOwnedPyObject *ret; @@ -167,7 +167,7 @@ static const char *ararchive_extractdata_doc = "extractdata(name: str) -> bytes\n\n" "Return the contents of the member, as a bytes object. Raise\n" "LookupError if there is no ArMember with the given name."; -PyObject *ararchive_extractdata(PyArArchiveObject *self, PyObject *args) +static PyObject *ararchive_extractdata(PyArArchiveObject *self, PyObject *args) { char *name = 0; if (PyArg_ParseTuple(args, "s:extractdata", &name) == 0) @@ -243,7 +243,7 @@ static const char *ararchive_extract_doc = "returns True if the owner could be set or False if the owner could not\n" "be changed. It may also raise LookupError if there is member with\n" "the given name."; -PyObject *ararchive_extract(PyArArchiveObject *self, PyObject *args) +static PyObject *ararchive_extract(PyArArchiveObject *self, PyObject *args) { char *name = 0; char *target = ""; @@ -350,7 +350,7 @@ static PyObject *ararchive_iter(PyArArchiveObject *self) { return iter; } -PyMethodDef ararchive_methods[] = { +static PyMethodDef ararchive_methods[] = { {"getmember",(PyCFunction)ararchive_getmember,METH_O, ararchive_getmember_doc}, {"gettar",(PyCFunction)ararchive_gettar,METH_VARARGS, @@ -368,7 +368,8 @@ PyMethodDef ararchive_methods[] = { {NULL} }; -PyObject *ararchive_new(PyTypeObject *type, PyObject *args, PyObject *kwds) +static PyObject *ararchive_new(PyTypeObject *type, PyObject *args, + PyObject *kwds) { PyObject *file; PyArArchiveObject *self; -- cgit v1.2.3 From e643b71504412a6d70a10449845eecdd72529df0 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Mon, 17 Aug 2009 16:21:41 +0200 Subject: python/arfile.cc: Introduce DebFile. This is the final commit which Closes: #536096, as everything doable with the functions can now be done using the classes. --- debian/changelog | 4 +- python/apt_instmodule.cc | 1 + python/apt_instmodule.h | 1 + python/arfile.cc | 171 +++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 176 insertions(+), 1 deletion(-) (limited to 'python') diff --git a/debian/changelog b/debian/changelog index 1d735656..d644d7e6 100644 --- a/debian/changelog +++ b/debian/changelog @@ -11,6 +11,7 @@ python-apt (0.7.92) UNRELEASED; urgency=low - Make AcquireFile a subclass of AcquireItem, thus inheriting attributes. - New progress handling in apt.progress.base and apt.progress.text. Still missing Qt4 progress handlers. + - Classes in apt_inst (Closes: #536096) * Unification of dependency handling: - apt_pkg.parse_[src_]depends() now use CompType instead of CompTypeDeb @@ -34,8 +35,9 @@ python-apt (0.7.92) UNRELEASED; urgency=low - The documentation has been restructured and enhanced with tutorials. - Only recommend lsb-release instead of depending on it. Default to Debian unstable if lsb_release is not available. + * - -- Julian Andres Klode Sun, 02 Aug 2009 16:35:42 +0200 + -- Julian Andres Klode Mon, 17 Aug 2009 16:19:51 +0200 python-apt (0.7.91) experimental; urgency=low diff --git a/python/apt_instmodule.cc b/python/apt_instmodule.cc index 3baaf985..9cb166ed 100644 --- a/python/apt_instmodule.cc +++ b/python/apt_instmodule.cc @@ -207,6 +207,7 @@ extern "C" void initapt_inst() ADDTYPE(module,"ArMember",&PyArMember_Type); ADDTYPE(module,"ArArchive",&PyArArchive_Type); + ADDTYPE(module,"DebFile",&PyDebFile_Type); ADDTYPE(module,"TarFile",&PyTarFile_Type); ADDTYPE(module,"TarMember",&PyTarMember_Type); RETURN(module); diff --git a/python/apt_instmodule.h b/python/apt_instmodule.h index 94ada0f8..9f978e44 100644 --- a/python/apt_instmodule.h +++ b/python/apt_instmodule.h @@ -22,6 +22,7 @@ extern char *doc_tarExtract; extern PyTypeObject PyArMember_Type; extern PyTypeObject PyArArchive_Type; +extern PyTypeObject PyDebFile_Type; extern PyTypeObject PyTarFile_Type; extern PyTypeObject PyTarMember_Type; diff --git a/python/arfile.cc b/python/arfile.cc index 5ac0f727..1abb738f 100644 --- a/python/arfile.cc +++ b/python/arfile.cc @@ -473,3 +473,174 @@ PyTypeObject PyArArchive_Type = { 0, // tp_alloc ararchive_new // tp_new }; + +/** + * Representation of a Debian package. + * + * This does not resemble debDebFile in apt-inst, but instead is a subclass + * of ArFile which adds properties for the control.tar.{lzma,bz2,gz} and + * data.tar.{lzma,bz2,gz} members which return TarFile objects. It also adds + * a descriptor 'version' which returns the content of 'debian-binary'. + * + * We are using it this way as it seems more natural to represent this special + * kind of AR archive as an AR archive with some extras. + */ +struct PyDebFileObject : PyArArchiveObject { + PyObject *data; + PyObject *control; + PyObject *debian_binary; +}; + +static PyObject *debfile_get_data(PyDebFileObject *self) +{ + return Py_INCREF(self->data), self->data; +} + +static PyObject *debfile_get_control(PyDebFileObject *self) +{ + return Py_INCREF(self->control), self->control; +} + +static PyObject *debfile_get_debian_binary(PyDebFileObject *self) +{ + return Py_INCREF(self->debian_binary), self->debian_binary; +} + +static PyObject *_gettar(PyDebFileObject *self, const ARArchive::Member *m, + const char *comp) +{ + if (!m) + return 0; + PyTarFileObject *tarfile = (PyTarFileObject*)CppOwnedPyObject_NEW(self,&PyTarFile_Type); + new (&tarfile->Fd) FileFd(self->Fd); + tarfile->min = m->Start; + tarfile->Object = new ExtractTar(self->Fd, m->Size, comp); + return tarfile; +} + + + +static PyObject *debfile_new(PyTypeObject *type, PyObject *args, PyObject *kwds) +{ + PyDebFileObject *self = (PyDebFileObject*)ararchive_new(type, args, kwds); + + // DebFile + self->control = _gettar(self, self->Object->FindMember("control.tar.gz"), + "gzip"); + if (!self->control) + return PyErr_Format(PyExc_SystemError, "No debian archive, missing %s", + "control.tar.gz"); + + self->data = _gettar(self, self->Object->FindMember("data.tar.gz"), + "gzip"); + if (!self->data) + self->data = _gettar(self, self->Object->FindMember("data.tar.bz2"), + "bzip2"); + if (!self->data) + self->data = _gettar(self, self->Object->FindMember("data.tar.lzma"), + "lzma"); + if (!self->data) + return PyErr_Format(PyExc_SystemError, "No debian archive, missing %s", + "data.tar.gz or data.tar.bz2 or data.tar.lzma"); + + + const ARArchive::Member *member = self->Object->FindMember("debian-binary"); + if (!member) + return PyErr_Format(PyExc_SystemError, "No debian archive, missing %s", + "debian-binary"); + + if (!self->Fd.Seek(member->Start)) + return HandleErrors(); + + char* value = new char[member->Size]; + self->Fd.Read(value, member->Size, true); + self->debian_binary = PyBytes_FromStringAndSize(value, member->Size); + delete[] value; + return self; +} + +static int debfile_traverse(PyObject *_self, visitproc visit, void* arg) +{ + PyDebFileObject *self = (PyDebFileObject*)_self; + Py_VISIT(self->data); + Py_VISIT(self->control); + Py_VISIT(self->debian_binary); + return PyArArchive_Type.tp_traverse(self, visit, arg); +} + +static int debfile_clear(PyObject *_self) { + PyDebFileObject *self = (PyDebFileObject*)_self; + Py_CLEAR(self->data); + Py_CLEAR(self->control); + Py_CLEAR(self->debian_binary); + return PyArArchive_Type.tp_clear(self); +} + +static void debfile_dealloc(PyObject *self) { + debfile_clear((PyDebFileObject *)self); + PyArArchive_Type.tp_dealloc(self); +} + +static PyGetSetDef debfile_getset[] = { + {"control",(getter)debfile_get_control,0, + "The TarFile object associated with the control.tar.gz member."}, + {"data",(getter)debfile_get_data,0, + "The TarFile object associated with the data.tar.{gz,bz2,lzma} member."}, + {"debian_binary",(getter)debfile_get_debian_binary,0, + "The package version, as contained in debian-binary."}, + {NULL} +}; + +static const char *debfile_doc = + "DebFile(file: str/int/file)\n\n" + "A DebFile object represents a file in the .deb package format.\n\n" + "The parameter 'file' may be a string specifying the path of a file, or\n" + "a file-like object providing the fileno() method. It may also be an int\n" + "specifying a file descriptor (returned by e.g. os.open()).\n" + "The recommended way is to pass in the path to the file.\n\n" + "It differs from ArArchive by providing the members 'control', 'data'\n" + "and 'version' for accessing the control.tar.gz,data.tar.{gz,bz2,lzma}\n" + ",debian-binary members in the archive."; + +PyTypeObject PyDebFile_Type = { + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "apt_inst.DebFile", // tp_name + sizeof(PyDebFileObject), // tp_basicsize + 0, // tp_itemsize + // Methods + debfile_dealloc, // tp_dealloc + 0, // tp_print + 0, // tp_getattr + 0, // tp_setattr + 0, // tp_compare + 0, // tp_repr + 0, // tp_as_number + 0, // tp_as_sequence + 0, // tp_as_mapping + 0, // tp_hash + 0, // tp_call + 0, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + Py_TPFLAGS_DEFAULT | // tp_flags + Py_TPFLAGS_HAVE_GC, + debfile_doc, // tp_doc + debfile_traverse, // tp_traverse + debfile_clear, // tp_clear + 0, // tp_richcompare + 0, // tp_weaklistoffset + 0, // tp_iter + 0, // tp_iternext + 0, // tp_methods + 0, // tp_members + debfile_getset, // tp_getset + &PyArArchive_Type, // tp_base + 0, // tp_dict + 0, // tp_descr_get + 0, // tp_descr_set + 0, // tp_dictoffset + 0, // tp_init + 0, // tp_alloc + debfile_new // tp_new +}; -- cgit v1.2.3 From 3f286a1033479a7cfe40bc0e81c662eb3cd1d0f3 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Tue, 18 Aug 2009 13:49:42 +0200 Subject: python: Disable the functions in apt_inst if built without COMPAT_0_7. Developers should use the class-based API instead. --- python/apt_instmodule.cc | 19 ++++++++----------- python/apt_instmodule.h | 3 ++- python/tar.cc | 4 ++++ 3 files changed, 14 insertions(+), 12 deletions(-) (limited to 'python') diff --git a/python/apt_instmodule.cc b/python/apt_instmodule.cc index 9cb166ed..2721509e 100644 --- a/python/apt_instmodule.cc +++ b/python/apt_instmodule.cc @@ -23,6 +23,8 @@ #include /*}}}*/ +#ifdef COMPAT_0_7 + // debExtractControl - Exctract an arbitary control member /*{{{*/ // --------------------------------------------------------------------- /* This is a common operation so this function will stay, but others that @@ -149,25 +151,20 @@ static PyObject *arCheckMember(PyObject *Self,PyObject *Args) static PyMethodDef methods[] = { // access to ar files - {"ar_check_member", arCheckMember, METH_VARARGS, doc_arCheckMember}, + {"arCheckMember", arCheckMember, METH_VARARGS, doc_arCheckMember}, // access to deb files - {"deb_extract_control",debExtractControl,METH_VARARGS,doc_debExtractControl}, - {"deb_extract_archive",debExtractArchive,METH_VARARGS,doc_debExtractArchive}, - - // access to tar streams - {"tar_extract",tarExtract,METH_VARARGS,doc_tarExtract}, - {"deb_extract",debExtract,METH_VARARGS,doc_debExtract}, - -#ifdef COMPAT_0_7 - {"arCheckMember", arCheckMember, METH_VARARGS, doc_arCheckMember}, {"debExtractControl",debExtractControl,METH_VARARGS,doc_debExtractControl}, {"debExtractArchive",debExtractArchive,METH_VARARGS,doc_debExtractArchive}, + + // access to tar streams {"tarExtract",tarExtract,METH_VARARGS,doc_tarExtract}, {"debExtract",debExtract,METH_VARARGS,doc_debExtract}, -#endif {} }; +#else +static PyMethodDef *methods = 0; +#endif // defined(COMPAT_0_7) static const char *apt_inst_doc = diff --git a/python/apt_instmodule.h b/python/apt_instmodule.h index 9f978e44..2b07261b 100644 --- a/python/apt_instmodule.h +++ b/python/apt_instmodule.h @@ -14,11 +14,12 @@ #include "generic.h" #include +#ifdef COMPAT_0_7 PyObject *debExtract(PyObject *Self,PyObject *Args); extern char *doc_debExtract; PyObject *tarExtract(PyObject *Self,PyObject *Args); extern char *doc_tarExtract; - +#endif extern PyTypeObject PyArMember_Type; extern PyTypeObject PyArArchive_Type; diff --git a/python/tar.cc b/python/tar.cc index b93ba31a..b994d4e7 100644 --- a/python/tar.cc +++ b/python/tar.cc @@ -4,10 +4,13 @@ /* ###################################################################### Tar Inteface + * THIS FILE IS COMPLETELY DEPRECATED, AND NOT USED ANYMORE IF BUILT * + * WITHOUT COMPATIBILITY. * ##################################################################### */ /*}}}*/ // Include Files /*{{{*/ +#ifdef COMPAT_0_7 #include "generic.h" #include @@ -189,3 +192,4 @@ PyObject *debExtract(PyObject *Self,PyObject *Args) return HandleErrors(Py_None); } /*}}}*/ +#endif // defined(COMPAT_0_7) -- cgit v1.2.3 From 24567ef6dddd56c1777a5908a2fd9b29374cde7e Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Tue, 18 Aug 2009 15:11:40 +0200 Subject: python/tarfile.cc: Introduce TarFile.extractdata(). This works by enhancing PyDirStream to support handling only one member, making the PyObjects for the current member instance variables and after calling TarFile.Go() return the value of 'py_data'. --- python/tarfile.cc | 97 +++++++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 77 insertions(+), 20 deletions(-) (limited to 'python') diff --git a/python/tarfile.cc b/python/tarfile.cc index f3e11d2b..9c3797fb 100644 --- a/python/tarfile.cc +++ b/python/tarfile.cc @@ -30,12 +30,21 @@ * * This calls a Python callback in FinishedFile() with the Item as the first * argument and the data as the second argument. + * + * It can also work without a callback, in which case it just sets the + * 'py_member' and 'py_data' members. This can be combined with setting + * 'member' to extract a single member into the memory. */ class PyDirStream : public pkgDirStream { public: PyObject *callback; + // The current member and data. + CppOwnedPyObject *py_member; + PyObject *py_data; + // The requested member or NULL. + const char *member; // Set to true if an error occured in the Python callback. bool error; // Place where the copy of the data is stored. @@ -46,21 +55,27 @@ public: virtual bool Process(Item &Itm,const unsigned char *Data, unsigned long Size,unsigned long Pos); - PyDirStream(PyObject *callback) : callback(callback), error(false), copy(0) { - Py_INCREF(callback); + PyDirStream(PyObject *callback, const char *member=0) : callback(callback), + py_member(0), py_data(0), member(member), error(false), copy(0) + { + Py_XINCREF(callback); } virtual ~PyDirStream() { - Py_DECREF(callback); + Py_XDECREF(callback); + Py_XDECREF(py_member); + Py_XDECREF(py_data); delete[] copy; } }; bool PyDirStream::DoItem(Item &Itm, int &Fd) { - delete[] copy; - copy = new char[Itm.Size]; - Fd = -2; + if (!member || strcmp(Itm.Name, member) == 0) { + delete[] copy; + copy = new char[Itm.Size]; + Fd = -2; + } return true; } @@ -73,15 +88,21 @@ bool PyDirStream::Process(Item &Itm,const unsigned char *Data, bool PyDirStream::FinishedFile(Item &Itm,int Fd) { - PyObject *py_member = CppOwnedPyObject_NEW(0,&PyTarMember_Type,&Itm); - - ((CppOwnedPyObject*)py_member)->NoDelete = true; - PyObject *py_data = PyBytes_FromStringAndSize(copy, Itm.Size); - PyObject *result = PyObject_CallFunctionObjArgs(callback, py_member, - py_data, 0); - if (result == 0) - error = true; - return (result != 0); + if (member && strcmp(Itm.Name, member) != 0) + // Skip non-matching Items, if a specific one is requested. + return true; + + // Clear the old objects and create new ones. + Py_XDECREF(py_member); + Py_XDECREF(py_data); + py_member = CppOwnedPyObject_NEW(0, &PyTarMember_Type, &Itm); + py_member->NoDelete = true; + py_data = PyBytes_FromStringAndSize(copy, Itm.Size); + + if (!callback) + return true; + error = PyObject_CallFunctionObjArgs(callback, py_member, py_data, 0) == 0; + return (!error); } // The tarfile.TarInfo interface for our TarMember class. @@ -332,24 +353,60 @@ static PyObject *tarfile_extractall(PyObject *self, PyObject *args) } static const char *tarfile_go_doc = - "go(callback: callable) -> True\n\n" + "go(callback: callable[, member: str]) -> True\n\n" "Go through the archive and call the callable callback for each\n" "member with 2 arguments. The first argument is the TarMember and\n" - "the second one is the data, as bytes."; -static PyObject *tarfile_go(PyObject *self, PyObject *arg) + "the second one is the data, as bytes.\n\n" + "The optional parameter 'member' can be used to specify the member for\n" + "which call the callback. If not specified, it will be called for all\n" + "members. If specified and not found, LookupError will be raised."; +static PyObject *tarfile_go(PyObject *self, PyObject *args) { + PyObject *callback; + char *member = 0; + if (PyArg_ParseTuple(args,"O|s",&callback,&member) == 0) + return 0; + if (strcmp(member, "") == 0) + member = 0; pkgDirStream Extract; - PyDirStream stream(arg); + PyDirStream stream(callback, member); ((PyTarFileObject*)self)->Fd.Seek(((PyTarFileObject*)self)->min); bool res = GetCpp(self)->Go(stream); if (stream.error) return 0; + if (member && !stream.py_data) + return PyErr_Format(PyExc_LookupError, "There is no member named '%s'", + member); return HandleErrors(PyBool_FromLong(res)); } +static const char *tarfile_extractdata_doc = + "extractdata(member: str) -> bytes\n\n" + "Return the contents of the member, as a bytes object. Raise\n" + "LookupError if there is no member with the given name."; +static PyObject *tarfile_extractdata(PyObject *self, PyObject *args) +{ + const char *member; + if (PyArg_ParseTuple(args,"s",&member) == 0) + return 0; + PyDirStream stream(NULL, member); + ((PyTarFileObject*)self)->Fd.Seek(((PyTarFileObject*)self)->min); + // Go through the stream. + GetCpp(self)->Go(stream); + + if (!stream.py_data) + return PyErr_Format(PyExc_LookupError, "There is no member named '%s'", + member); + if (stream.error) { + return 0; + } + return Py_INCREF(stream.py_data), stream.py_data; +} + static PyMethodDef tarfile_methods[] = { + {"extractdata",tarfile_extractdata,METH_VARARGS,tarfile_extractdata_doc}, {"extractall",tarfile_extractall,METH_VARARGS,tarfile_extractall_doc}, - {"go",tarfile_go,METH_O,tarfile_go_doc}, + {"go",tarfile_go,METH_VARARGS,tarfile_go_doc}, {NULL} }; -- cgit v1.2.3