#! /usr/bin/env python """ replace variables in a template with specific variables """ import logging import yaml def parse_arguments(): from argparse import ArgumentParser, FileType arg_parser = ArgumentParser() arg_parser.add_argument("--template", "-t", type=FileType("r")) arg_parser.add_argument( "--input", "-i", type=FileType("r"), help="yaml format template parameter" ) arg_parser.add_argument( "--output", "-o", type=FileType("w"), help="filled in template", default="-" ) return arg_parser.parse_args() def inject(template, variables): import re variable_regex = re.compile("\$([a-zA-Z\_]+)") variables_in_template = variable_regex.findall(template) # we need to be able to fill in every variable assert (v in variables for v in variables_in_template) if not all(v in variables_in_template for v in variables): logging.warn( f"There are unused variables: {filter(lambda v: v not in variables_in_template, [v for v in variables])}" ) filled_template = template for variable, value in variables.items(): filled_template = filled_template.replace(f"${variable}", value) return filled_template if __name__ == "__main__": argv = parse_arguments() with argv.input as yaml_stream: variables = yaml.safe_load(yaml_stream) with argv.template as string_stream: template = string_stream.read() with argv.output as output_stream: output_stream.write( inject(template, variables) ) output_stream.close()