summaryrefslogtreecommitdiff
path: root/python
diff options
context:
space:
mode:
Diffstat (limited to 'python')
-rw-r--r--python/acquire-item.cc76
-rw-r--r--python/acquire.cc17
-rw-r--r--python/apt_instmodule.cc143
-rw-r--r--python/apt_instmodule.h6
-rw-r--r--python/apt_pkgmodule.cc281
-rw-r--r--python/arfile.cc136
-rw-r--r--python/cache.cc102
-rw-r--r--python/cdrom.cc36
-rw-r--r--python/configuration.cc12
-rw-r--r--python/depcache.cc33
-rw-r--r--python/generic.cc92
-rw-r--r--python/generic.h53
-rw-r--r--python/indexfile.cc4
-rw-r--r--python/indexrecords.cc8
-rw-r--r--python/lock.cc5
-rw-r--r--python/pkgmanager.cc15
-rw-r--r--python/pkgrecords.cc9
-rw-r--r--python/pkgsrcrecords.cc62
-rw-r--r--python/policy.cc14
-rw-r--r--python/progress.cc135
-rw-r--r--python/sourcelist.cc9
-rw-r--r--python/string.cc2
-rw-r--r--python/tag.cc95
-rw-r--r--python/tar.cc197
-rw-r--r--python/tarfile.cc71
25 files changed, 502 insertions, 1111 deletions
diff --git a/python/acquire-item.cc b/python/acquire-item.cc
index 5e7423ab..d07f4c82 100644
--- a/python/acquire-item.cc
+++ b/python/acquire-item.cc
@@ -224,23 +224,43 @@ PyTypeObject PyAcquireItem_Type = {
static PyObject *acquirefile_new(PyTypeObject *type, PyObject *Args, PyObject * kwds)
{
PyObject *pyfetcher;
- char *uri, *md5, *descr, *shortDescr, *destDir, *destFile;
+ const char *uri, *hash, *md5, *descr, *shortDescr;
+ PyApt_Filename destDir, destFile;
int size = 0;
- uri = md5 = descr = shortDescr = destDir = destFile = "";
+ uri = hash = md5 = descr = shortDescr = destDir = destFile = "";
- char *kwlist[] = {"owner","uri", "md5", "size", "descr", "short_descr",
- "destdir", "destfile", NULL
+ // "md5" is only in this list for backward compatiblity, everyone should
+ // use "hash"
+ char *kwlist[] = {"owner", "uri", "hash", "size", "descr", "short_descr",
+ "destdir", "destfile", "md5", NULL
};
-
- if (PyArg_ParseTupleAndKeywords(Args, kwds, "O!s|sissss", kwlist,
- &PyAcquire_Type, &pyfetcher, &uri, &md5,
- &size, &descr, &shortDescr, &destDir, &destFile) == 0)
+#if PY_MAJOR_VERSION >= 3
+ const char *fmt = "O!s|sissO&O&$s";
+#else
+ // no "$" support to indicate that the remaining args are keyword only
+ // in py2.x :/
+ const char *fmt = "O!s|sissO&O&s";
+#endif
+ if (PyArg_ParseTupleAndKeywords(Args, kwds, fmt, kwlist,
+ &PyAcquire_Type, &pyfetcher, &uri, &hash,
+ &size, &descr, &shortDescr,
+ PyApt_Filename::Converter, &destDir,
+ PyApt_Filename::Converter, &destFile,
+ &md5) == 0)
return 0;
+ // issue deprecation warning for md5
+ if (strlen(md5) > 0) {
+ PyErr_Warn(PyExc_DeprecationWarning,
+ "Using the md5 keyword is deprecated, please use 'hash' instead");
+ }
+ // support "md5" keyword for backward compatiblity
+ if (strlen(hash) == 0 && strlen(md5) != 0)
+ hash = md5;
pkgAcquire *fetcher = GetCpp<pkgAcquire*>(pyfetcher);
pkgAcqFile *af = new pkgAcqFile(fetcher, // owner
uri, // uri
- md5, // md5
+ hash, // hash
size, // size
descr, // descr
shortDescr,
@@ -320,41 +340,3 @@ PyTypeObject PyAcquireFile_Type = {
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<pkgAcquire*>(pyfetcher);
- pkgAcqFile *af = new pkgAcqFile(fetcher, // owner
- uri, // uri
- md5, // md5
- size, // size
- descr, // descr
- shortDescr,
- destDir,
- destFile); // short-desc
- CppPyObject<pkgAcqFile*> *AcqFileObj = CppPyObject_NEW<pkgAcqFile*>(NULL, &PyAcquireFile_Type);
- AcqFileObj->Object = af;
- AcqFileObj->NoDelete = true;
-
- return AcqFileObj;
-}
-#endif
diff --git a/python/acquire.cc b/python/acquire.cc
index 45b4493c..621f0eef 100644
--- a/python/acquire.cc
+++ b/python/acquire.cc
@@ -244,10 +244,11 @@ static PyObject *PkgAcquireShutdown(PyObject *Self,PyObject *Args)
static PyMethodDef PkgAcquireMethods[] = {
{"run",PkgAcquireRun,METH_VARARGS,
"run() -> int\n\nRun the fetcher and return one of RESULT_CANCELLED,\n"
- "RESULT_CONTINUE, RESULT_FAILED. RESULT_CONTINUE means that all items\n"
- "which where queued prior to calling run() have been fetched\n"
- "successfully. RESULT_CANCELLED means that the process was canceled\n"
- "by the progress class. And RESULT_FAILED means a generic failure."},
+ "RESULT_CONTINUE, RESULT_FAILED.\n\n"
+ "RESULT_CONTINUE means that all items which where queued prior to\n"
+ "calling run() have been fetched successfully or failed transiently.\n\n"
+ "RESULT_CANCELLED means canceled by the progress class.\n\n"
+ "RESULT_FAILED means a generic failure."},
{"shutdown",PkgAcquireShutdown, METH_VARARGS,
"shutdown()\n\n"
"Shut the fetcher down, removing all items from it. Future access to\n"
@@ -400,12 +401,4 @@ PyTypeObject PyAcquire_Type = {
PkgAcquireNew, // tp_new
};
-#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(&PyAcquire_Type,Args,0);
-}
-#endif
diff --git a/python/apt_instmodule.cc b/python/apt_instmodule.cc
index 732f1bd0..8094550a 100644
--- a/python/apt_instmodule.cc
+++ b/python/apt_instmodule.cc
@@ -23,148 +23,7 @@
#include <Python.h>
/*}}}*/
-#ifdef COMPAT_0_7
-
-// debExtractControl - Exctract an arbitary control member /*{{{*/
-// ---------------------------------------------------------------------
-/* This is a common operation so this function will stay, but others that
- expose the full range of the apt-inst .deb processing will join it some
- day. */
-static char *doc_debExtractControl =
-"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)
-{
- char *Member = "control";
- PyObject *File;
- 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
- int fileno = PyObject_AsFileDescriptor(File);
- if (fileno == -1)
- return 0;
- FileFd Fd(fileno,false);
- debDebFile Deb(Fd);
- if (_error->PendingError() == true)
- return HandleErrors();
-
- debDebFile::MemControlExtract Extract(Member);
- if (Extract.Read(Deb) == false)
- return HandleErrors();
-
- // Build the return result
-
- if (Extract.Control == 0)
- {
- Py_INCREF(Py_None);
- Res = Py_None;
- }
- else
- Res = PyString_FromStringAndSize(Extract.Control,Extract.Length+2);
- }
-
- return HandleErrors(Res);
-}
- /*}}}*/
-
-// debExtractArchive - Exctract the archive /*{{{*/
-// ---------------------------------------------------------------------
-static char *doc_debExtractArchive =
-"deb_extract_archive(File,rootdir) -> Bool\n"
-"Extracts the Archive into the given root dir";
-static PyObject *debExtractArchive(PyObject *Self,PyObject *Args)
-{
- char *Rootdir = NULL;
- char cwd[512];
- PyObject *File;
- if (PyArg_ParseTuple(Args,"O|s",&File,&Rootdir) == 0)
- return 0;
-
- // Subscope makes sure any clean up errors are properly handled.
- bool res = false;
- {
- if(Rootdir != NULL)
- {
- getcwd(cwd, sizeof(cwd));
- chdir(Rootdir);
- }
-
- // Open the file and associate the .deb
- int fileno = PyObject_AsFileDescriptor(File);
- if (fileno == -1)
- return 0;
- FileFd Fd(fileno,false);
- debDebFile Deb(Fd);
- if (_error->PendingError() == true) {
- if (Rootdir != NULL)
- chdir (cwd);
- return HandleErrors();
- }
-
- // extracts relative to the current dir
- pkgDirStream Extract;
- res = Deb.ExtractArchive(Extract);
-
- if (Rootdir != NULL)
- chdir (cwd);
- if (res == false)
- return HandleErrors(PyBool_FromLong(res));
- }
- return HandleErrors(PyBool_FromLong(res));
-}
- /*}}}*/
-// arFindMember - Find member in AR archive /*{{{*/
-// ---------------------------------------------------------------------
-static char *doc_arCheckMember =
-"ar_check_member(file, membername) -> Bool\n";
-static PyObject *arCheckMember(PyObject *Self,PyObject *Args)
-{
- char *Member = NULL;
- bool res = false;
- PyObject *File;
- if (PyArg_ParseTuple(Args,"Os",&File,&Member) == 0)
- return 0;
-
- // Open the file and associate the .deb
- int fileno = PyObject_AsFileDescriptor(File);
- if (fileno == -1)
- return 0;
- FileFd Fd(fileno,false);
- ARArchive AR(Fd);
- if (_error->PendingError() == true)
- return HandleErrors();
-
- if(AR.FindMember(Member) != 0)
- res = true;
-
- return HandleErrors(PyBool_FromLong(res));
-}
- /*}}}*/
-
-// initapt_inst - Core Module Initialization /*{{{*/
-// ---------------------------------------------------------------------
-/* */
-static PyMethodDef methods[] =
-{
- // access to ar files
- {"arCheckMember", arCheckMember, METH_VARARGS, doc_arCheckMember},
-
- // access to deb files
- {"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},
- {}
-};
-#else
static PyMethodDef *methods = 0;
-#endif // defined(COMPAT_0_7)
static const char *apt_inst_doc =
@@ -193,7 +52,7 @@ static struct PyModuleDef moduledef = {
extern "C" PyObject * PyInit_apt_inst()
#else
extern "C" void initapt_inst()
-#define RETURN(x)
+#define RETURN(x) return
#endif
{
#if PY_MAJOR_VERSION >= 3
diff --git a/python/apt_instmodule.h b/python/apt_instmodule.h
index f6b337f4..ad4e9f72 100644
--- a/python/apt_instmodule.h
+++ b/python/apt_instmodule.h
@@ -14,12 +14,6 @@
#include "generic.h"
#include <apt-pkg/extracttar.h>
-#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/apt_pkgmodule.cc b/python/apt_pkgmodule.cc
index 1a991a48..8870a6e0 100644
--- a/python/apt_pkgmodule.cc
+++ b/python/apt_pkgmodule.cc
@@ -21,12 +21,13 @@
#include <apt-pkg/tagfile.h>
#include <apt-pkg/md5.h>
#include <apt-pkg/sha1.h>
-#include <apt-pkg/sha256.h>
+#include <apt-pkg/sha2.h>
#include <apt-pkg/init.h>
#include <apt-pkg/pkgsystem.h>
#include <apt-pkg/orderlist.h>
#include <apt-pkg/aptconfiguration.h>
#include <apt-pkg/fileutl.h>
+#include <apt-pkg/gpgv.h>
#include <sys/stat.h>
#include <libintl.h>
@@ -53,23 +54,15 @@ static PyObject *py_gettext(PyObject *self, PyObject *Args) {
// 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)
-{
- PyErr_WarnEx(PyExc_DeprecationWarning, "apt_pkg.newConfiguration() is "
- "deprecated. Use apt_pkg.Configuration() instead.", 1);
- return CppPyObject_NEW<Configuration*>(NULL, &PyConfiguration_Type, new Configuration());
-}
-#endif
/*}}}*/
// Version Wrappers /*{{{*/
// These are kind of legacy..
static char *doc_VersionCompare =
"version_compare(a: str, b: str) -> int\n\n"
- "Compare the given versions; return -1 if 'a' is smaller than 'b',\n"
- "0 if they are equal, and 2 if 'a' is larger than 'b'.";
+ "Compare the given versions; return a strictly negative value if 'a' is \n"
+ "smaller than 'b', 0 if they are equal, and a strictly positive value if\n"
+ "'a' is larger than 'b'.";
static PyObject *VersionCompare(PyObject *Self,PyObject *Args)
{
char *A;
@@ -124,32 +117,6 @@ static PyObject *CheckDep(PyObject *Self,PyObject *Args)
return PyBool_FromLong(_system->VS->CheckDep(A,Op,B));
}
-#ifdef COMPAT_0_7
-static char *doc_CheckDepOld = "CheckDep(PkgVer,DepOp,DepVer) -> bool";
-static PyObject *CheckDepOld(PyObject *Self,PyObject *Args)
-{
- char *A;
- char *B;
- char *OpStr;
- unsigned int Op = 0;
-
- if (PyArg_ParseTuple(Args,"sss",&A,&OpStr,&B) == 0)
- return 0;
- if (*debListParser::ConvertRelation(OpStr,Op) != 0)
- {
- PyErr_SetString(PyExc_ValueError,"Bad comparision operation");
- return 0;
- }
-
- if (_system == 0)
- {
- PyErr_SetString(PyExc_ValueError,"_system not initialized");
- return 0;
- }
-
- return PyBool_FromLong(_system->VS->CheckDep(A,Op,B));
-}
-#endif
static char *doc_UpstreamVersion =
"upstream_version(ver: str) -> str\n\n"
@@ -163,17 +130,19 @@ static PyObject *UpstreamVersion(PyObject *Self,PyObject *Args)
}
static const char *doc_ParseDepends =
-"parse_depends(s: str) -> list\n"
+"parse_depends(s: str[, strip_multi_arch : bool = True]) -> list\n"
"\n"
"Parse the dependencies given by 's' and return a list of lists. Each of\n"
"these lists represents one or more options for an 'or' dependency in\n"
"the form of '(pkg, ver, comptype)' tuples. The tuple element 'pkg'\n"
"is the name of the package; the element 'ver' is the version, or ''\n"
"if no version was requested. The element 'ver' is a comparison\n"
-"operator ('<', '<=', '=', '>=', or '>').";
+"operator ('<', '<=', '=', '>=', or '>').\n\n"
+"If 'strip_multi_arch' is True, :any (and potentially other special values)\n"
+"will be stripped from the full package name";
static const char *parse_src_depends_doc =
-"parse_src_depends(s: str) -> list\n"
+"parse_src_depends(s: str[, strip_multi_arch : bool = True]) -> list\n"
"\n"
"Parse the dependencies given by 's' and return a list of lists. Each of\n"
"these lists represents one or more options for an 'or' dependency in\n"
@@ -184,10 +153,12 @@ static const char *parse_src_depends_doc =
"\n\n"
"Dependencies may be restricted to certain architectures and the result\n"
"only contains those dependencies for the architecture set in the\n"
-"configuration variable APT::Architecture";
+"configuration variable APT::Architecture\n\n"
+"If 'strip_multi_arch' is True, :any (and potentially other special values)\n"
+"will be stripped from the full package name";
static PyObject *RealParseDepends(PyObject *Self,PyObject *Args,
- bool ParseArchFlags, std::string name,
- bool debStyle=false)
+ bool ParseArchFlags, bool ParseRestrictionsList,
+ std::string name, bool debStyle=false)
{
std::string Package;
std::string Version;
@@ -210,7 +181,8 @@ static PyObject *RealParseDepends(PyObject *Self,PyObject *Args,
break;
Start = debListParser::ParseDepends(Start,Stop,Package,Version,Op,
- ParseArchFlags, StripMultiArch);
+ ParseArchFlags, StripMultiArch,
+ ParseRestrictionsList);
if (Start == 0)
{
PyErr_SetString(PyExc_ValueError,"Problem Parsing Dependency");
@@ -243,22 +215,12 @@ static PyObject *RealParseDepends(PyObject *Self,PyObject *Args,
}
static PyObject *ParseDepends(PyObject *Self,PyObject *Args)
{
- return RealParseDepends(Self, Args, false, "parse_depends");
+ return RealParseDepends(Self, Args, false, false, "parse_depends");
}
static PyObject *ParseSrcDepends(PyObject *Self,PyObject *Args)
{
- return RealParseDepends(Self, Args, true, "parse_src_depends");
+ return RealParseDepends(Self, Args, true, true, "parse_src_depends");
}
-#ifdef COMPAT_0_7
-static PyObject *ParseDepends_old(PyObject *Self,PyObject *Args)
-{
- return RealParseDepends(Self, Args, false, "ParseDepends", true);
-}
-static PyObject *ParseSrcDepends_old(PyObject *Self,PyObject *Args)
-{
- return RealParseDepends(Self, Args, true, "ParseSrcDepends", true);
-}
-#endif
/*}}}*/
// md5sum - Compute the md5sum of a file or string /*{{{*/
// ---------------------------------------------------------------------
@@ -350,7 +312,7 @@ static PyObject *sha1sum(PyObject *Self,PyObject *Args)
return 0;
}
/*}}}*/
-// sha256sum - Compute the sha1sum of a file or string /*{{{*/
+// sha256sum - Compute the sha256sum of a file or string /*{{{*/
// ---------------------------------------------------------------------
static const char *doc_sha256sum =
"sha256sum(object) -> str\n\n"
@@ -395,6 +357,51 @@ static PyObject *sha256sum(PyObject *Self,PyObject *Args)
return 0;
}
/*}}}*/
+// sha512sum - Compute the sha512sum of a file or string /*{{{*/
+// ---------------------------------------------------------------------
+static const char *doc_sha512sum =
+ "sha512sum(object) -> str\n\n"
+ "Return the sha512sum of the object. 'object' may either be a string, in\n"
+ "which case the sha512sum of the string is returned, or a file() object\n"
+ "(or file descriptor), in which case the sha512sum of its contents is\n"
+ "returned.";;
+static PyObject *sha512sum(PyObject *Self,PyObject *Args)
+{
+ PyObject *Obj;
+ if (PyArg_ParseTuple(Args,"O",&Obj) == 0)
+ return 0;
+
+ // Digest of a string.
+ if (PyBytes_Check(Obj) != 0)
+ {
+ char *s;
+ Py_ssize_t len;
+ SHA512Summation Sum;
+ PyBytes_AsStringAndSize(Obj, &s, &len);
+ Sum.Add((const unsigned char*)s, len);
+ return CppPyString(Sum.Result().Value());
+ }
+
+ // Digest of a file
+ int Fd = PyObject_AsFileDescriptor(Obj);
+ if (Fd != -1)
+ {
+ SHA512Summation Sum;
+ struct stat St;
+ if (fstat(Fd,&St) != 0 ||
+ Sum.AddFD(Fd,St.st_size) == false)
+ {
+ PyErr_SetFromErrno(PyExc_SystemError);
+ return 0;
+ }
+
+ return CppPyString(Sum.Result().Value());
+ }
+
+ PyErr_SetString(PyExc_TypeError,"Only understand strings and files");
+ return 0;
+}
+ /*}}}*/
// get_architectures - return the list of architectures /*{{{*/
// ---------------------------------------------------------------------
static const char *doc_GetArchitectures =
@@ -466,6 +473,25 @@ static PyObject *InitSystem(PyObject *Self,PyObject *Args)
return HandleErrors(Py_None);
}
/*}}}*/
+// gpgv.cc:OpenMaybeClearSignedFile /*{{{*/
+// ---------------------------------------------------------------------
+static char *doc_OpenMaybeClearSignedFile =
+"open_maybe_clear_signed_file(file: str) -> int\n\n"
+"Open a file and ignore a PGP clear signature.\n"
+"Return a open file descriptor or a error.";
+static PyObject *PyOpenMaybeClearSignedFile(PyObject *Self,PyObject *Args)
+{
+ PyApt_Filename file;
+ char errors = false;
+ if (PyArg_ParseTuple(Args,"O&",PyApt_Filename::Converter, &file,&errors) == 0)
+ return 0;
+
+ FileFd Fd;
+ if (OpenMaybeClearSignedFile(file, Fd) == false)
+ return HandleErrors(MkPyNumber(-1));
+
+ return HandleErrors(MkPyNumber(dup(Fd.Fd())));
+}
// fileutils.cc: GetLock /*{{{*/
// ---------------------------------------------------------------------
@@ -479,9 +505,9 @@ static char *doc_GetLock =
"provided by apt_pkg.FileLock instead using the with-statement.";
static PyObject *GetLock(PyObject *Self,PyObject *Args)
{
- const char *file;
+ PyApt_Filename file;
char errors = false;
- if (PyArg_ParseTuple(Args,"s|b",&file,&errors) == 0)
+ if (PyArg_ParseTuple(Args,"O&|b",PyApt_Filename::Converter, &file,&errors) == 0)
return 0;
int fd = GetLock(file, errors);
@@ -542,6 +568,9 @@ static PyMethodDef methods[] =
{"rewrite_section",RewriteSection,METH_VARARGS,doc_RewriteSection},
#endif
+ {"open_maybe_clear_signed_file",PyOpenMaybeClearSignedFile,METH_VARARGS,
+ doc_OpenMaybeClearSignedFile},
+
// Locking
{"get_lock",GetLock,METH_VARARGS,doc_GetLock},
{"pkgsystem_lock",PkgSystemLock,METH_VARARGS,doc_PkgSystemLock},
@@ -562,10 +591,11 @@ static PyMethodDef methods[] =
{"parse_depends",ParseDepends,METH_VARARGS,doc_ParseDepends},
{"parse_src_depends",ParseSrcDepends,METH_VARARGS,parse_src_depends_doc},
- // Stuff
+ // Hashes
{"md5sum",md5sum,METH_VARARGS,doc_md5sum},
{"sha1sum",sha1sum,METH_VARARGS,doc_sha1sum},
{"sha256sum",sha256sum,METH_VARARGS,doc_sha256sum},
+ {"sha512sum",sha512sum,METH_VARARGS,doc_sha512sum},
// multiarch
{"get_architectures", GetArchitectures, METH_VARARGS, doc_GetArchitectures},
@@ -617,57 +647,6 @@ static PyMethodDef methods[] =
"Convert the given RFC 1123 formatted string to a Unix timestamp."},
// DEPRECATED
- #ifdef COMPAT_0_7
- {"CheckDep",CheckDepOld,METH_VARARGS,doc_CheckDepOld},
- {"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},
-#ifdef HAVE_OPEN_MEMSTREAM
- {"RewriteSection",RewriteSection,METH_VARARGS,doc_RewriteSection},
-#endif
-
- {"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},
- {"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"},
- {"SizeToStr",StrSizeToStr,METH_VARARGS,"SizeToStr(int) -> String"},
- {"TimeToStr",StrTimeToStr,METH_VARARGS,"TimeToStr(int) -> String"},
- {"URItoFileName",StrURItoFileName,METH_VARARGS,"URItoFileName(String) -> String"},
- {"Base64Encode",StrBase64Encode,METH_VARARGS,"Base64Encode(String) -> String"},
- {"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"},
- {"GetPkgSrcRecords",GetPkgSrcRecords,METH_VARARGS,"GetPkgSrcRecords() -> PkgSrcRecords"},
- {"GetPkgSourceList",GetPkgSourceList,METH_VARARGS,"GetPkgSourceList() -> PkgSourceList"},
- {"GetPkgProblemResolver",GetPkgProblemResolver,METH_VARARGS,"GetDepProblemResolver(DepCache) -> PkgProblemResolver"},
- {"GetPkgActionGroup",GetPkgActionGroup,METH_VARARGS,"GetPkgActionGroup(DepCache) -> PkgActionGroup"},
- {"GetCdrom",GetCdrom,METH_VARARGS,"GetCdrom() -> Cdrom"},
- {"GetAcquire",GetAcquire,METH_VARARGS,"GetAcquire() -> Acquire"},
- {"GetPkgAcqFile",(PyCFunction)GetPkgAcqFile,METH_KEYWORDS|METH_VARARGS, doc_GetPkgAcqFile},
- {"GetPackageManager",GetPkgManager,METH_VARARGS,"GetPackageManager(DepCache) -> PackageManager"},
- #endif
{}
};
@@ -825,10 +804,6 @@ extern "C" void initapt_pkg()
// Global configuration, should never be deleted.
Config->NoDelete = true;
PyModule_AddObject(Module,"config",Config);
- #ifdef COMPAT_0_7
- Py_INCREF(Config);
- PyModule_AddObject(Module,"Config",Config);
- #endif
@@ -908,14 +883,6 @@ extern "C" void initapt_pkg()
MkPyNumber(pkgAcquire::Continue));
PyDict_SetItemString(PyAcquire_Type.tp_dict, "RESULT_FAILED",
MkPyNumber(pkgAcquire::Failed));
-#ifdef COMPAT_0_7
- PyDict_SetItemString(PyAcquire_Type.tp_dict, "ResultCancelled",
- MkPyNumber(pkgAcquire::Cancelled));
- PyDict_SetItemString(PyAcquire_Type.tp_dict, "ResultContinue",
- MkPyNumber(pkgAcquire::Continue));
- PyDict_SetItemString(PyAcquire_Type.tp_dict, "ResultFailed",
- MkPyNumber(pkgAcquire::Failed));
-#endif
// Dependency constants
PyDict_SetItemString(PyDependency_Type.tp_dict, "TYPE_DEPENDS",
MkPyNumber(pkgCache::Dep::Depends));
@@ -945,15 +912,9 @@ extern "C" void initapt_pkg()
PyDict_SetItemString(PyPackageManager_Type.tp_dict, "RESULT_INCOMPLETE",
MkPyNumber(pkgPackageManager::Incomplete));
-#ifdef COMPAT_0_7
- PyDict_SetItemString(PyPackageManager_Type.tp_dict, "ResultCompleted",
- MkPyNumber(pkgPackageManager::Completed));
- PyDict_SetItemString(PyPackageManager_Type.tp_dict, "ResultFailed",
- MkPyNumber(pkgPackageManager::Failed));
- PyDict_SetItemString(PyPackageManager_Type.tp_dict, "ResultIncomplete",
- MkPyNumber(pkgPackageManager::Incomplete));
-#endif
-
+ PyDict_SetItemString(PyVersion_Type.tp_dict, "MULTI_ARCH_NO",
+ MkPyNumber(pkgCache::Version::None));
+ // NONE is deprecated (#782802)
PyDict_SetItemString(PyVersion_Type.tp_dict, "MULTI_ARCH_NONE",
MkPyNumber(pkgCache::Version::None));
PyDict_SetItemString(PyVersion_Type.tp_dict, "MULTI_ARCH_ALL",
@@ -982,18 +943,6 @@ extern "C" void initapt_pkg()
PyDict_SetItemString(PyAcquireItem_Type.tp_dict, "STAT_AUTH_ERROR",
MkPyNumber(pkgAcquire::Item::StatAuthError));
-#ifdef COMPAT_0_7
- PyDict_SetItemString(PyAcquireItem_Type.tp_dict, "StatIdle",
- MkPyNumber(pkgAcquire::Item::StatIdle));
- PyDict_SetItemString(PyAcquireItem_Type.tp_dict, "StatFetching",
- MkPyNumber(pkgAcquire::Item::StatFetching));
- PyDict_SetItemString(PyAcquireItem_Type.tp_dict, "StatDone",
- MkPyNumber(pkgAcquire::Item::StatDone));
- PyDict_SetItemString(PyAcquireItem_Type.tp_dict, "StatError",
- MkPyNumber(pkgAcquire::Item::StatError));
- PyDict_SetItemString(PyAcquireItem_Type.tp_dict, "StatAuthError",
- MkPyNumber(pkgAcquire::Item::StatAuthError));
-#endif
#if PY_MAJOR_VERSION >= 3 && PY_MINOR_VERSION >= 1
PyObject *PyCapsule = PyCapsule_New(&API, "apt_pkg._C_API", NULL);
@@ -1004,8 +953,13 @@ extern "C" void initapt_pkg()
// 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 DATE
+ PyModule_AddStringConstant(Module,"DATE",DATE);
+ PyModule_AddStringConstant(Module,"TIME",TIME);
+#else
+ PyModule_AddStringConstant(Module,"DATE", "Jan 1 1970");
+ PyModule_AddStringConstant(Module,"TIME", "00:00:00");
+#endif
// My constants
PyModule_AddIntConstant(Module,"PRI_IMPORTANT",pkgCache::State::Important);
@@ -1033,39 +987,6 @@ extern "C" void initapt_pkg()
PyModule_AddIntConstant(Module,"INSTSTATE_HOLD_REINSTREQ",pkgCache::State::HoldReInstReq);
- // 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);
- PyModule_AddIntConstant(Module,"_COMPAT_0_7",1);
- #else
- PyModule_AddIntConstant(Module,"_COMPAT_0_7",0);
- #endif
#if PY_MAJOR_VERSION >= 3
return Module;
#endif
diff --git a/python/arfile.cc b/python/arfile.cc
index 96702f57..d4d7eed6 100644
--- a/python/arfile.cc
+++ b/python/arfile.cc
@@ -147,14 +147,14 @@ static const char *ararchive_getmember_doc =
"LookupError if there is no ArMember with the given name.";
static PyObject *ararchive_getmember(PyArArchiveObject *self, PyObject *arg)
{
- const char *name;
+ PyApt_Filename name;
CppPyObject<ARArchive::Member*> *ret;
- if (! (name = PyObject_AsString(arg)))
+ if (!name.init(arg))
return 0;
const ARArchive::Member *member = self->Object->FindMember(name);
if (!member) {
- PyErr_Format(PyExc_LookupError,"No member named '%s'",name);
+ PyErr_Format(PyExc_LookupError,"No member named '%s'",name.path);
return 0;
}
@@ -171,18 +171,30 @@ static const char *ararchive_extractdata_doc =
"LookupError if there is no ArMember with the given name.";
static PyObject *ararchive_extractdata(PyArArchiveObject *self, PyObject *args)
{
- char *name = 0;
- if (PyArg_ParseTuple(args, "s:extractdata", &name) == 0)
+ PyApt_Filename name;
+ if (PyArg_ParseTuple(args, "O&:extractdata", PyApt_Filename::Converter, &name) == 0)
return 0;
const ARArchive::Member *member = self->Object->FindMember(name);
if (!member) {
- PyErr_Format(PyExc_LookupError,"No member named '%s'",name);
+ PyErr_Format(PyExc_LookupError,"No member named '%s'",name.path);
+ return 0;
+ }
+ if (member->Size > SIZE_MAX) {
+ PyErr_Format(PyExc_MemoryError,
+ "Member '%s' is too large to read into memory",name.path);
return 0;
}
if (!self->Fd.Seek(member->Start))
return HandleErrors();
- char* value = new char[member->Size];
+ char* value;
+ try {
+ value = new char[member->Size];
+ } catch (std::bad_alloc&) {
+ PyErr_Format(PyExc_MemoryError,
+ "Member '%s' is too large to read into memory",name.path);
+ return 0;
+ }
self->Fd.Read(value, member->Size, true);
PyObject *result = PyBytes_FromStringAndSize(value, member->Size);
delete[] value;
@@ -221,18 +233,19 @@ static PyObject *_extract(FileFd &Fd, const ARArchive::Member *member,
// Read 4 KiB from the file, until all of the file is read. Deallocated
// automatically when the function returns.
SPtrArray<char> value = new char[4096];
- unsigned long size = member->Size;
- unsigned long read = 4096;
+ unsigned long long size = member->Size;
+ unsigned long 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)
+ if (write(outfd, value, read) != (signed long long)read)
return PyErr_SetFromErrnoWithFilename(PyExc_OSError, outfile);
size -= read;
}
- utimbuf time = {member->MTime, member->MTime};
+ utimbuf time = {static_cast<time_t>(member->MTime),
+ static_cast<time_t>(member->MTime)};
if (utime(outfile,&time) == -1)
return PyErr_SetFromErrnoWithFilename(PyExc_OSError, outfile);
Py_RETURN_TRUE;
@@ -247,15 +260,17 @@ static const char *ararchive_extract_doc =
"does not exist, raise LookupError.";
static PyObject *ararchive_extract(PyArArchiveObject *self, PyObject *args)
{
- char *name = 0;
- char *target = "";
- if (PyArg_ParseTuple(args, "s|s:extract", &name, &target) == 0)
+ PyApt_Filename name;
+ PyApt_Filename target;
+
+ target = "";
+ if (PyArg_ParseTuple(args, "O&|O&:extract", PyApt_Filename::Converter, &name, PyApt_Filename::Converter, &target) == 0)
return 0;
const ARArchive::Member *member = self->Object->FindMember(name);
if (!member) {
- PyErr_Format(PyExc_LookupError,"No member named '%s'",name);
+ PyErr_Format(PyExc_LookupError,"No member named '%s'",name.path);
return 0;
}
return _extract(self->Fd, member, target);
@@ -269,8 +284,9 @@ static const char *ararchive_extractall_doc =
static PyObject *ararchive_extractall(PyArArchiveObject *self, PyObject *args)
{
- char *target = "";
- if (PyArg_ParseTuple(args, "|s:extractall", &target) == 0)
+ PyApt_Filename target;
+ target = "";
+ if (PyArg_ParseTuple(args, "|O&:extractall", PyApt_Filename::Converter, &target) == 0)
return 0;
const ARArchive::Member *member = self->Object->Members();
@@ -292,14 +308,14 @@ static const char *ararchive_gettar_doc =
"It just opens a new TarFile on the given position in the stream.";
static PyObject *ararchive_gettar(PyArArchiveObject *self, PyObject *args)
{
- const char *name;
+ PyApt_Filename name;
const char *comp;
- if (PyArg_ParseTuple(args, "ss:gettar", &name, &comp) == 0)
+ if (PyArg_ParseTuple(args, "O&s:gettar", PyApt_Filename::Converter, &name, &comp) == 0)
return 0;
const ARArchive::Member *member = self->Object->FindMember(name);
if (!member) {
- PyErr_Format(PyExc_LookupError,"No member named '%s'",name);
+ PyErr_Format(PyExc_LookupError,"No member named '%s'",name.path);
return 0;
}
@@ -374,13 +390,13 @@ static PyObject *ararchive_new(PyTypeObject *type, PyObject *args,
{
PyObject *file;
PyArArchiveObject *self;
- char *filename = 0;
+ PyApt_Filename filename;
int fileno;
if (PyArg_ParseTuple(args,"O:__new__",&file) == 0)
return 0;
// We receive a filename.
- if ((filename = (char*)PyObject_AsString(file))) {
+ if (filename.init(file)) {
self = (PyArArchiveObject *)CppPyObject_NEW<ARArchive*>(0,type);
new (&self->Fd) FileFd(filename,FileFd::ReadOnly);
}
@@ -409,8 +425,8 @@ static void ararchive_dealloc(PyObject *self)
// Return bool or -1 (exception).
static int ararchive_contains(PyObject *self, PyObject *arg)
{
- const char *name = PyObject_AsString(arg);
- if (!name)
+ PyApt_Filename name;
+ if (!name.init(arg))
return -1;
return (GetCpp<ARArchive*>(self)->FindMember(name) != 0);
}
@@ -519,6 +535,45 @@ static PyObject *_gettar(PyDebFileObject *self, const ARArchive::Member *m,
return tarfile;
}
+/*
+ * Mostly copy-paste from APT
+ */
+static PyObject *debfile_get_tar(PyDebFileObject *self, const char *Name)
+{
+ // Get the archive member
+ const ARArchive::Member *Member = NULL;
+ const ARArchive &AR = *self->Object;
+ std::string Compressor;
+
+ std::vector<APT::Configuration::Compressor> compressor =
+ APT::Configuration::getCompressors();
+ for (std::vector<APT::Configuration::Compressor>::const_iterator c =
+ compressor.begin(); c != compressor.end(); ++c) {
+ Member = AR.FindMember(std::string(Name).append(c->Extension).c_str());
+ if (Member == NULL)
+ continue;
+ Compressor = c->Binary;
+ break;
+ }
+
+ if (Member == NULL)
+ Member = AR.FindMember(std::string(Name).c_str());
+
+ if (Member == NULL) {
+ std::string ext = std::string(Name) + ".{";
+ for (std::vector<APT::Configuration::Compressor>::const_iterator c =
+ compressor.begin(); c != compressor.end(); ++c) {
+ if (!c->Extension.empty())
+ ext.append(c->Extension.substr(1));
+ }
+ ext.append("}");
+ _error->Error(("Internal error, could not locate member %s"),
+ ext.c_str());
+ return HandleErrors();
+ }
+
+ return _gettar(self, Member, Compressor.c_str());
+}
static PyObject *debfile_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
@@ -528,34 +583,13 @@ static PyObject *debfile_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
return NULL;
// 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");
-
- // try all compression types
- std::vector<std::string> types = APT::Configuration::getCompressionTypes();
- for (std::vector<std::string>::const_iterator t = types.begin();
- t != types.end(); ++t) {
- std::string member = std::string("data.tar.").append(*t);
- std::string comp = _config->Find(std::string("Acquire::CompressionTypes::").append(*t));
- self->data = _gettar(self, self->Object->FindMember(member.c_str()),
- comp.c_str());
- if (self->data)
- break;
- }
- // no data found, we need to
- if (!self->data) {
- std::string error;
- for (std::vector<std::string>::const_iterator t = types.begin();
- t != types.end(); ++t)
- error.append(*t + ",");
- return PyErr_Format(PyExc_SystemError,
- "No debian archive, missing data.tar.{%s}",
- error.c_str());
- }
+ self->control = debfile_get_tar(self, "control.tar");
+ if (self->control == NULL)
+ return NULL;
+ self->data = debfile_get_tar(self, "data.tar");
+ if (self->data == NULL)
+ return NULL;
const ARArchive::Member *member = self->Object->FindMember("debian-binary");
if (!member)
diff --git a/python/cache.cc b/python/cache.cc
index 01330adb..e03462a5 100644
--- a/python/cache.cc
+++ b/python/cache.cc
@@ -49,7 +49,7 @@ template<typename T> struct IterListStruct
IterListStruct() : LastIndex(0) {};
bool move(unsigned long Index) {
- if (Index < 0 || (unsigned)Index >= Count())
+ if ((unsigned)Index >= Count())
{
PyErr_SetNone(PyExc_IndexError);
return false;
@@ -161,63 +161,10 @@ 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, "
- "because it causes segfaults. Delete the Cache instead.", 1);
- PyObject *CacheFilePy = GetOwner<pkgCache*>(Self);
- pkgCacheFile *Cache = GetCpp<pkgCacheFile*>(CacheFilePy);
- Cache->Close();
-
- Py_INCREF(Py_None);
- return HandleErrors(Py_None);
-}
-
-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<pkgCache*>(Self);
- pkgCacheFile *Cache = GetCpp<pkgCacheFile*>(CacheFilePy);
-
- PyObject *pyCallbackInst = 0;
- if (PyArg_ParseTuple(Args, "|O", &pyCallbackInst) == 0)
- return 0;
-
- if(pyCallbackInst != 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();
- }
-
- //std::cout << "new cache is " << (pkgCache*)(*Cache) << std::endl;
-
- // ensure that the states are correct (LP: #659438)
- pkgApplyStatus(*Cache);
-
- // update the cache pointer after the cache was rebuild
- ((CppPyObject<pkgCache*> *)Self)->Object = (pkgCache*)(*Cache);
-
- Py_INCREF(Py_None);
- return HandleErrors(Py_None);
-}
-#endif
static PyMethodDef PkgCacheMethods[] =
{
{"update",PkgCacheUpdate,METH_VARARGS,cache_update_doc},
-#ifdef COMPAT_0_7
- {"Open", PkgCacheOpen, METH_VARARGS,
- "Open the cache; deprecated and unsafe"},
- {"Close", PkgCacheClose, METH_VARARGS,"Close the cache"},
-#endif
{}
};
@@ -233,8 +180,12 @@ static PyObject *PkgCacheGetGroups(PyObject *Self, void*) {
static PyObject *PkgCacheGetPolicy(PyObject *Self, void*) {
pkgCacheFile *CacheFile = GetCpp<pkgCacheFile *>(Self);
- std::cerr << "policy: " << CacheFile->Policy << std::endl;
- return CppPyObject_NEW<pkgPolicy*>(Self,&PyPolicy_Type,CacheFile->Policy);
+ CppPyObject<pkgPolicy*> *obj;
+
+ obj = CppPyObject_NEW<pkgPolicy*>(Self,&PyPolicy_Type,CacheFile->Policy);
+ obj->NoDelete = true;
+
+ return obj;
}
static PyObject *PkgCacheGetPackages(PyObject *Self, void*) {
@@ -378,7 +329,7 @@ static PyObject *PkgCacheNew(PyTypeObject *type,PyObject *Args,PyObject *kwds)
if (pyCallbackInst == Py_None) {
OpProgress Prog;
- if (Cache->Open(Prog,false) == false)
+ if (Cache->Open(&Prog,false) == false)
return HandleErrors();
} else if(pyCallbackInst != 0) {
// sanity check for the progress object, see #497049
@@ -394,12 +345,12 @@ static PyObject *PkgCacheNew(PyTypeObject *type,PyObject *Args,PyObject *kwds)
}
PyOpProgress progress;
progress.setCallbackInst(pyCallbackInst);
- if (Cache->Open(progress,false) == false)
+ if (Cache->Open(&progress,false) == false)
return HandleErrors();
}
else {
OpTextProgress Prog;
- if (Cache->Open(Prog,false) == false)
+ if (Cache->Open(&Prog,false) == false)
return HandleErrors();
}
@@ -645,7 +596,16 @@ PyTypeObject PyGroupList_Type =
MkGet(PackageGetName,PyString_FromString(Pkg.Name()))
MkGet(PackageGetArch,PyString_FromString(Pkg.Arch()))
-MkGet(PackageGetSection,Safe_FromString(Pkg.Section()))
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
+static PyObject *PackageGetSection(PyObject *Self,void*)
+{
+ pkgCache::PkgIterator &Pkg = GetCpp<pkgCache::PkgIterator>(Self);
+ if (PyErr_WarnEx(PyExc_DeprecationWarning, "Package.section is deprecated, use Version.section instead", 1) == -1)
+ return NULL;
+ return Safe_FromString(Pkg.Section());
+}
+#pragma GCC diagnostic pop
MkGet(PackageGetRevDependsList,CppPyObject_NEW<RDepListStruct>(Owner,
&PyDependencyList_Type, Pkg.RevDependsList()))
MkGet(PackageGetProvidesList,CreateProvides(Owner,Pkg.ProvidesList()))
@@ -654,7 +614,6 @@ MkGet(PackageGetInstState,MkPyNumber(Pkg->InstState))
MkGet(PackageGetCurrentState,MkPyNumber(Pkg->CurrentState))
MkGet(PackageGetID,MkPyNumber(Pkg->ID))
#
-MkGet(PackageGetAuto,PyBool_FromLong((Pkg->Flags & pkgCache::Flag::Auto) != 0))
MkGet(PackageGetEssential,PyBool_FromLong((Pkg->Flags & pkgCache::Flag::Essential) != 0))
MkGet(PackageGetImportant,PyBool_FromLong((Pkg->Flags & pkgCache::Flag::Important) != 0))
#undef MkGet
@@ -755,9 +714,6 @@ static PyGetSetDef PackageGetSet[] = {
"CURSTATE_UNPACKED of the apt_pkg module."},
{"id",PackageGetID,0,
"The numeric ID of the package"},
- {"auto",PackageGetAuto,0,
- "Ignore it, it does nothing. You want to use\n"
- "DepCache.is_auto_installed instead."},
{"essential",PackageGetEssential,0,
"Boolean value determining whether the package is essential."},
{"important",PackageGetImportant,0,
@@ -777,11 +733,8 @@ static PyGetSetDef PackageGetSet[] = {
static PyObject *PackageRepr(PyObject *Self)
{
pkgCache::PkgIterator &Pkg = GetCpp<pkgCache::PkgIterator>(Self);
-
- return PyString_FromFormat("<%s object: name:'%s' section: "
- "'%s' id:%u>", Self->ob_type->tp_name,
- Pkg.Name(), (Pkg.Section() ? Pkg.Section() : ""),
- Pkg->ID);
+ return PyString_FromFormat("<%s object: name:'%s' id:%u>", Self->ob_type->tp_name,
+ Pkg.Name(), Pkg->ID);
}
static const char *package_doc =
@@ -1506,7 +1459,8 @@ static PyObject *DependencyGetID(PyObject *Self,void*)
static PyGetSetDef DependencyGetSet[] = {
{"comp_type",DependencyGetCompType,0,
- "The type of comparison, as a string (one of '<', '<=', '=', '>=', '>')."},
+ "The type of comparison, as a string, namely one of:\n"
+ "'<', '<=', '=', '!=', '>=', '>', ''."},
{"dep_type",DependencyGetDepType,0,
"The type of the dependency; may be translated"},
{"dep_type_untranslated",DependencyGetDepTypeUntranslated,0,
@@ -1654,11 +1608,3 @@ PyTypeObject PyDependencyList_Type =
/*}}}*/
-#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(&PyCache_Type,Args,0);
-}
-#endif
diff --git a/python/cdrom.cc b/python/cdrom.cc
index 46bb769c..392dd834 100644
--- a/python/cdrom.cc
+++ b/python/cdrom.cc
@@ -78,38 +78,10 @@ static PyObject *cdrom_ident(PyObject *Self,PyObject *Args)
}
}
-#ifdef COMPAT_0_7
-static PyObject *cdrom_ident_old(PyObject *Self,PyObject *Args)
-{
- PyErr_WarnEx(PyExc_DeprecationWarning, "Method 'Ident' of the "
- "'apt_pkg.Cdrom' object is deprecated, use 'ident' instead.",
- 1);
- pkgCdrom &Cdrom = GetCpp<pkgCdrom>(Self);
-
- PyObject *pyCdromProgressInst = 0;
- if (PyArg_ParseTuple(Args, "O", &pyCdromProgressInst) == 0) {
- return 0;
- }
-
- PyCdromProgress progress;
- progress.setCallbackInst(pyCdromProgressInst);
-
- std::string ident;
- bool res = Cdrom.Ident(ident, &progress);
-
- PyObject *boolres = PyBool_FromLong(res);
- PyObject *result = Py_BuildValue("(Os)", boolres, ident.c_str());
-
- return HandleErrors(result);
-}
-#endif
static PyMethodDef cdrom_methods[] = {
{"add",cdrom_add,METH_VARARGS,cdrom_add_doc},
{"ident",cdrom_ident,METH_VARARGS,cdrom_ident_doc},
-#ifdef COMPAT_0_7
- {"Ident",cdrom_ident_old,METH_VARARGS,"DEPRECATED. DO NOT USE"},
-#endif
{}
};
@@ -165,11 +137,3 @@ PyTypeObject PyCdrom_Type = {
cdrom_new, // tp_new
};
-#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 cdrom_new(&PyCdrom_Type,Args,0);
-}
-#endif
diff --git a/python/configuration.cc b/python/configuration.cc
index 37374625..c57bc79c 100644
--- a/python/configuration.cc
+++ b/python/configuration.cc
@@ -351,8 +351,8 @@ char *doc_LoadConfig =
"options in the configuration object.";
PyObject *LoadConfig(PyObject *Self,PyObject *Args)
{
- char *Name = 0;
- if (PyArg_ParseTuple(Args,"Os",&Self,&Name) == 0)
+ PyApt_Filename Name;
+ if (PyArg_ParseTuple(Args,"OO&",&Self,PyApt_Filename::Converter, &Name) == 0)
return 0;
if (PyConfiguration_Check(Self)== 0)
{
@@ -373,8 +373,8 @@ char *doc_LoadConfigISC =
"configuration files.";
PyObject *LoadConfigISC(PyObject *Self,PyObject *Args)
{
- char *Name = 0;
- if (PyArg_ParseTuple(Args,"Os",&Self,&Name) == 0)
+ PyApt_Filename Name;
+ if (PyArg_ParseTuple(Args,"OO&",&Self,PyApt_Filename::Converter, &Name) == 0)
return 0;
if (PyConfiguration_Check(Self)== 0)
{
@@ -394,8 +394,8 @@ char *doc_LoadConfigDir =
"correct order.";
PyObject *LoadConfigDir(PyObject *Self,PyObject *Args)
{
- char *Name = 0;
- if (PyArg_ParseTuple(Args,"Os",&Self,&Name) == 0)
+ PyApt_Filename Name;
+ if (PyArg_ParseTuple(Args,"OO&",&Self,PyApt_Filename::Converter, &Name) == 0)
return 0;
if (PyConfiguration_Check(Self)== 0)
{
diff --git a/python/depcache.cc b/python/depcache.cc
index 73993c82..c9dc79f3 100644
--- a/python/depcache.cc
+++ b/python/depcache.cc
@@ -89,9 +89,11 @@ static PyObject *PkgDepCacheCommit(PyObject *Self,PyObject *Args)
PyFetchProgress progress;
progress.setCallbackInst(pyFetchProgressInst);
- pkgAcquire Fetcher(&progress);
+ pkgAcquire Fetcher;
pkgPackageManager *PM;
PM = _system->CreatePM(depcache);
+
+ Fetcher.Setup(&progress);
if(PM->GetArchives(&Fetcher, &List, &Recs) == false ||
_error->PendingError() == true) {
std::cerr << "Error in GetArchives" << std::endl;
@@ -109,7 +111,7 @@ static PyObject *PkgDepCacheCommit(PyObject *Self,PyObject *Args)
bool Transient = false;
if (Fetcher.Run() == pkgAcquire::Failed)
- return false;
+ return HandleErrors();
// Print out errors
bool Failed = false;
@@ -794,14 +796,6 @@ PyTypeObject PyDepCache_Type =
PkgDepCacheNew, // tp_new
};
-#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(&PyDepCache_Type,Args,0);
-}
-#endif
@@ -829,14 +823,6 @@ static PyObject *PkgProblemResolverNew(PyTypeObject *type,PyObject *Args,PyObjec
return PkgProblemResolverPyObj;
}
-#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(&PyProblemResolver_Type,Args,0);
-}
-#endif
static PyObject *PkgProblemResolverResolve(PyObject *Self,PyObject *Args)
{
@@ -909,7 +895,9 @@ static PyObject *PkgProblemResolverInstallProtect(PyObject *Self,PyObject *Args)
pkgProblemResolver *fixer = GetCpp<pkgProblemResolver *>(Self);
if (PyArg_ParseTuple(Args,"") == 0)
return 0;
+ PY_APT_BEGIN_DEPRECATED;
fixer->InstallProtect();
+ PY_APT_END_DEPRECATED;
Py_INCREF(Py_None);
return HandleErrors(Py_None);
}
@@ -1121,15 +1109,6 @@ PyTypeObject PyActionGroup_Type =
PkgActionGroupNew, // tp_new
};
-#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(&PyActionGroup_Type,Args,0);
-}
-#endif
/*}}}*/
diff --git a/python/generic.cc b/python/generic.cc
index e04743ff..5e712899 100644
--- a/python/generic.cc
+++ b/python/generic.cc
@@ -49,75 +49,6 @@ PyObject *HandleErrors(PyObject *Res)
return 0;
}
-# ifdef COMPAT_0_7
-// Helpers for deprecation.
-
-// Given the name of the old attribute, return the name of the new attribute
-// in a PyObject.
-static PyObject *_PyApt_NewNameForAttribute(const char *attr) {
- // Some exceptions from the standard algorithm.
- if (strcasecmp(attr, "FileName") == 0) return PyString_FromString("filename");
- if (strcasecmp(attr, "DestFile") == 0) return PyString_FromString("destfile");
- if (strcasecmp(attr, "FileSize") == 0) return PyString_FromString("filesize");
- if (strcasecmp(attr, "SubTree") == 0) return PyString_FromString("subtree");
- if (strcasecmp(attr, "ReadPinFile") == 0) return PyString_FromString("read_pinfile");
- if (strcasecmp(attr, "SetReInstall") == 0) return PyString_FromString("set_reinstall");
- if (strcasecmp(attr, "URI") == 0) return PyString_FromString("uri");
- if (strcasecmp(attr, "ArchiveURI") == 0) return PyString_FromString("archive_uri");
- if (strcasecmp(attr, "MD5Hash") == 0) return PyString_FromString("md5_hash");
- if (strcasecmp(attr, "SHA1Hash") == 0) return PyString_FromString("sha1_hash");
- if (strcasecmp(attr, "SHA256Hash") == 0) return PyString_FromString("sha256_hash");
- if (strcasecmp(attr, "UntranslatedDepType") == 0) return PyString_FromString("dep_type_untranslated");
- size_t attrlen = strlen(attr);
- // Reserve the old name + 5, this should reduce resize to a minimum.
- string new_name;
- new_name.reserve(attrlen + 5);
- for(unsigned int i=0; i < attrlen; i++) {
- // Replace all uppercase ASCII characters with their lower-case ones.
- if (attr[i] > 64 && attr[i] < 91) {
- if (i > 0)
- new_name += "_";
- new_name += attr[i] + 32;
- } else {
- new_name += attr[i];
- }
- }
- return CppPyString(new_name);
-}
-
-// Handle deprecated attributes by setting a warning and returning the new
-// attribute.
-PyObject *_PyAptObject_getattro(PyObject *self, PyObject *attr) {
- PyObject *value = PyObject_GenericGetAttr(self, attr);
- if (value == NULL) {
- PyObject *ptype, *pvalue, *ptraceback;
- PyErr_Fetch(&ptype, &pvalue, &ptraceback);
- const char *attrname = PyObject_AsString(attr);
- PyObject *newattr = _PyApt_NewNameForAttribute(attrname);
- value = PyObject_GenericGetAttr(self, newattr);
- if (value != NULL) {
- const char *newattrname = PyString_AsString(newattr);
- const char *cls = self->ob_type->tp_name;
- char *warning_string = new char[strlen(newattrname) + strlen(cls) +
- strlen(attrname) + 66];
- sprintf(warning_string, "Attribute '%s' of the '%s' object is "
- "deprecated, use '%s' instead.", attrname, cls, newattrname);
- PyErr_WarnEx(PyExc_DeprecationWarning, warning_string, 1);
- delete[] warning_string;
- } else {
- Py_XINCREF(ptype);
- Py_XINCREF(pvalue);
- Py_XINCREF(ptraceback);
- PyErr_Restore(ptype, pvalue, ptraceback);
- }
- Py_DECREF(newattr);
- Py_XDECREF(ptype);
- Py_XDECREF(pvalue);
- Py_XDECREF(ptraceback);
- }
- return value;
-}
-# endif //COMPAT_0_7
/*}}}*/
// ListToCharChar - Convert a list to an array of char char /*{{{*/
// ---------------------------------------------------------------------
@@ -162,3 +93,26 @@ PyObject *CharCharToList(const char **List,unsigned long Size)
return PList;
}
/*}}}*/
+
+int PyApt_Filename::init(PyObject *object)
+{
+ this->object = NULL;
+ this->path = NULL;
+
+#if PY_MAJOR_VERSION < 3 || (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION < 2)
+ this->path = PyObject_AsString(object);
+ return this->path ? 1 : 0;
+#else
+ if (PyUnicode_Check(object)) {
+ object = PyUnicode_EncodeFSDefault(object);
+ } else if (PyBytes_Check(object)) {
+ Py_INCREF(object);
+ } else {
+ return 0;
+ }
+
+ this->object = object;
+ this->path = PyBytes_AS_STRING(this->object);
+ return 1;
+#endif
+}
diff --git a/python/generic.h b/python/generic.h
index 914456e2..bcc4a5e4 100644
--- a/python/generic.h
+++ b/python/generic.h
@@ -58,8 +58,6 @@ typedef int Py_ssize_t;
#define PyInt_Check PyLong_Check
#define PyInt_AsLong PyLong_AsLong
#define PyInt_FromLong PyLong_FromLong
-// 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)
@@ -77,6 +75,11 @@ typedef int Py_ssize_t;
#define PyErr_WarnEx(cat,msg,stacklevel) PyErr_Warn(cat,msg)
#endif
+#define PY_APT_BEGIN_DEPRECATED { \
+ _Pragma("GCC diagnostic push"); \
+ _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\""); }
+#define PY_APT_END_DEPRECATED _Pragma("GCC diagnostic pop")
+
static inline const char *PyUnicode_AsString(PyObject *op) {
// Convert to bytes object, using the default encoding.
@@ -247,14 +250,50 @@ inline PyObject *MkPyNumber(long long o) { return PyLong_FromLongLong(o); }
inline PyObject *MkPyNumber(long o) { return PyInt_FromLong(o); }
inline PyObject *MkPyNumber(int o) { return PyInt_FromLong(o); }
inline PyObject *MkPyNumber(short o) { return PyInt_FromLong(o); }
-inline PyObject *MkPyNumber(char o) { return PyInt_FromLong(o); }
+inline PyObject *MkPyNumber(signed char o) { return PyInt_FromLong(o); }
inline PyObject *MkPyNumber(double o) { return PyFloat_FromDouble(o); }
-# ifdef COMPAT_0_7
-PyObject *_PyAptObject_getattro(PyObject *self, PyObject *attr);
-# else
# define _PyAptObject_getattro 0
-# endif
+
+
+/**
+ * Magic class for file name handling
+ *
+ * This manages decoding file names from Python objects; bytes and unicode
+ * objects. On Python 2, this does the same conversion as PyObject_AsString,
+ * on Python3, it uses PyUnicode_EncodeFSDefault for unicode objects.
+ */
+class PyApt_Filename {
+public:
+ PyObject *object;
+ const char *path;
+
+ PyApt_Filename() {
+ object = NULL;
+ path = NULL;
+ }
+
+ int init(PyObject *object);
+
+ ~PyApt_Filename() {
+ Py_XDECREF(object);
+ }
+
+ static int Converter(PyObject *object, void *out) {
+ return static_cast<PyApt_Filename *>(out)->init(object);
+ }
+
+ operator const char *() {
+ return path;
+ }
+ operator const std::string() {
+ return path;
+ }
+
+ const char *operator=(const char *path) {
+ return this->path = path;
+ }
+};
#endif
diff --git a/python/indexfile.cc b/python/indexfile.cc
index bf0df516..1a146bac 100644
--- a/python/indexfile.cc
+++ b/python/indexfile.cc
@@ -18,9 +18,9 @@
static PyObject *IndexFileArchiveURI(PyObject *Self,PyObject *Args)
{
pkgIndexFile *File = GetCpp<pkgIndexFile*>(Self);
- char *path;
+ PyApt_Filename path;
- if (PyArg_ParseTuple(Args, "s",&path) == 0)
+ if (PyArg_ParseTuple(Args, "O&", PyApt_Filename::Converter, &path) == 0)
return 0;
return HandleErrors(Safe_FromString(File->ArchiveURI(path).c_str()));
}
diff --git a/python/indexrecords.cc b/python/indexrecords.cc
index c7623cfd..9446fad1 100644
--- a/python/indexrecords.cc
+++ b/python/indexrecords.cc
@@ -37,8 +37,8 @@ static PyObject *indexrecords_new(PyTypeObject *type,PyObject *Args,
static PyObject *indexrecords_load(PyObject *self,PyObject *args)
{
- const char *filename;
- if (PyArg_ParseTuple(args, "s", &filename) == 0)
+ PyApt_Filename filename;
+ if (PyArg_ParseTuple(args, "O&", PyApt_Filename::Converter, &filename) == 0)
return 0;
indexRecords *records = GetCpp<indexRecords*>(self);
return HandleErrors(PyBool_FromLong(records->Load(filename)));
@@ -51,8 +51,8 @@ static char *indexrecords_lookup_doc =
"and the second element 'size' is an int object.";
static PyObject *indexrecords_lookup(PyObject *self,PyObject *args)
{
- const char *keyname;
- if (PyArg_ParseTuple(args, "s", &keyname) == 0)
+ PyApt_Filename keyname;
+ if (PyArg_ParseTuple(args, "O&", PyApt_Filename::Converter, &keyname) == 0)
return 0;
indexRecords *records = GetCpp<indexRecords*>(self);
const indexRecords::checkSum *result = records->Lookup(keyname);
diff --git a/python/lock.cc b/python/lock.cc
index 38a2bc74..7a76c9fd 100644
--- a/python/lock.cc
+++ b/python/lock.cc
@@ -183,9 +183,10 @@ static PyObject *filelock_exit(filelock_object *self, PyObject *args)
static PyObject *filelock_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- char *filename = 0;
+ PyApt_Filename filename;
char *kwlist[] = {"filename", NULL};
- if (PyArg_ParseTupleAndKeywords(args, kwds, "s:__init__", kwlist,
+ if (PyArg_ParseTupleAndKeywords(args, kwds, "O&:__init__", kwlist,
+ PyApt_Filename::Converter,
&filename) == 0) {
return NULL;
}
diff --git a/python/pkgmanager.cc b/python/pkgmanager.cc
index 9a5d0e5b..05f033f3 100644
--- a/python/pkgmanager.cc
+++ b/python/pkgmanager.cc
@@ -191,7 +191,7 @@ class PyPkgManager : public pkgDPkgPM {
StatusFd));
}
virtual void Reset() {
- CppPyRef(PyObject_CallMethod(pyinst, "reset", NULL));
+ Py_XDECREF(PyObject_CallMethod(pyinst, "reset", NULL));
}
public:
@@ -225,23 +225,14 @@ static PyObject *PkgManagerNew(PyTypeObject *type,PyObject *Args,PyObject *kwds)
return PkgManagerObj;
}
-#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(&PyPackageManager2_Type,Args,0);
-}
-#endif
static PyObject *PkgManagerInstall(PyObject *Self,PyObject *Args)
{
PyPkgManager *pm = GetCpp<PyPkgManager*>(Self);
PyObject *pkg;
- const char *file;
+ PyApt_Filename file;
- if (PyArg_ParseTuple(Args, "O!s", &PyPackage_Type,&pkg, &file) == 0)
+ if (PyArg_ParseTuple(Args, "O!O&", &PyPackage_Type,&pkg, PyApt_Filename::Converter, &file) == 0)
return 0;
return HandleErrors(PyBool_FromLong(pm->callInstall(PyPackage_ToCpp(pkg), file)));
diff --git a/python/pkgrecords.cc b/python/pkgrecords.cc
index 8d2cb502..8e6084a9 100644
--- a/python/pkgrecords.cc
+++ b/python/pkgrecords.cc
@@ -218,12 +218,3 @@ PyTypeObject PyPackageRecords_Type =
/*}}}*/
-#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(&PyPackageRecords_Type,Args,0);
-}
-#endif
diff --git a/python/pkgsrcrecords.cc b/python/pkgsrcrecords.cc
index 4c889129..6ec4e63c 100644
--- a/python/pkgsrcrecords.cc
+++ b/python/pkgsrcrecords.cc
@@ -75,10 +75,34 @@ static PyObject *PkgSrcRecordsRestart(PyObject *Self,PyObject *Args)
return HandleErrors(Py_None);
}
+static char *doc_PkgSrcRecordsStep =
+ "step() -> bool\n\n"
+ "Go to the source package. Each call moves\n"
+ "the position of the records parser forward. If there are no\n"
+ "more records, return None. If the lookup failed this way,\n"
+ "access to any of the attributes will result in an AttributeError.";
+static PyObject *PkgSrcRecordsStep(PyObject *Self,PyObject *Args)
+{
+ PkgSrcRecordsStruct &Struct = GetCpp<PkgSrcRecordsStruct>(Self);
+
+ if (PyArg_ParseTuple(Args,"") == 0)
+ return 0;
+
+ Struct.Last = (pkgSrcRecords::Parser*)Struct.Records->Step();
+ if (Struct.Last == 0) {
+ Struct.Records->Restart();
+ Py_INCREF(Py_None);
+ return HandleErrors(Py_None);
+ }
+
+ return PyBool_FromLong(1);
+}
+
static PyMethodDef PkgSrcRecordsMethods[] =
{
{"lookup",PkgSrcRecordsLookup,METH_VARARGS,doc_PkgSrcRecordsLookup},
{"restart",PkgSrcRecordsRestart,METH_VARARGS,doc_PkgSrcRecordsRestart},
+ {"step",PkgSrcRecordsStep,METH_VARARGS,doc_PkgSrcRecordsStep},
{}
};
@@ -205,29 +229,6 @@ static PyObject *PkgSrcRecordsGetBuildDepends(PyObject *Self,void*) {
return Dict;
}
-#ifdef COMPAT_0_7
-static PyObject *PkgSrcRecordsGetBuildDepends_old(PyObject *Self,void*) {
- PkgSrcRecordsStruct &Struct = GetStruct(Self,"BuildDepends");
- if (Struct.Last == 0)
- return 0;
- PyObject *List = PyList_New(0);
-
- vector<pkgSrcRecords::Parser::BuildDepRec> bd;
- if(!Struct.Last->BuildDepends(bd, false /* arch-only*/))
- return NULL; // error
-
- PyObject *v;
- for(unsigned int i=0;i<bd.size();i++) {
- v = Py_BuildValue("(ssNN)", bd[i].Package.c_str(),
- bd[i].Version.c_str(),
- MkPyNumber(bd[i].Op),
- MkPyNumber(bd[i].Type));
- PyList_Append(List, v);
- Py_DECREF(v);
- }
- return List;
-}
-#endif
static PyGetSetDef PkgSrcRecordsGetSet[] = {
{"binaries",PkgSrcRecordsGetBinaries,0,
@@ -251,9 +252,6 @@ static PyGetSetDef PkgSrcRecordsGetSet[] = {
"The section of the source package."},
{"version",PkgSrcRecordsGetVersion,0,
"The version of the source package."},
-#ifdef COMPAT_0_7
- {"BuildDepends",PkgSrcRecordsGetBuildDepends_old,0,"Deprecated function and deprecated output format."},
-#endif
{}
};
@@ -316,15 +314,3 @@ PyTypeObject PySourceRecords_Type =
/*}}}*/
-#ifdef COMPAT_0_7
-PyObject *GetPkgSrcRecords(PyObject *Self,PyObject *Args)
-{
- 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;
-
- return HandleErrors(CppPyObject_NEW<PkgSrcRecordsStruct>(NULL, &PySourceRecords_Type));
-}
-#endif
diff --git a/python/policy.cc b/python/policy.cc
index 96b83abd..0ace3e67 100644
--- a/python/policy.cc
+++ b/python/policy.cc
@@ -93,11 +93,12 @@ static char *policy_read_pinfile_doc =
"and add it to the policy.";
static PyObject *policy_read_pinfile(PyObject *self, PyObject *arg) {
- if (!PyString_Check(arg))
+ PyApt_Filename name;
+ if (!name.init(arg))
return 0;
pkgPolicy *policy = GetCpp<pkgPolicy *>(self);
- return PyBool_FromLong(ReadPinFile(*policy, PyString_AsString(arg)));
+ return PyBool_FromLong(ReadPinFile(*policy, name));
}
#if (APT_PKG_MAJOR >= 4 && APT_PKG_MINOR >= 8)
@@ -107,11 +108,12 @@ static char *policy_read_pindir_doc =
"and add them to the policy.";
static PyObject *policy_read_pindir(PyObject *self, PyObject *arg) {
- if (!PyString_Check(arg))
+ PyApt_Filename name;
+ if (!name.init(arg))
return 0;
pkgPolicy *policy = GetCpp<pkgPolicy *>(self);
- return PyBool_FromLong(ReadPinDir(*policy, PyString_AsString(arg)));
+ return PyBool_FromLong(ReadPinDir(*policy, name));
}
#endif
@@ -132,9 +134,9 @@ static PyObject *policy_create_pin(PyObject *self, PyObject *args) {
pkgPolicy *policy = GetCpp<pkgPolicy *>(self);
if (strcmp(type,"Version") == 0 || strcmp(type, "version") == 0)
match_type = pkgVersionMatch::Version;
- if (strcmp(type,"Release") == 0 || strcmp(type, "release") == 0)
+ else if (strcmp(type,"Release") == 0 || strcmp(type, "release") == 0)
match_type = pkgVersionMatch::Release;
- if (strcmp(type,"Origin") == 0 || strcmp(type, "origin") == 0)
+ else if (strcmp(type,"Origin") == 0 || strcmp(type, "origin") == 0)
match_type = pkgVersionMatch::Origin;
else
match_type = pkgVersionMatch::None;
diff --git a/python/progress.cc b/python/progress.cc
index 9e870875..425ca501 100644
--- a/python/progress.cc
+++ b/python/progress.cc
@@ -95,15 +95,7 @@ void PyOpProgress::Update()
setattr(callbackInst, "subop", "s", SubOp.c_str());
setattr(callbackInst, "major_change", "b", MajorChange);
setattr(callbackInst, "percent", "N", MkPyNumber(Percent));
-#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("(N)", MkPyNumber(Percent));
- RunSimpleCallback("update", arglist);
-#else
RunSimpleCallback("update");
-#endif
}
void PyOpProgress::Done()
@@ -134,7 +126,7 @@ bool PyFetchProgress::MediaChange(std::string Media, std::string Drive)
PyCbObj_END_ALLOW_THREADS
//std::cout << "MediaChange" << std::endl;
PyObject *arglist = Py_BuildValue("(ss)", Media.c_str(), Drive.c_str());
- PyObject *result;
+ PyObject *result = NULL;
if(PyObject_HasAttrString(callbackInst, "mediaChange"))
RunSimpleCallback("mediaChange", arglist, &result);
@@ -241,13 +233,6 @@ void PyFetchProgress::Start()
//std::cout << "Start" << std::endl;
pkgAcquireStatus::Start();
-#ifdef COMPAT_0_7
- setattr(callbackInst, "currentCPS", "N", MkPyNumber(0));
- setattr(callbackInst, "currentBytes", "N", MkPyNumber(0));
- setattr(callbackInst, "currentItems", "N", MkPyNumber(0));
- setattr(callbackInst, "totalItems", "N", MkPyNumber(0));
- setattr(callbackInst, "totalBytes", "N", MkPyNumber(0));
-#endif
RunSimpleCallback("start");
/* After calling the start method we can safely allow
@@ -314,106 +299,7 @@ bool PyFetchProgress::Pulse(pkgAcquire * Owner)
PyCbObj_BEGIN_ALLOW_THREADS
return true;
}
-#ifdef COMPAT_0_7
- setattr(callbackInst, "currentCPS", "N", MkPyNumber(CurrentCPS));
- setattr(callbackInst, "currentBytes", "N", MkPyNumber(CurrentBytes));
- setattr(callbackInst, "totalBytes", "N", MkPyNumber(TotalBytes));
- setattr(callbackInst, "fetchedBytes", "N", MkPyNumber(FetchedBytes));
- setattr(callbackInst, "currentItems", "N", MkPyNumber(CurrentItems));
- setattr(callbackInst, "totalItems", "N", MkPyNumber(TotalItems));
- // Go through the list of items and add active items to the
- // activeItems vector.
- map<pkgAcquire::Worker *, pkgAcquire::ItemDesc *> activeItemMap;
-
- for(pkgAcquire::Worker *Worker = Owner->WorkersBegin();
- Worker != 0; Worker = Owner->WorkerStep(Worker)) {
-
- if (Worker->CurrentItem == 0) {
- // Ignore workers with no item running
- continue;
- }
- activeItemMap.insert(std::make_pair(Worker, Worker->CurrentItem));
- }
-
- // Create the tuple that is passed as argument to pulse().
- // This tuple contains activeItemMap.size() item tuples.
- PyObject *arglist;
-
- if (((int)activeItemMap.size()) > 0) {
- PyObject *itemsTuple = PyTuple_New((Py_ssize_t) activeItemMap.size());
-
- // Go through activeItems, create an item tuple in the form
- // (URI, Description, ShortDesc, FileSize, PartialSize) and
- // add that tuple to itemsTuple.
- map<pkgAcquire::Worker *, pkgAcquire::ItemDesc *>::iterator iter;
- int tuplePos;
-
- for(tuplePos = 0, iter = activeItemMap.begin();
- iter != activeItemMap.end(); ++iter, tuplePos++) {
- pkgAcquire::Worker *worker = iter->first;
- pkgAcquire::ItemDesc *itm = iter->second;
-
- PyObject *itmTuple = Py_BuildValue("(sssNN)", itm->URI.c_str(),
- itm->Description.c_str(),
- itm->ShortDesc.c_str(),
- MkPyNumber(worker->TotalSize),
- MkPyNumber(worker->CurrentSize));
- PyTuple_SetItem(itemsTuple, tuplePos, itmTuple);
- }
-
- // Now our itemsTuple is ready for being passed to pulse().
- // pulse() is going to receive a single argument, being the
- // tuple of items, which again contains one tuple with item
- // information per item.
- //
- // Python Example:
- //
- // class MyFetchProgress(FetchProgress):
- // def pulse(self, items):
- // for itm in items:
- // uri, desc, shortdesc, filesize, partialsize = itm
- //
- arglist = PyTuple_Pack(1, itemsTuple);
- }
- else {
- arglist = Py_BuildValue("(())");
- }
-
- PyObject *result;
- bool res = true;
-
- if (RunSimpleCallback("pulse_items", arglist, &result)) {
- if (result != NULL && PyArg_Parse(result, "b", &res) && res == false) {
- // the user returned a explicit false here, stop
- PyCbObj_BEGIN_ALLOW_THREADS
- return false;
- }
- }
-
-
- arglist = Py_BuildValue("()");
- if (!RunSimpleCallback("pulse", arglist, &result)) {
- PyCbObj_BEGIN_ALLOW_THREADS
- return true;
- }
-
- if((result == NULL) || (!PyArg_Parse(result, "b", &res)))
- {
- // 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. There may be a Python exception on the stack
- // that must be cleared.
- PyErr_Clear();
- PyCbObj_BEGIN_ALLOW_THREADS
- return true;
- }
-
- PyCbObj_BEGIN_ALLOW_THREADS
- // fetching can be canceld by returning false
- return res;
-#else
return false;
-#endif
}
@@ -422,24 +308,21 @@ bool PyFetchProgress::Pulse(pkgAcquire * Owner)
void PyInstallProgress::StartUpdate()
{
- if (!RunSimpleCallback("startUpdate"))
- RunSimpleCallback("start_update");
+ RunSimpleCallback("start_update");
PyCbObj_BEGIN_ALLOW_THREADS
}
void PyInstallProgress::UpdateInterface()
{
PyCbObj_END_ALLOW_THREADS
- if (!RunSimpleCallback("updateInterface"))
- RunSimpleCallback("update_interface");
+ RunSimpleCallback("update_interface");
PyCbObj_BEGIN_ALLOW_THREADS
}
void PyInstallProgress::FinishUpdate()
{
PyCbObj_END_ALLOW_THREADS
- if (!RunSimpleCallback("finishUpdate"))
- RunSimpleCallback("finish_update");
+ RunSimpleCallback("finish_update");
}
pkgPackageManager::OrderResult PyInstallProgress::Run(pkgPackageManager *pm)
@@ -476,6 +359,9 @@ pkgPackageManager::OrderResult PyInstallProgress::Run(pkgPackageManager *pm)
child_id = fork();
}
+ PyObject *child_o = PyLong_FromLong(child_id);
+ PyObject_SetAttrString(callbackInst, "child_pid", child_o);
+ Py_DECREF(child_o);
#if 0 // FIXME: this needs to be merged into apt to support medium swaping
if (child_id == 0) {
@@ -548,16 +434,13 @@ void PyCdromProgress::Update(std::string text, int current)
{
PyObject *arglist = Py_BuildValue("(si)", text.c_str(), current);
setattr(callbackInst, "total_steps", "i", totalSteps);
- #ifdef COMPAT_0_7
- setattr(callbackInst, "totalSteps", "i", totalSteps);
- #endif
RunSimpleCallback("update", arglist);
}
bool PyCdromProgress::ChangeCdrom()
{
PyObject *arglist = Py_BuildValue("()");
- PyObject *result;
+ PyObject *result = NULL;
if (PyObject_HasAttrString(callbackInst, "changeCdrom"))
RunSimpleCallback("changeCdrom", arglist, &result);
else
@@ -576,7 +459,7 @@ bool PyCdromProgress::AskCdromName(std::string &Name)
PyObject *arglist = Py_BuildValue("()");
const char *new_name;
bool res;
- PyObject *result;
+ PyObject *result = NULL;
// Old style: (True, name) on success, (False, name) on failure.
if (PyObject_HasAttrString(callbackInst, "askAdromName")) {
diff --git a/python/sourcelist.cc b/python/sourcelist.cc
index 784b161e..a38cb1bb 100644
--- a/python/sourcelist.cc
+++ b/python/sourcelist.cc
@@ -168,12 +168,3 @@ PyTypeObject PySourceList_Type =
PkgSourceListNew, // tp_new
};
-#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(&PySourceList_Type,Args,0);
-}
-#endif
diff --git a/python/string.cc b/python/string.cc
index 62aa34e7..9b02c933 100644
--- a/python/string.cc
+++ b/python/string.cc
@@ -113,8 +113,10 @@ PyObject *StrStrToTime(PyObject *Self,PyObject *Args)
return 0;
time_t Result;
+ PY_APT_BEGIN_DEPRECATED;
if (StrToTime(Str,Result) == false)
{
+ PY_APT_END_DEPRECATED;
Py_INCREF(Py_None);
return Py_None;
}
diff --git a/python/tag.cc b/python/tag.cc
index 46fb8f34..61b919aa 100644
--- a/python/tag.cc
+++ b/python/tag.cc
@@ -338,11 +338,14 @@ static PyObject *TagFileNext(PyObject *Self)
const char *Start;
const char *Stop;
Obj.Section->Object.GetSection(Start,Stop);
- // Duplicate the data
- Obj.Section->Data = new char[Stop-Start];
- strncpy(Obj.Section->Data, Start, Stop-Start);
+ // Duplicate the data and
+ // append a \n because GetSection() will only give us a single \n
+ // but Scan() needs \n\n to work
+ Obj.Section->Data = new char[Stop-Start+2];
+ snprintf(Obj.Section->Data, Stop-Start+2, "%s\n", Start);
// Rescan it
- Obj.Section->Object.Scan(Obj.Section->Data, Stop-Start);
+ if(Obj.Section->Object.Scan(Obj.Section->Data, Stop-Start+2) == false)
+ return HandleErrors(NULL);
Py_INCREF(Obj.Section);
return HandleErrors(Obj.Section);
@@ -381,6 +384,61 @@ static PyObject *TagFileJump(PyObject *Self,PyObject *Args)
return HandleErrors(PyBool_FromLong(1));
}
+
+static char *doc_Close =
+ "close()\n\n"
+ "Close the file.";
+static PyObject *TagFileClose(PyObject *self, PyObject *args)
+{
+ if (args != NULL && !PyArg_ParseTuple(args, ""))
+ return NULL;
+
+ TagFileData &Obj = *(TagFileData *) self;
+
+ Obj.Fd.Close();
+
+ Py_INCREF(Py_None);
+ return HandleErrors(Py_None);
+}
+
+static PyObject *TagFileExit(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;
+ }
+
+ PyObject *res = TagFileClose(self, NULL);
+
+ if (res == NULL) {
+ // The close 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.
+ if (exc_type == Py_None)
+ return NULL;
+
+ PyErr_WriteUnraisable(self);
+ } else {
+ Py_DECREF(res);
+ }
+ // Return False, as required by the context manager protocol.
+ Py_RETURN_FALSE;
+}
+
+static PyObject *TagFileEnter(PyObject *self, PyObject *args)
+{
+ if (!PyArg_ParseTuple(args, ""))
+ return NULL;
+
+ Py_INCREF(self);
+
+ return self;
+}
+
/*}}}*/
// ParseSection - Parse a single section from a tag file /*{{{*/
// ---------------------------------------------------------------------
@@ -418,16 +476,6 @@ static PyObject *TagSecNew(PyTypeObject *type,PyObject *Args,PyObject *kwds) {
return New;
}
-#ifdef COMPAT_0_7
-char *doc_ParseSection = "ParseSection(Text) -> TagSection()\n\nDeprecated.";
-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(&PyTagSection_Type,Args,0);
-}
-#endif
/*}}}*/
// ParseTagFile - Parse a tagd file /*{{{*/
// ---------------------------------------------------------------------
@@ -445,9 +493,8 @@ static PyObject *TagFileNew(PyTypeObject *type,PyObject *Args,PyObject *kwds)
// check if we got a filename or a file object
int fileno = -1;
- const char *filename = NULL;
- filename = PyObject_AsString(File);
- if (filename == NULL) {
+ PyApt_Filename filename;
+ if (!filename.init(File)) {
PyErr_Clear();
fileno = PyObject_AsFileDescriptor(File);
}
@@ -485,6 +532,8 @@ static PyObject *TagFileNew(PyTypeObject *type,PyObject *Args,PyObject *kwds)
#if PY_MAJOR_VERSION >= 3
if (fileno != -1) {
New->Encoding = PyObject_GetAttr(File, PyUnicode_FromString("encoding"));
+ if (!New->Encoding)
+ PyErr_Clear();
if (New->Encoding && !PyUnicode_Check(New->Encoding))
New->Encoding = 0;
} else
@@ -507,15 +556,6 @@ static PyObject *TagFileNew(PyTypeObject *type,PyObject *Args,PyObject *kwds)
return HandleErrors(New);
}
-#ifdef COMPAT_0_7
-char *doc_ParseTagFile = "ParseTagFile(file) -> TagFile()\n\nDeprecated.";
-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(&PyTagFile_Type,Args,0);
-}
-#endif
/*}}}*/
#ifdef HAVE_OPEN_MEMSTREAM
// RewriteSection - Rewrite a section.. /*{{{*/
@@ -673,6 +713,9 @@ static PyMethodDef TagFileMethods[] =
{"step",TagFileStep,METH_VARARGS,doc_Step},
{"offset",TagFileOffset,METH_VARARGS,doc_Offset},
{"jump",TagFileJump,METH_VARARGS,doc_Jump},
+ {"close",TagFileClose,METH_VARARGS,doc_Close},
+ {"__enter__",TagFileEnter,METH_VARARGS,"Context manager entry, return self."},
+ {"__exit__",TagFileExit,METH_VARARGS,"Context manager exit, calls close."},
{}
};
diff --git a/python/tar.cc b/python/tar.cc
deleted file mode 100644
index e42a9c50..00000000
--- a/python/tar.cc
+++ /dev/null
@@ -1,197 +0,0 @@
-// -*- mode: cpp; mode: fold -*-
-// Description /*{{{*/
-// $Id: tar.cc,v 1.4 2004/12/12 17:55:54 mdz Exp $
-/* ######################################################################
-
- 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 <apt-pkg/extracttar.h>
-#include <apt-pkg/error.h>
-#include <apt-pkg/debfile.h>
-#include "apt_instmodule.h"
-
-#include <Python.h>
- /*}}}*/
-
-class ProcessTar : public pkgDirStream
-{
- public:
-
- PyObject *Function;
-
- virtual bool DoItem(Item &Itm,int &Fd);
-
- ProcessTar(PyObject *Function) : Function(Function)
- {
- Py_INCREF(Function);
- }
- virtual ~ProcessTar()
- {
- Py_DECREF(Function);
- }
-};
-
-// ProcessTar::DoItem - Feed an item to a python function /*{{{*/
-// ---------------------------------------------------------------------
-/* The function is called with a tuple that has:
- (FileName,Link,Mode,UID,GID,Size,MTime,Major,Minor) */
-bool ProcessTar::DoItem(Item &Itm,int &Fd)
-{
- const char *Type;
- switch (Itm.Type)
- {
- case Item::File:
- Type = "FILE";
- break;
-
- case Item::HardLink:
- Type = "HARDLINK";
- break;
-
- case Item::SymbolicLink:
- Type = "SYMLINK";
- break;
-
- case Item::CharDevice:
- Type = "CHARDEV";
- break;
-
- case Item::BlockDevice:
- Type = "BLKDEV";
- break;
-
- case Item::Directory:
- Type = "DIR";
- break;
-
- 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)
- return false;
-
- Fd = -1;
- return true;
-}
- /*}}}*/
-
-// tarExtract - Examine files from a tar /*{{{*/
-// ---------------------------------------------------------------------
-/* */
-char *doc_tarExtract =
-"tarExtract(File,Func,Comp) -> None\n"
-"The tar file referenced by the file object File, Func called for each\n"
-"Tar member. Comp must be the string \"gzip\" (gzip is automatically invoked) \n";
-PyObject *tarExtract(PyObject *Self,PyObject *Args)
-{
- PyObject *File;
- PyObject *Function;
- char *Comp;
-
- if (PyArg_ParseTuple(Args,"OOs",&File, &Function,&Comp) == 0)
- return 0;
-
- if (PyCallable_Check(Function) == 0)
- {
- PyErr_SetString(PyExc_TypeError,"argument 2: expected something callable.");
- return 0;
- }
-
- {
- // Open the file and associate the tar
- 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();
-
- ProcessTar Proc(Function);
- if (Tar.Go(Proc) == false)
- return HandleErrors();
- }
-
- Py_INCREF(Py_None);
- return HandleErrors(Py_None);
-}
- /*}}}*/
-
-// debExtract - Examine files from a deb /*{{{*/
-// ---------------------------------------------------------------------
-/* */
-char *doc_debExtract =
-"debExtract(File,Func,Chunk) -> None\n"
-"The deb referenced by the file object File is examined. The AR member\n"
-"given by Chunk is treated as a tar.gz and fed through Func like\n"
-"tarExtract\n";
-PyObject *debExtract(PyObject *Self,PyObject *Args)
-{
- PyObject *File;
- PyObject *Function;
- char *Chunk;
- const char *Comp = "gzip";
-
- if (PyArg_ParseTuple(Args,"OOs",&File,&Function,&Chunk) == 0)
- return 0;
-
- if (PyCallable_Check(Function) == 0)
- {
- PyErr_SetString(PyExc_TypeError,"argument 2: expected something callable.");
- 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,false);
- debDebFile Deb(Fd);
- if (_error->PendingError() == true)
- return HandleErrors();
-
- // Get the archive member and positition the file
- const ARArchive::Member *Member = Deb.GotoMember(Chunk);
- if (Member == 0)
- {
- _error->Error("Cannot find chunk %s",Chunk);
- return HandleErrors();
- }
-
- // Extract it.
- if (strcmp(".bz2", &Chunk[strlen(Chunk)-4]) == 0)
- Comp = "bzip2";
- else if(strcmp(".lzma", &Chunk[strlen(Chunk)-5]) == 0)
- Comp = "lzma";
- else if(strcmp(".xz", &Chunk[strlen(Chunk)-3]) == 0)
- Comp = "xz";
- ExtractTar Tar(Deb.GetFile(),Member->Size,Comp);
- ProcessTar Proc(Function);
- if (Tar.Go(Proc) == false)
- return HandleErrors();
- }
-
- Py_INCREF(Py_None);
- return HandleErrors(Py_None);
-}
- /*}}}*/
-#endif // defined(COMPAT_0_7)
diff --git a/python/tarfile.cc b/python/tarfile.cc
index 920f032e..0aeae662 100644
--- a/python/tarfile.cc
+++ b/python/tarfile.cc
@@ -43,7 +43,8 @@ public:
PyObject *py_data;
// The requested member or NULL.
const char *member;
- // Set to true if an error occured in the Python callback.
+ // Set to true if an error occured in the Python callback, or a file
+ // was too large to read in extractdata.
bool error;
// Place where the copy of the data is stored.
char *copy;
@@ -52,9 +53,13 @@ public:
virtual bool DoItem(Item &Itm,int &Fd);
virtual bool FinishedFile(Item &Itm,int Fd);
+#if (APT_PKG_MAJOR >= 4 && APT_PKG_MINOR >= 14)
+ virtual bool Process(Item &Itm,const unsigned char *Data,
+ unsigned long long Size,unsigned long long Pos);
+#else
virtual bool Process(Item &Itm,const unsigned char *Data,
unsigned long Size,unsigned long Pos);
-
+#endif
PyDirStream(PyObject *callback, const char *member=0) : callback(callback),
py_data(0), member(member), error(false), copy(0), copy_size(0)
{
@@ -72,9 +77,13 @@ bool PyDirStream::DoItem(Item &Itm, int &Fd)
{
if (!member || strcmp(Itm.Name, member) == 0) {
// Allocate a new buffer if the old one is too small.
+ if (Itm.Size > SIZE_MAX)
+ goto to_large;
if (copy == NULL || copy_size < Itm.Size) {
delete[] copy;
- copy = new char[Itm.Size];
+ copy = new (std::nothrow) char[Itm.Size];
+ if (copy == NULL)
+ goto to_large;
copy_size = Itm.Size;
}
Fd = -2;
@@ -82,12 +91,31 @@ bool PyDirStream::DoItem(Item &Itm, int &Fd)
Fd = -1;
}
return true;
+to_large:
+ delete[] copy;
+ copy = NULL;
+ copy_size = 0;
+ /* If we are looking for a specific member, abort reading now */
+ if (member) {
+ error = true;
+ PyErr_Format(PyExc_MemoryError,
+ "The member %s was too large to read into memory",
+ Itm.Name);
+ return false;
+ }
+ return true;
}
+#if (APT_PKG_MAJOR >= 4 && APT_PKG_MINOR >= 14)
+bool PyDirStream::Process(Item &Itm,const unsigned char *Data,
+ unsigned long long Size,unsigned long long Pos)
+#else
bool PyDirStream::Process(Item &Itm,const unsigned char *Data,
unsigned long Size,unsigned long Pos)
+#endif
{
- memcpy(copy + Pos, Data,Size);
+ if (copy != NULL)
+ memcpy(copy + Pos, Data,Size);
return true;
}
@@ -98,7 +126,12 @@ bool PyDirStream::FinishedFile(Item &Itm,int Fd)
return true;
Py_XDECREF(py_data);
- py_data = PyBytes_FromStringAndSize(copy, Itm.Size);
+ if (copy == NULL) {
+ Py_INCREF(Py_None);
+ py_data = Py_None;
+ } else {
+ py_data = PyBytes_FromStringAndSize(copy, Itm.Size);
+ }
if (!callback)
return true;
@@ -309,7 +342,7 @@ static PyObject *tarfile_new(PyTypeObject *type,PyObject *args,PyObject *kwds)
{
PyObject *file;
PyTarFileObject *self;
- char *filename;
+ PyApt_Filename filename;
int fileno;
int min = 0;
int max = 0xFFFFFFFF;
@@ -323,8 +356,8 @@ static PyObject *tarfile_new(PyTypeObject *type,PyObject *args,PyObject *kwds)
self = (PyTarFileObject*)CppPyObject_NEW<ExtractTar*>(file,type);
// We receive a filename.
- if ((filename = (char*)PyObject_AsString(file)))
- new (&self->Fd) FileFd(filename,FileFd::ReadOnly);
+ if (filename.init(file))
+ new (&self->Fd) FileFd((const char *) filename,FileFd::ReadOnly);
else if ((fileno = PyObject_AsFileDescriptor(file)) != -1) {
// clear the error set by PyObject_AsString().
PyErr_Clear();
@@ -349,8 +382,8 @@ static const char *tarfile_extractall_doc =
static PyObject *tarfile_extractall(PyObject *self, PyObject *args)
{
std::string cwd = SafeGetCWD();
- char *rootdir = 0;
- if (PyArg_ParseTuple(args,"|s:extractall",&rootdir) == 0)
+ PyApt_Filename rootdir;
+ if (PyArg_ParseTuple(args,"|O&:extractall", PyApt_Filename::Converter, &rootdir) == 0)
return 0;
if (rootdir) {
@@ -384,8 +417,8 @@ static const char *tarfile_go_doc =
static PyObject *tarfile_go(PyObject *self, PyObject *args)
{
PyObject *callback;
- char *member = 0;
- if (PyArg_ParseTuple(args,"O|s",&callback,&member) == 0)
+ PyApt_Filename member;
+ if (PyArg_ParseTuple(args,"O|O&",&callback, PyApt_Filename::Converter, &member) == 0)
return 0;
if (member && strcmp(member, "") == 0)
member = 0;
@@ -397,7 +430,7 @@ static PyObject *tarfile_go(PyObject *self, PyObject *args)
return 0;
if (member && !stream.py_data)
return PyErr_Format(PyExc_LookupError, "There is no member named '%s'",
- member);
+ member.path);
return HandleErrors(PyBool_FromLong(res));
}
@@ -407,20 +440,20 @@ static const char *tarfile_extractdata_doc =
"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)
+ PyApt_Filename member;
+ if (PyArg_ParseTuple(args,"O&", PyApt_Filename::Converter, &member) == 0)
return 0;
PyDirStream stream(NULL, member);
((PyTarFileObject*)self)->Fd.Seek(((PyTarFileObject*)self)->min);
// Go through the stream.
GetCpp<ExtractTar*>(self)->Go(stream);
+ if (stream.error)
+ return 0;
+
if (!stream.py_data)
return PyErr_Format(PyExc_LookupError, "There is no member named '%s'",
- member);
- if (stream.error) {
- return 0;
- }
+ member.path);
return Py_INCREF(stream.py_data), stream.py_data;
}