1
0

prebuild.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. const char* load_kPythonLib(const char* name);
  27. '''
  28. for key in sorted(sources.keys()):
  29. value = sources[key]
  30. data += f'extern const char kPythonLibs_{key}[];\n'
  31. f.write(data)
  32. with open("src/common/_generated.c", "wt", encoding='utf-8', newline='\n') as f:
  33. data = '''// generated by prebuild.py
  34. #include "pocketpy/common/_generated.h"
  35. #include <string.h>
  36. '''
  37. for key in sorted(sources.keys()):
  38. value = sources[key]
  39. data += f'const char kPythonLibs_{key}[] = {value};\n'
  40. f.write(data)
  41. f.write("\n")
  42. f.write("const char* load_kPythonLib(const char* name) {\n")
  43. f.write(" if (strchr(name, '.') != NULL) return NULL;\n")
  44. for key in sorted(sources.keys()):
  45. if key.startswith('_'):
  46. continue
  47. f.write(f' if (strcmp(name, "{key}") == 0) return kPythonLibs_{key};\n')
  48. f.write(" return NULL;\n")
  49. f.write("}\n")