diff options
Diffstat (limited to '')
| -rw-r--r-- | patternutils/commands/targs.py | 58 |
1 files changed, 58 insertions, 0 deletions
diff --git a/patternutils/commands/targs.py b/patternutils/commands/targs.py new file mode 100644 index 0000000..41334ed --- /dev/null +++ b/patternutils/commands/targs.py @@ -0,0 +1,58 @@ +import json +import multiprocessing +import shlex +import subprocess + +from typing import ( + Union, + List, +) + +import click + +import patternutils + + +@click.command(context_settings={'help_option_names': ('-h', '--help', '-?')}) +@click.option('--read-from', default='-', type=click.File('r')) +@click.option('-s', '--shell', is_flag=True, default=False, + help='run command in a shell') +@click.option('-t', '--template-engine', default='python', type=click.Choice(['python', 'jinja2']), + help='select the template engine to use') +@click.option('-v', '--verbose', is_flag=True, default=False, + help='explain what is being done') +@click.version_option() +@click.argument('command') +def targs( + command: str, + read_from: click.File, + shell: bool, + template_engine: str, + verbose: bool, +) -> None: + + try: + data = json.load(read_from) + except json.JSONDecodeError: + click.secho('JSON not valid!', fg='red') + raise SystemExit + + use_jinja = True if template_engine == 'jinja2' else False + try: + render = patternutils.template.get_render_function(command, use_jinja=use_jinja) + except RuntimeError: + click.secho('jinja2 not installed!', fg='red') + raise SystemExit + + for r in data: + c = render(**r) + if not shell: + prepared_command = shlex.split(c) # type: Union[str, List[str]] + else: + prepared_command = c + + subprocess.run(prepared_command, shell=shell) + + +if __name__ == '__main__': + targs() |
