Update generator.py

-improved readability
-files now build in the order they appear instead of reverse
-added "with" statements for error handling
master
dekerr 2018-06-05 08:22:06 -04:00 committed by Willem Melching
parent 5db3dfe7a5
commit 9c49b88e85
1 changed files with 29 additions and 23 deletions

View File

@ -2,36 +2,42 @@
import os
import re
def read_dbc(filename):
with open(os.path.join(dir_name, filename), 'r') as file_in:
return file_in.read()
cur_path = os.path.dirname(os.path.realpath(__file__))
generator_path = os.path.join(cur_path, '../')
for dir_name, _, _ in os.walk(cur_path):
if dir_name == cur_path:
continue
include_pattern = r'CM_ "IMPORT (.*?)"'
print dir_name
for dir_name, _, filenames in os.walk(cur_path):
if dir_name == cur_path:
continue
for filename in os.listdir(dir_name):
if filename.startswith('_'):
continue
print dir_name
print filename
dbc_file = open(os.path.join(dir_name, filename)).read()
dbc_file = '\nCM_ "%s starts here"\n' % filename + dbc_file
for filename in filenames:
if filename.startswith('_'):
continue
includes = re.finditer(r'CM_ "IMPORT (.*?)"', dbc_file)
for include in includes:
dbc_file = dbc_file.replace(include.group(0), '')
include_path = os.path.join(dir_name, include.group(1))
print filename
dbc_file_in = read_dbc(filename)
# Load included file
include_file = open(include_path).read()
include_file = '\n\nCM_ "Imported file %s starts here"\n' % include.group(1) + include_file
dbc_file = include_file + dbc_file
includes = re.findall(include_pattern, dbc_file_in)
output_filename = filename.replace('.dbc', '_generated.dbc')
dbc_file = 'CM_ "AUTOGENERATED FILE, DO NOT EDIT"\n' + dbc_file
with open(os.path.join(generator_path, output_filename), 'a') as dbc_file_out:
dbc_file_out.write('CM_ "AUTOGENERATED FILE, DO NOT EDIT"\n')
output_filename = filename.replace('.dbc', '_generated.dbc')
output_dbc_file = open(os.path.join(generator_path, output_filename), 'w')
output_dbc_file.write(dbc_file)
output_dbc_file.close()
for include_filename in reversed(includes):
include_file_header = '\n\nCM_ "Imported file %s starts here"\n' % include_filename
dbc_file_out.write(include_file_header)
include_file = read_dbc(include_filename)
dbc_file_out.write(include_file)
dbc_file_out.write('\nCM_ "%s starts here"\n' % filename)
dbc_file_out.write(dbc_file_in)