101 lines
2.8 KiB
Python
Executable File
101 lines
2.8 KiB
Python
Executable File
#!/usr/bin/env python
|
|
import sys,re,os
|
|
from argparse import ArgumentParser
|
|
from argparse import RawTextHelpFormatter
|
|
|
|
def setup_options():
|
|
parser = ArgumentParser(
|
|
description="""Template Filler
|
|
|
|
=== Template example: ===
|
|
Hello [[name]]!
|
|
[[letter]]
|
|
|
|
== Value file/Value pair example: ==
|
|
[[name]]=John
|
|
[[letter]]=@letter.txt
|
|
""",
|
|
formatter_class = RawTextHelpFormatter
|
|
)
|
|
parser.add_argument(
|
|
"-e",
|
|
action = "store_true",
|
|
dest = "env",
|
|
default = False,
|
|
help = "Use the environment to replace ${env} style variables."
|
|
)
|
|
parser.add_argument(
|
|
"-f",
|
|
action = "store",
|
|
dest = "file",
|
|
help = "File name to read keys/values."
|
|
)
|
|
parser.add_argument(
|
|
"-p",
|
|
action = "append",
|
|
dest = "values",
|
|
default = [],
|
|
help = "key=value pairs. This option may be issued several times."
|
|
)
|
|
parser.add_argument(
|
|
'template',
|
|
action = "store",
|
|
nargs = '?',
|
|
help = "Template file to be filled. If not defined, stdin used."
|
|
)
|
|
options = parser.parse_args()
|
|
return options
|
|
|
|
|
|
def parse_file(filename):
|
|
pairs = []
|
|
with open(filename, "r") as reader:
|
|
for i, l in enumerate(reader):
|
|
l = l.rstrip("\n\r")
|
|
if len(l) == 0:
|
|
continue
|
|
tokens = l.split('=', 1)
|
|
if len(tokens) != 2:
|
|
print("File %s:%i key=value pair '%s' does not parse"%(
|
|
filename, i+1, l,
|
|
))
|
|
sys.exit(1)
|
|
pairs.append( (tokens[0], tokens[1].decode('string_escape')) )
|
|
return pairs
|
|
|
|
def parse_arguments(args):
|
|
pairs = []
|
|
for p in args:
|
|
tokens = p.split('=', 1)
|
|
if len(tokens) != 2:
|
|
print("Argument key=value pair '%s' does not parse"%(p,))
|
|
sys.exit(1)
|
|
pairs.append( (tokens[0], tokens[1].decode('string_escape')) )
|
|
return pairs
|
|
|
|
|
|
if __name__ == "__main__":
|
|
options = setup_options();
|
|
pairs = []
|
|
if options.file != None:
|
|
pairs.extend(parse_file(options.file))
|
|
pairs.extend(parse_arguments(options.values))
|
|
if options.template == None:
|
|
in_reader = sys.stdin
|
|
else:
|
|
in_reader = open(options.template, 'rb')
|
|
for l in in_reader:
|
|
for p in pairs:
|
|
value = p[1]
|
|
if len(value) > 0:
|
|
if value[0] == "@":
|
|
value = open(value[1:], 'rt').read()
|
|
elif value[0:2] == "\\@":
|
|
value = value[1:]
|
|
l = l.replace(p[0], value)
|
|
if options.env:
|
|
var_list = [m.group(0) for m in re.finditer('\${[^ ]+}', l)]
|
|
for v in var_list:
|
|
l = l.replace(v, os.environ.get(v[:-1][2:], ""))
|
|
sys.stdout.write(l)
|