52 lines
No EOL
2 KiB
Python
52 lines
No EOL
2 KiB
Python
from typing import Dict
|
|
from os import walk, makedirs
|
|
from os.path import isdir, join, exists
|
|
from shutil import copytree
|
|
from article import read_article_file
|
|
|
|
def compile(work_directory: str, template_directory: str=None, target_directory: str=None, force: bool=False):
|
|
if not isdir(work_directory):
|
|
raise FileNotFoundError("One or more of the directories you specified do not exist")
|
|
|
|
if template_directory is None:
|
|
template_directory = join(work_directory, 'template')
|
|
|
|
if not isdir(template_directory):
|
|
raise FileNotFoundError("Template doesn't exist. Add one to your project or specify one with -t")
|
|
|
|
if target_directory is None:
|
|
target_directory = join(work_directory, 'generated_out')
|
|
if exists(target_directory) and not force:
|
|
raise FileExistsError(target_directory + " already exists. Delete it, specify a different one with -o, or pass the -f flag to merge")
|
|
|
|
copytree(join(template_directory, 'static'), join(target_directory, 'static'), dirs_exist_ok=True)
|
|
copytree(join(work_directory, 'posts'), join(target_directory, 'post'), dirs_exist_ok=True)
|
|
|
|
file = open(join(template_directory, 'post.html'))
|
|
post_template = file.read()
|
|
file.close()
|
|
|
|
for root, dirs, files in walk(join(target_directory, 'post')):
|
|
for fn in files:
|
|
if fn.endswith('.html'):
|
|
file = open(join(root, fn), 'r+')
|
|
article = read_article_file(file)
|
|
|
|
content = process_html(post_template, {
|
|
'title': article.title,
|
|
'summary': article.summary,
|
|
'content': article.content
|
|
})
|
|
|
|
file.seek(0)
|
|
file.write(content)
|
|
file.close()
|
|
|
|
def process_html(content: str, variables: Dict[str, str]) -> str:
|
|
for k, v in variables.items():
|
|
content = replace_variable(content, k, v)
|
|
|
|
return content
|
|
|
|
def replace_variable(content: str, var: str, val: str) -> str:
|
|
return content.replace('{{ ' + var + ' }}', val) |