Create a website from a json.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

88 lines
2.0 KiB

"""Jinja2 generator."""
from json import load
from os import getenv, listdir, mkdir
import shutil
from jinja2 import Environment, FileSystemLoader # type: ignore
BASE_PATH = 'config.json'
BASE = 'builder/'
STATIC_FOLDER = 'static/'
OUT_DIR = 'build/'
env = Environment(loader=FileSystemLoader(BASE + 'templates'))
def get_congig_path():
if (path := getenv('CONFIG_PATH')):
return path
return BASE_PATH
def get_arguments() -> dict:
with open(get_congig_path(), encoding='utf-8') as f:
return load(f)
def render(file: str, args: dict) -> str:
"""Render a template file."""
template = env.get_template(file)
return template.render(config=args)
def get_files_to_process() -> list:
"""List the files in the template directory."""
return listdir(BASE + 'templates')
def write_output(result, location) -> None:
"""Write output to file."""
with open(location, "w") as f:
f.write(result)
def process_templates() -> None:
"""Process all templates."""
args = get_arguments()
files = get_files_to_process()
for file in files:
print(f'┃ Templating {file}...')
write_output(
render(
file,
args
),
OUT_DIR + file
)
def list_static_files() -> list:
"""Return a list of static files."""
return listdir(STATIC_FOLDER)
def process_static() -> None:
"""Copy all static files."""
print(f'┃ Copying {OUT_DIR + STATIC_FOLDER}...')
shutil.copytree(STATIC_FOLDER, OUT_DIR + STATIC_FOLDER)
def main():
"""Script entrypoint."""
print('┏ Clearing output directory...')
try:
shutil.rmtree(OUT_DIR)
print('┃ Output directory deleted.')
except FileNotFoundError:
print('┃ Output directory does not exist.')
mkdir(OUT_DIR)
print('┗ Done.')
print('┏ Processing templates...')
process_templates()
print('┗ Done.')
print('┏ Copying static files...')
process_static()
print('┗ Done.')
if __name__ == "__main__":
main()