# 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 subprocess

import jinja2
from fastcore.script import *

from kicad_helpers import get_git_root, setup_test_repo, get_project_metadata, get_gitignore_list, in_gitignore
from .core import _set_root

# Cell
@call_parse
def update_templates(v:Param("verbose", bool),
                     overwrite:Param("overwrite existing templates", bool),
                     root:Param("project root directory", str)="."):
    """
    Update project templates from the `kicad_helpers/templates` directory
    (ignoring anything in the project's `.gitignore` list).
    """
    templates_path = os.path.abspath(pkg_resources.resource_filename('kicad_helpers', 'templates'))
    root = _set_root(root)
    metadata = get_project_metadata(root)

    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(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):
                        if v:
                            print(f"{ path } already exists")
                        if not overwrite:
                            continue

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

                    with open(dst_path, "w") as f:
                        if v:
                            print(f"Rendering { path } template.")
                        f.write(template.render(**metadata))