# AUTOGENERATED! DO NOT EDIT! File to edit: notebooks/01_update_project.ipynb (unless otherwise specified).

__all__ = ['update_templates']

# Cell
import os
import pkg_resources

import jinja2
from fastcore.script import *

from kicad_helpers import get_project_root, get_project_metadata, get_gitignore_list, in_gitignore

# Cell
@call_parse
def update_templates():
    # Render all files in the `templates` directory (ignoring anything that is
    # in the `.gitignore` list) as jinja2 templates.
    templates_path = os.path.abspath(pkg_resources.resource_filename('kicad_helpers', 'templates'))
    PROJECT_ROOT = get_project_root()
    metadata = get_project_metadata()

    file_list = []
    for root, dirs, files in os.walk(templates_path):
        if len(files):
            for file in files:
                path = os.path.join(root[len(templates_path) + 1:], file)
                if not in_gitignore(path):
                    src_path = os.path.abspath(os.path.join(templates_path, path))
                    dst_path = os.path.abspath(os.path.join(PROJECT_ROOT, path))

                    # Create the `dst_path` directory if it doesn't exist
                    os.makedirs(os.path.split(dst_path)[0], exist_ok=True)

                    if os.path.exists(dst_path):
                        print(f"{dst_path} already exists")

                    with open(src_path) as f:
                        template = jinja2.Template(f.read())

                    with open(dst_path, "w") as f:
                        f.write(template.render(**metadata))