site/export.py

78 lines
2.5 KiB
Python
Raw Normal View History

2020-11-01 14:09:20 +01:00
#!/usr/bin/python3
import os
import shutil
import tarfile
import time
from argparse import ArgumentParser
from jinja2 import Environment, PackageLoader, select_autoescape
from config import context
def dev(args, output):
while True:
time.sleep(0.5)
render(args, output, quiet=True)
def render(args, output, quiet=False):
# do build folder
if os.path.exists(output):
shutil.rmtree(output)
if not quiet:
print("copying static folder")
try:
shutil.copytree(os.path.join(os.getcwd(), 'static'), output)
except Exception:
pass
# build environement
env = Environment(
loader=PackageLoader(__name__, 'templates'),
autoescape=select_autoescape(['html'])
)
templates_folder = os.path.join(os.getcwd(), 'templates')
for root, dirs, templates in os.walk(templates_folder):
if root == os.path.join(templates_folder, 'meta'):
continue
for template_name in templates:
template_absolute_path = os.path.join(root, template_name)
template_file = template_absolute_path[len(templates_folder) + 1:]
if not quiet:
print('processing ' + template_file)
page = template_name[:-len('.html')]
template = env.get_template(template_file)
compiled_template = template.render(page=page, **context)
create_folder(output, template_file)
with open(os.path.join(output, template_file), mode='w') as fp:
fp.write(compiled_template)
def create_folder(container, template_file):
split_path = template_file.split(os.path.sep)
base_path = container
for folder in split_path[:-1]:
full_path = os.path.join(base_path, folder)
if not os.path.exists(full_path):
os.mkdir(full_path)
parser = ArgumentParser(description="Build website")
parser.add_argument('-o', '--output', default='build',
help="Output folder or file")
parser.add_argument('-f', '--format', default="folder",
choices=("gzip", "folder", 'dev'),
help="Format output (either gzip, dev or folder)")
args = parser.parse_args()
output = args.output if args.format != 'gzip' else '_build'
render(args, output)
# compress
if args.format == 'gzip':
with tarfile.open(args.output, "w:gz") as tar:
tar.add(output, arcname=os.path.basename(output))
shutil.rmtree(output)
elif args.format == 'dev':
dev(args, output)
shutil.rmtree(output)