Last active
February 12, 2018 13:45
-
-
Save earonesty/ef3e9482d3e61c412d2731b65d212e0f to your computer and use it in GitHub Desktop.
python template expander ... based on format strings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/env python3.6 | |
import os, sys, json | |
from argparse import ArgumentParser | |
def main(): | |
parser = ArgumentParser(description='Python template expander. \ | |
Make a template with a format string syntax and environment vars, arguments and config file vars are expanded.') | |
parser.add_argument('input', nargs='?', | |
help='Input file') | |
parser.add_argument('--var', action='append', default=[], | |
help='Variable key[=value] pair') | |
parser.add_argument('--conf', action='append', default=[], | |
help='Json file with vars in it') | |
args = parser.parse_args() | |
var = os.environ.copy() | |
for e in args.var: | |
if '=' in e: | |
(k, v) = e.split('=') | |
else: | |
(k, v) = e, "1" | |
var[k] = v | |
for f in args.conf: | |
var.update(json.load(open(f))) | |
# replace dash with underscore because python vars can't have dashes, but vars can | |
var = {k.replace("-", "_"): v for k, v in var.items()} | |
if args.input is None: | |
inf = sys.stdin | |
else: | |
inf = open(args.input) | |
ind = inf.read() | |
ind.replace('\\', '\\\\') | |
ind.replace('"""', '\\"\\"\\"') | |
ind = 'f"""' + ind + '"""' | |
def ifdef(and_vars, if_val, else_val=""): | |
if isinstance(and_vars, str): | |
and_vars = [and_vars] | |
for v in and_vars: | |
if v not in var: | |
return else_val | |
return if_val | |
var["ifdef"] = ifdef | |
ind = eval(ind, {}, var) | |
print(ind) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment