pocketpy/prebuild.py
blueloveTH 3c87bf8630 ...
2024-08-04 15:19:49 +08:00

66 lines
1.9 KiB
Python

import os
def get_sources():
sources = {}
for file in sorted(os.listdir("python")):
if not file.endswith(".py"):
continue
key = file.split(".")[0]
const_char_array = []
with open("python/" + file) as f:
specials = { 10: '\\n', 34: '\\"' }
for c in f.read().encode('utf-8'):
if c in specials:
const_char_array.append(specials[c])
elif c >= 32 and c <= 126 and c != 92:
const_char_array.append(chr(c))
else:
const_char_array.append(f'\\x{c:02x}')
const_char_array = ''.join(const_char_array)
sources[key] = '"' + const_char_array + '"'
return sources
sources = get_sources()
# use LF line endings instead of CRLF
with open("include/pocketpy/common/_generated.h", "wt", encoding='utf-8', newline='\n') as f:
data = '''#pragma once
// generated by prebuild.py
#ifdef __cplusplus
extern "C" {
#endif
const char* load_kPythonLib(const char* name);
'''
for key in sorted(sources.keys()):
value = sources[key]
data += f'extern const char kPythonLibs_{key}[];\n'
data += '''
#ifdef __cplusplus
} // extern "C"
#endif
'''
f.write(data)
with open("src/common/_generated.c", "wt", encoding='utf-8', newline='\n') as f:
data = '''// generated by prebuild.py
#include "pocketpy/common/_generated.h"
#include <string.h>
'''
for key in sorted(sources.keys()):
value = sources[key]
data += f'const char kPythonLibs_{key}[] = {value};\n'
f.write(data)
f.write("\n")
f.write("const char* load_kPythonLib(const char* name) {\n")
for key in sorted(sources.keys()):
if key.startswith('_'):
continue
f.write(f' if (strcmp(name, "{key}") == 0) return kPythonLibs_{key};\n')
f.write(" return NULL;\n")
f.write("}\n")