58 lines
1.4 KiB
Python
58 lines
1.4 KiB
Python
|
# -*- encoding: utf-8 -*-
|
||
|
|
||
|
import os.path
|
||
|
import typing as T
|
||
|
|
||
|
import click
|
||
|
import jinja2
|
||
|
import yaml
|
||
|
|
||
|
|
||
|
def read_config(path: T.Text) -> T.Dict[T.Text, T.Any]:
|
||
|
"""
|
||
|
Read the config from the specified path
|
||
|
"""
|
||
|
if not os.path.exists(path):
|
||
|
raise ValueError(f"File does not exist {path}")
|
||
|
|
||
|
with open(path) as f:
|
||
|
data = yaml.safe_load(f)
|
||
|
|
||
|
if not isinstance(data, dict):
|
||
|
raise ValueError(f"Malformed configuration")
|
||
|
|
||
|
return data
|
||
|
|
||
|
|
||
|
def render_template(data: T.Dict[T.Text, T.Any], path: T.Text, dry_run: bool) -> None:
|
||
|
"""
|
||
|
Given the configuration values, renders the template into the desired path.
|
||
|
"""
|
||
|
loader = jinja2.PackageLoader("piker", "template")
|
||
|
env = jinja2.Environment(
|
||
|
loader=loader, autoescape=jinja2.select_autoescape(["yaml"])
|
||
|
)
|
||
|
template = env.get_template("drone.yml.j2")
|
||
|
value = template.render(**data)
|
||
|
if dry_run:
|
||
|
print(value)
|
||
|
return
|
||
|
with open(path, "w") as out:
|
||
|
out.write(value)
|
||
|
|
||
|
|
||
|
@click.command()
|
||
|
@click.option(
|
||
|
"--dry-run/--no-dry-run",
|
||
|
default=False,
|
||
|
help="Display result without actually writing it",
|
||
|
)
|
||
|
@click.argument("config", type=click.Path(exists=True), default="./piker.yml")
|
||
|
@click.argument("target", type=click.Path(), default="./.drone.yml")
|
||
|
def cli(dry_run: bool, config: T.Text, target: T.Text) -> None:
|
||
|
"""
|
||
|
CLI entrypoint
|
||
|
"""
|
||
|
conf_data = read_config(config)
|
||
|
render_template(conf_data, target, dry_run)
|