teapot-spreadsheet/src/tools/interpolate.py

40 lines
1.4 KiB
Python

# To get around the fact that fluid only allows numerical constants
# in some places that expressions would be preferred, this
# file takes a fluid file which may contain numerical constants of the form
#
# 9999NNN/*REPLACEMENT*/
#
# where the NNN are distinct digit sequences (of any length)
# and the corresponding fluid output and replaces any 9999NNN in the output
# with REPLACEMENT (which can of course be any text). Note that the
# entire numerical constant with its replacement comment must occur within
# a single line of the fluid file. The result is written
# to a new output file with the literal string `_interpolated` interpolated
# before its extension.
from pathlib import Path
import re
import sys
fluidin = sys.argv[1]
genfile = Path(sys.argv[2])
outfile = genfile.with_stem(genfile.stem + '_interpolated')
# First collect all of the replacements from the fluidfile
replacerPattern = re.compile(r"(9999\d*)/[*](.*)[*]/")
replacement = {}
with open(fluidin) as fluidf:
for line in fluidf:
foundpat = replacerPattern.search(line)
if foundpat:
replacement[foundpat[1]] = foundpat[2]
# Now make all replacements in the generated file
with open(outfile, 'w') as outf:
with open(genfile) as genf:
for line in genf:
line = line[:-1]
for key in replacement:
line = line.replace(key, replacement[key])
print(line, file=outf)