opendbc/generator/generator.py

65 lines
1.9 KiB
Python
Raw Permalink Normal View History

2019-09-26 17:37:00 -07:00
#!/usr/bin/env python3
2018-01-25 14:46:50 -08:00
import os
import re
2022-01-27 08:50:12 -08:00
import glob
import subprocess
2018-01-25 14:46:50 -08:00
generator_path = os.path.dirname(os.path.realpath(__file__))
opendbc_root = os.path.join(generator_path, '../')
include_pattern = re.compile(r'CM_ "IMPORT (.*?)";\n')
2022-01-27 08:50:12 -08:00
generated_suffix = '_generated.dbc'
2018-06-17 08:08:41 -07:00
def read_dbc(src_dir: str, filename: str) -> str:
with open(os.path.join(src_dir, filename), encoding='utf-8') as file_in:
return file_in.read()
def create_dbc(src_dir: str, filename: str, output_path: str):
dbc_file_in = read_dbc(src_dir, filename)
2018-01-25 14:46:50 -08:00
includes = include_pattern.findall(dbc_file_in)
2022-01-27 08:50:12 -08:00
output_filename = filename.replace('.dbc', generated_suffix)
output_file_location = os.path.join(output_path, output_filename)
with open(output_file_location, 'w', encoding='utf-8') as dbc_file_out:
2020-12-03 13:35:07 -08:00
dbc_file_out.write('CM_ "AUTOGENERATED FILE, DO NOT EDIT";\n')
for include_filename in includes:
2020-12-03 13:35:07 -08:00
include_file_header = '\n\nCM_ "Imported file %s starts here";\n' % include_filename
dbc_file_out.write(include_file_header)
2018-01-25 14:46:50 -08:00
include_file = read_dbc(src_dir, include_filename)
dbc_file_out.write(include_file)
2018-01-26 11:47:55 -08:00
2020-12-03 13:35:07 -08:00
dbc_file_out.write('\nCM_ "%s starts here";\n' % filename)
core_dbc = include_pattern.sub('', dbc_file_in)
dbc_file_out.write(core_dbc)
2018-06-12 20:51:46 -07:00
def create_all(output_path: str):
2022-01-27 08:50:12 -08:00
# clear out old DBCs
for f in glob.glob(f"{output_path}/*{generated_suffix}"):
2022-01-27 08:50:12 -08:00
os.remove(f)
# run python generator scripts first
for f in glob.glob(f"{generator_path}/*/*.py"):
subprocess.check_call(f)
for src_dir, _, filenames in os.walk(generator_path):
if src_dir == generator_path:
continue
2018-06-12 20:51:46 -07:00
#print(src_dir)
2018-06-12 20:51:46 -07:00
for filename in filenames:
if filename.startswith('_') or not filename.endswith('.dbc'):
continue
#print(filename)
create_dbc(src_dir, filename, output_path)
2018-06-12 20:51:46 -07:00
if __name__ == "__main__":
create_all(opendbc_root)