1#!/usr/bin/env python3 2import fileinput 3import os 4import re 5import sys 6 7btstack_root = os.path.abspath(os.path.dirname(sys.argv[0]) + '/../../') 8 9defines_to_add = [] 10defines_to_remove = [] 11 12# dictionary with existing lines as keys, and new text as value 13lines_to_replace = {} 14 15def get_line_ending(full_path): 16 with open(full_path, "r", newline='') as fin: 17 line = fin.readline() 18 if line.endswith('\r\n'): 19 return '\r\n' 20 if line.endswith('\r'): 21 return '\r' 22 return '\n' 23 24 25def configuration_from_block(block, line_ending): 26 global defines_to_add, defines_to_remove 27 configuration = "" 28 29 if len(block) == 0: 30 return "" 31 32 for item in defines_to_remove: 33 if item in block: 34 block.remove(item) 35 36 for item in temp_defines_to_add: 37 if item in block: 38 temp_defines_to_add.remove(item) 39 continue 40 41 if len(block) > 0: 42 prefix = block[0].split("_")[0] 43 if item.startswith(prefix): 44 block.append(item) 45 temp_defines_to_add.remove(item) 46 47 block.sort() 48 for item in block: 49 configuration += ("#define %s%s" % (item, line_ending)) 50 51 configuration += ("%s" % (line_ending)) 52 return configuration 53 54def read_and_update_configuration(full_path, line_ending): 55 global lines_to_replace, temp_defines_to_add 56 57 configuration = "" 58 block = [] 59 temp_defines_to_add = defines_to_add.copy() 60 61 with open(full_path, "rt") as fin: 62 for unstripped_line in fin: 63 line = unstripped_line.strip() 64 65 if not line: 66 if len(block) == 0: 67 # we have newline to deal with 68 configuration += line_ending 69 else: 70 configuration += configuration_from_block(block, line_ending) 71 block = [] 72 else: 73 if line in lines_to_replace.keys(): 74 configuration += ("%s%s" % (lines_to_replace[line], line_ending)) 75 continue 76 77 parts = re.match("#define\\s*(.*)", line) 78 if parts: 79 block.append(parts[1]) 80 else: 81 # if commented code follows directly block, process block, and start a new one 82 configuration += configuration_from_block(block, line_ending) 83 block = [] 84 configuration += ("%s%s" % (line, line_ending)) 85 86 if len(temp_defines_to_add) > 0: 87 print("Cannot add defines: " % temp_defines_to_add) 88 sys.exit(10) 89 90 # if end of file could not be detected, process last block 91 configuration += configuration_from_block(block, line_ending) 92 return configuration 93 94def write_configuration(full_path, config_file): 95 with open(full_path, "wb") as fout: 96 bytes = configuration.encode('utf-8') 97 fout.write(bytes) 98 99 100for root, dirs, files in os.walk(btstack_root, topdown=True): 101 for f in files: 102 if f.endswith("btstack_config.h"): 103 config_file = root + "/" + f 104 line_ending = get_line_ending(config_file) 105 configuration = read_and_update_configuration(config_file, line_ending) 106 write_configuration(config_file, configuration) 107