prebuild.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import os
  2. def get_sources():
  3. sources = {}
  4. for file in sorted(os.listdir("python")):
  5. if not file.endswith(".py"):
  6. continue
  7. key = file.split(".")[0]
  8. const_char_array = []
  9. with open("python/" + file) as f:
  10. specials = { 10: '\\n', 34: '\\"' }
  11. for c in f.read().encode('utf-8'):
  12. if c in specials:
  13. const_char_array.append(specials[c])
  14. elif c >= 32 and c <= 126 and c != 92:
  15. const_char_array.append(chr(c))
  16. else:
  17. const_char_array.append(f'\\x{c:02x}')
  18. const_char_array = ''.join(const_char_array)
  19. sources[key] = '"' + const_char_array + '"'
  20. return sources
  21. sources = get_sources()
  22. # use LF line endings instead of CRLF
  23. with open("include/pocketpy/common/_generated.h", "wt", encoding='utf-8', newline='\n') as f:
  24. data = '''#pragma once
  25. // generated by prebuild.py
  26. #ifdef __cplusplus
  27. extern "C" {
  28. #endif
  29. const char* load_kPythonLib(const char* name);
  30. '''
  31. for key in sorted(sources.keys()):
  32. value = sources[key]
  33. data += f'extern const char kPythonLibs_{key}[];\n'
  34. data += '''
  35. #ifdef __cplusplus
  36. } // extern "C"
  37. #endif
  38. '''
  39. f.write(data)
  40. with open("src/common/_generated.c", "wt", encoding='utf-8', newline='\n') as f:
  41. data = '''// generated by prebuild.py
  42. #include "pocketpy/common/_generated.h"
  43. #include <string.h>
  44. '''
  45. for key in sorted(sources.keys()):
  46. value = sources[key]
  47. data += f'const char kPythonLibs_{key}[] = {value};\n'
  48. f.write(data)
  49. f.write("\n")
  50. f.write("const char* load_kPythonLib(const char* name) {\n")
  51. f.write(" if (strchr(name, '.') != NULL) return NULL;\n")
  52. for key in sorted(sources.keys()):
  53. if key.startswith('_'):
  54. continue
  55. f.write(f' if (strcmp(name, "{key}") == 0) return kPythonLibs_{key};\n')
  56. f.write(" return NULL;\n")
  57. f.write("}\n")