Brian Silverman | 7b8899e | 2018-06-30 19:19:24 -0700 | [diff] [blame] | 1 | #!/usr/bin/python3 |
| 2 | |
| 3 | # Usage: gen_crosstool <base> <cortex_m4f> <output> |
| 4 | # Example: bazel run //tools/cpp:gen_crosstool $(readlink -f tools/cpp/static_crosstool.pb) $(readlink -f tools/cpp/cortex_m4f_crosstool.pb) $(readlink -f tools/cpp/CROSSTOOL) |
| 5 | |
| 6 | import sys |
| 7 | |
| 8 | from third_party.bazel.protos import crosstool_config_pb2 |
| 9 | from google.protobuf import text_format |
| 10 | from google.protobuf.descriptor import FieldDescriptor |
| 11 | |
| 12 | def process_string(string, substitutions): |
| 13 | for a, b in substitutions.items(): |
| 14 | string = string.replace(a, b) |
| 15 | return string |
| 16 | |
| 17 | def rename_message_contents(proto, substitutions): |
| 18 | for descriptor, value in proto.ListFields(): |
| 19 | if descriptor.type == FieldDescriptor.TYPE_STRING: |
| 20 | if descriptor.label == FieldDescriptor.LABEL_REPEATED: |
| 21 | new_value = [] |
| 22 | for string in value: |
| 23 | new_value.append(process_string(string, substitutions)) |
| 24 | value[:] = new_value |
| 25 | else: |
| 26 | setattr(proto, descriptor.name, process_string(value, substitutions)) |
| 27 | if descriptor.type == FieldDescriptor.TYPE_MESSAGE: |
| 28 | if descriptor.label == FieldDescriptor.LABEL_REPEATED: |
| 29 | for sub_proto in value: |
| 30 | rename_message_contents(sub_proto, substitutions) |
| 31 | else: |
| 32 | rename_message_contents(value, substitutions) |
| 33 | |
| 34 | def add_m4f_toolchain(new_toolchain, m4f_proto, substitutions): |
| 35 | new_toolchain.CopyFrom(m4f_proto.toolchain[0]) |
| 36 | rename_message_contents(new_toolchain, substitutions) |
| 37 | |
| 38 | def main(args): |
| 39 | crosstool_proto = crosstool_config_pb2.CrosstoolRelease() |
| 40 | with open(args[0], 'r') as f: |
| 41 | text_format.Merge(f.read(), crosstool_proto) |
| 42 | |
| 43 | m4f_proto = crosstool_config_pb2.CrosstoolRelease() |
| 44 | with open(args[1], 'r') as f: |
| 45 | text_format.Merge(f.read(), m4f_proto) |
| 46 | add_m4f_toolchain(crosstool_proto.toolchain.add(), m4f_proto, { |
| 47 | '%NAME%': 'cortex-m4f', |
| 48 | '%CPU%': '__MK64FX512__', |
| 49 | '%F_CPU%': '120000000', |
| 50 | }) |
| 51 | |
| 52 | with open(args[2], 'w') as f: |
| 53 | f.write('# GENERATED FILE. DO NOT EDIT\n') |
| 54 | f.write('# Generated by tools/cpp/gen_crosstool.py\n') |
| 55 | f.write(text_format.MessageToString(crosstool_proto)) |
| 56 | |
| 57 | if __name__ == '__main__': |
| 58 | sys.exit(main(sys.argv[1:])) |