Minor changes

This commit is contained in:
dennis committed 2021-12-24 00:16:02 +01:00
1 parent 03e5eb55fd
commit e9c5496836
2 files changed
+33 -24

No files matched your search

+1
View File
@@ -1,5 +1,6 @@
<component name="InspectionProjectProfileManager"> <component name="InspectionProjectProfileManager">
<settings> <settings>
<option name="PROJECT_PROFILE" value="Default" />
<option name="USE_PROJECT_PROFILE" value="false" /> <option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" /> <version value="1.0" />
</settings> </settings>
+32 -24
View File
@@ -24,8 +24,10 @@ infilegroup.add_argument('--toml', dest='toml_file', type=str, required=False,
infilegroup.add_argument('--ini', dest='ini_file', type=str, required=False, infilegroup.add_argument('--ini', dest='ini_file', type=str, required=False,
help='INI fil path') help='INI fil path')
infilegroup.add_argument('--env', dest='env_file', action='store_true', infilegroup.add_argument('--env', dest='env_file', action='store_true',
help='Load environment variables') help='Load environment variables (from .env)')
argsparser.add_argument('--showvars', dest='show_vars', action='store_true',
help='Show all input variables and exit')
argsparser.add_argument('--output', default='/dev/stdout', argsparser.add_argument('--output', default='/dev/stdout',
help='Output File') help='Output File')
argsparser.add_argument('infile', metavar="input-file", argsparser.add_argument('infile', metavar="input-file",
@@ -33,8 +35,8 @@ argsparser.add_argument('infile', metavar="input-file",
# Print Errors # Print Errors
def print_error(*args, **kwargs): def print_error(*cmdargs, **kwargs):
print(*args, file=sys.stderr, **kwargs) print(*cmdargs, file=sys.stderr, **kwargs)
# Jinja Environment # Jinja Environment
@@ -46,6 +48,7 @@ jenv = Environment(autoescape=True,
# Jinja Context Functions # Jinja Context Functions
# -----------------------
@jinja2.pass_context @jinja2.pass_context
def get_filtered_variables(c, filter_str=None): def get_filtered_variables(c, filter_str=None):
ret_val = {} ret_val = {}
@@ -89,16 +92,20 @@ jenv.filters['hostbyname'] = filter_hostbyname
jenv.globals['variables'] = get_filtered_variables jenv.globals['variables'] = get_filtered_variables
# Loader # Loader
# ------ # ------
def load_template(filename): def load_template(filename):
try: try:
with open(filename) as file_: with open(filename) as file_:
template = jenv.from_string(file_.read()) input_template = jenv.from_string(file_.read())
return template return input_template
except TemplateError as exc: except TemplateError as exc:
print_error("Template Error:", exc.message) print_error("ERROR: Reading template failed:", exc.message)
return None except FileNotFoundError:
print_error("ERROR:", filename, "- Template file not found")
return None
def load_yaml_file(filename): def load_yaml_file(filename):
@@ -122,7 +129,7 @@ def load_toml_file(filename):
except toml.TomlDecodeError as exc: except toml.TomlDecodeError as exc:
print_error("TOML error:", exc) print_error("TOML error:", exc)
else: else:
print_error("ERROR:", filename, "- File not found") print_error("ERROR:", filename, "- TOML Input file not found")
return None return None
@@ -135,7 +142,7 @@ def load_json_file(filename):
except json.JSONDecodeError as exc: except json.JSONDecodeError as exc:
print_error("JSON error: [", exc.lineno, ",", exc.colno, "]", exc.msg) print_error("JSON error: [", exc.lineno, ",", exc.colno, "]", exc.msg)
else: else:
print_error("ERROR:", filename, "- File not found") print_error("ERROR:", filename, "- JSON Input file not found")
return None return None
@@ -146,36 +153,34 @@ def load_ini_file(filename):
iniparser.read(filename) iniparser.read(filename)
return iniparser.items() return iniparser.items()
else: else:
print_error("ERROR:", filename, "- File not found") print_error("ERROR:", filename, "- INI Input file not found")
return None return None
# Render # Render
# ------ # ------
def render_template(template, outfile, variables=None): def render_template(tpl, outfile, variables=None):
try: try:
with open(outfile, 'w') as file_: with open(outfile, 'w') as file_:
file_.write(template.render(variables)) if variables else file_.write(template.render()) output_content = tpl.render(variables) if variables else tpl.render()
file_.write(output_content)
except TemplateError as exc: except TemplateError as exc:
print_error("Rendering Error:", exc.message) print_error("Rendering Error:", exc.message)
print_error("Values:")
for i, v in variables.items():
print_error(" %s = %s", i, v)
if __name__ == '__main__': if __name__ == '__main__':
# Read command line arguments # Read command line arguments
args = argsparser.parse_args() args = argsparser.parse_args()
tpl = load_template(args.infile) # Load template file to ram
template = load_template(args.infile)
content = None content = None
# If template was found if template:
if tpl: # If template was found
if args.env_file: if args.env_file:
content = os.environ | dotenv_values("../test/.env") content = os.environ | dotenv_values(".env")
elif args.yaml_file: elif args.yaml_file:
content = load_yaml_file(args.yaml_file) content = load_yaml_file(args.yaml_file)
elif args.json_file: elif args.json_file:
@@ -185,9 +190,12 @@ if __name__ == '__main__':
elif args.ini_file: elif args.ini_file:
content = load_ini_file(args.ini_file) content = load_ini_file(args.ini_file)
# Render template with or without external content if content:
render_template(tpl, args.output, content) if content else render_template(tpl, args.output) if args.show_vars:
else: for i, v in content.items():
exit(1) print_error(i, "=", v)
else:
# Render template with or without external content
render_template(template, args.output, content) if content else render_template(template, args.output)
exit(0) exit(0)