forked from vitrine/wmaker
64 lines
1.8 KiB
Python
Executable File
64 lines
1.8 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
|
|
from os import path
|
|
from typing import List, Tuple
|
|
import argparse
|
|
|
|
|
|
def replace_all(
|
|
replacements: List[Tuple[str, str]],
|
|
lines: List[str],
|
|
) -> List[str]:
|
|
'''Runs string replacement on each of lines.
|
|
|
|
Only one pattern found in each line will be replaced.
|
|
'''
|
|
result = []
|
|
for l in lines:
|
|
for (needle, replacement) in replacements:
|
|
x = l.replace(needle, replacement)
|
|
result.append(x)
|
|
return result
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(
|
|
prog='generate_file',
|
|
description='Runs line-by-line string substitutions on input files',
|
|
epilog='Output files are named after input files with any .in extension stripped',
|
|
)
|
|
parser.add_argument(
|
|
'--replace',
|
|
'-r',
|
|
help='parameters <A> <B> will replace <A> with <B>',
|
|
required=True,
|
|
nargs=2,
|
|
action='append',
|
|
)
|
|
parser.add_argument(
|
|
'--outdir',
|
|
'-o',
|
|
required=True,
|
|
help='directory to write output to',
|
|
)
|
|
parser.add_argument('inputs', nargs='+', help='files to read in')
|
|
settings = parser.parse_args()
|
|
|
|
for infile in settings.inputs:
|
|
base = path.basename(infile)
|
|
if base.endswith('.in'):
|
|
base = base[0:-3]
|
|
if not base:
|
|
raise ValueError(
|
|
'Input file "{}" has an empty basefile name after stripping any ".in" suffix'
|
|
.format(infile))
|
|
outfile = path.join(settings.outdir, base)
|
|
with open(infile, 'r', encoding='utf-8') as reader:
|
|
lines = reader.readlines()
|
|
with open(outfile, 'w', encoding='utf-8') as writer:
|
|
writer.writelines(replace_all(settings.replace, lines))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|