prebuild.cpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #include <iostream>
  2. #include <string>
  3. #include <map>
  4. #include <algorithm>
  5. #include <filesystem>
  6. #include <fstream>
  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. for (const auto& file : std::filesystem::directory_iterator("python")) {
  22. if (file.path().extension() == ".py") {
  23. std::string key = file.path().stem().string();
  24. std::ifstream f(file.path());
  25. std::string content((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
  26. sources[key] = to_hex_string(content);
  27. }
  28. }
  29. return sources;
  30. }
  31. std::string generate_header(const std::map<std::string, std::string>& sources) {
  32. std::time_t timestamp = std::time(nullptr);
  33. std::tm* now = std::localtime(&timestamp);
  34. char timestamp_str[20];
  35. std::strftime(timestamp_str, sizeof(timestamp_str), "%Y-%m-%d %H:%M:%S", now);
  36. std::string header;
  37. header += "#pragma once\n";
  38. header += "// generated on ";
  39. header += timestamp_str;
  40. header += "\n#include <map>\n#include <string>\n\nnamespace pkpy{\n";
  41. header += " inline static std::map<std::string, std::string> kPythonLibs = {\n";
  42. for (const auto& [key, value] : sources) {
  43. header += " {\"" + key + "\", \"" + value + "\"},\n";
  44. }
  45. header += " };\n";
  46. header += "} // namespace pkpy\n";
  47. return header;
  48. }
  49. int main() {
  50. auto sources = generate_python_sources();
  51. std::string header = generate_header(sources);
  52. std::ofstream header_file("src/_generated.h");
  53. header_file << header;
  54. return 0;
  55. }