pocketpy/prebuild.py
2024-03-24 17:48:19 +08:00

41 lines
1.2 KiB
Python

import os
def generate_python_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:
# convert to char array (signed)
for c in f.read().encode('utf-8'):
if c < 128:
const_char_array.append(str(c))
else:
const_char_array.append(str(c - 256))
const_char_array.append('0')
const_char_array = ','.join(const_char_array)
sources[key] = '(const char[]){' + const_char_array + '}'
header = '''#pragma once
// generated by prebuild.py
#include <map>
#include <string>
namespace pkpy{
inline std::map<std::string, const char*> kPythonLibs = {
'''
for key, value in sources.items():
header += f' {{ "{key}", {value} }},\n'
header += ''' };
} // namespace pkpy
'''
return header
# use LF line endings instead of CRLF
with open("include/pocketpy/_generated.h", "wt", encoding='utf-8', newline='\n') as f:
f.write(generate_python_sources())