79 lines
No EOL
2.8 KiB
Python
79 lines
No EOL
2.8 KiB
Python
from json import loads
|
|
from math import ceil
|
|
from os import walk, mkdir
|
|
from os.path import isdir, join, exists
|
|
from shutil import copytree
|
|
from typing import Dict
|
|
|
|
from article import Article, Page, Site
|
|
from template import TemplateEnvironment
|
|
|
|
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, 'articles'), join(target_directory, 'article'), dirs_exist_ok=True)
|
|
|
|
try:
|
|
mkdir(join(target_directory, 'index'))
|
|
except FileExistsError:
|
|
pass
|
|
|
|
file = open(join(work_directory, 'config.json'))
|
|
site = Site.from_open_file(file)
|
|
file.close()
|
|
|
|
template = TemplateEnvironment(template_directory, site)
|
|
articles_per_page = template.config.articles_per_page
|
|
articles = []
|
|
|
|
for root, dirs, files in walk(join(target_directory, 'article')):
|
|
for fn in files:
|
|
if fn.endswith('.html'):
|
|
file = open(join(root, fn), 'r+')
|
|
id = fn.split('.')[0]
|
|
|
|
article = Article.from_open_file(id, file)
|
|
content = template.process_article(article)
|
|
|
|
file.seek(0)
|
|
file.write(content)
|
|
file.close()
|
|
|
|
articles += [article]
|
|
|
|
page_index = 1
|
|
pages = ceil(len(articles) / articles_per_page)
|
|
while len(articles) > 0:
|
|
page = Page(
|
|
page_index, pages,
|
|
f'/index/page{page_index - 1}.html' if page > 1 else None,
|
|
f'/index/page{page_index + 1}.html' if page < pages else None
|
|
)
|
|
|
|
if page_index == 1:
|
|
fn = join(target_directory, 'index.html')
|
|
else:
|
|
fn = join(target_directory, 'index', f'page{page_index}.html')
|
|
|
|
articles_on_page = articles[:articles_per_page] # TODO make this customizable
|
|
content = template.process_index(page, *articles_on_page)
|
|
|
|
file = open(fn, 'w')
|
|
file.write(content)
|
|
file.close()
|
|
|
|
articles = articles[articles_per_page:]
|
|
page_index += 1 |