From 9c49b88e850e9d05908039b905ab41d50071c335 Mon Sep 17 00:00:00 2001 From: dekerr Date: Tue, 5 Jun 2018 08:22:06 -0400 Subject: [PATCH] Update generator.py -improved readability -files now build in the order they appear instead of reverse -added "with" statements for error handling --- generator/generator.py | 52 +++++++++++++++++++++++------------------- 1 file changed, 29 insertions(+), 23 deletions(-) diff --git a/generator/generator.py b/generator/generator.py index e5f69e4..27fb0c7 100755 --- a/generator/generator.py +++ b/generator/generator.py @@ -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)