80 lines
1.8 KiB
Python
80 lines
1.8 KiB
Python
import argparse
|
|
from jinja2 import FileSystemLoader
|
|
from jinja2.environment import Environment
|
|
import os
|
|
import sys
|
|
import yaml
|
|
|
|
|
|
def to_snake_case(d):
|
|
for k in d:
|
|
v = d[k]
|
|
del d[k]
|
|
d[k.replace('-', '_')] = v
|
|
if type(k) == dict:
|
|
to_snake_case(d)
|
|
|
|
|
|
def wrap_text(text, width=80):
|
|
out = ""
|
|
i = 0
|
|
for word in text.split():
|
|
i += len(word)
|
|
if len(word) > width:
|
|
out += word
|
|
out += "\n"
|
|
i = 0
|
|
if i > width:
|
|
out += "\n"
|
|
out += word
|
|
i = len(word)
|
|
else:
|
|
out += word
|
|
out += " "
|
|
i += 1
|
|
|
|
return out
|
|
|
|
|
|
def to_paragraphs(d, *args):
|
|
for k in args:
|
|
if type(d[k]) == str:
|
|
d[k] = wrap_text(d[k])
|
|
|
|
|
|
def ossa_date_formatter(value):
|
|
return "{:%B %d, %Y}".format(value)
|
|
|
|
|
|
def csv_list_formatter(value):
|
|
return ", ".join(value)
|
|
|
|
|
|
def render_template(template, data):
|
|
loader = FileSystemLoader(os.getcwd())
|
|
env = Environment(trim_blocks=True, loader=loader)
|
|
env.filters["ossa_date"] = ossa_date_formatter
|
|
env.filters["csv_list"] = csv_list_formatter
|
|
template = env.get_template(template)
|
|
return template.render(**data)
|
|
|
|
|
|
def render(source, template):
|
|
vals = yaml.safe_load(open(source).read())
|
|
to_snake_case(vals)
|
|
to_paragraphs(vals, 'description')
|
|
return render_template(template, vals)
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description="Convert YAML to RST")
|
|
parser.add_argument("--source", required=True, help="YAML source file")
|
|
parser.add_argument("--template", required=True,
|
|
help="Jinja2 template file")
|
|
args = parser.parse_args()
|
|
print(render(args.source, args.template))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|