prebuild.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #include <iostream>
  2. #include <string>
  3. #include <map>
  4. #include <algorithm>
  5. #include <cstdio>
  6. #include <dirent.h>
  7. #include <ctime>
  8. std::string to_hex_string(const std::string& input) {
  9. std::string result;
  10. result.reserve(input.length() * 4);
  11. for (const auto& c : input) {
  12. char buf[5] = {0};
  13. sprintf(buf, "%02x", static_cast<unsigned char>(c));
  14. result += "\\x";
  15. result += buf;
  16. }
  17. return result;
  18. }
  19. std::map<std::string, std::string> generate_python_sources() {
  20. std::map<std::string, std::string> sources;
  21. DIR *dir;
  22. struct dirent *ent;
  23. if ((dir = opendir ("python")) != NULL)
  24. {
  25. while ((ent = readdir (dir)) != NULL)
  26. {
  27. std::string filename = ent->d_name;
  28. size_t pos = filename.rfind(".py");
  29. if (pos != std::string::npos)
  30. {
  31. std::string key = filename.substr(0, filename.length() - 3);
  32. std::string filepath = "python/" + filename;
  33. FILE* file = fopen(filepath.c_str(), "r");
  34. if(file == NULL) exit(2);
  35. std::string content;
  36. char buffer[1024];
  37. while (fgets(buffer, sizeof(buffer), file) != NULL)
  38. {
  39. content += buffer;
  40. }
  41. fclose(file);
  42. sources[key] = to_hex_string(content);
  43. }
  44. }
  45. closedir (dir);
  46. }else{
  47. exit(1);
  48. }
  49. return sources;
  50. }
  51. std::string generate_header(const std::map<std::string, std::string>& sources) {
  52. std::time_t timestamp = std::time(nullptr);
  53. std::tm* now = std::localtime(&timestamp);
  54. char timestamp_str[20];
  55. std::strftime(timestamp_str, sizeof(timestamp_str), "%Y-%m-%d %H:%M:%S", now);
  56. std::string header;
  57. header += "#pragma once\n";
  58. header += "// generated on ";
  59. header += timestamp_str;
  60. header += "\n#include <map>\n#include <string>\n\nnamespace pkpy{\n";
  61. header += " inline static std::map<std::string, std::string> kPythonLibs = {\n";
  62. for (auto it=sources.begin(); it!=sources.end(); ++it) {
  63. header += " {\"" + it->first + "\", \"" + it->second + "\"},\n";
  64. }
  65. header += " };\n";
  66. header += "} // namespace pkpy\n";
  67. return header;
  68. }
  69. int main() {
  70. auto sources = generate_python_sources();
  71. std::string header = generate_header(sources);
  72. FILE* f = fopen("src/_generated.h", "w");
  73. fprintf(f, "%s", header.c_str());
  74. fclose(f);
  75. return 0;
  76. }