circuitpython/tools/gen_ld_files.py

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

74 lines
2.0 KiB
Python
Raw Normal View History

2019-10-20 23:50:12 -04:00
#! /usr/bin/env python3
2020-06-03 18:40:05 -04:00
# SPDX-FileCopyrightText: 2014 MicroPython & CircuitPython contributors (https://github.com/adafruit/circuitpython/graphs/contributors)
#
# SPDX-License-Identifier: MIT
2019-10-20 23:50:12 -04:00
import argparse
import os
import os.path
import sys
import re
from string import Template
2021-03-15 09:57:36 -04:00
parser = argparse.ArgumentParser(description="Apply #define values to .template.ld file.")
parser.add_argument(
"template_files",
metavar="TEMPLATE_FILE",
type=argparse.FileType("r"),
nargs="+",
help="template filename: <something>.template.ld",
)
parser.add_argument("--defines", type=argparse.FileType("r"), required=True)
parser.add_argument("--out_dir", required=True)
2019-10-20 23:50:12 -04:00
args = parser.parse_args()
defines = {}
2019-12-05 22:45:53 -05:00
#
2021-03-15 09:57:36 -04:00
REMOVE_UL_RE = re.compile("([0-9]+)UL")
2019-12-05 22:45:53 -05:00
def remove_UL(s):
2021-03-15 09:57:36 -04:00
return REMOVE_UL_RE.sub(r"\1", s)
2019-12-05 22:45:53 -05:00
# We skip all lines before
# // START_LD_DEFINES
# Then we look for lines like this:
# /*NAME_OF_VALUE=*/ NAME_OF_VALUE;
2021-03-15 09:57:36 -04:00
VALUE_LINE_RE = re.compile(r"^/\*\s*(\w+)\s*=\*/\s*(.*);\s*$")
2019-12-05 22:45:53 -05:00
start_processing = False
2019-10-20 23:50:12 -04:00
for line in args.defines:
2019-12-05 22:45:53 -05:00
line = line.strip()
2021-03-15 09:57:36 -04:00
if line == "// START_LD_DEFINES":
2019-12-05 22:45:53 -05:00
start_processing = True
continue
if start_processing:
match = VALUE_LINE_RE.match(line)
if match:
name = match.group(1)
value = match.group(2).strip()
defines[name] = remove_UL(value)
2019-10-20 23:50:12 -04:00
fail = False
for template_file in args.template_files:
ld_template_basename = os.path.basename(template_file.name)
2021-03-15 09:57:36 -04:00
ld_pathname = os.path.join(args.out_dir, ld_template_basename.replace(".template.ld", ".ld"))
with open(ld_pathname, "w") as output:
for k, v in defines.items():
print("/*", k, "=", v, "*/", file=output)
2019-12-05 22:45:53 -05:00
print(file=output)
2019-10-20 23:50:12 -04:00
try:
output.write(Template(template_file.read()).substitute(defines))
except KeyError as e:
print("ERROR: {}: No #define for '{}'".format(ld_pathname, e.args[0]), file=sys.stderr)
fail = True
if fail:
sys.exit(1)