PageRenderTime 26ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/Sources/Plasma/Apps/plPythonPack/main.cpp

https://github.com/Deledrius/Plasma
C++ | 402 lines | 280 code | 60 blank | 62 comment | 53 complexity | 8e61e88b2f6812deeaab6694fc911ab2 MD5 | raw file
  1. /*==LICENSE==*
  2. CyanWorlds.com Engine - MMOG client, server and tools
  3. Copyright (C) 2011 Cyan Worlds, Inc.
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation, either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. Additional permissions under GNU GPL version 3 section 7
  15. If you modify this Program, or any covered work, by linking or
  16. combining it with any of RAD Game Tools Bink SDK, Autodesk 3ds Max SDK,
  17. NVIDIA PhysX SDK, Microsoft DirectX SDK, OpenSSL library, Independent
  18. JPEG Group JPEG library, Microsoft Windows Media SDK, or Apple QuickTime SDK
  19. (or a modified version of those libraries),
  20. containing parts covered by the terms of the Bink SDK EULA, 3ds Max EULA,
  21. PhysX SDK EULA, DirectX SDK EULA, OpenSSL and SSLeay licenses, IJG
  22. JPEG Library README, Windows Media SDK EULA, or QuickTime SDK EULA, the
  23. licensors of this Program grant you additional
  24. permission to convey the resulting work. Corresponding Source for a
  25. non-source form of such a combination shall include the source code for
  26. the parts of OpenSSL and IJG JPEG Library used as well as that of the covered
  27. work.
  28. You can contact Cyan Worlds, Inc. by email legal@cyan.com
  29. or by snail mail at:
  30. Cyan Worlds, Inc.
  31. 14617 N Newport Hwy
  32. Mead, WA 99021
  33. *==LICENSE==*/
  34. #include "PythonInterface.h"
  35. #include "hsStream.h"
  36. #include "plCmdParser.h"
  37. #include <vector>
  38. #include <string>
  39. #include <algorithm>
  40. #include <string_theory/stdio>
  41. #include <unordered_set>
  42. static const char* kPackFileName = "python.pak";
  43. static const char* kModuleFile = "__init__.py";
  44. /** Directories that should not generate their own .pak file. */
  45. static const std::unordered_set<ST::string, ST::hash_i, ST::equal_i> s_ignoreSubdirs{
  46. ST_LITERAL("plasma"),
  47. ST_LITERAL("system"),
  48. ST_LITERAL("__pycache__"),
  49. };
  50. #if HS_BUILD_FOR_WIN32
  51. #define NULL_DEVICE "NUL:"
  52. #else
  53. #define NULL_DEVICE "/dev/null"
  54. #endif
  55. FILE* out = stdout;
  56. void WritePythonFile(const plFileName &fileName, const plFileName &path, hsStream *s)
  57. {
  58. hsUNIXStream pyStream, glueStream;
  59. plFileName filePath;
  60. ST_ssize_t filestart = fileName.AsString().find_last('.');
  61. plFileName glueFile = plFileName::Join("plasma", "glue.py");
  62. if (filestart >= 0)
  63. filePath = fileName.AsString().substr(filestart+1);
  64. else
  65. filePath = fileName;
  66. filePath = plFileName::Join(path, filePath + ".py");
  67. if (!pyStream.Open(filePath) || !glueStream.Open(glueFile))
  68. {
  69. ST::printf(stderr, "Unable to open path {}, ", filePath);
  70. return;
  71. }
  72. ST::printf(out, "== Packing {}, ", fileName);
  73. pyStream.FastFwd();
  74. uint32_t pyFileSize = pyStream.GetPosition();
  75. pyStream.Rewind();
  76. glueStream.FastFwd();
  77. uint32_t glueFileSize = glueStream.GetPosition();
  78. glueStream.Rewind();
  79. uint32_t totalSize = pyFileSize + glueFileSize + 2;
  80. char *code = new char[totalSize];
  81. uint32_t amountRead = pyStream.Read(pyFileSize, code);
  82. hsAssert(amountRead == pyFileSize, "Bad read");
  83. code[pyFileSize] = '\n';
  84. amountRead = glueStream.Read(glueFileSize, code+pyFileSize+1);
  85. hsAssert(amountRead == glueFileSize, "Bad read");
  86. code[totalSize-1] = '\0';
  87. // remove the CRs, they seem to give Python heartburn
  88. int k = 0;
  89. for (int i = 0; i < totalSize; i++)
  90. {
  91. if (code[i] != '\r') // is it not a CR?
  92. code[k++] = code[i];
  93. // else
  94. // skip the CRs
  95. }
  96. // import the module first, to make packages work correctly
  97. PyObject* fModule = PyImport_ImportModule(fileName.AsString().c_str());
  98. if (!fModule)
  99. ST::printf(stderr, "......import failed ");
  100. PyObject* pythonCode = PythonInterface::CompileString(code, fileName);
  101. if (pythonCode)
  102. {
  103. // run the code
  104. if (PythonInterface::RunPYC(pythonCode, fModule) )
  105. {
  106. // set the name of the file (in the global dictionary of the module)
  107. PyObject* dict = PyModule_GetDict(fModule);
  108. PyObject* pfilename = PyUnicode_FromString(fileName.AsString().c_str());
  109. PyDict_SetItemString(dict, "glue_name", pfilename);
  110. Py_DECREF(pfilename);
  111. // next we need to:
  112. // - create instance of class
  113. PyObject* getID = PythonInterface::GetModuleItem("glue_getBlockID",fModule);
  114. bool foundID = false;
  115. if (getID != nullptr && PyCallable_Check(getID))
  116. {
  117. PyObject* id = PyObject_CallFunction(getID, nullptr);
  118. if ( id && PyLong_Check(id) )
  119. foundID = true;
  120. }
  121. if ( foundID == false ) // then there was an error or no ID or somethin'
  122. {
  123. // oops, this is not a PythonFile modifier
  124. // re-read the source and compile it without the glue code this time
  125. pyStream.Rewind();
  126. amountRead = pyStream.Read(pyFileSize, code);
  127. hsAssert(amountRead == pyFileSize, "Bad read");
  128. code[amountRead] = '\n';
  129. code[amountRead+1] = '\0';
  130. k = 0;
  131. int len = strlen(code)+1;
  132. for (int i = 0; i < len; i++)
  133. {
  134. if (code[i] != '\r') // is it not a CR?
  135. code[k++] = code[i];
  136. // else
  137. // skip the CRs
  138. }
  139. pythonCode = PythonInterface::CompileString(code, fileName);
  140. hsAssert(pythonCode,"Not sure why this didn't compile the second time???");
  141. ST::printf(out, "an import file ");
  142. }
  143. else
  144. ST::printf(out, "a PythonFile modifier(tm) ");
  145. }
  146. else
  147. {
  148. ST::printf(stderr, "......blast! Error during run-code in {}!\n", fileName);
  149. PyErr_Print();
  150. }
  151. }
  152. // make sure that we have code to save
  153. if (pythonCode)
  154. {
  155. Py_ssize_t size;
  156. char* pycode;
  157. PythonInterface::DumpObject(pythonCode,&pycode,&size);
  158. ST::printf(out, "\n");
  159. s->WriteLE32((int32_t)size);
  160. s->Write(size, pycode);
  161. delete[] pycode;
  162. }
  163. else
  164. {
  165. ST::printf(stderr, "......blast! Compile error in {}!\n", fileName);
  166. s->WriteLE32(0);
  167. PyErr_Print();
  168. PyErr_Clear();
  169. }
  170. delete [] code;
  171. Py_XDECREF(pythonCode);
  172. Py_XDECREF(fModule);
  173. pyStream.Close();
  174. glueStream.Close();
  175. }
  176. void FindFiles(std::vector<plFileName> &filenames, std::vector<plFileName> &pathnames, const plFileName& path)
  177. {
  178. // Get the names of all the python files
  179. std::vector<plFileName> pys = plFileSystem::ListDir(path, "*.py");
  180. for (auto iter = pys.begin(); iter != pys.end(); ++iter)
  181. {
  182. filenames.push_back(iter->GetFileName());
  183. pathnames.push_back(path);
  184. }
  185. }
  186. void FindSubDirs(std::vector<plFileName> &dirnames, const plFileName &path)
  187. {
  188. std::vector<plFileName> subdirs = plFileSystem::ListSubdirs(path);
  189. for (auto iter = subdirs.begin(); iter != subdirs.end(); ++iter) {
  190. ST::string name = iter->GetFileName();
  191. if (s_ignoreSubdirs.find(name) == s_ignoreSubdirs.end())
  192. dirnames.push_back(name);
  193. }
  194. }
  195. void FindPackages(std::vector<plFileName>& fileNames, std::vector<plFileName>& pathNames, const plFileName& path, const ST::string& parent_package={})
  196. {
  197. std::vector<plFileName> packages;
  198. FindSubDirs(packages, path);
  199. for (int i = 0; i < packages.size(); i++)
  200. {
  201. ST::string packageName;
  202. if (!parent_package.empty())
  203. packageName = parent_package + ".";
  204. packageName += packages[i].AsString();
  205. std::vector<plFileName> packageFileNames;
  206. std::vector<plFileName> packagePathNames;
  207. plFileName packagePath = plFileName::Join(path, packages[i]);
  208. FindFiles(packageFileNames, packagePathNames, packagePath);
  209. // Check for the magic file to make sure this is really a package...
  210. if (std::find(packageFileNames.begin(), packageFileNames.end(), kModuleFile) != packageFileNames.end()) {
  211. for (int j = 0; j < packageFileNames.size(); j++) {
  212. fileNames.push_back(packageName+"."+packageFileNames[j].AsString());
  213. pathNames.push_back(packagePathNames[j]);
  214. }
  215. FindPackages(fileNames, pathNames, packagePath, packageName);
  216. }
  217. }
  218. }
  219. void PackDirectory(const plFileName& dir, const plFileName& rootPath, const plFileName& pakName, std::vector<plFileName>& extraDirs, bool packSysAndPlasma = false)
  220. {
  221. ST::printf(out, "\nCreating {} using the contents of {}\n", pakName, dir);
  222. ST::printf(out, "Changing working directory to {}\n", rootPath);
  223. if (!plFileSystem::SetCWD(rootPath))
  224. {
  225. ST::printf(stderr, "ERROR: Directory change to {} failed for some reason\n", rootPath);
  226. ST::printf(stderr, "Unable to continue with the packing of this directory, aborting...\n");
  227. return;
  228. }
  229. else
  230. ST::printf(out, "Directory changed to {}\n", rootPath);
  231. std::vector<plFileName> fileNames;
  232. std::vector<plFileName> pathNames;
  233. FindFiles(fileNames, pathNames, dir);
  234. FindPackages(fileNames, pathNames, dir);
  235. if (packSysAndPlasma)
  236. {
  237. ST::printf(out, "\nAdding the system and plasma directories to this pack file...\n");
  238. plFileName tempPath;
  239. tempPath = plFileName::Join(dir, "system");
  240. FindFiles(fileNames, pathNames, tempPath);
  241. FindPackages(fileNames, pathNames, tempPath);
  242. tempPath = plFileName::Join(dir, "plasma");
  243. FindFiles(fileNames, pathNames, tempPath);
  244. FindPackages(fileNames, pathNames, tempPath);
  245. }
  246. // ok, we know how many files we're gonna pack, so make a fake index (we'll fill in later)
  247. hsUNIXStream s;
  248. if (!s.Open(pakName, "wb"))
  249. return;
  250. s.WriteLE32((uint32_t)fileNames.size());
  251. for (const plFileName& fn : fileNames)
  252. {
  253. s.WriteSafeString(fn.AsString());
  254. s.WriteLE32(0);
  255. }
  256. PythonInterface::initPython(rootPath, extraDirs, out, stderr);
  257. std::vector<uint32_t> filePositions;
  258. filePositions.resize(fileNames.size());
  259. for (size_t i = 0; i < fileNames.size(); i++)
  260. {
  261. // strip '.py' from the file name
  262. plFileName properFileName = fileNames[i].StripFileExt();
  263. uint32_t initialPos = s.GetPosition();
  264. WritePythonFile(properFileName, pathNames[i], &s);
  265. filePositions[i] = initialPos;
  266. }
  267. s.SetPosition(sizeof(uint32_t));
  268. for (size_t i = 0; i < fileNames.size(); i++)
  269. {
  270. s.WriteSafeString(fileNames[i].AsString());
  271. s.WriteLE32(filePositions[i]);
  272. }
  273. s.Close();
  274. ST::printf(out, "\nPython Package written to {}\n", pakName);
  275. PythonInterface::finiPython();
  276. }
  277. void PrintUsage()
  278. {
  279. ST::printf("The Python Pack Utility\n");
  280. ST::printf("Usage:\n");
  281. ST::printf("plPythonPack [options] <directory to pack...>\n");
  282. ST::printf("NOTE: the directory to pack must have full system and plasma dirs.\n");
  283. ST::printf("\nAvailable options:\n");
  284. ST::printf("\t-q\tQuiet - Only print errors\n");
  285. ST::printf("\t-h\tHelp - Print this help\n");
  286. }
  287. int main(int argc, char *argv[])
  288. {
  289. // Parse arguments
  290. ST::string packDir = ".";
  291. enum { kArgPath, kArgQuiet, kArgHelp1, kArgHelp2 };
  292. const plCmdArgDef cmdLineArgs[] = {
  293. { kCmdArgOptional | kCmdTypeString, "path", kArgPath},
  294. { kCmdArgFlagged | kCmdTypeBool, "quiet", kArgQuiet},
  295. { kCmdArgFlagged | kCmdTypeBool, "help", kArgHelp1},
  296. { kCmdArgFlagged | kCmdTypeBool, "?", kArgHelp2},
  297. };
  298. std::vector<ST::string> args;
  299. args.reserve(argc);
  300. for (size_t i = 0; i < argc; i++) {
  301. args.emplace_back(ST::string::from_utf8(argv[i]));
  302. }
  303. plCmdParser cmdParser(cmdLineArgs, std::size(cmdLineArgs));
  304. if (cmdParser.Parse(args)) {
  305. if (cmdParser.GetBool(kArgHelp1) || cmdParser.GetBool(kArgHelp2)) {
  306. PrintUsage();
  307. return 0;
  308. }
  309. if (cmdParser.GetBool(kArgQuiet))
  310. out = fopen(NULL_DEVICE, "w");
  311. if (cmdParser.IsSpecified(kArgPath))
  312. packDir = cmdParser.GetString(kArgPath);
  313. } else {
  314. ST::printf(stderr, "An error occurred while parsing the provided arguments.\n");
  315. ST::printf(stderr, "Use the --help option to display usage information.\n");
  316. return 1;
  317. }
  318. ST::printf(out, "The Python Pack Utility\n");
  319. std::vector<plFileName> dirNames;
  320. FindSubDirs(dirNames, packDir);
  321. plFileName rootPath(packDir);
  322. rootPath = rootPath.AbsolutePath();
  323. PackDirectory(rootPath, rootPath, plFileName::Join(rootPath, kPackFileName), dirNames, true);
  324. for (auto it = dirNames.begin(); it != dirNames.end(); ++it) {
  325. // Make sure this subdirectory is not just a python module. Those are packed into the
  326. // main python root package...
  327. plFileName dir = plFileName::Join(rootPath, *it);
  328. if (plFileSystem::ListDir(dir, kModuleFile).empty())
  329. PackDirectory(*it, rootPath, plFileName::Join(rootPath, *it + ".pak"), dirNames);
  330. }
  331. if (out && out != stdout)
  332. fclose(out);
  333. return 0;
  334. }